diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index cef21517..f847e524 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -5,6 +5,11 @@ name: lint # fills the gitignored wasm payloads from the published npm tarballs. Lint # stays its own fast job so a style break is visible in seconds, not after a # 450MB payload fetch. +# +# This fork lints only the JavaScript it changes relative to upstream +# (monteslu/romdev main, from the merge base). Errors in upstream's own files +# are upstream's to fix; fixing them here would spread the fork's diff over +# files it does not otherwise touch and conflict on every upstream merge. on: push: @@ -19,12 +24,17 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 # the merge base with upstream - uses: actions/setup-node@v4 with: node-version: 24 # repo engines floor is >=24 cache: npm + - name: Check workspace pins + run: node scripts/check-pins.mjs + # --ignore-scripts skips romdevtools' postinstall (it expects bundled wasm, # absent in CI). We DO install workspace deps (not --workspaces=false) so # the pure-JS tests get romdevtools' runtime deps (zod, pngjs). The core/ @@ -33,5 +43,10 @@ jobs: - name: Install deps run: npm ci --ignore-scripts - - name: ESLint - run: npm run lint + - name: ESLint (files this fork changes) + run: | + git fetch --no-tags https://github.com/monteslu/romdev.git main + base=$(git merge-base HEAD FETCH_HEAD) + mapfile -t files < <(git diff --name-only --diff-filter=ACMR "$base" HEAD -- '*.js' '*.mjs' '*.cjs') + echo "linting ${#files[@]} file(s) changed since $(git rev-parse --short "$base")" + if [ ${#files[@]} -gt 0 ]; then npx eslint --no-warn-ignored "${files[@]}"; fi diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6b360004..06143332 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -57,6 +57,9 @@ jobs: # --ignore-scripts skips romdevtools' postinstall (SDL prebuilt fetch for # the playtest window; no window opens in CI and the runtime self-heals). + - name: Check workspace pins + run: node scripts/check-pins.mjs + - name: Install deps run: npm ci --ignore-scripts @@ -73,6 +76,44 @@ jobs: ROMDEV_NO_GL: "1" run: npm test --workspace=romdevtools 2>&1 | tee /tmp/test-output.txt + # The decomp packages' own suites. Each runs even when an earlier one + # failed, so one red package never hides another's result. Their inputs + # that a clean checkout cannot have skip with a stated reason, never fail + # opaquely: + # - upstream corpora read from the dev box: m2c's e2e/visualize cases + # ($M2C_SRC, else ~/.romdev/tools/m2c), permuter's job corpus + # ($ROMDEV_PERMUTER_CORPUS, else ~/.romdev/decomp/*/jobs), splat's + # Python reference-tree differential ($ROMDEV_SPLAT_PROJECT/CONFIG/REF) + # and pycparser's upstream c_files not shipped with the fork; + # - gitignored WASM payloads, filled from npm by the step above: + # romdev-rabbitizer's wasm/ (rabbitizer + every spimdisasm test that + # decodes), romdev-toolchain-mips-gcc (pycparser's use_cpp cases, + # permuter's compile/score cases) and romdev-toolchain-ido (permuter's + # import and permuter@home cases). + - name: Test romdev-pycparser + if: ${{ !cancelled() }} + run: npm test --workspace=romdev-pycparser 2>&1 | tee /tmp/test-output-pycparser.txt + + - name: Test romdev-rabbitizer + if: ${{ !cancelled() }} + run: npm test --workspace=romdev-rabbitizer 2>&1 | tee /tmp/test-output-rabbitizer.txt + + - name: Test romdev-spimdisasm + if: ${{ !cancelled() }} + run: npm test --workspace=romdev-spimdisasm 2>&1 | tee /tmp/test-output-spimdisasm.txt + + - name: Test romdev-splat + if: ${{ !cancelled() }} + run: npm test --workspace=romdev-splat 2>&1 | tee /tmp/test-output-splat.txt + + - name: Test romdev-m2c + if: ${{ !cancelled() }} + run: npm test --workspace=romdev-m2c 2>&1 | tee /tmp/test-output-m2c.txt + + - name: Test romdev-permuter + if: ${{ !cancelled() }} + run: npm test --workspace=romdev-permuter 2>&1 | tee /tmp/test-output-permuter.txt + # A green badge that silently covers nothing is the same failure class as # a tool returning ok:true on a black frame: the signal reports success # while meaning nothing. So SAY what this run could not test, in the job @@ -81,7 +122,9 @@ jobs: - name: Report what this run could NOT cover if: always() run: | - skipped=$(grep -c '^# SKIP' /tmp/test-output.txt 2>/dev/null || echo 0) + # node --test's spec reporter ends each run with "ℹ skipped N". + count() { { grep -hE '^ℹ skipped [0-9]+' "$@" 2>/dev/null || true; } | awk '{s += $3} END {print s + 0}'; } + skipped=$(count /tmp/test-output.txt) { echo "### Coverage gaps in this run" echo @@ -93,7 +136,17 @@ jobs: echo "- \`test/roms/nestest.nes\` is commercial content and ships in no tarball," echo " so the tests needing it skip themselves by design." echo - echo "Total skipped in this run: **${skipped}**" + echo "Total skipped in the romdevtools suite: **${skipped}**" + echo + echo "#### Decomp packages" + echo + echo "| package | skipped | reasons |" + echo "|---|---|---|" + for p in pycparser rabbitizer spimdisasm splat m2c permuter; do + f=/tmp/test-output-$p.txt + reasons=$({ grep -hE '^ *﹣ .* # ' "$f" 2>/dev/null || true; } | sed 's/.* # //' | sort | uniq -c | sort -rn | awk '{n=$1; $1=""; printf "%s x%s
", substr($0, 2), n}') + echo "| romdev-$p | $(count "$f") | ${reasons:-none} |" + done echo echo "A green check here means everything runnable passed - not that" echo "everything was run." diff --git a/NOTICE b/NOTICE index 7c779248..24a17428 100644 --- a/NOTICE +++ b/NOTICE @@ -1,99 +1,598 @@ -romdev - third-party component inventory -======================================== - -TL;DR - Games you build with romdev are YOURS, including to sell commercially. -A built ROM contains only your code + permissive runtime libraries, compiled by -toolchains with runtime exceptions. The non-commercial caveat below applies ONLY -to redistributing the romdev tool bundle (which contains two non-commercial -emulator cores) - never to the games you make with it. - -romdev's own code is MIT (see LICENSE). It bundles and redistributes -third-party emulator cores, compiler toolchains, and game runtime libraries, -each under its own license. This file inventories them. - -Two kinds of bundled component, governed differently: - - • COMPILERS / TOOLCHAINS produce the user's ROM. Several are GPL/LGPL, but - compilers carry a RUNTIME EXCEPTION: the license of the compiler does NOT - extend to its output. A game compiled with GPL gcc/cc65/sdcc is the - author's own work, freely licensable. The GPL obligation falls on US (we - redistribute the compiler binary) - satisfied by shipping the build recipe - + pinned upstream source so anyone can reproduce the binary (see - packages/romdev/scripts/ and BUILDING.md). - - • EMULATOR CORES never touch the user's ROM - they are a dev instrument - (run + observe). Their license governs only OUR redistribution of the core - binary. Most are GPL (OSI open source, source available upstream). Two are - NON-COMMERCIAL (see below), which is why romdev as a whole is distributed - as SOURCE-AVAILABLE / FREE FOR NON-COMMERCIAL USE rather than OSI open - source. romdev's own code is MIT and the game runtime libraries are - permissive, so games you BUILD with romdev are unencumbered (see below); - the non-commercial terms apply only to redistributing the bundled core - binaries themselves. - - -NON-COMMERCIAL COMPONENTS (why romdev is "free for non-commercial use") ------------------------------------------------------------------------ -These two cores are under custom NON-COMMERCIAL licenses. They forbid -commercial redistribution of the core, so a distribution of romdev that -bundles them is free for non-commercial use and is not labeled OSI open -source. (Your code is MIT; your built games are unencumbered - this affects -only redistribution of these emulator binaries.) - - snes9x SNES core non-commercial (snes9x license) - genesis_plus_gx Genesis/SMS/GG core non-commercial (Genesis Plus GX license) +romdevtools - licence statement and third-party inventory +========================================================== + +This file is the licence of the romdevtools npm package (package.json: +"SEE LICENSE IN NOTICE"). It has three parts: + + 1. romdev's own code is MIT. The full text is in LICENSE. + + 2. Third-party components. romdevtools contains some third-party code + itself (listed under "Third-party code inside romdevtools"), and it + depends on separate npm packages (romdev-core-*, romdev-platform-*, + romdev-toolchain-*, romdev-analysis*, and the decompilation ports) that + redistribute emulator cores, compiler toolchains and tools, each under + its own licence. This file lists all of them. Each component's own + licence governs that component. + + 3. Recompiled carts. The static recompiler (disasm({target:'recompile'}), + emit 'wasmcart' or 'sync32') builds code ported from a reference + emulator into every cart it makes. A recompiled cart carries that + emulator's licence: GPL-2.0 for NES and GB/GBC, MPL-2.0 for GBA, and + non-commercial for SMS/GG, Genesis and SNES. It also contains the code + of the game it was recompiled from. See "Recompiled carts" below. + +In short: + + - Games you COMPILE with romdev from your own source are yours, including + to sell commercially. A compiled ROM contains only your code plus + permissive runtime libraries, built by toolchains whose licences do not + extend to their output. + - RECOMPILED carts are not unencumbered (part 3). + - The non-commercial terms of two emulator cores apply to redistributing + the romdev tool bundle that contains them (and to recompiled carts built + from their code), never to games you compile. + +This section describes what each licence says; it is not legal advice. + + +How the kinds of component are governed +--------------------------------------- + + COMPILERS / TOOLCHAINS produce the user's ROM. Several are GPL or LGPL, but + their licences do not reach the compiled output: gcc's runtime library + carries the GCC Runtime Library Exception, SDCC's runtime libraries carry a + linking exception, and the other assemblers and linkers place no + conditions on what they produce. A game compiled with GPL gcc, cc65 or + sdcc is the author's own work, freely licensable. The GPL obligation falls + on romdev as the redistributor of the compiler binaries. It is met by + publishing the build recipes, romdev's patches and the pinned upstream + sources in the source repository (https://github.com/monteslu/romdev): + see packages/romdevtools/scripts/BUILD_MAP.md (which recipe builds which + package) and packages/romdevtools/scripts/versions.json (every upstream + URL and pinned commit). The recipes and patches are not in the npm + tarballs. + + EMULATOR CORES are a development instrument: running a game on a core puts + none of the core's code into the game. A core's licence governs the + redistribution of the core binary. Most are GPL. Two are non-commercial + (below), which is why a romdev distribution that bundles them is free for + non-commercial use rather than OSI open source. + + THE STATIC RECOMPILER is the exception: it copies code ported from the + reference cores into its output. Every recompiled cart carries the licence + of the core it was ported from (see "Recompiled carts"). + + +Non-commercial components +------------------------- +These two cores are under custom non-commercial licences that forbid +commercial redistribution of the core. Your own code and the games you +compile are unencumbered; a cart the recompiler builds for SMS/GG, +Genesis or SNES contains code from these cores and is non-commercial. + + snes9x SNES snes9x licence (non-commercial) + genesis_plus_gx Genesis / SMS / GG Genesis Plus GX licence + (non-commercial) + +romdevtools itself ships source derived from both (the recompiler backends +under src/analysis/recompile/), under their terms. Their licence texts are in +LICENSES/ in this package. + + +Third-party code inside romdevtools +----------------------------------- +Everything in this package not listed here is romdev's own code (MIT). + + src/analysis/recompile/ recompiler backends: code ported or generated + from fceumm, gambatte, mGBA, Genesis Plus GX, + snes9x, ares and musl. Each backend directory's + NOTICE.txt lists the ported files; licences in + "Recompiled carts" and LICENSES/. + src/decomp/asm-processor.js + JS port of asm-processor + (https://github.com/simonlindholm/asm-processor), + public domain (Unlicense). + src/decomp/maspsx.js JS port of maspsx (https://github.com/mkst/maspsx), + MIT, Copyright (c) 2023 Mark Street. + src/decomp/workbench/ JS port of n64-decomp-workbench 0.8.0 + (https://github.com/akratch/n64-decomp-workbench) + and its bundled data (field guide, compiler-law + notes, skills, fingerprints), CC0-1.0. + src/git/wildmatch.js port of git's wildmatch.c (Rich Salz, Wayne + Davison), public domain. + src/platforms/*/lib/ game runtime libraries, shipped as source (see + "Game runtime / SDK libraries"). Emulator cores -------------- - fceumm NES GPL-2.0 - gambatte GB / GBC GPL-2.0 - genesis_plus_gx Genesis / SMS / GG non-commercial ⚠ (see above) - snes9x SNES non-commercial ⚠ (see above) - mgba GBA MPL-2.0 - vice (x64) C64 GPL-2.0 (see "C64 ROMs" below) - stella2014 Atari 2600 GPL-2.0 - prosystem Atari 7800 GPL-2.0 - handy Atari Lynx zlib - -C64 ROMs - free replacements, not Commodore's ----------------------------------------------- - Upstream vice-libretro compiles Commodore's KERNAL, BASIC and CHARGEN ROMs - into the core (USE_EMBEDDED). Those images are "Copyright C by Commodore - Business Machines" per VICE's own README; the GPL covers VICE's code, not - them. romdev builds VICE with that define disabled and redistributes none of - them. - - In their place romdev-core-vice bundles MEGA65 Open ROMs (GPL-3.0 / - LGPL-3.0), a clean-room KERNAL/BASIC/CHARGEN, so the C64 works out of the - box. Licences ship alongside the images in that package's roms/ directory. - Set ROMDEV_C64_ROM_DIR to use original ROMs you own instead. - -Compiler toolchains (runtime exception - does not encumber compiled ROMs) --------------------------------------------------------------------------- - cc65 NES/C64/2600/7800/Lynx zlib - sdcc GB/GBC/SMS/GG GPL-2.0 (runtime libs: GPL + linking exception) - arm-none-eabi-gcc GBA GPL-3.0 (GCC Runtime Library Exception) - m68k-elf-gcc Genesis (C) GPL-3.0 (GCC Runtime Library Exception) - binutils (gcc toolchains) GPL-3.0 - newlib (gcc toolchains) BSD-style (mixed permissive) - asar SNES (asm) LGPL-3.0 - dasm Atari 2600 (asm) GPL-2.0 - vasm (m68k) Genesis (asm) free for any use (vasm license) - rgbds GB/GBC (asm) MIT - tcc816 SNES (C) LGPL-2.1 - wla-dx SNES (asm) GPL-2.0 - -Game runtime / SDK libraries (linked into the user's game; shipped as source) ------------------------------------------------------------------------------- - SGDK Genesis C engine MIT - PVSnesLib SNES C library MIT - libtonc / libgba GBA C libraries public domain / zlib-style - maxmod / mmutil GBA music ISC - hUGEDriver GB/GBC music MIT-style (see LICENSE-HUGEDRIVER) - FamiTone2 NES music permissive (see LICENSE-FAMITONE) - -Full license texts for the bundled SDK libraries live alongside their source -under packages/romdev/src/platforms/*/lib/. Emulator-core and compiler license -texts travel with their upstream source, which is fetched at build time from -the pinned commits recorded in packages/romdev/scripts/versions.json. +Each core is built to WebAssembly from its upstream source (at the commit +pinned in versions.json in the source repository, where one is pinned), +with romdev's patch, and shipped in the package named. 18 cores in 18 packages. + + Core Platform Licence Package + ---------------- ------------------- ----------------- ------------------------ + fceumm NES GPL-2.0 romdev-core-fceumm + https://github.com/libretro/libretro-fceumm + gambatte GB / GBC GPL-2.0 romdev-core-gambatte + https://github.com/libretro/gambatte-libretro + genesis_plus_gx Genesis / SMS / GG non-commercial romdev-core-gpgx + https://github.com/libretro/genesis-plus-gx + snes9x SNES non-commercial romdev-platform-snes + https://github.com/libretro/snes9x + (with ares's chip cores, ISC; see below) + bsnes SNES (accuracy GPL-3.0 (libco, romdev-core-bsnes + reference for the nall: ISC) + firmware chips) + https://github.com/libretro/bsnes + A separate core, linked into nothing else. + mGBA GBA MPL-2.0 romdev-platform-gba + https://github.com/libretro/mgba + stella2014 Atari 2600 GPL-2.0 romdev-platform-atari2600 + https://github.com/libretro/stella2014-libretro + ProSystem Atari 7800 GPL-2.0 romdev-core-prosystem + https://github.com/libretro/prosystem-libretro + Handy Atari Lynx zlib romdev-core-handy + https://github.com/libretro/libretro-handy + VICE (x64) C64 GPL-2.0 romdev-core-vice + https://github.com/libretro/vice-libretro + (see "Firmware and BIOS" for the C64 ROMs) + Geargrafx PC Engine / TG-16 GPL-3.0 romdev-core-geargrafx + https://github.com/drhelius/Geargrafx + blueMSX MSX / MSX2 blueMSX licence romdev-core-bluemsx + https://github.com/libretro/blueMSX-libretro + (zlib-style; some sound-chip files from openMSX and fMSX-SDL + are GPL, per upstream license.txt) + (with C-BIOS, BSD-style; see "Firmware and BIOS") + GameTank GameTank MIT romdev-core-gametank + https://github.com/monteslu/gametank-libretro (libretro core), built on + GameTankEmulator (https://github.com/clydeshaffer/GameTankEmulator, + MIT, Copyright 2020 Clyde Shaffer) and its mos6502 core (MIT, + Copyright 2017 Gianluca Ghettini) + FAKE-08 PICO-8 carts MIT romdev-core-fake08 + https://github.com/jtothebell/fake-08 (with z8lua, MIT) + A clean-room PICO-8 player; not Lexaloffle's PICO-8. + ParaLLEl-N64 N64 GPL-2.0 romdev-core-parallel-n64 + https://github.com/libretro/parallel-n64 + Built with the glide64 GPU renderer (GL). + Beetle PSX HW PlayStation GPL-2.0 romdev-core-beetle-psx-hw + https://github.com/libretro/beetle-psx-libretro (a Mednafen PSX fork), + GLES3 hardware renderer, with OpenBIOS embedded (see "Firmware and + BIOS") + Flycast Dreamcast GPL-2.0 romdev-core-flycast + https://github.com/flyinghead/flycast, with its reios HLE BIOS + s32core sync32 MIT romdev-core-s32core + First-party interpreter for sync32, an open RP2350-based console. + +The SNES coprocessor code from ares +----------------------------------- + The firmware-running SNES coprocessors (the ST010/ST011 NEC uPD96050 and the + ST018 ARM) are compiled from ares (https://github.com/ares-emulator/ares, at + the commit pinned in versions.json, cores.ares): its processor cores + ares/component/processor/upd96050 and arm7tdmi, the Super Famicom driver + files ares/sfc/coprocessor/necdsp/memory.cpp and armdsp/memory.cpp and + io.cpp, and the nall headers they use, with romdev's glue (MIT) restating + the rest of those drivers and ares's thread clock. That code is compiled + into: + - recompiled SNES carts built with options.firmware (ST011 / ST018): the + units in src/analysis/recompile/wat/snes/ares-chips.json in this + package; + - romdev's snes9x core (romdev-platform-snes), used when st011.rom / + st018.rom is in the system directory. + ares is under the ISC license, a permissive license whose only condition is + keeping its notice, so it can sit with snes9x's non-commercial license and + with romdev's MIT code. A recompiled cart (in its licence entry's notices) + or a snes9x core build that contains it carries this notice: + + ares + + Copyright (c) 2004-2025 ares team, Near et al + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + A recompiled SNES cart's machine follows snes9x and carries snes9x's own + chip units, so those parts of a cart stay under snes9x's non-commercial + license; the ares code adds no condition of its own. No bsnes (GPL-3.0) + code is compiled into snes9x or into a cart: bsnes ships only as its own + core, romdev-core-bsnes. + + +Firmware and BIOS +----------------- +romdev ships no console manufacturer's BIOS or firmware. Where a system +needs one, romdev uses a free replacement or its own code, or the user +supplies the image. + + C64 MEGA65 Open ROMs (https://github.com/MEGA65/open-roms), + GPL-3.0 / LGPL-3.0, a clean-room KERNAL, BASIC and CHARGEN, + in romdev-core-vice roms/ with their licence files. Upstream + vice-libretro compiles Commodore's ROMs into the core; romdev + builds VICE with that disabled and redistributes none of them. + Set ROMDEV_C64_ROM_DIR to use original ROMs you own instead. + MSX C-BIOS (https://cbios.sourceforge.net), BSD-style licence, in + romdev-core-bluemsx bios/ (licence in each cbios.txt). + PlayStation OpenBIOS from PCSX-Redux (https://github.com/grumpycoders/ + pcsx-redux), MIT, embedded in romdev-core-beetle-psx-hw. + Dreamcast Flycast's reios HLE BIOS (part of Flycast, GPL-2.0). + GBA mGBA's own HLE BIOS (part of mGBA, MPL-2.0). + N64 build({platform:'n64'}) adds romdev's own minimal IPL3 boot + stub (MIT) to the ROM it produces. + SNES The SPC700 boot program in recompiled SNES carts and in + romdev's SNES path is romdev's own code (MIT), written from + the documented behaviour of the console's boot ROM. + Coprocessor firmware is supplied by the user and never ships + with romdev: the ST010/ST011 and ST018 programs (for + recompiled carts through options.firmware; for the snes9x and + bsnes cores as st011.rom / st018.rom in the system directory), + and likewise the DSP-1 data ROM, which a DSP-1 cart needs + supplied as firmware. + PICO-8 FAKE-08 needs no BIOS. + + +Analysis engines +---------------- + Rizin (CFG, xrefs, functions) LGPL-3.0 romdev-analysis + https://github.com/rizinorg/rizin + Ghidra decompiler and SLEIGH Apache-2.0 romdev-analysis-decompiler + https://github.com/NationalSecurityAgency/ghidra, built via rz-ghidra + (https://github.com/rizinorg/rz-ghidra, LGPL-3.0), plus the SLEIGH + specs GhidraBoy (SM83, Apache-2.0), ghidra-snes (65816, MIT) and + Ghidra_HuC6280 (HuC6280, Apache-2.0). Each package's NOTICE has the + full attribution. + + +Compiler toolchains (their licences do not encumber compiled ROMs) +------------------------------------------------------------------- + Toolchain Used for Licence Package + ------------------------ ---------------------- ---------------- --------------------------- + cc65 NES, 2600, 7800, C64, zlib romdev-toolchain-cc65 + Lynx, PC Engine, + GameTank + SDCC 4.4.0 GB/GBC, SMS/GG, MSX GPL-2.0 (runtime romdev-toolchain-sdcc + libs: GPL with a + linking exception) + binutils 2.42, z80-elf Z80/SM83 disassembly GPL-3.0 romdev-toolchain-sdcc + and reassembly + RGBDS GB/GBC (asm) MIT romdev-toolchain-rgbds + m68k-elf gcc 14.2.0, Genesis (C and asm) GPL-3.0 with the romdev-toolchain-m68k-gcc + binutils 2.42, newlib GCC Runtime + 4.4.0 Library Exception; + newlib BSD-style + sjasm (from SGDK) Genesis Z80 driver asm zlib romdev-toolchain-m68k-gcc + bintos (from SGDK) Z80 blob embedding MIT romdev-toolchain-m68k-gcc + asar SNES (asm) LGPL-3.0 romdev-platform-snes + tcc816 (alekmaul/tcc) SNES (C) LGPL-2.1 romdev-platform-snes + wla-dx (wla-65816, SNES (asm, link) GPL-2.0 romdev-platform-snes + wlalink) + dasm Atari 2600 (asm) GPL-2.0 romdev-platform-atari2600 + arm-none-eabi gcc 14.2.0, GBA, sync32 (C) GPL-3.0 with the romdev-platform-gba + binutils 2.42, newlib GCC Runtime + 4.4.0 Library Exception; + newlib BSD-style + mips-elf gcc 14.2.0, N64, PS1 (C) GPL-3.0 with the romdev-toolchain-mips-gcc + binutils 2.42, newlib GCC Runtime + 4.4.0 Library Exception; + newlib BSD-style + mips-linux-gnu binutils N64 decomp builds GPL-3.0 romdev-toolchain-mips-gcc + 2.46 + armips N64 decomp RSP MIT romdev-toolchain-mips-gcc + microcode + sh-elf gcc 14.2.0, Dreamcast (C) GPL-3.0 with the romdev-toolchain-sh-gcc + binutils 2.42, newlib GCC Runtime + 4.4.0 Library Exception; + newlib BSD-style + mips-linux-gnu gcc 14.2.0 N64 decomp data TUs, GPL-3.0; glibc's romdev-toolchain-decomp-gcc + .s and linker-script stdc-predef.h + preprocessing LGPL-2.1 + KMC gcc 2.7.2 + N64 decomp (N64 SDK GPL-2.0 romdev-toolchain-decomp-gcc + binutils 2.6 as compiler) + EGCS 1.1.2 (gcc 2.91.66) N64 decomp (iQue GPL-2.0 romdev-toolchain-decomp-gcc + + binutils 2.9.5 as builds) + gcc 2.6.3 (PS1 recipe of PS1 decomp GPL-2.0 romdev-toolchain-decomp-gcc + decompals/old-gcc) + slinky-cli 0.5.0, decomp builds (linker MIT romdev-toolchain-decomp-gcc + pigment64 0.6.3, scripts, textures, + crunch64 compression) + raw-deflate (zlib 1.3.1) decomp builds zlib romdev-toolchain-decomp-gcc + A PS1 decomp project's PS1 decomp setup AGPL-3.0 romdev-toolchain-decomp-gcc + own setup tools (string (Go runtime: + encoder, disc extractor, BSD-3-Clause) + asset tool) + + Upstream sources: gcc, binutils and newlib from https://gnu.org and + https://sourceware.org/newlib; cc65 https://github.com/cc65/cc65; SDCC + https://sdcc.sourceforge.net; RGBDS https://github.com/gbdev/rgbds; SGDK + https://github.com/Stephane-D/SGDK; asar https://github.com/RPGHacker/asar; + tcc816 https://github.com/alekmaul/tcc; wla-dx https://github.com/vhelin/wla-dx; + dasm https://github.com/dasm-assembler/dasm; armips + https://github.com/Kingcom/armips; the decomp compilers and tools from + https://github.com/decompals (mips-gcc-2.7.2, mips-binutils-2.6, + mips-gcc-egcs-2.91.66, mips-binutils-egcs-2.9.5, old-gcc, slinky, + pigment64, crunch64). The exact versions and commits are in versions.json + in the source repository. + + The PS1 decomp projects' assembly post-processor, maspsx, is ported to JS + inside romdevtools (see "Third-party code inside romdevtools"). + +IDO (not shipped) +----------------- + SGI's IDO 5.3 and 7.1 C compilers, which many N64 decompilation projects + build with, are proprietary. romdev does not ship them, and no romdev npm + package contains them. romdev-toolchain-ido is a private package in the + source repository that npm will not publish. To use IDO, build it yourself + from a checkout with packages/romdevtools/scripts/build-ido.sh (it + statically recompiles the IRIX programs with the pinned ido-static-recomp, + https://github.com/decompals/ido-static-recomp, MIT, and compiles the + result to WebAssembly), or set ROMDEV_IDO_DIR to a directory holding your + own build (its 5.3/ and 7.1/ folders). The IRIX programs remain the + property of their owners. + + +Game runtime / SDK libraries (linked into the user's game) +----------------------------------------------------------- + SGDK Genesis C engine MIT romdev-toolchain-m68k-gcc + PVSnesLib SNES C library MIT romdevtools + libgba 0.5.4 GBA C library LGPL with static- romdev-platform-gba + linking exceptions + libtonc 1.4.5 GBA C library MIT romdev-platform-gba + devkitPro crt0 GBA start-up code MPL-2.0 romdev-platform-gba + maxmod GBA music ISC romdev-platform-gba + hUGEDriver GB/GBC music public domain romdevtools + FamiTone2 NES music public domain romdevtools + cc65 runtime 6502 targets zlib romdev-toolchain-cc65, + romdevtools (cc65-src/) + SDCC runtime Z80 / SM83 targets GPL with a romdev-toolchain-sdcc + linking exception + libgcc gcc targets (incl. GPL-3.0 with the the gcc toolchain + sync32's ARMv8-M GCC Runtime packages, + build) Library Exception romdev-platform-sync32 + newlib gcc targets BSD-style (mixed) the gcc toolchain packages + + Notes for games that link these: + - libgba's licence says static linking does not make your game a + derivative work, but asks that a program identify its use of libgba + (for example: "based in part on the work of the devkitpro project"). + - The devkitPro crt0 is MPL-2.0: you may ship a game that contains it + under any licence; the MPL applies only to that file's source. + - libtonc is MIT: a game that links it should carry its copyright and + permission notice (libtonc/LICENSE) in its credits or documentation. + - Licence texts ship beside the libraries (LICENSE-HUGEDRIVER, + LICENSE-FAMITONE, pvsneslib/LICENSE, sgdk/LICENSE and COPYING.RUNTIME, + maxmod/LICENSE-MAXMOD, libgba/LICENSE, libtonc/LICENSE). + + Upstreams: SGDK https://github.com/Stephane-D/SGDK; PVSnesLib + https://github.com/alekmaul/pvsneslib; libgba + https://github.com/devkitPro/libgba; libtonc + https://github.com/devkitPro/libtonc; maxmod + https://github.com/devkitPro/maxmod; hUGEDriver + https://github.com/SuperDisk/hUGEDriver. + + +Decompilation tools (development instruments; they never touch a built ROM) +----------------------------------------------------------------------------- +JS ports, each in its own package with its own LICENSE and NOTICE. +romdevtools only calls them; their output is the user's work. + + Package Port of (upstream) Licence + ----------------- ---------------------------------------- --------------- + romdev-splat splat 0.37.1 (and 0.34.1 behaviour) MIT + https://github.com/ethteck/splat, + with n64img 0.3.3, pypng's writer, zlib + romdev-spimdisasm spimdisasm 1.42.4, 1.39.3, 1.35.0 MIT, plus + https://github.com/Decompollaborate/ PSF-2.0 for + spimdisasm tables and + algorithms + derived from + CPython + romdev-rabbitizer rabbitizer 1.16.2, 1.14.3, 1.13.0 (C MIT + library built to WASM, JS binding) + https://github.com/Decompollaborate/rabbitizer + romdev-m2c m2c at 1d1c4454 GPL-3.0 + https://github.com/matt-kempster/m2c (kept in its own + package) + romdev-permuter decomp-permuter at 41bd0bfc MIT + https://github.com/simonlindholm/decomp-permuter + romdev-pycparser pycparser 2.23 as vendored by m2c and BSD-3-Clause + decomp-permuter, with PLY 3.10 + https://github.com/eliben/pycparser + + Graphviz (WASM) used only by romdev-m2c for --visualize SVG output, via + the @viz-js/viz npm package (MIT wrapper); Graphviz is + EPL-1.0 and runs as a separate program. + + Also inside romdevtools: the asm-processor, maspsx and + n64-decomp-workbench ports (see "Third-party code inside romdevtools"). + + +Audio tool ports +---------------- + romdev-famitone FamiTone2's text2data (Shiru) public domain + (the port is MIT) + romdev-maxmod devkitPro mmutil (Mukunda Johnson) ISC (the port + is MIT) + romdev-xgm2 SGDK's xgm2tool MIT + + +Recompiled carts (WAT and native backends) +------------------------------------------ + disasm({target:'recompile', emit:'wasmcart'}) turns a ROM into a wasmcart + (backends: src/analysis/recompile/wat// in this package), and + emit:'sync32' turns a Genesis ROM into a sync32 .s32 + (src/analysis/recompile/native/genesis/). A recompiled cart does not run on + an emulator: so that it matches its reference core frame for frame, the + backend builds the core's machine model INTO the cart, from code ported by + hand from the core's source or generated mechanically from it. Every cart + a backend builds contains that code, so the cart is under that code's + licence. + + romdev's own parts of those directories (the CPU instruction lowerers, the + dispatch and layout code, the WAT assembler, the packer) are MIT, and each + backend directory's NOTICE.txt lists which files are ported. In a built + cart the two are combined, so the cart as a whole follows this table. + Commits are short here; the full ones are in every cart's licence entry + (and in versions.json in the source repository). + + NES (wat/nes) + from fceumm: PPU, APU, CPU timing, mappers, frame loop + https://github.com/libretro/libretro-fceumm @ 3a84a6fd + licence GPL-2.0-or-later + means sharing the cart requires offering its complete corresponding + source under the GPL. + + Game Boy / Game Boy Color (wat/gb) + from gambatte: PPU, APU, MBCs, timers, CPU timing; blipper resampler + https://github.com/libretro/gambatte-libretro @ 3262c2aa + licence GPL-2.0-only AND MIT (blipper) + means sharing the cart requires offering its complete corresponding + source under the GPL; the MIT notice travels in the cart. + + GBA (wat/gba) + from mGBA 0.11: ARM7TDMI, bus, scheduler, DMA, timers, video, audio, + GPIO/RTC, its HLE BIOS; musl's sin/cos (Emscripten 4.0.18, + with the FreeBSD msun notice of the files they come from) + https://github.com/libretro/mgba @ 6dce57ee + licence MPL-2.0 AND MIT (musl) + means file-level copyleft: sharing the cart requires making the source + of the MPL-covered files available; the MIT and msun notices + travel in the cart. + + Master System / Game Gear (wat/sms) + from Genesis Plus GX: VDP, I/O, frame order, SN76489 PSG, blip_buf + https://github.com/libretro/genesis-plus-gx @ 162c3439 + licence Genesis Plus GX licence (non-commercial) AND LGPL-2.1-or-later + (blip_buf, Shay Green) + means no commercial distribution: the cart may not be sold or used in + a commercial product or activity; the blip_buf part's source + must be offered. + + Genesis / Mega Drive (wat/genesis, and native/genesis for sync32) + from Genesis Plus GX: VDP, memory map, Z80 bus, YM2612 (from MAME's + fm.c), PSG, blip_buf, frame loop; its Musashi 68000 core 3.32 + and MAME z80.c 3.9 opcode handlers, evaluated into the cart; + SVP carts also get svp.c / ssp16.c (notaz). The sync32 backend + vendors the upstream C files (runtime/gpgx/, see UPSTREAM.txt). + https://github.com/libretro/genesis-plus-gx @ 162c3439 + licence Genesis Plus GX licence AND Musashi licence AND z80.c licence + (all non-commercial) AND LGPL-2.1-or-later (blip_buf); SVP carts + add the SVP code's licence (free for non-commercial use only) + means no commercial distribution; Musashi's notice must stay in every + binary (the cart carries it); the blip_buf part's source must be + offered. + + SNES (wat/snes) + from snes9x: memory map and ROM loading, CPU timing, DMA/HDMA, PPU, + SPC700 (its 64-byte boot ROM is romdev's own, MIT, see "SNES boot + ROM and chip data"), the coprocessors (SA-1, SuperFX from + fxinst.cpp, S-DD1, CX4, SPC7110, DSP-1..4, ST010/011/018 HLE, + OBC1, S-RTC, BS-X, MSU-1; no chip data ROM: a DSP-1, DSP-3 or + ST010 cart is built with the user's, options.firmware), and the + S-DSP from snes_spc (Shay Green) + https://github.com/libretro/snes9x @ 185488cd + SPC7110 carts: spc7110emu/dec (byuu and neviksti, ISC-style) + CX4 carts: musl's sin/cos/atan (MIT) + ST011 / ST018 carts built with options.firmware: ares (ISC, + https://github.com/ares-emulator/ares @ 4cb8d92b, see above) + The SPC700 boot program is romdev's own (see "Firmware and + BIOS"). Coprocessor firmware, including the DSP-1 data ROM, is + supplied by the user and is not part of romdev. + licence snes9x licence (non-commercial) AND LGPL-2.1-or-later (S-DSP), + plus ISC / MIT for those chips + means no commercial distribution; snes9x's licence text must go with + every copy (the cart carries it); the S-DSP part's source must + be offered. + + The cart says this itself. Its romdev.recompile custom section (for a + sync32 .s32, the metadata in rd_meta.c) has a `licence` entry: + spdx the SPDX expression above, e.g. "GPL-2.0-or-later" + terms one plain line per licence + upstream [{name, url, commit, spdx}] of each transplanted component + source the romdevtools version and directory holding the ported + code: that package, at that version, is where the + corresponding source of the emulator code is + licenceTexts where the full licence texts are (romdevtools LICENSES/) + romCode the reminder about the game's own code (below) + notices verbatim, the notices that must travel with every copy + (the non-commercial licences, Musashi, snes9x, and the + MIT / ISC notices); the standard GPL, LGPL and MPL texts + are named by SPDX id and found in LICENSES/ + The entry depends only on the platform, the cart's chips and the romdev + version, so the same inputs still build a byte-identical cart. + + The game inside. A cart recompiled from someone else's game also contains + that game's code (and any BIOS, firmware, MSU-1 data or add-on images built + into it). It can only be shared with the game owner's permission, whatever + the emulator licences allow. + + blip_buf and snes_spc are LGPL-2.1 libraries inside non-commercial cores; + the carts combine them the same way the upstream cores do. If you plan to + distribute recompiled carts, read the licences in LICENSES/. + + +Bundled data (cheat database, used by cheats({op:'lookup'|'apply'|'make'})) +----------------------------------------------------------------------------- + The cheat database ships in the romdev_game_codes package (index/), a + pre-parsed, per-platform index built from the community-aggregated + RetroArch / libretro-database cheat collection (the same data RetroArch, + RetroDECK and Batocera ship). These codes are an aggregation assembled over + years from Game Genie / Pro Action Replay code books and community cheat + dumps; the collection has no single uniform license and individual codes + carry no stated provenance. romdev redistributes a pre-parsed form (game + name to decoded address/value entries) rather than the raw .cht files, and + uses it only as a read/inspect aid and for non-destructive cheat + application. It is not linked into any built game and does not affect the + license of games you make. Source: + https://github.com/libretro/libretro-database (cht/). The index is rebuilt + from a local .cht tree with packages/romdevtools/scripts/build-cheat-index.mjs + in the source repository. + +SNES boot ROM and chip data - romdev's own, or the user's +-------------------------------------------------------- + The SPC700 sound CPU starts from a 64-byte boot ROM (the IPL) that runs the + upload protocol over ports $2140-$2143. Upstream snes9x and bsnes embed + Nintendo's. romdev uses its own instead: a clean-room reimplementation + written from the public description of the protocol and of the state it + hands over (romdevtools scripts/spc700-ipl/ipl.asm, MIT), assembled with + asar. Its port timing was matched by measuring the ports from outside + only, so a program uploads on the same SPC700 cycles as on the console. + The snes9x core, the bsnes core and every recompiled SNES cart run it; the + builds replace the upstream array (scripts/spc700-ipl/install-ipl.mjs). + + romdev ships no chip firmware, chip data ROM or boot ROM. snes9x embeds the + DSP-1 data ROM (and a sine table taken from it), the DSP-3 data ROM and the + ST010's data ROM tables; bsnes embeds the DSP-1 data ROM, the ST010 tables, + the Cx4 data ROM and the Super Game Boy boot ROMs. romdev builds both with + those tables emptied (scripts/recompile-gen/snes9x-chips/hle-data.mjs, + scripts/patches/bsnes/strip-firmware.mjs) and takes the user's files + instead: snes9x reads dsp1b.data.rom, dsp3.data.rom or st010.data.rom from + its system directory, a recompiled cart is built with the same file + (options.firmware), and bsnes reads each chip's firmware (and sgb_boot.bin / + sgb2_boot.bin) from its system directory. Without the file such a cart is + refused with the file and its size named; bsnes runs a Cx4 cart with its + high-level emulation when cx4.data.rom is absent. + + +Where the licence texts and sources are +--------------------------------------- + - romdev's own licence: LICENSE in this package. + - Licences of the emulator code the recompiler carries into carts: + LICENSES/ in this package (copied verbatim from the pinned upstream + sources; LICENSES/README.txt maps each file to its origin). + - SDK library licences: beside each library (see "Game runtime / SDK + libraries"). + - The decompilation ports: LICENSE and NOTICE in each package. + - Emulator-core and compiler licence texts travel with their upstream + source, fetched at build time from the pinned commits. The recipes, + patches and pins are in the source repository, + https://github.com/monteslu/romdev, under packages/romdevtools/scripts/ + (BUILD_MAP.md maps each recipe to the package it builds; versions.json + holds every upstream URL, commit and licence). diff --git a/README.md b/README.md index b878e2b3..b811af0e 100644 --- a/README.md +++ b/README.md @@ -1,155 +1,125 @@ # romdev -**Vibe-code real retro games.** One command, and your coding agent can make actual working ROMs for NES, SNES, Game Boy, Genesis, Atari, Commodore 64, and more - that run on RetroArch, native emulators, flash carts, and real hardware. No SDK installs. No emulator setup. No PATH fiddling. No "this only works on Linux." +romdev is a tool server that lets a coding agent (or you) build, run, debug, reverse-engineer and recompile retro console games. It covers 19 consoles and computers from the Atari 2600 to the Dreamcast, plus PICO-8 and two native WebAssembly game runtimes. Every compiler, emulator core and analysis engine ships as WebAssembly through npm, so there is nothing else to install. ``` npx romdevtools ``` -That's the whole setup. Everything - emulators, assemblers, C compilers, starter libraries, example projects, hardware reference docs - ships as bundled WebAssembly and data via npm. Same on Linux, Windows, and macOS (Node 24+). +That starts the server on `http://127.0.0.1:7331`. It works the same on Linux, Windows and macOS (Node 24 or newer). The output is a standard ROM (`.nes`, `.gb`, `.md`, `.sfc`, `.gba`, ...) that runs in other emulators, on flash carts and on real hardware. -## Features +## What it does -You (or your coding assistant, over [MCP](https://modelcontextprotocol.io/) / plain HTTP) get a tool surface for the full homebrew loop: +romdev exposes 38 tools over MCP and plain HTTP. Each tool is a verb with an operation axis, such as `memory({op:'search'})` or `disasm({target:'cfg'})`. -- **Building** - bundled per-platform toolchains (cc65, SDCC, RGBDS, asar, vasm, SGDK, PVSnesLib, libtonc, ...) compiled to WebAssembly. The agent writes source, compiles it, and gets a real ROM. -- **Asset conversion** - turn external art and audio into native data without leaving the server: PNG → platform tiles/tilemaps (`convertImageToTiles`, `imageToTilemap` - row-major or hardware sprite order), PNG quantize-to-palette, sprite-sheet/Aseprite/GIF loaders, and audio importers (`pcmToBrr` for SNES, `wavToXgm2Pcm` for Genesis XGM2 PCM). Path-in, native-data-out. -- **Running** - load the ROM into an emulated console (libretro cores as WASM) and step through it frame by frame. -- **Seeing** - capture the framebuffer as a PNG and hand it to the agent. -- **Driving** - emit controller input, run input scripts, replay sequences. -- **Inspecting** - read CPU/video/save RAM, watch memory, disassemble, inspect sprites/palettes/tilemaps, read CPU + sound-chip state. -- **Reverse-engineering & romhacking** - a full RE toolkit for modifying existing games: iterative value search (`memory({op:'search'})` → `memory({op:'searchNext'})`, the Cheat-Engine loop), `memory({op:'classify'})` (is this "table" really ASCII?), `breakpoint({on:'write'})` (the exact instruction that wrote a byte), `memory({op:'readCart'})` (confirm a patch is live in the running image), `input({op:'navigate'})` (drive menus by screen-change), `watch({on:'dma'})` (Genesis: which ROM offset a graphic was DMA'd from), a bundled cheat database as a free labeled RAM map, `disasm({target:'accessScan'})` (bound every instruction that can reach a RAM byte, indexed bases included), `disasm({target:'script'})` (decode in-game script interpreters from a declarative grammar), and a cross-platform [ROM-hacking playbook](packages/romdevtools/src/platforms/_guides/ROMHACKING_PLAYBOOK.md) (`platform({op:'doc', platform:'romhacking', name:'playbook'})`). -- **Structural analysis & decompilation** - an open-source RE engine (Rizin + Ghidra, compiled to WebAssembly) covering **all 18 platforms** (incl. the 3D consoles' MIPS R3000/R4300 + SH-4): `disasm({target:'functions'})` (auto-detected function list, ranked real-code-first with a `looksLikeData` flag), `disasm({target:'cfg'})` (control-flow graph), `disasm({target:'xrefs'})` (deep cross-references following the analysis graph), **`disasm({target:'reachable', entries})`** (the CLOSED SET of basic blocks reachable from one or more entry points, following BOTH halves of every call - the callee AND the return site, which is what a recompiler, decompiler or coverage tool actually needs; computed jumps are not followed and the response says so, pointing at the live jumptable resolver below), `symbols({op:'analyze'})` (one-shot structural map), and `disasm({target:'decompile'})` (Ghidra C-like pseudocode, with hardware-register MMIO named and 6502 SLEIGH clutter folded to readable C - quality excellent on GBA/Genesis, good on Game Boy/Z80, rough on the 6502 family; on N64/PS1/Dreamcast the image is analyzed at its TRUE load address so calls and globals resolve, and an N64 splat project's segment map gives overlay-exact mapping with provenance). And the differentiator no static tool has: **live computed-jumptable recovery** - `breakpoint({on:'jumptable'})` runs the emulator to resolve the `JMP (table,X)` / RTS-trick dispatchers (game-state machines, script/battle VMs) that static analysis collapses to `(*_IRQ)()`. Understand *how* a routine works before you touch it; no $3,000 IDA license, no install. -- **Saving/restoring** - named save states for try-this-then-undo workflows. -- **Active Bezels** - an executable companion to a specific ROM (a `.ab` package) that runs once per emulated frame, reads the core's live memory, and renders the complete final scene: a map, a HUD, reconstructed world graphics, around or over the game. `loadMedia({useActiveBezel:true})` picks up the same-basename sidecar (`Game.nes` → `Game.ab`) and makes the composite the presented and captured picture. romdev is where a package gets **verified**, not just played: one can load cleanly, tick without trapping, emit perfectly valid draw commands, and still be completely wrong about the game - so `frame({op:'screenshot', source:'both'})` returns the composite and the raw core framebuffer for the *same* frame, alongside the three geometries (core framebuffer / intended display aspect / bezel scene) that are easy to conflate. Compare those against the guest's own memory reads and you are checking the package's *interpretation*, not merely that it drew something. -- **Matching decompilation (N64 proven)** - `decomp({op})` runs the function-level *generate → compile → compare → refine* loop against a registered [splat](https://github.com/ethteck/splat) project's **own** compiler (IDO 5.3 via ido-static-recomp, or MIPS GCC) and build: `import` (ROM sha1 verified, toolchain fingerprinted, the exact per-file compile command captured from `make`), `plan` (payoff-ordered queue + batches over the call graph), `generate` (m2c with the translation unit's real type context), **`compare`** (the candidate compiled *inside* its TU with the TU's flags; one aggregate verdict from strict instruction+relocation equality, ROM-linked words, the function's own jump tables/literals, and the rest of the TU unchanged - a check that could not run is `unknown`/`error`, never `exact`), `search` (bounded decomp-permuter jobs), `integrate` (reviewable patch; apply + full-ROM byte verify, auto-revert on mismatch), `types` (evidence → proposed structs), `progress` (code bytes per object, asm/C/library kept apart), and the runtime side - `trace` (real PC breaks: arguments at entry, return value at `ra`), `coverage` (instruction-exact via the core's PC bitmap, per function and basic block), `overlays`/`symbolize` (which overlay is resident, by bytes in RAM), `smoke` (base vs rebuilt ROM, decoded pixels + registers). Ghidra's `disasm({target:'decompile'})` stays the *understanding* tool and now loads N64/PS1/Dreamcast segments at their true addresses. Start with `platform({op:'doc', platform:'n64', name:'decomp'})`. -- **Native game runtimes (not just emulation)** - the same run/see/drive/debug loop works on two *native* game formats, not only libretro cores: **wasmcart** (`.wasc` - WASM games compiled from any language; created 2026) and **jsgame** (`.jsgame` - JavaScript canvas/WebGL games; created 2024). `loadMedia({platform:'wasmcart'|'jsgame'})` → `frame({op:'step'|'screenshot'})` → `input` - screenshots, scripted input, and deterministic frame-stepping over the exact same tools. wasmcart carts add a deterministic-replay path (`loadMedia({deterministicSeed})` - same seed + same input = identical frames), a debug-event timeline (`wasm({op:'events'})`), and an absolute pointer (`input({op:'pointer', x, y, left, right})`) for mouse-UI carts a gamepad vocabulary can't drive. Plus V8/WASM introspection an emulator can't give (peek the cart's WASM heap + exports; the JS game's globals). GL carts (wasm imports from the `gl` module) render headless on an **offscreen WebGL2 context** - screenshots and frame hashes show the real GPU draws, no window needed (wasmcart 0.6.0+; older installs fall back to stubbed GL, reported in `status.gl`) - and when a human is playing, `loadMedia({presentWindow:true})` gives the cart its own context so the playtest window presents by GPU blit + swap instead of round-tripping every frame through the CPU (measured `convertMs` 3.52 → 0 on a 1080p 3D cart); captures stay byte-identical to the headless path either way. `pack({target:'wasc'|'jsgame'})` zips a source dir into the distributable archive (the "build" step - romdev doesn't compile the WASM; you bring your own). Emulator-only tools (memory regions, cpuState, disasm) report *not-applicable* for these kinds via a capability descriptor. - -The deliverable is **the ROM**, not the tool: a standard, hardware-valid `.nes`/`.gba`/`.md`/... that runs anywhere ROMs run. The bundled WASM cores are the *dev instrument* (build → observe → iterate), not the distribution runtime. +- **Building.** Per-platform toolchains (cc65, SDCC, RGBDS, asar, gcc and binutils for m68k/ARM/MIPS/SH, SGDK, PVSnesLib, libtonc and more) compiled to WebAssembly. Fork a working example game with `examples({op:'fork'})`, then `build({output:'run'})` builds, loads, runs and screenshots it in one call. Output ROMs get the checksums and headers real hardware needs. +- **Assets.** `encodeArt` turns PNGs into tiles, tilemaps and palettes; `importArt` reads Aseprite/LibreSprite, Tiled, GIF and TexturePacker files; `sprites({op:'capture'})` lifts a multi-sprite character from a running game; `encodeAudio` produces SNES BRR, Genesis XGM2, GBA maxmod soundbanks, NES FamiTone2 data and note tables for the other sound chips. +- **Running and inspecting.** libretro emulator cores as WebAssembly: step frames, take screenshots, drive input, read and write memory, inspect sprites, palettes, tilemaps, CPU and sound-chip state, save and restore states. `frame({op:'verify'})` reports whether a game is rendering without needing to look at the picture. +- **Reverse engineering.** Value search, write/read/execution breakpoints, single-stepping, coverage traces, byte-exact rebuildable disassembly (`disasm({target:'project'})` and `build({output:'reassemble'})`), a bundled cheat database as a labeled RAM map, ROM patching with re-injection of compressed assets, custom-font text tools, and a [romhacking playbook](packages/romdevtools/src/platforms/_guides/ROMHACKING_PLAYBOOK.md). +- **Analysis and decompilation.** Rizin and Ghidra compiled to WebAssembly: function detection, control-flow graphs, cross-references, reachable-block sets and C pseudocode on 18 platforms, including the MIPS and SH-4 3D consoles. `breakpoint({on:'jumptable'})` resolves computed-jump dispatchers by running the game. +- **Static recompilation.** `disasm({target:'recompile', emit:'wasmcart'})` recompiles a whole NES, SNES (including its coprocessor carts), Game Boy, Game Boy Color, GBA, Master System, Game Gear or Genesis ROM into a wasmcart. `frame({op:'verifyRecompile'})` checks the result against the reference emulator core frame by frame (pixels, memory, audio, must-fail controls); `findDiverge`, `fuzzRecompile` and `traceInstructions` locate differences down to the instruction. A Genesis ROM can also be built as a native cart for the sync32 console. +- **Matching decompilation.** `decomp({op})` drives a splat-based N64 or PlayStation decomp project: generate candidate C with m2c, compile it with the project's original compiler, compare per instruction, search with the permuter, and integrate with a full-ROM byte check. Everything runs as JavaScript and WebAssembly in process; no Python, make or host compiler. IDO, SGI's compiler, is proprietary and not distributed; build it once with `packages/romdevtools/scripts/build-ido.sh` from this repository or point `ROMDEV_IDO_DIR` at your own build. KMC gcc 2.7.2, EGCS 1.1.2, PS1 gcc 2.6.3 and mips-linux-gnu gcc 14 ship as WebAssembly. +- **Native runtimes.** wasmcart (`.wasc`, WebAssembly games written in any language, with GL and WebGPU rendering) and jsgame (JavaScript canvas and WebGL games) run through the same load, step, screenshot and input loop, with cart introspection through `wasm({op})`. +- **Active Bezels.** `.ab` companion packages that read a game's memory every frame and draw a composite scene (maps, HUDs). romdev returns the composite and the raw core frame for the same frame so a bezel can be checked against the game. +- **A human in the loop.** `playtest()` opens an SDL window with gamepad support on the running game while the agent keeps working; `host({op:'play'})` shows a session on the `/livestream` page. ``` -your agent <--MCP--> romdev server <-> WASM libretro core <-> your game - | - +-> WASM homebrew toolchain (cc65, SDCC, SGDK, ...) +your agent <--MCP / HTTP--> romdev server <-> WASM libretro core <-> your game + | + +-> WASM toolchains, Rizin/Ghidra, recompiler ``` -## Who is it for? - -- **Homebrew developers** who want a tighter loop than reload-the-emulator-by-hand - build, run, inspect, and patch real ROMs from one tool surface, drive it from your editor's AI, a TUI, the Inspector, or your own scripts. -- **Anyone making a retro game with an AI's help**, no prior homebrew experience needed. Run `npx romdevtools`, point your coding assistant at it, and describe the game you want. -- **Reverse-engineers and romhackers** - disassembly, control-flow graphs, a decompiler, live memory search, and write-breakpoints across all 18 systems, no $3,000 IDA license. - -Every capability is exposed as a tool, so a coding agent can drive the whole loop end-to-end - but the tools are just as usable by hand. The agent is the interface, not a requirement. - -## Supported systems - pick your platform - -Nineteen consoles/computers, oldest → newest - sixteen 2D systems (including the open-hardware GameTank and sync32) plus three 3D consoles (N64, PlayStation, Dreamcast) - plus the **PICO-8** fantasy console and the two **native game runtimes** (wasmcart, jsgame), each its own tier after the 3D consoles. They vary enormously in how hard a game is to make and how hard an existing game is to hack. **Build** = write code → compile → run. **Hack** = modify an existing commercial ROM (find data → patch → reinsert). A system can be easy on one and hard on the other. (Difficulty is rated *as it feels through romdev today* - see the note under the table; it gets easier as the tooling improves.) - -| System | Year | Languages (toolkit) | Build a game | Romhack a game | Best for | -|---|---|---|---|---|---| -| **Atari 2600** | 1977 | 6502 asm (dasm) | 🔴 Hardest | 🟠 Hard | The deep end. "Race the beam": no framebuffer, 128 B RAM, every scanline cycle-counted. Iconic, brutal, deeply rewarding. | -| **Commodore 64** | 1982 | C / 6502 asm (cc65) | 🟢 Easy | - | 40 years of docs, weird but forgiving hardware. A great first 8-bit target. | -| **MSX / MSX2** | 1983 | C / Z80 asm (SDCC) | 🟢 Easy | - | Z80 + the same TMS9918/V9938 VDP family as the Master System. Boots cartridge homebrew on the open C-BIOS (no proprietary ROM). Big international library. | -| **NES / Famicom** | 1983 | C / 6502 asm (cc65) | 🔴 Hard | 🟡 Medium | "Everyone knows the NES" - but the PPU is unforgiving (OAM/NMI timing, CHR-RAM traps, silent black screens). Hacking is friendlier: lots of games store data plainly; the disassembler is mapper-aware. | -| **Sega Master System** | 1985 | C / Z80 asm (SDCC) | 🟢 Easy | 🟡 Medium | Simple Z80 + VDP. Near-identical twin of the Game Gear. | -| **PC Engine / TurboGrafx-16** | 1987 | C / HuC6280 asm (cc65) | 🟡 Medium | - | HuC6280 (65C02 superset) + the HuC6270 VDC. cc65 has no sprite library, so romdev ships a direct-register helper lib; 9-bit GRB color, 64 hardware sprites. HuCards boot with no BIOS. | -| **Atari 7800** | 1986 | C / 6502 asm (cc65) | 🔴 Hard | 🟠 Hard | MARIA display-list graphics (~100 sprites, little flicker) but a unique model with sparse docs. | -| **Sega Genesis / Mega Drive** | 1988 | C (SGDK) / 68000 asm (vasm) | 🟡 Medium | 🟢 Easy | SGDK is a real C engine (high productivity) with a big API + sharp edges. **Easiest system to hack:** flat 16 MB 68000 addressing, no bank-switching, near-ASCII text in many games. | -| **Game Boy** | 1989 | C / SM83 asm (SDCC / RGBDS) | 🟢 Easy | 🟢 Easy | The recommended starting point. Simple hardware, mature C tooling; games often store data uncompressed → easy to hack too. | -| **Atari Lynx** | 1989 | C / 6502 asm (cc65) | 🟡 Medium | - | Color handheld; Suzy/Mikey display-list sprite engine is its own thing + a tiny community = few references. | -| **Game Gear** | 1990 | C / Z80 asm (SDCC) | 🟢 Easy | 🟡 Medium | Same Mode-4 VDP as the Master System; only the visible window differs. | -| **Super Nintendo (SNES)** | 1990 | C (PVSnesLib) / 65816 asm (asar) | 🟡 Medium | 🟡 Medium | PVSnesLib works but is quirky (many "looks right, renders nothing" traps). Big ROMs often skip compression → medium to hack. | -| **Game Boy Color** | 1998 | C / SM83 asm (SDCC / RGBDS) | 🟢 Easy | 🟢 Easy | The Game Boy with a real color palette - same easy tooling, plus CGB color. | -| **Game Boy Advance** | 2001 | C (libtonc / libgba) | 🟡 Medium | - | 32-bit ARM, comfortable C with the well-documented Tonc library - but a big machine (IRQ/DMA/video modes = lots of surface to learn). | -| **GameTank** | 2024 | C / 6502 asm (cc65) | 🟡 Medium | - | Clyde Shaffer's **open-hardware** W65C02S console - a 128×128 framebuffer drawn by a hardware blitter + a second 65C02 audio coprocessor. Full Tier-1 (build/run/cpuState/watchpoints/audioDebug/cart). Open docs + a clean SDK make it a friendly modern 8-bit target; ships ~July 2026. | -| **sync32** | 2026 | C (arm-none-eabi, Cortex-M33) | 🟢 Easy | - | An RP2350 console with a **flat framebuffer and a function-pointer ABI** - no PPU, no tilemap, no banking, no scanline timing. A game is `game_main(api)` drawing into a byte array, so it is the gentlest build target here despite being the newest hardware. Build/run/cpuState/memory/palette are wired; there is no romhack column because there are no commercial ROMs. | - -The three **3D consoles** are a newer, distinct tier - they compile + boot + render on the **real GPU**, but they're at a different maturity than the 2D lineup: no genre scaffolds yet, and their renderable starting points come from open GPU SDKs (libdragon / PSn00bSDK) rather than romdev's own helper libs. Build = bare C that drives the GPU; Hack = code analysis works (disasm/decompile), data-romhack tooling is minimal. - -| System | Year | Languages (toolkit) | Build a game | Romhack a game | Best for | -|---|---|---|---|---|---| -| **Nintendo 64** | 1996 | C (mips-elf-gcc) | 🟠 Hard | - | MIPS R4300 + the RDP/RSP. Renders on glide64 through the GPU; bare C drives a GBI display list (or use libdragon). The 3D end of the pool. | -| **Sony PlayStation** | 1994 | C (mips-elf-gcc) | 🟠 Hard | - | MIPS R3000. Renders on Beetle PSX HW through the GPU; OpenBIOS embedded (no Sony firmware). Bare C writes the GP0/GP1 ports, or link PSn00bSDK. | -| **Sega Dreamcast** | 1998 | C (sh-elf-gcc) | 🟠 Hard | - | SH-4 + PowerVR2. Boots an ELF on Flycast's reios HLE; the bundled `dc.h` brings up a 640×480 framebuffer. No KallistiOS yet (bare-metal C). | - -The **PICO-8** fantasy console is its own tier again - not a hardware machine but a Lua VM ([FAKE-08](https://github.com/jtothebell/fake-08), MIT, no BIOS). It runs `.p8` (Lua source) and `.p8.png` (cart-in-a-PNG) carts at 128×128 with sound, and it's the **friendliest build target on the whole list**: the "code" is plain Lua, so `build({platform:'pico8', source: lua})` just packages a runnable `.p8` (no compiler, no linker, no crt0). Because it's a VM, there's no machine code to disassemble - `disasm({target:'source'})` hands back the cart's Lua directly, and `memory({region:'system_ram'})` reads its 64 KB address space. Thousands of freely-shareable community carts run as-is. +The tools work just as well called by hand or from scripts. -| System | Year | Language (toolkit) | Build a game | "Hack" a cart | Best for | -|---|---|---|---|---|---| -| **PICO-8** | 2015 | Lua (FAKE-08) | 🟢 Easiest | 🟢 Easy | The gentlest on-ramp: Lua carts are plain text, so "build" is packaging and "hack" is editing source. Huge community library. | +## Supported systems -The two **native game runtimes** are the newest tier - not emulated hardware but native game formats driven through the *same* run/see/drive/debug loop (`loadMedia` → `frame` → `input` → `playtest`). Here romdev is the **harness, not the compiler**: you bring your own toolchain, `pack({target:'wasc'|'jsgame'})` packages the distributable, and the deliverable is the exact artifact you debugged. Emulator-only tools (cpuState, disasm, memory regions) report *not-applicable* via a capability descriptor; in their place you get WASM/V8 introspection an emulator can't offer. +**Build** is writing a new game; **Hack** is modifying an existing one. Ratings describe how much friction to expect with romdev's current examples and libraries, not the hardware in the abstract. A dash means there is no romhack tooling beyond code analysis for that system yet. -| System | Year | Language (toolkit) | Build a game | "Hack" a cart | Best for | +| System | Year | Languages (toolkit) | Build | Hack | Notes | |---|---|---|---|---|---| -| **wasmcart** | 2026 | any language that targets WASM - C, C++, Rust, Zig, mruby, ... (`wc_cart.h` ABI) | 🟢 Easy | - | Ship the same `.wasc` you debugged. The harness adds deterministic replay (`loadMedia({deterministicSeed})`), a debug-event timeline (`wasm({op:'events'})`), named debug state, absolute pointer input for mouse-UI carts, conformance verdicts ("won't load, why"), regression goldens - and GL carts render headless on an offscreen WebGL2 context, so screenshots show the real GPU draws. | -| **jsgame** | 2024 | JavaScript (canvas / WebGL2) | 🟢 Easy | - | The web-game developer's on-ramp: run a JS canvas/WebGL game like a cart - screenshots, scripted input, deterministic frame-stepping - plus V8 introspection (read the game's live globals). | - -**Difficulty legend:** 🟢 Easy · 🟡 Medium · 🟠 Hard · 🔴 Hardest. **Build** ratings come from an agent that actually shipped games across the lineup; **Hack** ratings are for text/data edits (a `-` means no romhack data yet - it's CPU-and-game-dependent, and any game using custom compression jumps to Hard regardless of system). - -The **RE analysis engine** (control-flow graphs, cross-references, function detection, and a Ghidra decompiler) works on **all 18 systems** - including the 3D consoles' MIPS R3000/R4300 and SH-4 - regardless of the Hack rating above; the rating reflects how hard the *data* is to edit, not whether the *code* can be analyzed. Decompiler readability tracks the CPU: excellent on the 32-bit ARM (GBA) and 68000 (Genesis), good on the MIPS/SH-4 3D CPUs and Z80, down to rough on the 8-bit 6502 family. (The byte-exact *rebuildable-project* disassembler - `disasm({target:'project'})` - covers the 15 classic platforms, and **`build({output:'reassemble'})` rebuilds any of them into a byte-identical ROM in one call**; the 3D consoles get analysis/decompile, not full reassembly yet.) - -> **These ratings reflect difficulty *with romdev's current tooling* - not an abstract take on the hardware.** The biggest predictor of how hard a platform feels here isn't its raw hardware but the quality of its scaffolds, snippets, and SDK integration. Good tooling moves a platform a whole tier: the Atari 2600 is the hardest hardware on the list, yet a thick, hardware-verified snippet shelf made it *hard-but-shippable*; the same agent that found NES "hard" shipped on the C-and-SDK platforms in a single pass. **These numbers drift toward easier over time** as scaffolds, footgun fixes, and richer runtimes land. Treat the column as "expect roughly this much friction today," not "this system is permanently this hard." - -**If you just want to ship something fast:** Game Boy, Game Boy Color, Master System, Game Gear, or C64. **If you want a challenge / iconic constraint:** NES or Atari 2600. **If you want to modify a classic game:** Genesis or Game Boy (their data is usually uncompressed). The harder systems are very doable but take more iterations - worth choosing deliberately. - -## Each platform ships a real SDK + sound + scaffolds - -Every 2D platform has a working core, ready-made starter projects, and **5 genre scaffolds** - shmup / platformer / puzzle / sports / racing - plus a music demo. That now includes the Atari 2600 (all five, match-3 board and all), the open-hardware GameTank, and sync32. The 3D consoles are the exception: N64 and PlayStation ship the five, Dreamcast ships starter projects only. PC Engine and MSX *also* ship a hardware helper library and sprite/music example projects alongside their genre scaffolds; Genesis adds a `two_plane_parallax` scaffold (hardware scroll, no per-frame tilemap writes). Each platform has a sound API, per-platform `MENTAL_MODEL.md` + `TROUBLESHOOTING.md` docs (readable in-session via `platform({op:'doc'})`), and debug helpers. Scaffold a project in one call with `scaffold({op:'project'})` (or `scaffold({op:'game'})` for the genre-shaped baselines). Every scaffold builds with zero warnings and renders visible content (checked via `frame({op:'verify'})`). - -| Platform | Core | Compiler / SDK | Sound | Music engine | -|---|---|---|---|---| -| NES | fceumm | cc65 | `sound_play_tone/noise` (APU) | FamiTone2 | -| Game Boy | gambatte | SDCC (sm83) / RGBDS | `sound_play_tone/noise` (DMG APU) | hUGEDriver | -| Game Boy Color | gambatte (CGB) | SDCC / RGBDS | APU + CGB color | hUGEDriver | -| SNES | snes9x | PVSnesLib (C) / asar (asm) | `sfx_play` (SPC700 + BRR) | SPC700 engine | -| Genesis | genesis_plus_gx | SGDK (m68k-gcc) / vasm (asm) | `sfx_*` PSG | XGM2 via SGDK | -| SMS | genesis_plus_gx | SDCC (z80) | `sfx_*` SN76489 PSG | 3-voice PSG tracker | -| Game Gear | genesis_plus_gx | SDCC (z80) | `sfx_*` (same PSG) | PSG tracker | -| C64 | vice_x64 | cc65 | `sfx_*` SID (ADSR) | 3-voice SID sequencer | -| GBA | mGBA | libtonc / libgba (arm-gcc) | `sfx_*` libtonc | maxmod | -| Atari Lynx | handy | cc65 | `sfx_*` MIKEY 4-voice | cc65 lynx audio | -| Atari 2600 | stella2014 | dasm (asm) | (asm) | 2-voice 6507 chiptune | -| Atari 7800 | prosystem | cc65 | `sfx_*` TIA | 2-voice TIA tracker | -| PC Engine | geargrafx | cc65 | `psg_tone` (HuC6280 PSG, 6 ch) | hand-authored PSG | -| MSX / MSX2 | blueMSX | SDCC (z80) | `msx_psg_tone` (AY-3-8910) | hand-authored PSG | -| Nintendo 64 | parallel_n64 (glide64, **GPU**) | mips-gcc (C) | AI / RSP | - | -| PlayStation | beetle_psx_hw (**GPU**) | mips-gcc (C; PSn00bSDK) | SPU | - | -| Dreamcast | flycast (**GPU**) | sh-gcc (C) | AICA | - | -| wasmcart | CartHost (native WASM host - no emulator; GL carts on an offscreen WebGL2 context) | bring-your-own WASM toolchain (`wc_cart.h`) | 48 kHz PCM ring (`wc_audio` / `wc_pcm_mixer`) | - | -| jsgame | rungame (native V8 host - no emulator) | JavaScript (canvas / WebGL2) | game's own WebAudio graph (not captured in-harness yet) | - | - -(The two native-runtime rows are the harness tier: no scaffolds and no bundled compiler - `pack({target:'wasc'|'jsgame'})` packages a source dir you built with your own toolchain.) - -The `platformer` scaffold side-scrolls (hardware camera + per-platform column streaming) on every platform except NES and the Atari 2600 - both single-screen, since neither has hardware background scroll. - -The three 3D consoles (N64 / PlayStation / Dreamcast) render on the **real GPU** through [`native-gles`](https://github.com/monteslu/native-gles) - headless OpenGL/EGL, no browser, no software rasterizer - one engine across all three. PlayStation embeds [OpenBIOS](https://github.com/grumpycoders/pcsx-redux) (MIT, region-free), so no proprietary firmware ships. These don't ship genre scaffolds yet; their renderable starting points come from the open GPU SDKs - [libdragon](https://github.com/DragonMinded/libdragon) (Unlicense) for N64, [PSn00bSDK](https://github.com/Lameguy64/PSn00bSDK) (MPL) for PlayStation - which emit the real GPU geometry the GL cores render. (The 2D consoles' software libs render to a CPU framebuffer the GL cores don't scan out.) - -## How it's packaged - -`romdev` is a small **monorepo** of npm packages. The thing you install is `romdevtools`; it hard-depends on a set of `romdev-*` binary packages that carry the WebAssembly: - -- **[`romdevtools`](./packages/romdevtools)** - the tool server (HTTP routes + Agent Skill + MCP), all generic tools, scaffolds, runtime/library source, debug helpers, and the `romdevtools` / `romdev-mcp` (alias) / `romdevtools-cli` binaries. The fast-churning layer; ships **zero wasm**. -- **`romdev-core-*`** (12) - shared emulator cores: `fceumm`, `gambatte`, `gpgx`, `vice`, `handy`, `prosystem`, `geargrafx` (PC Engine), `bluemsx` (MSX), `gametank` (GameTank), and the GPU cores `parallel-n64` (N64), `beetle-psx-hw` (PlayStation), `flycast` (Dreamcast). -- **[`romdev-core-host`](./packages/romdev-core-host)** + **[`romdev-core-runner`](./packages/romdev-core-runner)** (2) - the ISOMORPHIC libretro host runtime (paths under Node, factory + bytes in a browser/worker, one implementation) and the SDL "play it in a window" tier on top of it, published standalone so SDKs, web IDEs, and tools can run cores without the server. The server consumes the same host. -- **`romdev-platform-*`** (3) - self-contained platform bundles where the core + compiler are used by no one else: `snes`, `gba`, `atari2600`. -- **`romdev-toolchain-*`** (7) - shared compilers: `cc65`, `sdcc`, `m68k-gcc`, `vasm`, `rgbds`, `mips-gcc` (N64/PS1 C), `sh-gcc` (Dreamcast C). -- **`romdev-analysis*`** (2) - the RE engine: `romdev-analysis` (Rizin → WASM) + `romdev-analysis-decompiler` (Ghidra decompiler + SLEIGH specs → WASM). -- **`romdev_game_codes`** (1) - the bundled game-code / cheat database (~30 MB of pre-parsed cheats for thousands of known ROMs across 13 platforms). Split out so the main package stays small and the DB grows on its own cadence; lazy-loaded one platform at a time. - -`romdevtools` resolves each core/compiler from its package lazily - a toolchain's WASM is only loaded into memory the first time you build for that platform, so booting the server is fast and a session only pays for the platforms it actually uses. WASM is a **build output**: it ships via the npm packages, not committed to this git repo (which holds the source, recipes, and version pins). See [packages/romdevtools/BUILDING.md](./packages/romdevtools/BUILDING.md) for the platform × core × toolchain matrix and how the wasm is built (a pinned Emscripten container). +| Atari 2600 | 1977 | 6502 asm (dasm) | Hardest | Hard | No framebuffer, 128 bytes of RAM, every scanline cycle-counted. | +| Commodore 64 | 1982 | C / 6502 asm (cc65) | Easy | - | Forgiving hardware and decades of documentation. Boots on the MEGA65 Open ROMs. | +| MSX / MSX2 | 1983 | C / Z80 asm (SDCC) | Easy | - | Z80 with the TMS9918/V9938 VDP family. Runs on the open C-BIOS. | +| NES / Famicom | 1983 | C / 6502 asm (cc65) | Hard | Medium | The PPU is unforgiving (OAM/NMI timing, CHR-RAM). Many games store data plainly; the disassembler is mapper-aware. | +| Master System | 1985 | C / Z80 asm (SDCC) | Easy | Medium | Simple Z80 and VDP; near twin of the Game Gear. | +| Atari 7800 | 1986 | C / 6502 asm (cc65) | Hard | Hard | MARIA display-list graphics with sparse documentation. | +| PC Engine / TurboGrafx-16 | 1987 | C / HuC6280 asm (cc65) | Medium | - | romdev ships a direct-register helper library; HuCards need no BIOS. | +| Genesis / Mega Drive | 1988 | C (SGDK) / 68000 asm (Motorola syntax, GNU as) | Medium | Easy | Flat 68000 addressing and no bank switching make it the easiest to hack. | +| Game Boy | 1989 | C / SM83 asm (SDCC, RGBDS) | Easy | Easy | The recommended starting point. | +| Atari Lynx | 1989 | C / 6502 asm (cc65) | Medium | - | Suzy/Mikey sprite engine with few references. | +| Game Gear | 1990 | C / Z80 asm (SDCC) | Easy | Medium | Master System VDP with a smaller window and 12-bit colour. | +| Super Nintendo | 1990 | C (PVSnesLib) / 65816 asm (asar) | Medium | Medium | PVSnesLib has "renders nothing" traps; the mental model lists them. | +| Game Boy Color | 1998 | C / SM83 asm (SDCC, RGBDS) | Easy | Easy | The Game Boy toolchain plus CGB colour. | +| Game Boy Advance | 2001 | C (libtonc, libgba) | Medium | - | 32-bit ARM with a large hardware surface. | +| GameTank | 2024 | C / 6502 asm (cc65) | Medium | - | An open-hardware W65C02S console: a 128x128 framebuffer drawn by a blitter, and a second 65C02 for audio. | +| sync32 | 2026 | C (arm-none-eabi, Cortex-M33) | Easy | - | An open RP2350-based console: a flat framebuffer and a function-pointer ABI, no PPU, tilemap or banking. | +| Nintendo 64 | 1996 | C (mips-elf-gcc, libdragon) | Hard | - | Rendered on the GPU through parallel-n64's glide64. | +| PlayStation | 1994 | C (mips-elf-gcc, PSn00bSDK) | Hard | - | Rendered on the GPU through Beetle PSX HW; boots OpenBIOS, no Sony firmware. | +| Dreamcast | 1998 | C (sh-elf-gcc) | Hard | - | Rendered on the GPU through Flycast with its reios HLE BIOS; bare-metal C. | +| PICO-8 | 2015 | Lua (FAKE-08) | Easiest | Easy | Carts are Lua source, so building is packaging and hacking is editing. | +| wasmcart | 2026 | Any language that targets WebAssembly | Easy | - | You bring the compiler; romdev runs, inspects and packs the cart. Carts need wasmcart ABI v4. | +| jsgame | 2024 | JavaScript (canvas, WebGL2) | Easy | - | JavaScript games run like carts, with V8 introspection. | + +The Rizin/Ghidra analysis engine works on all 19 systems except sync32, whatever the Hack rating; the rating is about editing data, not analysing code. Decompiler output is most readable on ARM (GBA) and 68000 (Genesis), good on Z80 and the MIPS/SH-4 consoles, and rough on the 6502 family. Byte-exact rebuildable disassembly covers the 15 classic 2D systems. + +To ship something quickly, start with Game Boy, Game Boy Color, Master System, Game Gear, C64 or PICO-8. To modify an existing game, Genesis and Game Boy are the gentlest. + +## Examples, sound and docs per platform + +Every classic platform ships starter projects, a sound API, a music demo on that platform's usual engine, and five genre examples (shmup, platformer, puzzle, sports, racing); the Atari 2600 has four (no puzzle). GameTank, sync32, PICO-8, N64, PlayStation and Dreamcast ship genre examples too. Fork one with `examples({op:'fork', example:'nes/platformer', name, path})`. The platformer side-scrolls with a hardware camera on every platform except NES and the Atari 2600. Each platform has a mental model and troubleshooting guide readable in session with `platform({op:'doc', platform, name})`. + +| Platform | Core | Compiler / SDK | Music engine | +|---|---|---|---| +| NES | fceumm | cc65 | FamiTone2 | +| Game Boy / Color | gambatte | SDCC, RGBDS | hUGEDriver | +| SNES | snes9x (bsnes as an alternate) | PVSnesLib, asar | SPC700 driver | +| Genesis | genesis_plus_gx | SGDK (m68k gcc), 68000 asm (m68k GNU as) | XGM2 | +| Master System / Game Gear | genesis_plus_gx | SDCC | PSG tracker | +| C64 | VICE x64 | cc65 | SID sequencer | +| GBA | mGBA | libtonc, libgba (arm gcc) | maxmod | +| Atari Lynx | handy | cc65 | Lynx audio | +| Atari 2600 | stella2014 | dasm | 2-voice TIA | +| Atari 7800 | prosystem | cc65 | 2-voice TIA tracker | +| PC Engine | geargrafx | cc65 | HuC6280 PSG | +| MSX / MSX2 | blueMSX | SDCC | AY-3-8910 PSG | +| GameTank | GameTank core | cc65 | ACP audio coprocessor | +| sync32 | s32core | arm-none-eabi gcc | game-side software synth | +| Nintendo 64 | parallel-n64 (glide64, GPU) | mips gcc | - | +| PlayStation | Beetle PSX HW (GPU) | mips gcc, PSn00bSDK | - | +| Dreamcast | Flycast (GPU) | sh gcc | - | +| PICO-8 | FAKE-08 | Lua | built in | +| wasmcart | wasmcart host (no emulator) | your own | 48 kHz PCM ring | +| jsgame | rungame (no emulator) | your own | WebAudio | + +The 3D consoles render on the GPU through [native-gles](https://github.com/monteslu/native-gles) (headless OpenGL ES, no browser). + +## Packages + +The package you install is `romdevtools`. It depends on `romdev-*` packages that carry the WebAssembly binaries, so each one can be versioned and reused separately. A platform's binaries load the first time you use that platform. + +| Package group | Packages | +|---|---| +| Server | [`romdevtools`](./packages/romdevtools): the tool server (MCP, HTTP, Agent Skill), examples, libraries, docs. Bins: `romdevtools`, `romdevtools-cli`, `romdev-mcp` (alias). | +| Emulator cores (15) | `romdev-core-fceumm`, `-gambatte`, `-gpgx`, `-vice`, `-handy`, `-prosystem`, `-geargrafx`, `-bluemsx`, `-gametank`, `-bsnes`, `-fake08`, `-s32core`, `-parallel-n64`, `-beetle-psx-hw`, `-flycast` | +| Core runtime (2) | [`romdev-core-host`](./packages/romdev-core-host) (the libretro host, usable without the server) and [`romdev-core-runner`](./packages/romdev-core-runner) (an SDL window over it) | +| Platform bundles (4) | `romdev-platform-snes`, `-gba`, `-atari2600`, `-sync32`: a core and compiler used by no other platform | +| Toolchains (7) | `romdev-toolchain-cc65`, `-sdcc`, `-rgbds`, `-m68k-gcc`, `-mips-gcc` (also armips and mips-linux-gnu binutils), `-sh-gcc`, `-decomp-gcc` (KMC, EGCS and PS1 gcc for decomp projects) | +| Analysis (2) | `romdev-analysis` (Rizin), `romdev-analysis-decompiler` (Ghidra decompiler and SLEIGH specs) | +| Decomp tools (6) | `romdev-splat`, `romdev-spimdisasm`, `romdev-rabbitizer`, `romdev-m2c`, `romdev-permuter`, `romdev-pycparser`: JavaScript and WebAssembly ports of the community decomp tools | +| Audio (4) | `romdev-famitone`, `romdev-maxmod`, `romdev-xgm2`, `romdev-audio-resampler` | +| Data (1) | `romdev_game_codes`: the cheat database used as a labeled RAM and code map, loaded one platform at a time | + +`romdev-toolchain-ido` is private and never published; see "Matching decompilation" above. + +The WebAssembly binaries are build outputs shipped through npm; this repository holds the sources, build scripts, patches and version pins. [packages/romdevtools/scripts/BUILD_MAP.md](./packages/romdevtools/scripts/BUILD_MAP.md) maps each binary to the script that builds it. ## Connect -Boot the server (it stays in the foreground - `Ctrl-C` to stop): - ```bash -npx romdevtools # tool server on http://127.0.0.1:7331/mcp +npx romdevtools # MCP on http://127.0.0.1:7331/mcp ``` -The first run downloads the cores/toolchains; later runs start instantly from the npm cache. An **optional observer** for watching tool calls live is at `http://127.0.0.1:7331/livestream` - purely for humans, no agent needs it. - -Then register `http://127.0.0.1:7331/mcp` (streamable-HTTP transport) with your agent: +The first run downloads the packages; later runs start from the npm cache. `PORT` and `HOST` change the bind address. `http://127.0.0.1:7331/livestream` shows tool calls and running sessions live for a human watching. ### Claude Code @@ -159,8 +129,6 @@ claude mcp add --transport http romdev http://127.0.0.1:7331/mcp ### opencode -Add it to `opencode.json` (the `type` must be `"remote"` for an HTTP server): - ```json { "$schema": "https://opencode.ai/config.json", @@ -176,52 +144,52 @@ Add it to `opencode.json` (the `type` must be `"remote"` for an HTTP server): ### Codex CLI -Either run `codex mcp add romdev --url http://127.0.0.1:7331/mcp`, or add the table to `~/.codex/config.toml`: +```bash +codex mcp add romdev --url http://127.0.0.1:7331/mcp +``` + +or in `~/.codex/config.toml`: ```toml [mcp_servers.romdev] url = "http://127.0.0.1:7331/mcp" ``` -In a Codex session, `/mcp` lists the connected servers and their tools. - -### Any other MCP client +### Other MCP clients and plain HTTP -It's a standard **streamable-HTTP** MCP server - point any MCP-capable client at `http://127.0.0.1:7331/mcp`. Set `PORT` / `HOST` env vars to change the bind address. +Any streamable-HTTP MCP client can use `http://127.0.0.1:7331/mcp`. Both the session-based protocol (an `initialize` handshake and `Mcp-Session-Id`) and the stateless 2026-07-28 revision are served on that endpoint; on the stateless revision, pass one stable `session` argument on every call so your calls reach the same emulator. -**Both protocol eras are served on that one endpoint.** Legacy clients (the `initialize` handshake plus `Mcp-Session-Id`) work exactly as before. Clients speaking the stateless **2026-07-28** revision - no handshake, no session id, protocol version and capabilities in each request's `_meta` - are served natively, and `server/discover` advertises what the server supports. That revision has no protocol session to carry your identity, so the server ties your calls to *your* emulator three ways, in this order: a `_meta["dev.romdev/sessionHandle"]` handle; the optional **`session` argument every tool accepts** (the form an agent can produce from inside a tool call - pass one stable slug on every call); or, when a call names nothing, **your keep-alive connection** - the server keys the session to it and each result ends with a `session: ` line you can pass back. Claude Code 2.1.x names nothing, so it gets the connection default and the reminder line. Over plain HTTP the same job is done by the `x-romdev-session` header (send it on every call, and reuse ONE `Mcp-Session-Id` - re-initializing per call is a fresh session even with the header set). +Without MCP, every tool is an HTTP route: `POST /tool/{name}` with a JSON body and an `x-romdev-session` header. `GET /openapi.json` describes them, `GET /documentation` is a browsable console, and `GET /skills/romdev/SKILL.md` is an Agent Skill generated from the running server. ---- - -Then just describe what you want: +Then describe what you want: ``` > Make me a tiny NES game where a sprite moves around the screen. -[agent: scaffold({op:"game", platform:"nes", genre:"platformer"})] -[agent: build({output:"run", platform:"nes", path}) → builds, loads, runs, screenshots in one call] -[agent sees the result, iterates] +[agent: examples({op:"fork", example:"nes/platformer", name:"mygame", path:"/path/to/mygame"})] +[agent: build({output:"run", platform:"nes", path:"/path/to/mygame"}) -> builds, loads, runs, screenshots] +[agent looks at the result and iterates] ``` -`romdev` also doubles as a plain emulator: `romdev-cli play game.gba` opens an SDL window with hot-plug controllers and live fps in the title bar. +`romdevtools-cli play game.gba` also works as a plain emulator: an SDL window with hot-plugged controllers and live fps in the title bar. ## Development -This is an npm-workspaces monorepo (Node 24+): +An npm-workspaces monorepo (Node 24 or newer): ```bash -git clone git@github.com:monteslu/romdev.git +git clone https://github.com/monteslu/romdev.git cd romdev npm install -npm test # runs each package's tests +npm test ``` -The bundled WASM is built from pinned upstream source in a reproducible Emscripten container - see [packages/romdevtools/BUILDING.md](./packages/romdevtools/BUILDING.md). You only need to rebuild it when bumping an upstream version or adding a platform; day-to-day work uses the already-built wasm in the binary packages. - -Development workflow notes: [measured decompilation, bounded search and SMS IR](./packages/romdevtools/docs/decomp-throughput.md). These extend existing tools; the notes distinguish implemented behavior, verification limits and deployment requirements. +The WebAssembly binaries are built from pinned upstream sources in a reproducible Emscripten container; see [BUILD_MAP.md](./packages/romdevtools/scripts/BUILD_MAP.md). You only rebuild them when bumping an upstream or adding a platform. [docs/decomp-throughput.md](./packages/romdevtools/docs/decomp-throughput.md) describes the measured decompilation workflow, bounded permuter search and Z80 IR export. ## License -romdev's code is **MIT**, and **the games you build are yours - including to -sell.** Full details + the third-party component inventory: [LICENSE](./LICENSE) -and [NOTICE](./NOTICE). +romdev's own code is MIT ([LICENSE](./LICENSE)). The third-party components it bundles keep their own licences, listed in [NOTICE](./NOTICE). + +Games you build with romdev are yours, including to sell; the bundled runtime libraries they link are permissively licensed (see NOTICE). + +Recompiled carts are different: a cart made by the static recompiler contains code ported from the reference emulator (GPL, MPL or non-commercial terms depending on the platform) as well as the original game's code. Each recompiled cart carries a `licence` entry naming those components, and NOTICE explains the terms. diff --git a/browser-payloads.json b/browser-payloads.json index 010a9860..b29ab177 100644 --- a/browser-payloads.json +++ b/browser-payloads.json @@ -1,4 +1,4 @@ { - "release": "browser-payloads-4be2b1a7777a", - "sha256": "6a05620de4728392867eea07e87c2f6677cb0789197645c7b3559f9b0353c95d" + "release": "browser-payloads-6f59c4b0d7a7", + "sha256": "2ef2943b9891c0ca98e592dbfd5b6c5ba7ade5544268821b0b3d722ab4e540d7" } diff --git a/build-image/Dockerfile b/build-image/Dockerfile index 95ab964c..3587ed02 100644 --- a/build-image/Dockerfile +++ b/build-image/Dockerfile @@ -7,7 +7,7 @@ # bit-reproducible across emcc versions, so a bump is a real change. # # Covers the "light" builds: all emulator cores + the cc65/sdcc/asar/dasm/ -# vasm/rgbds toolchains (emcc + a Makefile/cmake). The heavy gcc-family +# rgbds toolchains (emcc + a Makefile/cmake). The heavy gcc-family # cross-toolchains (arm-gcc for GBA, m68k-gcc for Genesis-C) need a native # cross-gcc bootstrap and are NOT covered here yet - follow-up image. FROM emscripten/emsdk:4.0.18 diff --git a/package-lock.json b/package-lock.json index 8d23d3b2..99ecc10e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -717,6 +717,18 @@ "@types/node": "*" } }, + "node_modules/@viz-js/viz": { + "version": "3.31.0", + "resolved": "https://registry.npmjs.org/@viz-js/viz/-/viz-3.31.0.tgz", + "integrity": "sha512-r7zlQdRvcwvIpjHGgs+KNWHeE/P5/Dq7k8ZAKaMCbZqomxCBJV78gVuQYaHzFVca+kB0mX0fMW9UFevCOBG50A==", + "license": "MIT" + }, + "node_modules/@webgpu/types": { + "version": "0.1.72", + "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.72.tgz", + "integrity": "sha512-0cF7RFM2edNoiIS1ODJp0/Gzv4/xSXhwoR0YCza+OWpJWtn4wmo9DvK91aLlH9+uUnwIriP7ZiC3WitmyhuzBw==", + "license": "BSD-3-Clause" + }, "node_modules/accepts": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", @@ -2192,6 +2204,21 @@ "node": ">= 0.8.0" } }, + "node_modules/libsodium": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/libsodium/-/libsodium-0.8.4.tgz", + "integrity": "sha512-lMcYaRi0zcs7tarATsQUYC7rstliIXZuoq0c6zXSgNtSNtdvBgkSegjWhpMJAXzKX3SUSwIp7+zEsob+j3LuRw==", + "license": "ISC" + }, + "node_modules/libsodium-wrappers": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/libsodium-wrappers/-/libsodium-wrappers-0.8.4.tgz", + "integrity": "sha512-mu8aAWucZjTB5O/BtGXtW4e1agy7uHxNYG7zPthmmD1jU43LCDmSWZLN4JhflbdPXj3yDO4lxM1O9hLDgIOXDw==", + "license": "ISC", + "dependencies": { + "libsodium": "^0.8.0" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -2355,6 +2382,23 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/native-dawn": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/native-dawn/-/native-dawn-0.1.6.tgz", + "integrity": "sha512-1Yl+j3A2e4Zx8brtsIumv2hoaIfeRKsxGH4EuLoGWeVHSi1JACY7SlhSdePgTc3S9eQh+kya0BiG6BHIi5RsiQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@webgpu/types": "0.1.72", + "tar": "7.5.22" + }, + "bin": { + "native-dawn": "bin/native-dawn.js" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/native-gles": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/native-gles/-/native-gles-0.6.1.tgz", @@ -2743,6 +2787,10 @@ "resolved": "packages/romdev-core-bluemsx", "link": true }, + "node_modules/romdev-core-bsnes": { + "resolved": "packages/romdev-core-bsnes", + "link": true + }, "node_modules/romdev-core-fake08": { "resolved": "packages/romdev-core-fake08", "link": true @@ -2803,10 +2851,18 @@ "resolved": "packages/romdev-famitone", "link": true }, + "node_modules/romdev-m2c": { + "resolved": "packages/romdev-m2c", + "link": true + }, "node_modules/romdev-maxmod": { "resolved": "packages/romdev-maxmod", "link": true }, + "node_modules/romdev-permuter": { + "resolved": "packages/romdev-permuter", + "link": true + }, "node_modules/romdev-platform-atari2600": { "resolved": "packages/romdev-platform-atari2600", "link": true @@ -2823,10 +2879,34 @@ "resolved": "packages/romdev-platform-sync32", "link": true }, + "node_modules/romdev-pycparser": { + "resolved": "packages/romdev-pycparser", + "link": true + }, + "node_modules/romdev-rabbitizer": { + "resolved": "packages/romdev-rabbitizer", + "link": true + }, + "node_modules/romdev-spimdisasm": { + "resolved": "packages/romdev-spimdisasm", + "link": true + }, + "node_modules/romdev-splat": { + "resolved": "packages/romdev-splat", + "link": true + }, "node_modules/romdev-toolchain-cc65": { "resolved": "packages/romdev-toolchain-cc65", "link": true }, + "node_modules/romdev-toolchain-decomp-gcc": { + "resolved": "packages/romdev-toolchain-decomp-gcc", + "link": true + }, + "node_modules/romdev-toolchain-ido": { + "resolved": "packages/romdev-toolchain-ido", + "link": true + }, "node_modules/romdev-toolchain-m68k-gcc": { "resolved": "packages/romdev-toolchain-m68k-gcc", "link": true @@ -2847,10 +2927,6 @@ "resolved": "packages/romdev-toolchain-sh-gcc", "link": true }, - "node_modules/romdev-toolchain-vasm": { - "resolved": "packages/romdev-toolchain-vasm", - "link": true - }, "node_modules/romdev-xgm2": { "resolved": "packages/romdev-xgm2", "link": true @@ -3520,6 +3596,7 @@ "resolved": "https://registry.npmjs.org/wasmcart/-/wasmcart-0.24.0.tgz", "integrity": "sha512-dP5slbuNb8Du/VA66Ky3uvEbGlRRRdzgyMhMyngnVV5fX2FXC115s20Qpn9HkOmYdnY3j2/nu99qh+XzbGaNBw==", "license": "MIT", + "optional": true, "dependencies": { "@kmamal/sdl": "^0.11.13", "fflate": "^0.8.3", @@ -3560,12 +3637,43 @@ } }, "node_modules/webgl-node": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/webgl-node/-/webgl-node-1.5.1.tgz", - "integrity": "sha512-YzLpTxTvTA0vhHeEtDj6vnOdoft7uQdupBxXqHPp2YWqi9EBk/7lcUqyQi6cTM4PygtZf1Omc9tF4ON24Lr55A==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/webgl-node/-/webgl-node-1.6.1.tgz", + "integrity": "sha512-o5XP8Jb2sobB1zMpohVe0IKUt158oH0VMfPcf2D2o4NWMW6Ieq9Vixxmrb2Hnbc4t2eMl6mQnFPCZ/5k5wiMIA==", "license": "MIT", "dependencies": { - "native-gles": "^0.6.0" + "native-gles": "^0.7.1" + } + }, + "node_modules/webgl-node/node_modules/native-gles": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/native-gles/-/native-gles-0.7.1.tgz", + "integrity": "sha512-2tYkK/pj5uT8gFWCqCwUSGI4cIBaQ/IIgyOoq7Pn4p1nokhViuXEYORpfBn16Jd2sdzG1yR05mTjFysyC6Y+1w==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "tar": "^7.4.3" + } + }, + "node_modules/webgpu-node": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/webgpu-node/-/webgpu-node-0.2.0.tgz", + "integrity": "sha512-Y1hzzf7kqOWclZSlRpdSQ7VuXufgOm9YJmP9Nja/LZ6SwfsEw5digUljw08Ky9hatPPuH8C7ZPTLxSL40e/gzw==", + "license": "MIT", + "dependencies": { + "@webgpu/types": "0.1.72", + "native-dawn": "^0.1.0" + }, + "engines": { + "node": ">=22" + }, + "peerDependencies": { + "@kmamal/sdl": "^0.11.13" + }, + "peerDependenciesMeta": { + "@kmamal/sdl": { + "optional": true + } } }, "node_modules/which": { @@ -3737,21 +3845,21 @@ } }, "packages/romdev_game_codes": { - "version": "0.1.1", + "version": "0.1.2", "license": "MIT", "engines": { "node": ">=24" } }, "packages/romdev-analysis": { - "version": "0.2.1", + "version": "0.2.2", "license": "LGPL-3.0-only", "engines": { "node": ">=24" } }, "packages/romdev-analysis-decompiler": { - "version": "0.2.1", + "version": "0.2.2", "license": "Apache-2.0", "engines": { "node": ">=24" @@ -3765,19 +3873,26 @@ } }, "packages/romdev-core-beetle-psx-hw": { - "version": "0.3.1", + "version": "0.3.2", "license": "GPL-2.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-core-bluemsx": { - "version": "0.9.1", + "version": "0.9.2", "license": "BSD-3-Clause", "engines": { "node": ">=24" } }, + "packages/romdev-core-bsnes": { + "version": "0.1.0", + "license": "GPL-3.0-only", + "engines": { + "node": ">=24" + } + }, "packages/romdev-core-fake08": { "version": "0.1.1", "license": "MIT", @@ -3786,56 +3901,56 @@ } }, "packages/romdev-core-fceumm": { - "version": "0.15.0", + "version": "0.13.2", "license": "GPL-2.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-core-flycast": { - "version": "0.4.1", + "version": "0.4.2", "license": "GPL-2.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-core-gambatte": { - "version": "0.14.0", + "version": "0.12.2", "license": "GPL-2.0-only", "engines": { "node": ">=24" } }, "packages/romdev-core-gametank": { - "version": "0.5.1", + "version": "0.5.2", "license": "MIT", "engines": { "node": ">=24" } }, "packages/romdev-core-geargrafx": { - "version": "0.10.1", + "version": "0.10.2", "license": "GPL-3.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-core-gpgx": { - "version": "0.15.1", + "version": "0.15.2", "license": "SEE LICENSE IN README.md", "engines": { "node": ">=24" } }, "packages/romdev-core-handy": { - "version": "0.9.1", + "version": "0.9.2", "license": "Zlib", "engines": { "node": ">=24" } }, "packages/romdev-core-host": { - "version": "0.16.0", + "version": "0.14.1", "license": "MIT", "dependencies": { "@monteslu/chafa-wasm": "^0.4.0", @@ -3848,24 +3963,24 @@ } }, "packages/romdev-core-parallel-n64": { - "version": "0.3.1", + "version": "0.3.2", "license": "GPL-2.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-core-prosystem": { - "version": "0.10.1", + "version": "0.10.2", "license": "GPL-2.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-core-runner": { - "version": "0.2.18", + "version": "0.2.19", "license": "MIT", "dependencies": { - "romdev-core-host": "0.16.0" + "romdev-core-host": "0.14.1" }, "engines": { "node": ">=24" @@ -3875,14 +3990,14 @@ } }, "packages/romdev-core-s32core": { - "version": "0.2.1", + "version": "0.2.2", "license": "MIT", "engines": { "node": ">=24" } }, "packages/romdev-core-vice": { - "version": "0.12.0", + "version": "0.12.1", "license": "GPL-2.0-or-later", "engines": { "node": ">=24" @@ -3895,6 +4010,20 @@ "node": ">=24" } }, + "packages/romdev-m2c": { + "version": "0.1.0", + "license": "GPL-3.0-only", + "dependencies": { + "@viz-js/viz": "3.31.0", + "romdev-pycparser": "0.1.0" + }, + "bin": { + "romdev-m2c": "src/cli.js" + }, + "engines": { + "node": ">=24" + } + }, "packages/romdev-maxmod": { "version": "0.2.1", "license": "MIT", @@ -3902,57 +4031,128 @@ "node": ">=24" } }, + "packages/romdev-permuter": { + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "libsodium-wrappers": "0.8.4", + "romdev-pycparser": "0.1.0", + "romdev-toolchain-mips-gcc": "0.1.3" + }, + "bin": { + "romdev-permuter": "bin/permuter.mjs", + "romdev-permuter-import": "bin/import.mjs", + "romdev-permuter-remote": "bin/remote.mjs", + "romdev-permuter-remote-controller": "bin/remote-controller.mjs" + }, + "engines": { + "node": ">=24" + } + }, "packages/romdev-platform-atari2600": { - "version": "0.10.1", + "version": "0.10.2", "license": "GPL-2.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-platform-gba": { - "version": "0.14.0", - "license": "MPL-2.0", + "version": "0.14.1", + "license": "SEE LICENSE IN README.md", "engines": { "node": ">=24" } }, "packages/romdev-platform-snes": { - "version": "0.12.1", + "version": "0.12.2", "license": "SEE LICENSE IN README.md", "engines": { "node": ">=24" } }, "packages/romdev-platform-sync32": { - "version": "0.2.1", + "version": "0.2.2", "license": "MIT", "engines": { "node": ">=24" } }, + "packages/romdev-pycparser": { + "version": "0.1.0", + "license": "BSD-3-Clause", + "engines": { + "node": ">=24" + } + }, + "packages/romdev-rabbitizer": { + "version": "0.1.0", + "license": "MIT", + "engines": { + "node": ">=24" + } + }, + "packages/romdev-spimdisasm": { + "version": "0.1.0", + "license": "MIT AND PSF-2.0", + "dependencies": { + "romdev-rabbitizer": "0.1.0" + }, + "engines": { + "node": ">=24" + } + }, + "packages/romdev-splat": { + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "romdev-rabbitizer": "0.1.0", + "romdev-spimdisasm": "0.1.0", + "yaml": "2.9.0" + }, + "bin": { + "romdev-splat": "src/cli.js" + }, + "engines": { + "node": ">=24" + } + }, "packages/romdev-toolchain-cc65": { - "version": "0.1.4", + "version": "0.1.5", "license": "Zlib", "engines": { "node": ">=24" } }, + "packages/romdev-toolchain-decomp-gcc": { + "version": "0.1.0", + "license": "GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-2.1-or-later AND AGPL-3.0-only AND MIT AND Zlib", + "engines": { + "node": ">=24" + } + }, + "packages/romdev-toolchain-ido": { + "version": "0.1.0", + "license": "SEE LICENSE IN README.md", + "engines": { + "node": ">=24" + } + }, "packages/romdev-toolchain-m68k-gcc": { - "version": "0.4.1", + "version": "0.4.2", "license": "GPL-3.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-toolchain-mips-gcc": { - "version": "0.1.2", + "version": "0.1.3", "license": "GPL-3.0-or-later", "engines": { "node": ">=24" } }, "packages/romdev-toolchain-rgbds": { - "version": "0.1.2", + "version": "0.1.3", "license": "MIT", "engines": { "node": ">=24" @@ -3966,30 +4166,23 @@ } }, "packages/romdev-toolchain-sh-gcc": { - "version": "0.1.2", + "version": "0.1.3", "license": "GPL-3.0-or-later", "engines": { "node": ">=24" } }, - "packages/romdev-toolchain-vasm": { - "version": "0.1.2", - "license": "SEE LICENSE IN README.md", - "engines": { - "node": ">=24" - } - }, "packages/romdev-xgm2": { - "version": "0.2.1", + "version": "0.2.2", "license": "MIT", "engines": { "node": ">=24" } }, "packages/romdevtools": { - "version": "0.149.1", + "version": "0.151.1", "hasInstallScript": true, - "license": "MIT", + "license": "SEE LICENSE IN NOTICE", "dependencies": { "@kmamal/sdl": "^0.11.13", "@modelcontextprotocol/node": "2.0.0", @@ -4002,44 +4195,48 @@ "native-gles": "^0.6.1", "omggif": "^1.0.10", "pngjs": "^7.0.0", - "romdev_game_codes": "0.1.1", - "romdev-analysis": "0.2.1", - "romdev-analysis-decompiler": "0.2.1", + "romdev_game_codes": "0.1.2", + "romdev-analysis": "0.2.2", + "romdev-analysis-decompiler": "0.2.2", "romdev-audio-resampler": "0.1.1", - "romdev-core-beetle-psx-hw": "0.3.1", - "romdev-core-bluemsx": "0.9.1", + "romdev-core-beetle-psx-hw": "0.3.2", + "romdev-core-bluemsx": "0.9.2", + "romdev-core-bsnes": "0.1.0", "romdev-core-fake08": "0.1.1", - "romdev-core-fceumm": "0.14.0", - "romdev-core-flycast": "0.4.1", - "romdev-core-gambatte": "0.13.1", - "romdev-core-gametank": "0.5.1", - "romdev-core-geargrafx": "0.10.1", - "romdev-core-gpgx": "0.15.1", - "romdev-core-handy": "0.9.1", - "romdev-core-host": "0.16.0", - "romdev-core-parallel-n64": "0.3.1", - "romdev-core-prosystem": "0.10.1", - "romdev-core-runner": "0.2.18", - "romdev-core-s32core": "0.2.1", - "romdev-core-vice": "0.12.0", + "romdev-core-fceumm": "0.13.2", + "romdev-core-flycast": "0.4.2", + "romdev-core-gambatte": "0.12.2", + "romdev-core-gametank": "0.5.2", + "romdev-core-geargrafx": "0.10.2", + "romdev-core-gpgx": "0.15.2", + "romdev-core-handy": "0.9.2", + "romdev-core-host": "0.14.1", + "romdev-core-parallel-n64": "0.3.2", + "romdev-core-prosystem": "0.10.2", + "romdev-core-runner": "0.2.19", + "romdev-core-s32core": "0.2.2", + "romdev-core-vice": "0.12.1", "romdev-famitone": "0.2.1", + "romdev-m2c": "0.1.0", "romdev-maxmod": "0.2.1", - "romdev-platform-atari2600": "0.10.1", - "romdev-platform-gba": "0.14.0", - "romdev-platform-snes": "0.12.1", - "romdev-platform-sync32": "0.2.1", - "romdev-toolchain-cc65": "0.1.4", - "romdev-toolchain-m68k-gcc": "0.4.1", - "romdev-toolchain-mips-gcc": "0.1.2", - "romdev-toolchain-rgbds": "0.1.2", + "romdev-permuter": "0.1.0", + "romdev-platform-atari2600": "0.10.2", + "romdev-platform-gba": "0.14.1", + "romdev-platform-snes": "0.12.2", + "romdev-platform-sync32": "0.2.2", + "romdev-splat": "0.1.0", + "romdev-toolchain-cc65": "0.1.5", + "romdev-toolchain-decomp-gcc": "0.1.0", + "romdev-toolchain-m68k-gcc": "0.4.2", + "romdev-toolchain-mips-gcc": "0.1.3", + "romdev-toolchain-rgbds": "0.1.3", "romdev-toolchain-sdcc": "0.2.3", - "romdev-toolchain-sh-gcc": "0.1.2", - "romdev-toolchain-vasm": "0.1.2", - "romdev-xgm2": "0.2.1", + "romdev-toolchain-sh-gcc": "0.1.3", + "romdev-xgm2": "0.2.2", "rungame": "^0.13.0", "socket.io": "^4.8.3", "swagger-ui-dist": "^5.17.14", - "wasmcart": "^0.24.0", + "wasmcart": "^0.36.1", "webgl-node": "^1.5.1", "yaml": "^2.9.0", "yauzl": "^3.3.1", @@ -4056,6 +4253,29 @@ "engines": { "node": ">=24" } + }, + "packages/romdevtools/node_modules/wasmcart": { + "version": "0.36.1", + "resolved": "https://registry.npmjs.org/wasmcart/-/wasmcart-0.36.1.tgz", + "integrity": "sha512-bvWv5jFdwWd1Y4lQUq2OfHA9kBzFjj9b1uFwPMLADR0bAtw7q7xq+TSdsJy+Q2UI9qBVOfEa7zEfGqyENAGaeQ==", + "license": "MIT", + "dependencies": { + "@kmamal/sdl": "^0.11.13", + "fflate": "^0.8.3", + "native-dawn": "^0.1.6", + "webgl-node": "^1.6.0", + "webgpu-node": "^0.2.0", + "yauzl": "^3.2.0", + "yazl": "^2.5.1" + }, + "bin": { + "wasmcart": "bin/wasmcart.js", + "wasmcart-pack": "bin/wasmcart-pack.js", + "wasmcart-play": "bin/wasmcart-play.js" + }, + "engines": { + "node": ">=22.0.0" + } } } } diff --git a/packages/romdev-analysis-decompiler/README.md b/packages/romdev-analysis-decompiler/README.md index e4739902..cce7c8ea 100644 --- a/packages/romdev-analysis-decompiler/README.md +++ b/packages/romdev-analysis-decompiler/README.md @@ -1,35 +1,42 @@ # romdev-analysis-decompiler -Ghidra's decompiler - turns machine code into C-like pseudocode - compiled to -WebAssembly, with SLEIGH processor specifications for all 14 retro CPUs. +Ghidra's decompiler, which turns machine code into C-like pseudocode, compiled +to WebAssembly, with SLEIGH processor specifications for the CPUs romdev's +platforms use. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + compiled SLEIGH `.sla` tables and is resolved by the main -`romdev` package on demand (powers `disasm({target:'decompile'})`). You normally -install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and compiled SLEIGH `.sla` tables, and the main +`romdevtools` package loads it on demand for `disasm({target:'decompile'})`. +You normally install `romdevtools` (`npx romdevtools`), not this package +directly. ## What's bundled -- `wasm/decompile.{js,wasm}` - Ghidra's standalone decompiler REPL, built from - the Ghidra decompiler C++ (no JVM, no libbfd, no rizin) compiled to WASM. -- `sleigh/*.sla` + `.ldefs`/`.pspec`/`.cspec` - compiled processor tables for - 6502, 65C02, Z80, SM83, ARM (v4t), 68000, 65816, and HuC6280 - covering all - 14 romdev platforms. - -## CPU → platform coverage - -6502 (NES / Atari 2600 / Atari 7800 / C64), 65C02 (Lynx), Z80 (SMS / Game Gear / -MSX), SM83 (Game Boy / GBC), ARM7TDMI (GBA), 68000 (Genesis), 65816 (SNES), -HuC6280 (PC Engine). Decompiler quality is excellent on ARM/68000, good on -SM83/Z80, and rough on the 6502 family (an architecture limitation, not a bug). - -## Licensing & attribution - -Apache-2.0. This package redistributes **built artifacts only** (`.wasm`, `.sla`); -the source for each component is fetched on demand at the commit pinned in -romdev's `scripts/versions.json` and is never vendored here. Full per-component -attribution - including the Ghidra/NSA base (Apache-2.0), GhidraBoy (Apache-2.0), -ghidra-snes (MIT), and the HuC6280 spec (Apache-2.0 by derivation) - is in the -[NOTICE](./NOTICE) file. - -**Built by:** `romdevtools/scripts/build-decompiler.sh` (no patch - built clean). See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +- `wasm/decompile.{js,wasm}`: Ghidra's standalone decompiler, built from the + Ghidra decompiler C++ (no JVM, no libbfd, no rizin) and compiled to WASM. +- `sleigh/*.sla` with `.ldefs`/`.pspec`/`.cspec`: compiled processor tables + for 6502, 65C02, Z80, SM83, ARM (v4T), 68000, 65816, HuC6280, MIPS32 (both + endians) and SH-4. + +## CPU to platform coverage + +6502 (NES, Atari 2600, Atari 7800, C64), 65C02 (Lynx), Z80 (SMS, +Game Gear, MSX), SM83 (Game Boy, GBC), ARM7TDMI (GBA), 68000 (Genesis), 65816 +(SNES), HuC6280 (PC Engine), MIPS (N64, PS1) and SH-4 (Dreamcast). +Pseudocode reads best on ARM and 68000 code, well on SM83 and Z80, and roughly +on the 6502 family, where 8-bit idioms such as carry-chained 16-bit math do not +map cleanly to C (a property of the architecture, not a bug). + +## Licensing and attribution + +Apache-2.0. This package redistributes built artifacts only (`.wasm`, `.sla`). +The source for each component is fetched at the commit pinned in +`packages/romdevtools/scripts/versions.json` in the romdev repo and is not +vendored here. Per-component attribution, including the Ghidra base +(Apache-2.0), GhidraBoy (Apache-2.0), ghidra-snes (MIT) and the HuC6280 spec +(Apache-2.0 by derivation), is in the [NOTICE](./NOTICE) file. + +**Built by:** `packages/romdevtools/scripts/build-decompiler.sh` (no patches). +See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-analysis-decompiler/index.js b/packages/romdev-analysis-decompiler/index.js index f35ad23e..1bf17127 100644 --- a/packages/romdev-analysis-decompiler/index.js +++ b/packages/romdev-analysis-decompiler/index.js @@ -1,5 +1,5 @@ // romdev-analysis-decompiler - binary package: Ghidra decompiler (WASM) + -// SLEIGH specs for all 14 retro CPUs. Driven one-shot via the REPL through +// SLEIGH specs for the retro CPUs romdev supports. Driven one-shot via the REPL through // romdev's WASM worker pool. See NOTICE for attribution. import { fileURLToPath } from "node:url"; import path from "node:path"; diff --git a/packages/romdev-analysis-decompiler/package.json b/packages/romdev-analysis-decompiler/package.json index f5da41ef..dd990785 100644 --- a/packages/romdev-analysis-decompiler/package.json +++ b/packages/romdev-analysis-decompiler/package.json @@ -1,7 +1,7 @@ { "name": "romdev-analysis-decompiler", - "version": "0.2.1", - "description": "Ghidra C++ decompiler (pseudocode) for romdev, compiled to WASM, with SLEIGH specs for all 14 retro CPUs.", + "version": "0.2.2", + "description": "Ghidra C++ decompiler (pseudocode) for romdev, compiled to WASM, with SLEIGH specs for the retro CPUs romdev supports.", "type": "module", "main": "index.js", "exports": { diff --git a/packages/romdev-analysis/README.md b/packages/romdev-analysis/README.md index b7fdd924..3e7c97f1 100644 --- a/packages/romdev-analysis/README.md +++ b/packages/romdev-analysis/README.md @@ -1,27 +1,33 @@ # romdev-analysis -Rizin - reverse-engineering analysis engine (control-flow graphs, cross- -references, function detection), compiled to WebAssembly. +Rizin, the reverse-engineering analysis engine (control-flow graphs, +cross-references, function detection), compiled to WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand for `disasm({target:'functions'|'cfg'|'xrefs'})`. You normally install +`romdevtools` (`npx romdevtools`), not this package directly. -## Upstream & license +## Upstream and license -Bundles: **rizin** (https://github.com/rizinorg/rizin). +Bundles: **rizin** v0.8.2 (https://github.com/rizinorg/rizin). **License:** LGPL-3.0-only -This package redistributes the upstream binary built to WebAssembly; the source -and exact pinned commit are recorded in romdev's `scripts/versions.json`, and -the build recipe is `scripts/build-rizin.sh` + `scripts/patches/rizin-*.patch`. +This package redistributes the upstream source built to WebAssembly. The +upstream commit is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. ## CPU coverage used by romdev -6502 (NES / Atari 2600 / Atari 7800 / C64 / Lynx), Z80 (SMS / Game Gear / MSX), -SM83 (`gb` plugin - Game Boy / GBC), ARM (GBA), M68K (Genesis), 65816 (`snes` -plugin), SPC700. HuC6280 (PC Engine) analysis arrives with the rz-ghidra -decompiler package (SLEIGH spec). - -**Built by:** `romdevtools/scripts/build-rizin.sh` + patch(es) `rizin-romdev-emscripten.patch`, `rizin-libzip-emscripten.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +6502 (NES, Atari 2600, Atari 7800, C64, Lynx), Z80 (SMS, Game Gear, MSX), SM83 +(the `gb` plugin: Game Boy, GBC), ARM (GBA), M68K (Genesis), 65816 (the `snes` +plugin), MIPS (N64 big-endian, PS1 little-endian) and SH-4 (Dreamcast). Rizin +has no HuC6280 plugin, so PC Engine analysis uses the 6502 plugin: function and +control-flow results are approximate there, while `disasm({target:'decompile'})` +uses a proper HuC6280 SLEIGH spec from `romdev-analysis-decompiler`. + +**Built by:** `packages/romdevtools/scripts/build-rizin.sh` with patches +`rizin-romdev-emscripten.patch` and `rizin-libzip-emscripten.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-analysis/package.json b/packages/romdev-analysis/package.json index 58890635..a17620a7 100644 --- a/packages/romdev-analysis/package.json +++ b/packages/romdev-analysis/package.json @@ -1,6 +1,6 @@ { "name": "romdev-analysis", - "version": "0.2.1", + "version": "0.2.2", "description": "Rizin RE analysis engine (CFG, xrefs, function detection) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-beetle-psx-hw/README.md b/packages/romdev-core-beetle-psx-hw/README.md index 575ba524..d2d401c1 100644 --- a/packages/romdev-core-beetle-psx-hw/README.md +++ b/packages/romdev-core-beetle-psx-hw/README.md @@ -1,10 +1,27 @@ # romdev-core-beetle-psx-hw -[Beetle PSX HW](https://github.com/libretro/beetle-psx-libretro) (Sony PlayStation, a -mednafen PSX fork) compiled to WebAssembly for romdev, with the **GLES3/WebGL2 hardware -renderer** so the PS1 GPU renders on the real GPU through native-gles - the same path as -the glide64 N64 build and Flycast Dreamcast. - -Ships with **OpenBIOS embedded** (from [PCSX-Redux](https://github.com/grumpycoders/pcsx-redux), -MIT-licensed, region-free) - there is no copyrighted Sony BIOS to ship and no BIOS file to -supply. Built reproducibly by `romdevtools/scripts/build-beetle-psx-hw.sh`. +[Beetle PSX HW](https://github.com/libretro/beetle-psx-libretro) (Sony +PlayStation, a fork of mednafen's PSX emulator) compiled to WebAssembly for +[romdev](https://github.com/monteslu/romdev), with the GLES3/WebGL2 hardware +renderer, so the PS1 GPU renders on the real GPU through native-gles. That is +the same path as the N64 (ParaLLEl-N64 with glide64) and Dreamcast (Flycast) +cores. + +It ships with OpenBIOS embedded (from +[PCSX-Redux](https://github.com/grumpycoders/pcsx-redux), MIT, region-free), so +there is no Sony BIOS to ship and no BIOS file to supply. + +## Use + +A binary package: the main `romdevtools` package loads it on demand for +`loadMedia({platform:'ps1'})`, with `hwRender: true` and the headless GL +context `romdev-core-host` provides. You normally install `romdevtools` +(`npx romdevtools`), not this package directly. + +## License + +GPL-2.0-or-later (Beetle PSX and mednafen). The embedded OpenBIOS is MIT. + +**Built by:** `packages/romdevtools/scripts/build-beetle-psx-hw.sh`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-beetle-psx-hw/package.json b/packages/romdev-core-beetle-psx-hw/package.json index 4a0ab4c0..9ca4b5fb 100644 --- a/packages/romdev-core-beetle-psx-hw/package.json +++ b/packages/romdev-core-beetle-psx-hw/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-beetle-psx-hw", - "version": "0.3.1", + "version": "0.3.2", "description": "Beetle PSX HW libretro core (Sony PlayStation, GLES3 hardware renderer + embedded OpenBIOS) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-bluemsx/README.md b/packages/romdev-core-bluemsx/README.md index 23b7f300..a8b2bffd 100644 --- a/packages/romdev-core-bluemsx/README.md +++ b/packages/romdev-core-bluemsx/README.md @@ -3,10 +3,30 @@ The [blueMSX](https://github.com/libretro/blueMSX-libretro) MSX / MSX2 libretro core, compiled to WebAssembly for [romdev](https://github.com/monteslu/romdev). -Bundles **C-BIOS** (the open-source, BSD-licensed MSX BIOS) so cartridge -homebrew boots with no proprietary ROM. +It bundles **C-BIOS** (https://cbios.sourceforge.net), an open-source MSX BIOS, +in `bios/Machines/`, so cartridge homebrew boots with no proprietary ROM. +romdev's host points the core at that tree automatically. -License: BSD-3-Clause (blueMSX core + C-BIOS). Not intended for standalone use; -loaded by romdev's core registry. +## Use -**Built by:** `romdevtools/scripts/build-bluemsx.sh` + patch(es) `bluemsx-romdev-memory-regions.patch`, `bluemsx-emscripten-build.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +A binary package: the main `romdevtools` package loads it on demand for +`loadMedia({platform:'msx'})`. You normally install `romdevtools` +(`npx romdevtools`), not this package directly. + +## License + +- blueMSX: the blueMSX license, a permissive zlib-style license for the code + the blueMSX team wrote. Some upstream source files come from other projects + under their own terms, including GPL sound-chip code from openMSX and + fMSX-SDL; see `license.txt` in the upstream repository. +- C-BIOS: BSD (2-clause). Its copyright and license text ship beside the ROMs + in each machine folder as `cbios.txt`, as its binary-redistribution clause + requires. + +The upstream commit is pinned in `packages/romdevtools/scripts/versions.json` +in the romdev repo. + +**Built by:** `packages/romdevtools/scripts/build-bluemsx.sh` with patches +`bluemsx-romdev-memory-regions.patch` and `bluemsx-emscripten-build.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-bluemsx/package.json b/packages/romdev-core-bluemsx/package.json index c3ffe6d7..4aa7b663 100644 --- a/packages/romdev-core-bluemsx/package.json +++ b/packages/romdev-core-bluemsx/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-bluemsx", - "version": "0.9.1", + "version": "0.9.2", "description": "blueMSX libretro core (MSX / MSX2) for romdev, bundled as WASM. Ships C-BIOS (open-source MSX BIOS) so no proprietary ROM is required.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-bsnes/NOTICE b/packages/romdev-core-bsnes/NOTICE new file mode 100644 index 00000000..ca1c405a --- /dev/null +++ b/packages/romdev-core-bsnes/NOTICE @@ -0,0 +1,30 @@ +romdev-core-bsnes +================= + +wasm/bsnes_libretro.wasm and wasm/bsnes_libretro.js are built from bsnes +(https://github.com/libretro/bsnes, the libretro port of bsnes by byuu / Near +and contributors) at the commit pinned in romdevtools/scripts/versions.json +(cores.bsnes), with romdev's patches (romdevtools/scripts/patches/ +bsnes-romdev.patch, bsnes-romdev-firmware.patch and patches/bsnes/). + +bsnes is licensed under the GNU General Public License, version 3 +(GPL-3.0-only; the full text is GPLv3.txt in the bsnes source). libco and nall, +which bsnes includes, are under the ISC license. The built core is therefore +distributed under GPL-3.0; its corresponding source is the pinned bsnes commit +plus the romdev patch and build script named above. + +No bsnes code is transplanted elsewhere in romdev: this core is the only +place bsnes runs. The firmware coprocessors that romdev's snes9x core and its +recompiled SNES carts run (the uPD96050 for the ST010/ST011, the ARM for the +ST018) are compiled from ares instead, which is ISC-licensed (see romdev's +NOTICE). The only file this build shares with that code is romdev's own +libco backend for WebAssembly (romdevtools/scripts/patches/libco-wasm/, MIT); +the chip state layout this core writes (patches/bsnes/romdev_bsnes_chipstate.h, +romdev's own, MIT) is matched field for field by the ares side's own header. + +No coprocessor firmware, chip data ROM or boot ROM is included. The SPC700 +boot ROM in this core is romdev's own clean-room reimplementation (romdevtools +scripts/spc700-ipl/ipl.asm, MIT), not the one bsnes embeds. The DSP-1 data +ROM, ST010 tables, Cx4 data ROM and Super Game Boy boot ROMs bsnes embeds are +emptied before it is built (patches/bsnes/strip-firmware.mjs); the chips' +firmware and the boot ROMs are not part of romdev, a user supplies them. diff --git a/packages/romdev-core-bsnes/README.md b/packages/romdev-core-bsnes/README.md new file mode 100644 index 00000000..5e0f2bf3 --- /dev/null +++ b/packages/romdev-core-bsnes/README.md @@ -0,0 +1,46 @@ +# romdev-core-bsnes + +The [bsnes](https://github.com/libretro/bsnes) SNES libretro core, compiled to +WebAssembly for [romdev](https://github.com/monteslu/romdev). + +romdev's default SNES core is snes9x. bsnes is here as the accuracy reference +for the SNES coprocessors that run firmware, which snes9x only approximates: +the ST010/ST011 (a NEC uPD96050) and the ST018 (an ARM). bsnes runs their +firmware; put `st011.rom` / `st018.rom` (the program ROM followed by the data +ROM, as the chips are dumped) in the core's system directory. romdev loads it +with `loadMedia({platform:'snes', core:'bsnes'})` or as the reference of +`frame({op:'verifyRecompile', referenceCore:'bsnes'})`. + +The build differs from upstream in these ways, all in romdev's patches and +build script: + +- libco gets a WebAssembly backend: bsnes runs every chip as a cothread, and + the cothreads switch with binaryen's Asyncify inside the module; +- the libretro target serves memory regions with romdev's SNES region ids + (system_ram, video_ram, save_ram, snes_oam, snes_cgram, snes_aram, + snes_chipstate) and finds coprocessor firmware in the system directory; +- the reference defaults are deterministic and accurate: no entropy, the + accurate PPU and DSP, no HLE preference; +- no Nintendo boot ROM or chip data: the SPC700 boot ROM is romdev's own + clean-room one (MIT, `scripts/spc700-ipl/`), and the DSP-1 data ROM, the + ST010 tables, the Cx4 data ROM and the Super Game Boy boot ROMs upstream + embeds are emptied. A DSP-1, DSP-2, DSP-3, DSP-4, ST010 or ST011 cart needs + the chip's firmware in the system directory (e.g. `dsp1b.rom`, `st010.rom`, + the program ROM then the data ROM) and is refused with the file named + without it (DSP-2 and DSP-4 fall back to bsnes's high-level emulation); a + Cx4 cart runs bsnes's high-level emulation unless `cx4.data.rom` is there; + the Super Game Boy needs `sgb_boot.bin` / `sgb2_boot.bin`. + +License: GPL-3.0-only (bsnes; libco and nall are ISC). See NOTICE. Not intended for +standalone use; loaded by romdev's core registry. This core is a separate +reference: none of its code is compiled into romdev's snes9x core or into +recompiled carts (their firmware coprocessors come from ares, ISC). + +No coprocessor firmware ships in this package: supply your own dumps, for +example with `loadMedia({platform:'snes', core:'bsnes', firmware})`, which copies the +file into the system directory before the ROM loads. + +**Built by:** `packages/romdevtools/scripts/build-bsnes.sh` with +`bsnes-romdev.patch` and `bsnes-romdev-firmware.patch` (plus `patches/bsnes/` and `patches/libco-wasm/`). See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-bsnes/index.js b/packages/romdev-core-bsnes/index.js new file mode 100644 index 00000000..02a017bc --- /dev/null +++ b/packages/romdev-core-bsnes/index.js @@ -0,0 +1,20 @@ +// romdev-core-bsnes - binary package: the bsnes libretro core (SNES), built +// by romdevtools/scripts/build-bsnes.sh. Not loadMedia's default SNES core +// (that is snes9x): romdev's registry lists it in ALT_CORES as the accuracy +// reference for the coprocessors that run firmware, which a caller names with +// loadMedia({core:'bsnes'}) or verifyRecompile({referenceCore:'bsnes'}). The +// ST011 / ST018 need their firmware (st011.rom / st018.rom) in the core's +// system directory. GPL-3.0. +import { fileURLToPath } from "node:url"; +import path from "node:path"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const WASM = path.join(__dirname, "wasm"); + +export const platform = "snes"; + +export const core = { + name: "bsnes", + jsPath: path.join(WASM, "bsnes_libretro.js"), + wasmPath: path.join(WASM, "bsnes_libretro.wasm"), +}; diff --git a/packages/romdev-toolchain-vasm/package.json b/packages/romdev-core-bsnes/package.json similarity index 62% rename from packages/romdev-toolchain-vasm/package.json rename to packages/romdev-core-bsnes/package.json index d8a7a380..e4d90fe8 100644 --- a/packages/romdev-toolchain-vasm/package.json +++ b/packages/romdev-core-bsnes/package.json @@ -1,7 +1,7 @@ { - "name": "romdev-toolchain-vasm", - "version": "0.1.2", - "description": "vasm m68k (Motorola syntax) assembler for romdev Genesis dev, bundled as WASM.", + "name": "romdev-core-bsnes", + "version": "0.1.0", + "description": "bsnes libretro core for romdev, bundled as WASM: the SNES accuracy reference for the coprocessors that run firmware (ST010/ST011, ST018).", "type": "module", "main": "index.js", "exports": { @@ -11,16 +11,17 @@ "files": [ "index.js", "wasm", - "README.md" + "README.md", + "NOTICE" ], "engines": { "node": ">=24" }, - "license": "SEE LICENSE IN README.md", + "license": "GPL-3.0-only", "repository": { "type": "git", "url": "git+https://github.com/monteslu/romdev.git", - "directory": "packages/romdev-toolchain-vasm" + "directory": "packages/romdev-core-bsnes" }, "homepage": "https://github.com/monteslu/romdev#readme", "bugs": { diff --git a/packages/romdev-core-fceumm/README.md b/packages/romdev-core-fceumm/README.md index ccc5df36..a3e0ae8c 100644 --- a/packages/romdev-core-fceumm/README.md +++ b/packages/romdev-core-fceumm/README.md @@ -2,19 +2,21 @@ fceumm - NES emulator core (libretro), compiled to WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **fceumm**. +Bundles: **FCE Ultra mappers modified (fceumm)**, https://github.com/libretro/libretro-fceumm. **License:** GPL-2.0-or-later -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-fceumm.sh` + patch(es) `fceumm-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-fceumm.sh` with patch(es) `fceumm-romdev-memory-regions.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-fceumm/package.json b/packages/romdev-core-fceumm/package.json index f2b3f6c3..dc4b00f2 100644 --- a/packages/romdev-core-fceumm/package.json +++ b/packages/romdev-core-fceumm/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-fceumm", - "version": "0.15.0", + "version": "0.13.2", "description": "fceumm libretro core (NES) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-flycast/README.md b/packages/romdev-core-flycast/README.md index 327c9bc6..63247512 100644 --- a/packages/romdev-core-flycast/README.md +++ b/packages/romdev-core-flycast/README.md @@ -1,21 +1,35 @@ # romdev-core-flycast -The [Flycast](https://github.com/flyinghead/flycast) libretro core (Sega Dreamcast) -compiled to WebAssembly for romdev. - -A custom romdev build: single-threaded, with worker-thread creation neutered, threaded -rendering forced off, and the **reios HLE BIOS** defaulted on - so a raw homebrew `.elf` -boots directly with no GD-ROM image or firmware. The PowerVR2 renders through WebGL2; -`flycast_emulate_framebuffer` scans out a direct 2D framebuffer so simple homebrew -presents without authoring a PowerVR2 tile list. - -The SH-4 runs on a **WASM recompiler** (`core/rec-wasm`): each SH-4 basic block is -emitted as a WebAssembly module at runtime and dispatched via `call_indirect`. That is -roughly a 4-5x speedup over the interpreter this package shipped through 0.2.0, which -put heavy commercial titles well under playable. The AICA sound system (ARM7 + DSP) -is still interpreted - measured at under ~12% of frame time, so it is not currently -the bottleneck. - -Built reproducibly by `romdevtools/scripts/build-flycast.sh` - the recompiler is the -script's default, so a plain run reproduces this package's wasm byte-for-byte. Set -`ROMDEV_FLYCAST_INTERP=1` to build the SH-4 interpreter instead. +The [Flycast](https://github.com/flyinghead/flycast) libretro core (Sega +Dreamcast) compiled to WebAssembly for [romdev](https://github.com/monteslu/romdev). + +A custom romdev build: single-threaded, with worker-thread creation disabled, +threaded rendering forced off, and the reios HLE BIOS on by default, so a raw +homebrew `.elf` boots directly with no GD-ROM image or firmware. The PowerVR2 +renders through WebGL2; `flycast_emulate_framebuffer` scans out a direct 2D +framebuffer so simple homebrew can present without building a PowerVR2 tile +list. + +The SH-4 runs on a WebAssembly recompiler (`core/rec-wasm`): each SH-4 basic +block is emitted as a WebAssembly module at run time and dispatched through +`call_indirect`, roughly 4 to 5 times faster than the interpreter earlier +versions shipped. The AICA sound system (ARM7 and DSP) is still interpreted. + +## Use + +A binary package: the main `romdevtools` package loads it on demand for +`loadMedia({platform:'dreamcast'})`, with `hwRender: true` and the headless GL +context `romdev-core-host` provides. The core is built with NODERAWFS, so disc +images are read from disk as needed rather than loaded into memory. You +normally install `romdevtools` (`npx romdevtools`), not this package directly. + +## License + +GPL-2.0-or-later (Flycast). + +**Built by:** `packages/romdevtools/scripts/build-flycast.sh`, which adds the +recompiler sources from `scripts/patches/flycast-wasm-jit/`. The recompiler is +the script's default, so a plain run reproduces this package's wasm; set +`ROMDEV_FLYCAST_INTERP=1` to build the SH-4 interpreter instead. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-flycast/package.json b/packages/romdev-core-flycast/package.json index 589db596..e509927d 100644 --- a/packages/romdev-core-flycast/package.json +++ b/packages/romdev-core-flycast/package.json @@ -1,7 +1,7 @@ { "name": "romdev-core-flycast", - "version": "0.4.1", - "description": "Flycast libretro core (Sega Dreamcast, reios HLE BIOS) for romdev, bundled as WASM \u2014 single-threaded build with the WASM SH-4 recompiler; boots homebrew ELFs and commercial GD-ROM images.", + "version": "0.4.2", + "description": "Flycast libretro core (Sega Dreamcast, reios HLE BIOS) for romdev, bundled as WASM: a single-threaded build with the WASM SH-4 recompiler; boots homebrew ELFs and commercial GD-ROM images.", "type": "module", "main": "index.js", "exports": { diff --git a/packages/romdev-core-gambatte/README.md b/packages/romdev-core-gambatte/README.md index 279d419f..e0db9a34 100644 --- a/packages/romdev-core-gambatte/README.md +++ b/packages/romdev-core-gambatte/README.md @@ -2,19 +2,21 @@ gambatte - Game Boy / Game Boy Color emulator core (libretro), as WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **gambatte**. +Bundles: **gambatte**, https://github.com/libretro/gambatte-libretro. **License:** GPL-2.0-only -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-gambatte.sh` + patch(es) `gambatte-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-gambatte.sh` with patch(es) `gambatte-romdev-memory-regions.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-gambatte/package.json b/packages/romdev-core-gambatte/package.json index fb679e5d..82b85fa2 100644 --- a/packages/romdev-core-gambatte/package.json +++ b/packages/romdev-core-gambatte/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-gambatte", - "version": "0.15.0", + "version": "0.12.2", "description": "gambatte libretro core (Game Boy / Game Boy Color) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-gametank/README.md b/packages/romdev-core-gametank/README.md index 7c501242..26154d40 100644 --- a/packages/romdev-core-gametank/README.md +++ b/packages/romdev-core-gametank/README.md @@ -1,20 +1,33 @@ # romdev-core-gametank -gametank - GameTank (Clyde Shaffer's open W65C02S console) emulator core (libretro), as WebAssembly. +The GameTank libretro core (GameTank: Clyde Shaffer's open-source 8-bit +console, a WDC 65C02 main CPU with a second 65C02 driving audio), compiled to +WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand for `loadMedia({platform:'gametank'})`. You normally install +`romdevtools` (`npx romdevtools`), not this package directly. -## Upstream & license +## Upstream and license -Bundles: **handy**. +Bundles: **gametank-libretro** (https://github.com/monteslu/gametank-libretro), +a libretro wrapper around the hardware-emulation units of Clyde Shaffer's +[GameTankEmulator](https://github.com/clydeshaffer/GameTankEmulator) (CPU, +blitter, audio coprocessor, bus). -**License:** Zlib +**License:** MIT (gametank-libretro and GameTankEmulator, Copyright (c) 2020 +Clyde Shaffer; the vendored mos6502 CPU core is MIT, Copyright (c) 2017 +Gianluca Ghettini). -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +romdev's build adds its shared live-debug instrumentation (write and read +watchpoints, PC breakpoints, register get/set, coverage) through a small shim +appended to the core's `libretro.cpp`. This core is built from a local checkout +of gametank-libretro; it has no pinned commit in +`packages/romdevtools/scripts/versions.json`. -**Built by:** `romdevtools/scripts/build-handy.sh` + patch(es) `handy-romdev-watchpoint.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-gametank.sh` (shim: +`scripts/patches/romdev-snippets/gametank-debug.cpp`). Set `GAMETANK_SRC` to +the gametank-libretro checkout. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-gametank/package.json b/packages/romdev-core-gametank/package.json index f9151b9b..93a2aed1 100644 --- a/packages/romdev-core-gametank/package.json +++ b/packages/romdev-core-gametank/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-gametank", - "version": "0.5.1", + "version": "0.5.2", "description": "GameTank libretro core (Clyde Shaffer's open W65C02S console) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-geargrafx/README.md b/packages/romdev-core-geargrafx/README.md index ae6bc519..3f4fb078 100644 --- a/packages/romdev-core-geargrafx/README.md +++ b/packages/romdev-core-geargrafx/README.md @@ -1,10 +1,21 @@ # romdev-core-geargrafx -The [Geargrafx](https://github.com/drhelius/Geargrafx) PC Engine / TurboGrafx-16 -libretro core, compiled to WebAssembly for +The [Geargrafx](https://github.com/drhelius/Geargrafx) PC Engine / +TurboGrafx-16 libretro core, compiled to WebAssembly for [romdev](https://github.com/monteslu/romdev). -License: GPL-3.0-or-later. Not intended for standalone use; loaded by romdev's -core registry. +## Use -**Built by:** `romdevtools/scripts/build-geargrafx.sh` + patch(es) `geargrafx-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +A binary package: the main `romdevtools` package loads it on demand for +`loadMedia({platform:'pce'})`. You normally install `romdevtools` +(`npx romdevtools`), not this package directly. + +## License + +GPL-3.0-or-later (Geargrafx). The upstream commit is pinned in +`packages/romdevtools/scripts/versions.json` in the romdev repo. + +**Built by:** `packages/romdevtools/scripts/build-geargrafx.sh` with patch +`geargrafx-romdev-memory-regions.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-geargrafx/package.json b/packages/romdev-core-geargrafx/package.json index bf48961c..9ed2e80b 100644 --- a/packages/romdev-core-geargrafx/package.json +++ b/packages/romdev-core-geargrafx/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-geargrafx", - "version": "0.10.1", + "version": "0.10.2", "description": "Geargrafx libretro core (PC Engine / TurboGrafx-16) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-gpgx/README.md b/packages/romdev-core-gpgx/README.md index bf51ed95..99a20e00 100644 --- a/packages/romdev-core-gpgx/README.md +++ b/packages/romdev-core-gpgx/README.md @@ -2,19 +2,21 @@ Genesis Plus GX - Sega Genesis / Master System / Game Gear emulator core (libretro), as WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **Genesis Plus GX**. +Bundles: **Genesis Plus GX**, https://github.com/libretro/genesis-plus-gx. -**License:** NON-COMMERCIAL (Genesis Plus GX custom license) - free for non-commercial use; redistribution for profit is not permitted. +**License:** Genesis Plus GX license (non-commercial): free for non-commercial use; redistribution for profit is not permitted. See the upstream `LICENSE.txt`. -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-genesis-plus-gx.sh` + patch(es) `genesis-plus-gx-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-genesis-plus-gx.sh` with patch(es) `genesis-plus-gx-romdev-memory-regions.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-gpgx/package.json b/packages/romdev-core-gpgx/package.json index 2527b3c1..f2a0d102 100644 --- a/packages/romdev-core-gpgx/package.json +++ b/packages/romdev-core-gpgx/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-gpgx", - "version": "0.15.1", + "version": "0.15.2", "description": "Genesis Plus GX libretro core (Genesis / Master System / Game Gear) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-handy/README.md b/packages/romdev-core-handy/README.md index 102d1c8c..af97af7c 100644 --- a/packages/romdev-core-handy/README.md +++ b/packages/romdev-core-handy/README.md @@ -2,19 +2,21 @@ handy - Atari Lynx emulator core (libretro), as WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **handy**. +Bundles: **Handy**, https://github.com/libretro/libretro-handy. **License:** Zlib -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-handy.sh` + patch(es) `handy-romdev-watchpoint.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-handy.sh` with patch(es) `handy-romdev-watchpoint.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-handy/package.json b/packages/romdev-core-handy/package.json index 9308d50d..a045b6bf 100644 --- a/packages/romdev-core-handy/package.json +++ b/packages/romdev-core-handy/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-handy", - "version": "0.9.1", + "version": "0.9.2", "description": "Handy libretro core (Atari Lynx) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-host/LibretroGL.js b/packages/romdev-core-host/LibretroGL.js index 3bf741b8..eb964f27 100644 --- a/packages/romdev-core-host/LibretroGL.js +++ b/packages/romdev-core-host/LibretroGL.js @@ -59,9 +59,9 @@ export class LibretroGL { } /** - * Load the optional native GL module (lazy). MUST be awaited before the core - * boots, since the 14 software cores never call this and the module is an - * optional dependency. Populates the module-level `gl` used by + * Load the native GL module (lazy). MUST be awaited before the core + * boots. Software-rendered cores never call this, so the module loads only + * for HW-render cores. Populates the module-level `gl` used by * createContext/readbackFrame/destroy. * @returns {Promise} */ diff --git a/packages/romdev-core-host/LibretroHost.js b/packages/romdev-core-host/LibretroHost.js index c7d79605..964102cf 100644 --- a/packages/romdev-core-host/LibretroHost.js +++ b/packages/romdev-core-host/LibretroHost.js @@ -285,7 +285,18 @@ export class LibretroHost { systemDir: opts.systemDir ?? "/romdev-system", saveDir: opts.saveDir ?? "/romdev-save", }); - this.log = opts.log; + // The core's error-level log lines (RETRO_LOG_ERROR) are also kept, so a + // load the core refuses can say why in the core's own words (a missing + // firmware file, named by the core). + const userLog = opts.log; + this._coreErrors = []; + this.log = (level, msg) => { + if (level >= 3 && typeof msg === "string" && msg.trim()) { + this._coreErrors.push(msg.trim()); + if (this._coreErrors.length > 8) this._coreErrors.shift(); + } + if (userLog) userLog(level, msg); + }; this.status = { platform: null, corePath: null, @@ -307,7 +318,7 @@ export class LibretroHost { * @param {string} [wasmPath] * @param {Object} [opts] * @param {boolean} [opts.hwRender] this core HW-renders (GL) - n64/ps1. Loads the - * optional native GL stack and creates a headless context BEFORE the core boots + * native GL stack and creates a headless context BEFORE the core boots * (GL calls happen during init/load). The 14 software cores omit this. */ /** Infer the platform from a core's js filename stem (e.g. @@ -748,6 +759,7 @@ export class LibretroHost { // flag while YIELDING to the JS event loop - the event loop must keep turning so emscripten // can service the app-thread's pooled-Worker grabs / postMessage wakeups. A blocking call // would freeze the event loop → the core's threads can't be scheduled → deadlock. + this._coreErrors.length = 0; let ok; if (this._proxied) { // Deferred retro_init (see loadCore): now that the system dir is mirrored into the app-thread @@ -773,7 +785,7 @@ export class LibretroHost { mod._romdev_proxied_fire_context_reset(this.state.proxiedContextResetPtr); } } else { - ok = mod._retro_load_game(infoPtr); + ok = this._withClock(() => mod._retro_load_game(infoPtr)); } // Free the struct itself. Don't free pathPtr or dataPtr - the core may @@ -789,6 +801,10 @@ export class LibretroHost { `The '${platform}' core REFUSED this ${mediaKind || "media"} ` + `(${data ? data.length + " bytes" : "streamed from disk"}${ext ? `, ${ext}` : ""}, path ${mediaPath}). ` + `retro_load_game returned false - the bytes reached the core but it would not accept them. ` + + // the core's own reason, when it logged one (e.g. a firmware file it needs, by name) + (this._coreErrors.some((m) => m.startsWith("romdev:")) + ? `The core said: ${this._coreErrors.filter((m) => m.startsWith("romdev:")).join(" ")} ` + : "") + `Common causes: (1) wrong platform for this file (a GB ROM loaded as 'nes', etc.) - ` + `confirm the platform matches the file; (2) a corrupt or TRUNCATED image - re-check the byte length; ` + `(3) an unsupported mapper/board or a missing/!bad header. ` + @@ -908,9 +924,9 @@ export class LibretroHost { // - snes9x defaults to 256×224 but games select 256×239 or // 512×448 (interlaced) based on PPU regs the ROM sets up. // - // The rom-games agent reasonably expected fbWidth/Height after - // loadMedia to reflect "what screenshot will show me". Step a - // small number of frames here so the agent sees the ROM-chosen + // Callers expect fbWidth/Height after loadMedia to reflect "what + // screenshot will show me". Step a small number of frames here so + // the caller sees the ROM-chosen // geometry, not the pre-init default. // // 8 frames is generous - Genesis games typically settle their @@ -920,6 +936,9 @@ export class LibretroHost { // Proxied cores (PSP) drive frames through the async run path (run_start + poll); the // synchronous settle loop below uses the blocking sync run, so skip it. PSP geometry is the // fixed 480×272 av_info already read, so there's no pre-init default to settle past. + // A caller that must observe the settle frames themselves (the + // instruction differ traces power-on) arms its hooks here. + if (typeof args.beforeSettle === "function") args.beforeSettle(this); if (!args.deterministic && !this.status.paused && !this._proxied) { // Settle frames are core warm-up, not agent-visible gameplay // frames - don't increment frameCount. From the agent's POV the @@ -982,10 +1001,8 @@ export class LibretroHost { * * This is what makes host eviction actually reclaim anything. Without it a * long-lived server accumulates one full core heap per host it has ever - * created - which is how the server got OOM-killed twice on 2026-08-19 - * (~5.4 GB RSS, 300-500 GB of mapped address space) under a single agent - * running a 21-gate suite that loads 20+ carts. See - * internal-romdev/PLAN_mcp_v2_stateless_and_host_lifetime.md. + * created, which reached about 5.4 GB RSS (300-500 GB of mapped address + * space) under one client running a test suite that loads 20+ carts. * * Ordering matters: unload the game, then `retro_deinit` so the core frees * its own allocations while its heap is still valid, then drop every @@ -1069,7 +1086,44 @@ export class LibretroHost { * observes (frameCount is incremented after the frame runs). * A hook failure never breaks emulation: it is caught and remembered on * `beforeFrameError`; the callback owner surfaces it. */ + /** + * Pin the wall clock the core reads (Date.now, which emscripten's time() + * and clock_gettime call: gambatte's MBC3 RTC, mGBA's GPIO RTC) to a + * frame clock, so a verifier can give a recompiled cart the same one: + * baseMs + max(0, runs - startRun) * stepMs + * where runs counts retro_run calls since the pin was set (0 while the + * game loads), in UTC (localtime = gmtime while the core runs). baseMs + * should be a whole second. null restores the host + * clock. Set it before loadMedia so the load (gambatte's RTC base time) + * sees it too. + * @param {{baseMs: number, stepMs: number, startRun?: number|(() => number)}|null} pin + */ + setPinnedClock(pin) { + this._clockPin = pin ? { baseMs: pin.baseMs, stepMs: pin.stepMs, startRun: pin.startRun ?? 0, runs: 0 } : null; + } + + /** @param {() => any} fn run with Date.now pinned (see setPinnedClock) */ + _withClock(fn) { + const pin = this._clockPin; + if (!pin) return fn(); + const start = typeof pin.startRun === "function" ? pin.startRun() : pin.startRun; + const t = pin.baseMs + Math.max(0, pin.runs - start) * pin.stepMs; + const real = Date.now; + Date.now = () => t; + // localtime() is emscripten's JS Date getters in the host's zone; a + // pinned clock is UTC so the calendar a core computes (mGBA's RTC date + // and hour) does not depend on the machine running the verification + const env = globalThis.process?.env; + const tz = env?.TZ; + if (env) env.TZ = "UTC"; + try { return fn(); } finally { + Date.now = real; + if (env) { if (tz === undefined) delete env.TZ; else env.TZ = tz; } + } + } + _runCore() { + if (this._clockPin) this._clockPin.runs++; if (this.state.inputOverrides) this.state.inputOverrides.fill(null); if (this.beforeFrame) { try { @@ -1078,8 +1132,10 @@ export class LibretroHost { this.beforeFrameError = e; } } - if (this._proxied) this.mod._romdev_proxied_run(); - else this.mod._retro_run(); + this._withClock(() => { + if (this._proxied) this.mod._romdev_proxied_run(); + else this.mod._retro_run(); + }); } /** @@ -1983,7 +2039,7 @@ export class LibretroHost { if (typeof mod._retro_cheat_set !== "function") { throw new Error( "this core build does not expose the cheat interface (retro_cheat_set). " + - "Rebuild the core with the cheat exports, or apply RAM cheats via writeMemory.", + "Rebuild the core with the cheat exports, or apply RAM cheats via memory({op:'write'}).", ); } const bytes = encodeCString(String(code)); @@ -2038,7 +2094,7 @@ export class LibretroHost { * * The other mirror platforms (NES/GB/GBC/SMS/GG/Genesis) get the SAME * arm-side canonicalization so arming a mirror-form address matches the - * canonical-form writer (the common agent mistake). ⚠ Their core hooks + * canonical-form writer (the common agent mistake). Their core hooks * compare RAW bus addresses (only snes9x canonicalizes live accesses), so * a WRITER that itself uses a mirror form still evades on those platforms * - fixing that direction needs per-core hook patches (deferred; noted in @@ -2716,8 +2772,8 @@ export class LibretroHost { // interrupt raising). Without it, each "frame" of the call runs the // game's OWN per-frame logic concurrently (VBlank handlers via RAM // vectors etc.), which can stomp the buffer the driven routine is - // writing - a real session diffed a CORRECT codec reimplementation - // against that poisoned output for hours. gpgx (Genesis/SMS/GG) only. + // writing, so a CORRECT codec reimplementation can look wrong when + // diffed against that output. gpgx (Genesis/SMS/GG) only. pure = false, // presetMemory: [{addr, bytes}] CPU-space writes applied before the call // (codecs that read a global from RAM - a dest stride, a mode flag, etc). @@ -2787,7 +2843,7 @@ export class LibretroHost { } // Set caller-supplied registers. // regs accepts NAMES ('a','x','y','p','sp',..., per the platform's regNames - // map) OR raw numeric ids - field report: no 65816 reg-id table meant a + // map) OR raw numeric ids; without a 65816 reg-id table a // caller couldn't preset A without guessing. A name with no mapping, or a // non-numeric key on a platform without regNames, throws clearly. for (const [key, val] of Object.entries(regs)) { @@ -2920,7 +2976,7 @@ export class LibretroHost { // Use the platform's REAL register file (getCPUState decodes per-core: A/X/Y/ // P/DB/DP on 65816, D0-D7/A0-A7 on m68k, ...). The old _readCallRegs hardcoded // m68k names {D0,D1,A0,A1,PC,SP}, so on a 65816 core the values came back - // under WRONG labels - a caller couldn't read A/X/Y/P (field report). Fall + // under WRONG labels - a caller couldn't read A/X/Y/P. Fall // back to the raw m68k-id read only if the per-core decode is unavailable. try { const st = getCPUState(this, this._loadArgs?.platform); @@ -3047,8 +3103,8 @@ export class LibretroHost { case "snes": // 65816: A=0,X=1,Y=2,P=3,S=4,DB=5,D=6,PC=16. retBytes DEFAULTS to 3 for a // JSL/RTL callee; a JSR/RTS callee pushes only 2 (PCL,PCH) - pass - // callMode:'jsr' to size the sentinel/return-pop to 2 (field report: a - // plain jsr helper "returned" 1 byte off into vector-stub land). The + // callMode:'jsr' to size the sentinel/return-pop to 2 (otherwise a + // plain jsr helper "returns" 1 byte off into vector-stub land). The // 65816 stack is in bank 0; WRAM low mirror. ~3.58MHz / ~6 cyc / 60 ≈ 10k. return { spReg: 4, pcReg: 16, retBytes: 3, retBigEndian: false, defaultSentinel: 0, ramMask: 0x1FFF, retAdjust: -1, instrPerFrame: 12000, regNames: { a: 0, x: 1, y: 2, p: 3, s: 4, sp: 4, db: 5, d: 6, dp: 6, pc: 16 }, @@ -3187,6 +3243,106 @@ export class LibretroHost { } } + // ── instruction trace (free-running, exact) ──────────────────────────────── + // Every EXECUTED instruction's pc (and the core's clock at dispatch) in + // order, recorded by the core while it runs normally. stepInstruction is not + // a substitute: it freezes the CPU while the rest of the machine finishes the + // frame, so consecutive stepped instructions are a frame apart in machine + // time and every interrupt/poll lands somewhere else. + + /** True when this core build records the instruction trace (romdev_trace_*). */ + traceSupported() { + const mod = this.mod; + return !!(mod && typeof mod._romdev_trace_set === "function" && typeof mod._romdev_trace_info === "function"); + } + + /** + * Which dispatching CPUs the trace records for the loaded platform: bit 0 = + * the main CPU. genesis_plus_gx dispatches its Z80 as cpu 1, which is the + * MAIN CPU on SMS / Game Gear. + */ + traceCpuMask() { + const p = this.status.platform; + return p === "sms" || p === "gg" || p === "sg1000" ? 2 : 1; + } + + /** + * Arm (restart) or disarm the trace. The count restarts at 0. + * `registers:true` adds the core's per-instruction register columns + * (traceRegisterNames()) where the core provides them. + * @param {{capacity?:number, enabled?:boolean, cpuMask?:number, registers?:boolean}} [o] + * @returns {number} the ring capacity allocated (entries) + */ + setTrace({ capacity = 1 << 20, enabled = true, cpuMask, registers = false } = {}) { + const mod = this._needMod(); + if (!this.traceSupported()) throw new Error("this core build does not record an instruction trace (rebuild with romdev_trace_* exports)."); + if (typeof mod._romdev_trace_regs === "function") mod._romdev_trace_regs(registers ? 1 : 0); + return mod._romdev_trace_set(capacity >>> 0, enabled ? 1 : 0, (cpuMask ?? this.traceCpuMask()) >>> 0) >>> 0; + } + + /** Names of the register columns this core records with setTrace({registers:true}). */ + traceRegisterNames() { + const p = this.status.platform; + if (p === "gba") return [...Array.from({ length: 16 }, (_, i) => `r${i}`), "cpsr"]; + // gambatte: af (A << 8 | F) is the fifth column; an older build records + // four and readTrace keeps only the columns the core wrote + if (p === "gb" || p === "gbc") return ["sp", "hl", "bc", "de", "af"]; + if (p === "nes") return ["a", "x", "y", "s", "p"]; + // genesis_plus_gx: one filler for both CPUs (17 columns); the 68000's + // d0-d7, a0-a7 (a7 = the active stack pointer), sr, or on SMS / Game Gear + // the Z80's (r as LD A,R reads it; af2.. = the alternate set; the rest 0). + if (p === "genesis" || p === "md") return [...Array.from({ length: 8 }, (_, i) => `d${i}`), ...Array.from({ length: 8 }, (_, i) => `a${i}`), "sr"]; + if (p === "sms" || p === "gg") return ["af", "bc", "de", "hl", "ix", "iy", "sp", "r", "af2", "bc2", "de2", "hl2", "i"]; + // snes9x: p = the status byte as PHP pushes it, emulation flag at bit 8. + if (p === "snes") return ["a", "x", "y", "s", "d", "db", "p"]; + return []; + } + + /** @returns {{enabled:boolean, capacity:number, count:number, ptr:number, cpuMask:number, words:number, regs:number}} */ + traceInfo() { + const mod = this._needMod(); + if (!this.traceSupported()) throw new Error("this core build does not record an instruction trace."); + const p = mod._malloc(28); + try { + new Uint32Array(mod.HEAPU8.buffer, p, 7).fill(0); + mod._romdev_trace_info(p); + const u = new Uint32Array(mod.HEAPU8.buffer, p, 7); + return { enabled: !!u[0], capacity: u[1], count: u[2], ptr: u[3], cpuMask: u[4], words: u[5] || 2, regs: u[6] }; + } finally { mod._free(p); } + } + + /** + * Read recorded entries [from, to) (indices since setTrace). Entries older + * than count - capacity were overwritten; `from` is raised to the oldest + * surviving one and `lost` says how many were asked for but gone. + * @param {number} [from=0] + * @param {number} [to] default: everything recorded so far + * `regs` (when the trace was armed with registers) maps each + * traceRegisterNames() column to a Uint32Array parallel to `pc`. + * @returns {{from:number, to:number, lost:number, pc:Uint32Array, clock:Uint32Array, regs:Record|null}} + */ + readTrace(from = 0, to) { + const info = this.traceInfo(); + const end = Math.min(to ?? info.count, info.count); + const oldest = Math.max(0, info.count - info.capacity); + const start = Math.max(from, oldest); + const n = Math.max(0, end - start); + const W = info.words; + const pc = new Uint32Array(n), clock = new Uint32Array(n); + const names = W > 2 ? this.traceRegisterNames().slice(0, W - 2) : []; + const cols = names.map(() => new Uint32Array(n)); + if (n && info.ptr) { + const ring = new Uint32Array(this.mod.HEAPU8.buffer, info.ptr, info.capacity * W); + for (let k = 0; k < n; k++) { + const i = ((start + k) % info.capacity) * W; + pc[k] = ring[i]; clock[k] = ring[i + 1]; + for (let c = 0; c < cols.length; c++) cols[c][k] = ring[i + 2 + c]; + } + } + const regs = names.length ? Object.fromEntries(names.map((nm, c) => [nm, cols[c]])) : null; + return { from: start, to: start + n, lost: Math.max(0, Math.min(start, end) - from), pc, clock, regs }; + } + logPCRange(lo, hi, frames) { const mod = this._needMod(); this._needMedia(); @@ -3363,7 +3519,7 @@ export class LibretroHost { _emptyRegionError(region) { const plat = this.status && this.status.platform; - // SRAM gets an honest, specific answer: empty save_ram almost always means + // SRAM gets a specific answer: empty save_ram almost always means // "this cart/system has no battery save," NOT "the core is broken." if (region === "save_ram") { if (["atari2600", "atari7800", "lynx"].includes(plat)) { @@ -3397,13 +3553,13 @@ export class LibretroHost { sms: { video_ram: "sms_vram (or sms_cram for palette, sms_vdp_regs for VDP regs)" }, gg: { video_ram: "gg_vram (or gg_cram for the 64-byte 12-bit palette, sms_vdp_regs for VDP regs)" }, snes: { video_ram: "snes_oam (sprite OAM), snes_cgram (palette), snes_aram (SPC700), or snes_fillram (PPU/DMA reg shadow). The libretro generic 'video_ram' id isn't wired in snes9x." }, - genesis: { video_ram: "Genesis VRAM IS exposed via 'video_ram' (gpgx) once a ROM is loaded and a frame has run - if it reads empty, step a frame first (the SAT/sprites need the game to have written VRAM). Palette/scroll/VDP regs are genesis_cram / genesis_vsram / genesis_vdp_regs. For decoded views use inspectSprites / inspectPatternTiles / inspectBackgroundMap / getRenderingContext." }, + genesis: { video_ram: "Genesis VRAM IS exposed via 'video_ram' (gpgx) once a ROM is loaded and a frame has run - if it reads empty, step a frame first (the SAT/sprites need the game to have written VRAM). Palette/scroll/VDP regs are genesis_cram / genesis_vsram / genesis_vdp_regs. For decoded views use sprites({op:'inspect'}) / tiles({op:'png'}) / background({view:'map'}) / background({view:'renderState'})." }, c64: { video_ram: "c64_color_ram (1 KB) / c64_vic_regs / c64_sid_regs / c64_cia1_regs / c64_cia2_regs. The C64 has no separate VRAM - the VIC-II reads from main system_ram." }, }; const hint = suggestions[plat] && suggestions[plat][region]; if (hint) { return `memory region '${region}' is empty on platform '${plat}'. Try: ${hint}. ` + - `Or use inspectPatternTiles / inspectBackgroundMap / inspectSprites / inspectPalette which abstract over per-platform memory layout.`; + `Or use tiles({op:'png'}) / background({view:'map'}) / sprites({op:'inspect'}) / palette({source:'live'}), which abstract over per-platform memory layout.`; } return `memory region '${region}' is empty (core didn't expose it on platform '${plat || "?"}'). ` + `If you need raw bytes, see the platform-specific regions in src/host/types.js or the inspect* tools which know the right region per platform.`; diff --git a/packages/romdev-core-host/README.md b/packages/romdev-core-host/README.md index 404fa42d..39e00b08 100644 --- a/packages/romdev-core-host/README.md +++ b/packages/romdev-core-host/README.md @@ -3,14 +3,14 @@ The [romdev](https://github.com/monteslu/romdev) libretro host runtime, published standalone: load a `romdev-core-*` emulator core (WASM), run frames, read the framebuffer / audio / memory, drive input, save and load -state. This is the SAME host the romdev MCP server runs (the server consumes -this package too), so there is exactly one host implementation in the -ecosystem. Bundles NO cores; pass any `romdev-core-*` package. +state. This is the same host the romdevtools MCP server runs (the server +consumes this package too), so there is one host implementation. It bundles no +cores; pass any `romdev-core-*` package. -**Isomorphic**: the core surface has no top-level `node:` imports and no -pngjs. Under Node you load cores and ROMs by path; in a browser or worker -bundle you pass the Emscripten factory + wasm bytes and ROM bytes, and the -same host runs unchanged (see "Browser / bytes-only use" below). +The same code runs in Node and in a browser: the core surface has no top-level +`node:` imports and no pngjs. Under Node you load cores and ROMs by path; in a +browser or worker bundle you pass the Emscripten factory, the wasm bytes and the +ROM bytes, and the same host runs unchanged (see "Browser / bytes-only use" below). ```js import { LibretroHost } from "romdev-core-host"; @@ -83,8 +83,9 @@ write watchpoints, read watches, PC breakpoints, `runUntilPC(addr)` / (`exportDiskImage`, `importDiskImage`, `putDiskFile`). MSX: the bundled open C-BIOS system dir resolves automatically. The 3D cores (N64, PS1, Dreamcast) hardware-render through a headless GL context: pass -`{ hwRender: true }` to `loadCore` and install the optional `native-gles` -dependency; the software-rendered cores need neither. native-gles 0.6.0+ +`{ hwRender: true }` to `loadCore`. `native-gles` and `webgl-node` are regular +dependencies of this package and load lazily, only when a hardware-rendered +core boots; the software-rendered cores never touch GL. native-gles 0.6.0+ is multi-context: each core owns the context it renders into (created for it via webgl-node) and re-asserts it before every frame, so several GL consumers - more cores, an active-bezel compositor, a wasmcart cart - can @@ -152,21 +153,47 @@ For the full agent tooling surface (MCP server, build toolchains, disassembly, playtest) see [`romdevtools`](https://www.npmjs.com/package/romdevtools). -## 0.13.1 - exact PC coverage bitmap - -`pcBitmapSupported()` / `logPCBitmap(lo, hi, frames, {shift})`: on a core -built with the 0.13.0 shared debug lib (`romdev_covbits_set/get`), run -`frames` frames recording EVERY executed PC in `[lo, hi)` as one bit per PC - -O(1) per instruction, no distinct-PC cap - and return `{pcs, distinct, total, -words, shift, granularityBytes, exact}`. The bit granularity is `1 << shift` -bytes and defaults to `pcAlignShift()` for the loaded platform: 2 (word) on -MIPS (n64, ps1, psp), 1 (halfword) on the 68000 / Thumb / SH-4 machines -(genesis, gba, dreamcast, sync32), 0 (byte) on every byte-addressed CPU (6502, -Z80, SM83, 65816, HuC6280, W65C02) and when the platform is unknown. The core -reports the shift it recorded at; `exact` is false only when a caller asked for -a granularity coarser than the CPU's instruction alignment. `logPCRange` is -the older 8192-entry distinct ring (`romdev_cov_set/get`), still exported by -every core. Every romdev core carries the bitmap. +## Coverage, instruction trace and clock + +These are feature-detected like the rest of the debug tier. + +**PC coverage.** `pcBitmapSupported()` / `logPCBitmap(lo, hi, frames, {shift})` +runs `frames` frames and records every executed PC in `[lo, hi)` as one bit, +with no cap on distinct PCs, returning `{pcs, distinct, total, words, shift, +granularityBytes, exact}`. The granularity defaults to `pcAlignShift()` for the +loaded platform: word on MIPS (n64, ps1), halfword on the 68000, Thumb and SH-4 +machines (genesis, gba, dreamcast, sync32), byte on the 8-bit CPUs. +`logPCRange(lo, hi, frames)` is the older 8192-entry distinct-PC log. + +**Instruction trace.** Every executed instruction's PC, and the core's clock at +dispatch, in order, recorded while the core runs normally (unlike +`stepInstruction()`, which freezes the CPU while the rest of the machine +finishes the frame). + +- `traceSupported()`: whether the loaded core build records a trace. +- `traceCpuMask()`: which dispatching CPUs to record for the platform (bit 0 is + the main CPU; on SMS and Game Gear the Z80 is cpu 1 in genesis_plus_gx). +- `setTrace({capacity, enabled, cpuMask, registers})`: arm, restart or disarm + the ring; returns the capacity allocated. `registers: true` adds + per-instruction register columns where the core provides them. +- `traceRegisterNames()`: those columns for the platform (NES, GB/GBC, GBA, + Genesis, SMS/GG, SNES). +- `traceInfo()`: `{enabled, capacity, count, cpuMask, ...}`. +- `readTrace(from, to)`: `{from, to, lost, pc, clock, regs}` as typed arrays; + entries already overwritten in the ring are counted in `lost`. + +**Pinned clock.** `setPinnedClock({baseMs, stepMs, startRun})` pins the wall +clock a core reads (for example a cartridge real-time clock) to a frame clock, +`baseMs + runs * stepMs` in UTC, so two runs see the same time. Set it before +`loadMedia`; `setPinnedClock(null)` restores the host clock. + +**Additional memory regions.** On sync32: `sync32_timing` (0x1A3, per-frame +cycle counts) and `sync32_profile` (0x1A4, a writable PC-sampling profiler). +On gambatte: `gb_apu_raw` (the APU's stereo samples before resampling) and +`gb_lcdlog` (a ring of LCD timing decisions). On mGBA: `gba_audio_raw` (the +stereo samples before resampling). On Genesis carts with the SVP chip: +`genesis_svp_dram`, `genesis_svp_iram` and `genesis_svp_ssp` (size 0 on carts +without it). Region names map to ids through `MemoryRegionToRetro`. ## Deterministic GB/GBC/NES sessions @@ -179,7 +206,7 @@ slot numbers across gaps. Deterministic input accepts the eight native buttons. See `romdevtools/scripts/multiplayer/README.md` for the fixed session identities, frame-boundary restrictions, compiler records, reproducible builds and tests. -## Logical world observation (0.16.0) +## Logical world observation `startWorldObservation({trigger, tick, fields, value: 0xa5})` binds an explicit ROM publication write on GB/GBC/NES. After updating the world, the engine writes diff --git a/packages/romdev-core-host/cpu-state.js b/packages/romdev-core-host/cpu-state.js index 52d0b95c..c4c5baec 100644 --- a/packages/romdev-core-host/cpu-state.js +++ b/packages/romdev-core-host/cpu-state.js @@ -352,6 +352,22 @@ function decodeZ80(bytes) { * @param {string} [cpu] "main" (default) or "spc700" for SNES * @returns {CPUState | null} */ +/** `n` u32 LE words of a region, or null when this core build lacks it. */ +function readU32s(host, region, n) { + try { + if (!(host.regionSize?.(region) >= n * 4)) return null; + const b = host.readMemory(region, 0, n * 4); + const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); + return Array.from({ length: n }, (_, i) => dv.getUint32(i * 4, true) >>> 0); + } catch { return null; } +} + +/** mGBA's master clock (gba_timing), as `coreInternal`, when the core has it. */ +function gbaTiming(host) { + const t = readU32s(host, "gba_timing", 4); + return t ? { coreInternal: { masterClock: t[0], cpuCycles: t[1], nextEvent: t[2], masterCycles: t[3] } } : {}; +} + export function getCPUState(host, platform, cpu = "main") { if (platform === "n64" || platform === "ps1") { return decodeMips(host.getMipsRegs?.()); @@ -366,7 +382,10 @@ export function getCPUState(host, platform, cpu = "main") { if (platform === "snes") { const state = host.serializeState(); if (cpu === "spc700") return decodeSnes9xSPC(state); - return decodeSnes9xCPU(state); // 65816 + const st = decodeSnes9xCPU(state); // 65816 + const t = readU32s(host, "snes_timing", 5); + if (t) st.coreInternal = { ...(st.coreInternal ?? {}), masterClock: t[0], lineCycles: t[1], vCounter: t[2], hMax: t[3], totalFrames: t[4] }; + return st; } if (platform === "genesis") { if (cpu === "z80") { @@ -486,6 +505,11 @@ export function getCPUState(host, platform, cpu = "main") { ime: !!bytes[12], halted: !!bytes[13], }, + // Bytes 14-17 are gambatte's CPU clock (cycleCounter_) on cores built + // with it (0 on older builds, where they were reserved). + coreInternal: { + cycleCounter: (bytes[14] | (bytes[15] << 8) | (bytes[16] << 16) | (bytes[17] << 24)) >>> 0, + }, }; } if (platform === "gba") { @@ -531,6 +555,7 @@ export function getCPUState(host, platform, cpu = "main") { spsr: hex32(spsr), note: "ARM PC is pipeline-prefetched; the executing instruction is at execPc " + "(PC-8 in ARM, PC-4 in THUMB). Registers are decimal; cpsr/spsr/execPc are hex.", + ...gbaTiming(host), }; } if (platform === "sync32") { @@ -564,6 +589,26 @@ export function getCPUState(host, platform, cpu = "main") { if (bits !== 0) fpu["S" + i] = asFloat(bits); } const itstate = u32(49); + // Frame timing from the core's deterministic cycle model (sync32_timing, + // absent on older core builds): the last frame's work cycles against the + // ABI floor. The floor is the console's guarantee (150 MHz-equivalent); + // shipping boards clock core 0 at 252 or 315 MHz, so those budgets are + // reported too, as context. + const tm = readU32s(host, "sync32_timing", 10); + const timing = tm && tm[0] === 0x54323353 ? (() => { + const floor = tm[2], mhz = tm[3], fc = tm[5]; + const budget = (m) => Math.round(floor * m / mhz); + return { + frameCycles: fc, + framesPresented: tm[4], + totalCycles: tm[6] + tm[7] * 2 ** 32, + floorCycles: floor, + floorClockMHz: mhz, + pctOfFloor: Math.round(fc / floor * 10000) / 100, + budgets: { floor150MHz: floor, mhz252: budget(252), mhz315: budget(315) }, + note: "frameCycles = CPU cycles the cart spent between the previous present() and this one (the vblank wait excluded), from s32core's cycle model; costs are estimates until calibrated on hardware (no flash wait-state or XIP cache model).", + }; + })() : null; return { pc: gprs[15], sp: gprs[13], @@ -578,6 +623,7 @@ export function getCPUState(host, platform, cpu = "main") { // touches the FPU stays readable. ...(Object.keys(fpu).length ? { fpu } : {}), ...(itstate ? { itstate: hex32(itstate) } : {}), + ...(timing ? { coreInternal: timing } : {}), note: "Cortex-M33 is always Thumb. PC is the NEXT instruction to execute " + "(this is an interpreter, so there is no pipeline offset to undo). " + "Registers are decimal; flags.raw is the packed APSR (N|Z|C|V|Q in bits 4..0). " + diff --git a/packages/romdev-core-host/dsp-state.js b/packages/romdev-core-host/dsp-state.js index d8463d63..0d351dad 100644 --- a/packages/romdev-core-host/dsp-state.js +++ b/packages/romdev-core-host/dsp-state.js @@ -1,6 +1,6 @@ // SNES S-DSP state introspection. // -// Per the rom-games agent's audio-debugging asks: distinguish "voice +// Purpose: distinguish "voice // never produced output" (BRR/envelope issue) from "voice produced // output but mixer muted it" (master volume issue). The data lives in // the savestate's "SND" block, AFTER the SMP::save_state region. We @@ -156,7 +156,7 @@ export function decodeSnes9xDSP(state) { // rather than `kon` / `koff` / `endx` (state names) so callers don't // mistake the byte for a live interpretation. Field names are still // memorable (the address IS the canonical DSP register name) but - // semantically honest about what you're reading. + // semantically accurate about what you're reading. // // Source: snes9x/src/apu/bapu/dsp/SPC_DSP.h r_* constants; .cpp KON/ // ENDX special-case write handling at lines 285-291. diff --git a/packages/romdev-core-host/gamegenie.js b/packages/romdev-core-host/gamegenie.js index bd005e37..3422229f 100644 --- a/packages/romdev-core-host/gamegenie.js +++ b/packages/romdev-core-host/gamegenie.js @@ -114,7 +114,7 @@ export function encodeNesGameGenie({ address, value, compare }) { * (GATKGATX-style spellings) is a mis-published code, not a convention. * An earlier version left it clear on the strength of that outlier, * which made every emitted 8-letter code differ from its canonical - * published spelling by exactly this bit (SLZPLOVS for Contra's + * published spelling by exactly this bit (SLZPLOVS for a published * SLXPLOVS, and so on). * * Decoders are forgiving - fceumm branches on length and masks the bit @@ -433,7 +433,7 @@ export function decodeProActionReplay(code, platform) { * Returns one of: "game-genie", "pro-action-replay", "gameshark", * "action-replay", "raw", or "unknown". Per-platform, because the SAME shape * means different devices on different systems (8 hex = SNES PAR, but on GB = - * GameShark). This is what lets us be HONEST about device type. */ + * GameShark). This is what lets the device type be reported accurately. */ export function detectDevice(code, platform) { const c = code.trim(); if (c.includes(":")) return "raw"; @@ -593,7 +593,7 @@ export function encodeRaw({ address, value, compare }) { } // Which physical cheat DEVICE each platform's "native" code is for. This is the -// honesty layer: we don't call everything "Game Genie" - SNES native is Pro +// Accuracy layer: do not call everything "Game Genie" - SNES native is Pro // Action Replay, SMS/GG is Action Replay, GB has both GG (ROM) and GameShark // (RAM). `nativeDevicesFor` lists them best-first. export function nativeDevicesFor(platform) { diff --git a/packages/romdev-core-host/gametank-acp-state.js b/packages/romdev-core-host/gametank-acp-state.js index 5b2f66ec..50f988b4 100644 --- a/packages/romdev-core-host/gametank-acp-state.js +++ b/packages/romdev-core-host/gametank-acp-state.js @@ -26,7 +26,7 @@ export function decodeGameTankAcp(a) { const clkMult = a[9] & 0xFF; // "playing" = the audio CPU is running, not muted/resetting, and the DAC isn't - // parked at the midpoint silence ($80) - a coarse but honest activity signal. + // parked at the midpoint silence ($80) - a coarse but real activity signal. const playing = running && !muted && !resetting && dacReg !== 0x80; return { diff --git a/packages/romdev-core-host/glOptionalDep.js b/packages/romdev-core-host/glOptionalDep.js index 44723aac..6ec07c07 100644 --- a/packages/romdev-core-host/glOptionalDep.js +++ b/packages/romdev-core-host/glOptionalDep.js @@ -1,20 +1,20 @@ -// glOptionalDep.js - lazy, optional loader for the native GL stack. +// glOptionalDep.js - lazy loader for the native GL stack. // // The HW-render cores (N64 ParaLLEl, PS1 Beetle-PSX) need a real headless GL // context. romdev provides it through `native-gles` (EGL/GLES via a prebuilt // .node) and `webgl-node` (a WebGL2 context object for the minified Emscripten -// cores). Both are OPTIONAL dependencies: the 14 software-rendered cores never -// touch them, and a headless user who never boots N64/PS1 doesn't need them -// installed. We load them lazily and, if absent, throw ONE clear, actionable -// error instead of a cryptic module-not-found. +// cores). Both are regular dependencies of this package. They are loaded lazily, +// only when a HW-render core boots, so the software-rendered cores never load +// them; if the install is broken, ONE clear, actionable error replaces a cryptic +// module-not-found. let _gl = null; let _webgl = null; const INSTALL_HINT = - "N64/PS1 emulation needs the optional native GL module. Install it with:\n" + - " npm install native-gles webgl-node\n" + - "(the other 14 platforms are software-rendered and don't require it)."; + "N64/PS1/Dreamcast emulation needs the native GL modules (native-gles, webgl-node),\n" + + "which are dependencies of romdev-core-host but did not load. Reinstall them with:\n" + + " npm install native-gles webgl-node"; /** * Load the `native-gles` default export (the EGL/GLES binding). Cached. diff --git a/packages/romdev-core-host/gpgx-state.js b/packages/romdev-core-host/gpgx-state.js index d1ef3601..750d140e 100644 --- a/packages/romdev-core-host/gpgx-state.js +++ b/packages/romdev-core-host/gpgx-state.js @@ -252,7 +252,7 @@ export function decodeGenesisPSG(blob) { // // gpgx's YM2612 internal struct is large and implementation-private. We // decode what's safely reachable: the dacen flag + dacout value (DAC sample -// stream - the "PCM voice" Genesis games like Streets of Rage 2 use). Full +// stream - the "PCM voice" many Genesis games use). Full // per-channel envelope state requires walking FM_CH/FM_SLOT internals // whose layout isn't stable across gpgx versions; that's deferred. // diff --git a/packages/romdev-core-host/nes-apu-state.js b/packages/romdev-core-host/nes-apu-state.js index 391820bf..efe4bebd 100644 --- a/packages/romdev-core-host/nes-apu-state.js +++ b/packages/romdev-core-host/nes-apu-state.js @@ -1,6 +1,6 @@ // NES 2A03 APU state introspection. // -// Per the rom-games music-analysis asks: give NES titles the same "what is +// Gives NES titles the same "what is // each channel playing this frame?" decode that getAudioState already gives // SNES (dsp) and Genesis (psg/ym2612). Before this, an NES music job had to // reverse-engineer the game's private sound-driver RAM by hand; now the diff --git a/packages/romdev-core-host/package.json b/packages/romdev-core-host/package.json index 8d581ad3..67b8e2b9 100644 --- a/packages/romdev-core-host/package.json +++ b/packages/romdev-core-host/package.json @@ -1,7 +1,7 @@ { "name": "romdev-core-host", - "version": "0.16.0", - "description": "The romdev libretro host runtime, now ISOMORPHIC: load a romdev-core-* emulator core from disk (Node) or from a factory + wasm bytes (browser/worker), run frames, read the framebuffer/audio/memory regions as typed arrays, drive input, save/load state. The same hardened host the romdev MCP server uses.", + "version": "0.14.1", + "description": "The romdev libretro host runtime for Node and the browser: load a romdev-core-* emulator core from disk (Node) or from a factory + wasm bytes (browser/worker), run frames, read the framebuffer/audio/memory regions as typed arrays, drive input, save/load state. The same hardened host the romdev MCP server uses.", "type": "module", "main": "index.js", "exports": { diff --git a/packages/romdev-core-host/types.js b/packages/romdev-core-host/types.js index d6db36ef..af925432 100644 --- a/packages/romdev-core-host/types.js +++ b/packages/romdev-core-host/types.js @@ -11,21 +11,22 @@ * | "snes_oam" | "snes_cgram" | "snes_aram" | "snes_fillram" * | "genesis_cram" | "genesis_vsram" | "genesis_vdp_regs" * | "genesis_z80_ram" | "genesis_m68k" | "genesis_ym2612" | "genesis_psg" + * | "genesis_svp_dram" | "genesis_svp_iram" | "genesis_svp_ssp" * | "md_linepix" | "md_bgpix" | "md_objpix" | "md_pixrgb" | "md_linestate" * | "sms_linepix" | "sms_bgpix" | "sms_objpix" | "sms_pixrgb" | "sms_linestate" * | "gg_linepix" | "gg_bgpix" | "gg_objpix" | "gg_pixrgb" | "gg_linestate" * | "sms_vram" | "sms_cram" | "sms_vdp_regs" | "sms_z80_regs" - * | "gg_vram" | "gg_cram" + * | "gg_vram" | "gg_cram" | "gpgx_blip_deltas" * | "gb_vram" | "gb_oam" | "gb_io" | "gb_hram" * | "gb_bgpdata" | "gb_objpdata" | "gb_cpu_regs" * | "gb_lineregs" | "gb_bgpix" | "gb_sprpix" | "gb_palline" - * | "gb_bgcol15" | "gb_sprcol15" + * | "gb_bgcol15" | "gb_sprcol15" | "gb_lcdlog" | "gb_apu_raw" * | "a26_tia_regs" | "a26_cpu_regs" * | "a78_cpu_regs" * | "c64_color_ram" | "c64_vic_regs" | "c64_sid_regs" * | "c64_cia1_regs" | "c64_cia2_regs" | "c64_cpu_regs" - * | "gba_cpu_regs" | "gba_io_regs" | "gba_palette" | "gba_oam" | "gba_iwram" - * | "sync32_cpu_regs" | "sync32_palette" | "sync32_canvas" + * | "gba_cpu_regs" | "gba_io_regs" | "gba_palette" | "gba_oam" | "gba_iwram" | "gba_audio_raw" + * | "sync32_cpu_regs" | "sync32_palette" | "sync32_canvas" | "sync32_timing" | "sync32_profile" * | "lynx_cpu_regs" | "lynx_hw_regs" * | "pce_vdc_vram" | "pce_vdc_satb" | "pce_vdc_regs" * | "pce_vce_palette" | "pce_cpu_regs" | "pce_psg_regs" @@ -102,6 +103,18 @@ export const RetroMemory = { SNES_CLIPLINES: 0x1B5, SNES_LP_WORLD: 0x1B6, SNES_LP_OBJ: 0x1B7, + /** 20 bytes, 5 u32 LE: [0] master clock since line 0 (V_Counter*H_Max + Cycles), + * [1] CPU.Cycles, [2] CPU.V_Counter, [3] Timings.H_Max, [4] TotalEmulatedFrames. */ + SNES_TIMING: 0x1B8, + /** The active coprocessor's internal state, serialized on read by the same + * romdev_chipstate.h the recompiled cart's chip units compile (DSP-3, ST011, + * ST018, S-RTC, SPC7110, BS-X); size 0 on any other cart. */ + SNES_CHIPSTATE: 0x1B9, + /** The BS-X's 512KB PSRAM (where the BIOS loads a BS program); BS-X carts only. */ + SNES_BSX_PSRAM: 0x1BA, + // bsnes (romdev-core-bsnes) only: every S-CPU access to a firmware chip + // (ST010/ST011/ST018) with the master clock, a ring the cross-check replays + SNES_CHIPLOG: 0x1BB, GENESIS_CRAM: 0x120, GENESIS_VSRAM: 0x121, GENESIS_VDP_REGS: 0x122, @@ -121,6 +134,17 @@ export const RetroMemory = { SMS_Z80_REGS: 0x133, GG_VRAM: 0x134, GG_CRAM: 0x135, + /** RDAS per-frame event stream (s32 x 3, rate 0): every blip_add_delta on + * the main blip buffer this retro_run as (blip clock time, delta_l, delta_r) + * - the FM + PSG input to blip_buf BEFORE band-limited resampling. Shared by + * the genesis / sms / gg platforms (all genesis_plus_gx). */ + GPGX_BLIP_DELTAS: 0x136, + /** SVP carts (gpgx cart_hw/svp): the SSP1601 DRAM (128KB of host-order + * 16-bit words), its 2KB IRAM and the ssp1601_t state. Absent (size 0) + * on a cart without the chip. */ + GENESIS_SVP_DRAM: 0x137, + GENESIS_SVP_IRAM: 0x138, + GENESIS_SVP_SSP: 0x139, GB_VRAM: 0x140, GB_OAM: 0x141, GB_IO: 0x142, @@ -135,6 +159,10 @@ export const RetroMemory = { GB_PALLINE: 0x14A, GB_BGCOL15: 0x14B, GB_SPRCOL15: 0x14C, + GB_LCDLOG: 0x14D, + /** RDAS per-frame audio stream: every stereo s16 sample frame PSG::fillBuffer + * produced this retro_run at 2097152 Hz, BEFORE blipper / the CC resampler. */ + GB_APU_RAW: 0x14E, A78_CPU_REGS: 0x150, A26_TIA_REGS: 0x160, A26_CPU_REGS: 0x161, @@ -152,17 +180,36 @@ export const RetroMemory = { GBA_PALETTE: 0x182, GBA_OAM: 0x183, GBA_IWRAM: 0x184, + /** 16 bytes, 4 u32 LE: [0] master clock (mTimingCurrentTime), [1] cpu->cycles, + * [2] cpu->nextEvent, [3] timing.masterCycles. Assembled on read. */ + GBA_TIMING: 0x185, + /** RDAS per-frame audio stream (src/host/audio-verify.js AUDIO_STREAM): the + * stereo s16 samples GBAAudioSample produced this retro_run, at the native + * 16777216/sampleInterval Hz, BEFORE libretro's resampler to 65536 Hz. */ + GBA_AUDIO_RAW: 0x186, // Lynx (handy): CPU snapshot + the $FC00-$FDFF Suzy/Mikey HW register window // (sprite regs, LCD control, audio $FD20-$FD3F, palette $FDA0-$FDBF). LYNX_CPU_REGS: 0x190, LYNX_HW_REGS: 0x191, - // sync32 (s32core). The console is monteslu's own, so the core exposes + // sync32 (s32core). sync32 is a homebrew-only console, so the core exposes // exactly what a game DEVELOPER needs to debug their own cart - there are no // commercial ROMs here to reverse-engineer. SYNC32_CPU_REGS: 0x1A0, // Cortex-M33: r0-r15, APSR, s0-s31, ITSTATE SYNC32_PALETTE: 0x1A1, // 256 entries, RGB565 SYNC32_CANVAS: 0x1A2, // the 320x240 8-bit indexed framebuffer + /** Frame timing, u32 LE: [0] 'S32T', [1] layout version, [2] ABI floor + * cycles per frame, [3] floor clock MHz, [4] frames presented, [5] last + * frame's work cycles, [6..7] total cycles lo/hi, [8] history capacity, + * [9] frames recorded; [16..] ring of per-frame work cycles, recorded + * frame k (1-based) at 16 + (k - 1) % capacity. */ + SYNC32_TIMING: 0x1A3, + /** pc-sampling profiler, u32 LE, WRITABLE control block: [0] 'S32P', + * [1] enable, [2] base address, [3] shift, [4] bucket count, [5] active + * (core-set), [6] clear request, [7] frames profiled; [16..] buckets of + * CPU cycles, bucket (pc - base) >> shift, the last one also collecting + * every pc outside the window. The vblank idle snap is excluded. */ + SYNC32_PROFILE: 0x1A4, // Sprite sheets 0..31 at 0x1B0+n: 8-bit indices into the palette. sync32 has // no OAM - a game blits from these with api->sprite() - so the sheets ARE // the sprite data. Only sheet0 is named here; the rest are reachable by id. @@ -261,6 +308,10 @@ export const MemoryRegionToRetro = { snes_cliplines: RetroMemory.SNES_CLIPLINES, snes_lp_world: RetroMemory.SNES_LP_WORLD, snes_lp_obj: RetroMemory.SNES_LP_OBJ, + snes_timing: RetroMemory.SNES_TIMING, + snes_chipstate: RetroMemory.SNES_CHIPSTATE, + snes_bsx_psram: RetroMemory.SNES_BSX_PSRAM, + snes_chiplog: RetroMemory.SNES_CHIPLOG, genesis_cram: RetroMemory.GENESIS_CRAM, genesis_vsram: RetroMemory.GENESIS_VSRAM, genesis_vdp_regs: RetroMemory.GENESIS_VDP_REGS, @@ -268,6 +319,9 @@ export const MemoryRegionToRetro = { genesis_m68k: RetroMemory.GENESIS_M68K, genesis_ym2612: RetroMemory.GENESIS_YM2612, genesis_psg: RetroMemory.GENESIS_PSG, + genesis_svp_dram: RetroMemory.GENESIS_SVP_DRAM, + genesis_svp_iram: RetroMemory.GENESIS_SVP_IRAM, + genesis_svp_ssp: RetroMemory.GENESIS_SVP_SSP, /* gpgx resolved-layer capture (shared line renderer, so the same core * regions serve genesis/sms/gg; per-platform aliases below). */ md_linepix: RetroMemory.MD_LINEPIX, @@ -294,6 +348,7 @@ export const MemoryRegionToRetro = { sms_z80_regs: RetroMemory.SMS_Z80_REGS, gg_vram: RetroMemory.GG_VRAM, gg_cram: RetroMemory.GG_CRAM, + gpgx_blip_deltas: RetroMemory.GPGX_BLIP_DELTAS, gb_vram: RetroMemory.GB_VRAM, gb_oam: RetroMemory.GB_OAM, gb_io: RetroMemory.GB_IO, @@ -307,6 +362,8 @@ export const MemoryRegionToRetro = { gb_palline: RetroMemory.GB_PALLINE, gb_bgcol15: RetroMemory.GB_BGCOL15, gb_sprcol15: RetroMemory.GB_SPRCOL15, + gb_lcdlog: RetroMemory.GB_LCDLOG, + gb_apu_raw: RetroMemory.GB_APU_RAW, a78_cpu_regs: RetroMemory.A78_CPU_REGS, a26_tia_regs: RetroMemory.A26_TIA_REGS, a26_cpu_regs: RetroMemory.A26_CPU_REGS, @@ -321,9 +378,13 @@ export const MemoryRegionToRetro = { gba_palette: RetroMemory.GBA_PALETTE, gba_oam: RetroMemory.GBA_OAM, gba_iwram: RetroMemory.GBA_IWRAM, + gba_timing: RetroMemory.GBA_TIMING, + gba_audio_raw: RetroMemory.GBA_AUDIO_RAW, sync32_cpu_regs: RetroMemory.SYNC32_CPU_REGS, sync32_palette: RetroMemory.SYNC32_PALETTE, sync32_canvas: RetroMemory.SYNC32_CANVAS, + sync32_timing: RetroMemory.SYNC32_TIMING, + sync32_profile: RetroMemory.SYNC32_PROFILE, sync32_sheet0: RetroMemory.SYNC32_SHEET0, lynx_cpu_regs: RetroMemory.LYNX_CPU_REGS, lynx_hw_regs: RetroMemory.LYNX_HW_REGS, @@ -414,7 +475,7 @@ export const MemoryRegionToRetro = { * to cartridge; C64 depends on the file kind - a `.d64`/`.g64`/`.d71`/`.d81` is a * disk, a `.tap` is a tape, a `.crt` is a cartridge, and a bare `.prg`/`.p00` is * a program injected directly. The extension is passed when known (loadMedia has - * it) so disk/tape images report honestly in status() and the agent knows a + * it) so disk/tape images report accurately in status() and the agent knows a * writable disk exists for saves. * @param {string} platform * @param {string} [ext] lower- or mixed-case file extension incl. dot, e.g. ".d64" diff --git a/packages/romdev-core-parallel-n64/README.md b/packages/romdev-core-parallel-n64/README.md index 7cf243cc..2705ccbe 100644 --- a/packages/romdev-core-parallel-n64/README.md +++ b/packages/romdev-core-parallel-n64/README.md @@ -1,47 +1,40 @@ # romdev-core-parallel-n64 The [ParaLLEl-N64](https://github.com/libretro/parallel-n64) libretro core -(Nintendo 64) bundled as WASM for [romdev](https://github.com/monteslu/romdev), -built **headless-angrylion** (software). +(Nintendo 64), compiled to WebAssembly for +[romdev](https://github.com/monteslu/romdev). -## Why headless-angrylion +The RDP is rendered on the GPU by **glide64**, ParaLLEl-N64's GL renderer: it +translates the game's RDP display lists to GLES/WebGL2 calls, and the host +reads each frame back. The core is loaded with `hwRender: true` and needs the +headless GL context that `romdev-core-host` provides through `native-gles`, the +same path as the PS1 (Beetle PSX HW) and Dreamcast (Flycast) cores. romdev +selects glide64 through a core option. -The default ParaLLEl-N64 build renders through glide64/GL, which only presents the -**RDP display-lists** a game issues - it does NOT scan out a raw CPU-written VI -framebuffer. romdev's N64 homebrew (the bundled software-3D lib) draws directly into -an RDRAM framebuffer, so it needs a renderer that honors the **Video Interface -scanout**. This build compiles GL **out**, stubs the inactive video-plugin tables, -and forces the **angrylion** software RDP - which presents the VI framebuffer via -`video_cb` (no GL). Loaded with `hwRender: false`. +A binary package: the main `romdevtools` package loads it on demand for +`loadMedia({platform:'n64'})`. You normally install `romdevtools` +(`npx romdevtools`), not this package directly. ## Custom romdev build -Upstream core plus: -- `romdev_mips_regs_get` - live R4300 register file (`cpu({op:'read'})`) -- the live-debug set (`romdev_watchpoint_set` / `romdev_pcbreak_set` / - `romdev_range_set` / ...) - `breakpoint` + `watch` -- `romdev_ai_get` - the Audio Interface registers (`getAudioState({chip:'ai'})`) -- a minimal clean-room **IPL3** wrapper so `build({platform:'n64'})` produces a - self-booting `.z64` (PI-DMAs the game to RDRAM and jumps in). - -Built reproducibly by `scripts/build-parallel-n64.sh` in the romdev repo. - -The `.wasm` is gitignored and shipped to npm via the package's `files` allowlist. - -License: GPL-2.0-or-later (inherits ParaLLEl-N64's license). - -## 0.3.0 - the debug hooks work - -Through 0.2.0 `romdev_pcbreak_set` / single-step / the PC coverage log never -fired on this core: the hook was wired only into the pure interpreter (which -this wasm build cannot boot - it faults into the exception vector) and a hit -set `stop = 1`, which ended the emulation loop for good. 0.3.0 hooks the -CACHED interpreter's instruction loop (the default CPU here; the build is -NO_LIBCO, single-threaded) and a hit does `retro_return(0); break;` - the -frame ends with the CPU stopped AT the hit PC and the next `retro_run` -resumes there. `breakpoint({on:'pc'})`, `frame({op:'stepInstructions'})`, -`watch({on:'pc'})` and the new exact PC coverage bitmap -(`romdev_covbits_set/get`, host `logPCBitmap`) are real on N64 now. Measured -on a commercial ROM: single-step advances 0x80000184 → 0x80000188 → ..., an -osRecvMesg break hits with a0/a1/ra readable, 5 frames log 759,452 executed -instructions / 32,140 distinct PCs in 24 ms. +Upstream core (pinned at commit `1da824e13e725a7144f3245324f43d59623974f8`) +plus these exports: + +- `romdev_mips_regs_get`: the live R4300 register file (`cpu({op:'read'})`). +- romdev's shared live-debug set (`romdev_watchpoint_set`, `romdev_pcbreak_set`, + `romdev_range_set`, the PC coverage log and bitmap, and the rest), hooked + into the cached interpreter's instruction loop: `breakpoint`, `watch` and + `frame({op:'stepInstructions'})` stop with the CPU at the hit PC. +- `romdev_ai_get`: the Audio Interface registers + (`audioDebug({op:'inspect', chip:'ai'})`). + +## Upstream and license + +**License:** GPL-2.0-or-later (inherits ParaLLEl-N64's license). + +**Built by:** `packages/romdevtools/scripts/build-parallel-n64.sh` (it appends +`scripts/patches/romdev-snippets/n64-regsnap.c` to the core and adds +`n64-debug.c` plus romdev's shared debug library to the R4300 sources). See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. The `.wasm` is not in git; it ships to npm +through the package's `files` list. diff --git a/packages/romdev-core-parallel-n64/index.js b/packages/romdev-core-parallel-n64/index.js index 00afd3cf..9a28842f 100644 --- a/packages/romdev-core-parallel-n64/index.js +++ b/packages/romdev-core-parallel-n64/index.js @@ -1,13 +1,11 @@ // romdev-core-parallel-n64 - binary package: ParaLLEl-N64 libretro core (N64). -// HEADLESS-ANGRYLION software build: GL is compiled OUT and the angrylion software -// RDP is forced, so raw CPU-rendered VI framebuffers DISPLAY (the GL/glide64 build -// only presents RDP display-lists). This is what lets romdev's software-3D homebrew -// render. CUSTOM romdev build: upstream core + romdev's debug exports +// GL-rendered build: the RDP runs on the real GPU through glide64 (GL HLE) and +// romdev-core-host's native-gles bridge. CUSTOM romdev build: upstream core + romdev's debug exports // (romdev_mips_regs_get, watchpoint/pcbreak/range live-debug, romdev_ai_get for the // Audio Interface) + a clean-room IPL3 so build({platform:n64}) self-boots. // Built reproducibly by scripts/build-parallel-n64.sh. // -// Loaded with hwRender:false (the renderer presents via video_cb, not a GL FBO). +// Loaded with hwRender:true (glide64 renders into the host's GL framebuffer). import { fileURLToPath } from "node:url"; import path from "node:path"; @@ -16,10 +14,10 @@ const WASM = path.join(__dirname, "wasm"); export const platform = "n64"; -// Emulator core (libretro) - glue .js + .wasm. Software renderer (no GL bridge). +// Emulator core (libretro) - glue .js + .wasm. GL renderer (glide64). export const core = { name: "parallel_n64", jsPath: path.join(WASM, "parallel_n64_libretro.js"), wasmPath: path.join(WASM, "parallel_n64_libretro.wasm"), - hwRender: false, + hwRender: true, }; diff --git a/packages/romdev-core-parallel-n64/package.json b/packages/romdev-core-parallel-n64/package.json index 167ea4f1..1dabea5f 100644 --- a/packages/romdev-core-parallel-n64/package.json +++ b/packages/romdev-core-parallel-n64/package.json @@ -1,7 +1,7 @@ { "name": "romdev-core-parallel-n64", - "version": "0.3.1", - "description": "ParaLLEl-N64 libretro core (Nintendo 64), HEADLESS-ANGRYLION software build for romdev (no GL - scans out raw RDRAM framebuffers), bundled as WASM with romdev's CPU + AI + live-debug exports.", + "version": "0.3.2", + "description": "ParaLLEl-N64 libretro core (Nintendo 64), GL-rendered through glide64, for romdev, bundled as WASM with romdev's CPU + AI + live-debug exports.", "type": "module", "main": "index.js", "exports": { diff --git a/packages/romdev-core-prosystem/README.md b/packages/romdev-core-prosystem/README.md index 1035daf9..4d6d43af 100644 --- a/packages/romdev-core-prosystem/README.md +++ b/packages/romdev-core-prosystem/README.md @@ -2,19 +2,21 @@ ProSystem - Atari 7800 emulator core (libretro), as WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **prosystem**. +Bundles: **ProSystem**, https://github.com/libretro/prosystem-libretro. **License:** GPL-2.0-or-later -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-prosystem.sh` + patch(es) `prosystem-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-prosystem.sh` with patch(es) `prosystem-romdev-memory-regions.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-prosystem/package.json b/packages/romdev-core-prosystem/package.json index d5ceec12..affc232b 100644 --- a/packages/romdev-core-prosystem/package.json +++ b/packages/romdev-core-prosystem/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-prosystem", - "version": "0.10.1", + "version": "0.10.2", "description": "ProSystem libretro core (Atari 7800) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-runner/README.md b/packages/romdev-core-runner/README.md index 18fb34ec..91e15ef5 100644 --- a/packages/romdev-core-runner/README.md +++ b/packages/romdev-core-runner/README.md @@ -110,11 +110,12 @@ produces a zero-size window), `letterbox(winW, winH, aspect)`, `framebufferToRgba(fb, out?)` (pass the previous return value as `out` to reuse the buffer across ticks - no per-frame allocation), and `drawFpsOverlay(rgba, width, height, fps)` (the corner fps counter, pure -pixel writes), plus `initSdl()` (the hardened loader) and +pixel writes), plus `initSdl()` (the SDL loader with the self-repair step above) and `sdlPackageRoot()`. ## Requirements Node >= 24, ESM only. Software-rendered cores work everywhere SDL does; -the 3D cores additionally want the `native-gles` optional dependency (see -the `romdev-core-host` README). +the 3D cores also need a working GPU for the headless GL context that +`romdev-core-host` creates through its `native-gles` dependency (see the +`romdev-core-host` README). diff --git a/packages/romdev-core-runner/package.json b/packages/romdev-core-runner/package.json index 52d97031..18d66494 100644 --- a/packages/romdev-core-runner/package.json +++ b/packages/romdev-core-runner/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-runner", - "version": "0.2.18", + "version": "0.2.19", "description": "Play a ROM you just built: an SDL window over the romdev libretro host (romdev-core-host) with keyboard + hot-plug gamepad input, audio, and aspect-correct pixel-perfect scaling. The human 'fire it up' tier between an external emulator and the romdev MCP server. Bundles NO cores; pass any romdev-core-* package.", "type": "module", "main": "index.js", @@ -23,7 +23,7 @@ "url": "git+https://github.com/monteslu/romdev.git" }, "dependencies": { - "romdev-core-host": "0.16.0" + "romdev-core-host": "0.14.1" }, "optionalDependencies": { "@kmamal/sdl": "^0.11.13" diff --git a/packages/romdev-core-runner/runRom.js b/packages/romdev-core-runner/runRom.js index 4bc8b915..f25c987e 100644 --- a/packages/romdev-core-runner/runRom.js +++ b/packages/romdev-core-runner/runRom.js @@ -72,7 +72,7 @@ export async function runRom(rom, opts = {}) { const buttonMap = opts.buttonMap ?? SDL_BUTTON_TO_LIBRETRO_BIT; const keyMap = opts.keyMap ?? KEY_TO_LIBRETRO_BIT; - // SDL first - fail fast (and honestly: SDL_UNAVAILABLE) before touching the core. + // SDL first - fail fast (with SDL_UNAVAILABLE) before touching the core. const sdl = await initSdl({ log, ...(opts._initSdlOpts ?? {}) }); // Load core + ROM. diff --git a/packages/romdev-core-runner/sdl.js b/packages/romdev-core-runner/sdl.js index 86b4454f..f674f141 100644 --- a/packages/romdev-core-runner/sdl.js +++ b/packages/romdev-core-runner/sdl.js @@ -11,7 +11,7 @@ // verified (and repaired) BEFORE the first import. // - With no presentable display SDL silently picks the "offscreen"/"dummy" // video driver - createWindow SUCCEEDS but nothing appears on any screen. -// We ask SDL which driver it actually selected and fail honestly. +// We ask SDL which driver it actually selected and fail with a clear error. // // On failure throws an Error tagged `.code = "SDL_UNAVAILABLE"` plus // `.sdlKind` ("missing-binary" | "install-failed" | "sdl-error" | @@ -52,7 +52,7 @@ export function sdlPackageRoot(resolve = require.resolve) { let _sdlModule = null; /** - * Load @kmamal/sdl with the self-repair + honest-failure behavior described in + * Load @kmamal/sdl with the self-repair + clear-failure behavior described in * the header. Memoized per process (SDL can only init once anyway). * * @param {Object} [opts] diff --git a/packages/romdev-core-s32core/README.md b/packages/romdev-core-s32core/README.md index 32224262..7c6b06d9 100644 --- a/packages/romdev-core-s32core/README.md +++ b/packages/romdev-core-s32core/README.md @@ -1,50 +1,58 @@ # romdev-core-s32core The **sync32** console core for [romdev](https://github.com/monteslu/romdev), -bundled as WASM. +bundled as WebAssembly. -sync32 is monteslu's RP2350 console: games are Cortex-M33 ARM binaries shipped -as `.s32` files. `s32core` is a first-party pure-C interpreter for it, exposed -through the libretro API - the same shape as every other romdev core, so the -host runs it with no special-casing. +sync32 is an open RP2350-based console: games are Cortex-M33 ARM binaries +shipped as `.s32` files. `s32core` is a pure-C interpreter for it, exposed +through the libretro API, the same shape as every other romdev core, so the +host runs it with no special cases. -Built with **NODERAWFS**: the frontend `fopen()`s the `.s32` by its real path -and streams the game's `/` data directory straight off the host -filesystem, rather than preloading it into MEMFS. A cart with resources -therefore reads them from disk exactly as it does on hardware. +It is built with **NODERAWFS**: the frontend `fopen()`s the `.s32` by its real +path and streams the game's `/` data directory from the host +filesystem rather than preloading it into memory, so a cart reads its +resources from disk the way it does on hardware. ## Debugger views The core exposes its state through libretro's memory interface, so a frontend -can inspect a running game - this is aimed at **developing** a cart, since -sync32 has no commercial ROMs to reverse-engineer: +can inspect a running game while you develop a cart: | id | region | what it is | |---|---|---| -| `SYSTEM_RAM` | `system_ram` | the 520KB SRAM at `0x20000000` - a game's globals, its stack, and in ram mode its code | +| `SYSTEM_RAM` | `system_ram` | the 520KB SRAM at `0x20000000`: a game's globals, its stack, and in RAM mode its code | | `0x1A0` | `sync32_cpu_regs` | r0-r15, the packed APSR, s0-s31, ITSTATE | | `0x1A1` | `sync32_palette` | 256 entries, RGB565 | -| `0x1A2` | `sync32_canvas` | the 320x240 8-bit indexed framebuffer | +| `0x1A2` | `sync32_canvas` | the 8-bit indexed framebuffer: 320x240, 320x180, or 128x128 in the 128x128 video mode | +| `0x1A3` | `sync32_timing` | frame timing (u32 LE): the ABI cycle budget per frame, frames presented, the last frame's work cycles, and a ring of per-frame work cycles | +| `0x1A4` | `sync32_profile` | a PC-sampling profiler (u32 LE, writable control block): enable, base address, shift and bucket count, then CPU cycles per bucket; vblank idle time is excluded | | `0x1B0+n` | `sync32_sheet0`... | loaded sprite sheet *n*, 8-bit indices | -SAVE_RAM is deliberately **not** mapped: a frontend persists that to disk, and -dumping live stack into a `.srm` would be both wrong and useless - sync32 saves -go through the console's own save slots. +The video mode comes from the cart header: mode 0 is 320x240 (4:3), mode 1 is +320x180 (16:9 letterbox), and mode 2 is 128x128, shown at 3x for 128x128 +fantasy-console games. -These hand out pointers to live state rather than copies, so nothing is paid per -frame. The CPU block is the one exception - a snapshot refreshed on demand, -because the interpreter keeps each APSR flag as its own word (faster in the hot -loop) and packing them belongs on the debugger's side, not the emulator's. +SAVE_RAM is not mapped: a frontend persists that region to disk, and sync32 +saves go through the console's own save slots instead. -This package ships built artifacts only. The core's source lives in its own -repository, and romdev's `scripts/build-s32core.sh` compiles it here. +These regions hand out pointers to live state rather than copies, so nothing is +paid per frame. The CPU block is the exception: a snapshot refreshed on demand, +because the interpreter keeps each APSR flag in its own word and the packing +happens on the debugger's side. ## Use ```js import { core, platform } from "romdev-core-s32core"; -// → { name: "s32core", jsPath: ".../s32core_libretro.js", wasmPath: ".../...wasm" } +// core = { name: "s32core", jsPath: ".../s32core_libretro.js", wasmPath: ".../s32core_libretro.wasm" } ``` -Normally you do not import this directly - romdev's core registry resolves it -by platform id (`sync32`). +Normally you do not import this directly: romdevtools' core registry resolves +it for `loadMedia({platform:'sync32'})`. You normally install `romdevtools` +(`npx romdevtools`). + +## License + +MIT. This package ships built artifacts only. The core's source lives in its +own repository, and `packages/romdevtools/scripts/build-s32core.sh` in the +romdev repo compiles it from a local checkout (`S32CORE_SRC`). diff --git a/packages/romdev-core-s32core/package.json b/packages/romdev-core-s32core/package.json index 89b90439..60b96749 100644 --- a/packages/romdev-core-s32core/package.json +++ b/packages/romdev-core-s32core/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-s32core", - "version": "0.2.1", + "version": "0.2.2", "description": "sync32 console core (s32core) for romdev, bundled as WASM. sync32 is an RP2350/Cortex-M33 console; s32core is a first-party pure-C interpreter exposed through the libretro API.", "type": "module", "main": "index.js", diff --git a/packages/romdev-core-vice/README.md b/packages/romdev-core-vice/README.md index 46fb51c6..a91770ce 100644 --- a/packages/romdev-core-vice/README.md +++ b/packages/romdev-core-vice/README.md @@ -2,9 +2,10 @@ VICE (x64) - Commodore 64 emulator core (libretro), as WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. ## C64 ROMs: free replacements, bundled @@ -15,8 +16,8 @@ covers VICE's code rather than those ROMs. Instead this package ships **[MEGA65 Open ROMs](https://github.com/MEGA65/open-roms)** in `roms/` - a clean-room, dual GPL-3.0/LGPL-3.0 KERNAL+BASIC+CHARGEN written so -emulators can ship a working C64 legally. The host installs them automatically, -so **the C64 boots with zero setup**. +emulators can ship a working C64. The host installs them automatically, so the +C64 boots with no setup. The files are named after Commodore's part numbers (`kernal-901227-03.bin` and friends) because VICE resolves ROM images by those exact names. The contents are @@ -29,15 +30,18 @@ notably incomplete. If you own the originals, point `ROMDEV_C64_ROM_DIR` at a directory containing `kernal-901227-03.bin`, `basic-901226-01.bin` and `chargen-901225-01.bin`; that overrides the bundled set. -## Upstream & license +## Upstream and license -Bundles: **VICE**. +Bundles: **VICE** (x64), https://github.com/libretro/vice-libretro. **License:** GPL-2.0-or-later -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-vice.sh` + patch(es) `vice-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-vice.sh` with patches +`vice-romdev-memory-regions.patch` and `vice-no-embedded-roms.patch` (undefines +`USE_EMBEDDED`, so no Commodore ROM is compiled in). See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-core-vice/package.json b/packages/romdev-core-vice/package.json index 08afcb86..8ed43d83 100644 --- a/packages/romdev-core-vice/package.json +++ b/packages/romdev-core-vice/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-vice", - "version": "0.12.0", + "version": "0.12.1", "description": "VICE x64 libretro core (Commodore 64) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-m2c/LICENSE b/packages/romdev-m2c/LICENSE new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/packages/romdev-m2c/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/packages/romdev-m2c/NOTICE b/packages/romdev-m2c/NOTICE new file mode 100644 index 00000000..2af4f856 --- /dev/null +++ b/packages/romdev-m2c/NOTICE @@ -0,0 +1,38 @@ +romdev-m2c +========== + +This package is a JavaScript port of m2c, the MIPS/PowerPC/ARM/SuperH to C +decompiler, made for romdev. It is a derivative work of m2c and is therefore +licensed under the GNU General Public License, version 3 (see LICENSE). It is +kept in its own package so that its GPL terms stay separate from romdev's +MIT-licensed code, which only calls it. + +Components and attribution +-------------------------- + +1. m2c (formerly mips_to_c) + https://github.com/matt-kempster/m2c + Ported from commit 1d1c4454a445326541305f83f2b0cb680a9ecb2d. + Copyright the m2c contributors (Matt Kempster, Simon Lindholm, and others). + Licensed under the GNU General Public License v3.0 (LICENSE). + src/*.js are module-by-module translations of m2c/*.py; m2c_macros.h is + copied unchanged. + +2. pycparser (m2c's vendored, patched copy m2c_pycparser) + Not contained in this package: romdev-m2c depends on the separate + romdev-pycparser package (BSD 3-Clause, Eli Bendersky; PLY by David M. + Beazley), which is the shared JS port also used by romdev-permuter. + +3. CodeWarrior demangler (src/demangle_codewarrior.js) + Based on demangler.cs by arookas, 3-clause BSD License + (notice reproduced in the source file), as incorporated in m2c. + +Corresponding source: this package ships its complete JavaScript source. +The upstream Python source is available at the URL and commit above. + +Graphviz (used only for --visualize SVG output) + Not contained in this package: the @viz-js/viz npm dependency (MIT + wrapper, https://github.com/mdaines/viz-js) ships Graphviz compiled to + WebAssembly. Graphviz is licensed under the Eclipse Public License 1.0 + (https://graphviz.org/license/). It runs as a separate program on the dot + text m2c produces; no Graphviz code is part of romdev-m2c. diff --git a/packages/romdev-m2c/README.md b/packages/romdev-m2c/README.md new file mode 100644 index 00000000..44cf1126 --- /dev/null +++ b/packages/romdev-m2c/README.md @@ -0,0 +1,73 @@ +# romdev-m2c + +A plain JavaScript (ESM) port of [m2c](https://github.com/matt-kempster/m2c), +the MIPS/PowerPC/ARM/SuperH to C decompiler used by matching-decompilation +projects. It takes the same flags as upstream's command line and prints the +same C. No Python is needed. + +It is part of [romdev](https://github.com/monteslu/romdev) and is kept in its +own package so that m2c's GPL terms stay separate from romdev's MIT code, which +only calls it. + +## Upstream and license + +- Upstream: m2c, https://github.com/matt-kempster/m2c +- Ported from commit `1d1c4454a445326541305f83f2b0cb680a9ecb2d` +- License: GPL-3.0-only (a derivative of m2c). See `LICENSE` and `NOTICE`. +- `src/*.js` translate `m2c/*.py` module by module; `m2c_macros.h` is copied + unchanged. The CodeWarrior demangler is based on arookas' demangler.cs + (BSD-3-Clause, notice kept in the source file). +- The C parser is the separate + [`romdev-pycparser`](https://www.npmjs.com/package/romdev-pycparser) package. + `--visualize` SVG output uses the + [`@viz-js/viz`](https://www.npmjs.com/package/@viz-js/viz) dependency + (Graphviz compiled to WebAssembly, EPL-1.0), which runs as a separate program + on the dot text m2c produces. + +The end-to-end tests run upstream's `tests/end_to_end` corpus through the port +and compare each result byte for byte with upstream's expected output. + +## How romdev uses it + +romdevtools' `decomp` tool calls it to produce a first C candidate for a +function: `decomp({op:'generate', ...})` runs m2c on the function's assembly +with the translation unit's type context, and `decomp({op:'compare'})` then +compiles that candidate with the project's original compiler. + +## Command line + +```sh +npx romdev-m2c --target mips-ido-c --context ctx.c func.s +``` + +The bin is `romdev-m2c`. It accepts upstream m2c's flags, writes the same +stdout and stderr, and exits with the same code. + +## API + +```js +import { decompile, decompileInWorker, UPSTREAM } from "romdev-m2c"; + +const { code, stdout, stderr } = await decompile([ + "--target", "mips-ido-c", "--context", "ctx.c", "func.s", +]); +``` + +- `decompile(flags)`: runs m2c in process with upstream's CLI flags and + resolves to `{ code, stdout, stderr }`. Assembly inputs may also be passed + inline as `{ name, text }` objects. +- `decompileInWorker(flags, { timeoutMs })`: the same in a worker thread; + resolves to `{ code, stdout, stderr, timedOut }` and terminates the worker + on timeout. +- `parse_flags`, `run`, `ArgumentError`: lower-level entry points. +- `UPSTREAM`: `{ repo, commit }` of the ported m2c. + +Exports: `.` and `./m2c_macros.h` (the header m2c's output expects). + +## Requirements + +Node >= 24, ESM only. No Python, no native code. + +## Versions + +romdev-m2c 0.1.0 ports m2c at commit `1d1c4454`. diff --git a/packages/romdev-m2c/m2c_macros.h b/packages/romdev-m2c/m2c_macros.h new file mode 100644 index 00000000..d4095ead --- /dev/null +++ b/packages/romdev-m2c/m2c_macros.h @@ -0,0 +1,69 @@ +/* + * This header contains macros emitted by m2c in "valid syntax" mode, + * which can be enabled by passing `--valid-syntax` on the command line. + * + * In this mode, unhandled types and expressions are emitted as macros so + * that the output is compilable without human intervention. + */ + +#ifndef M2C_MACROS_H +#define M2C_MACROS_H + +/* Unknown types */ +typedef s32 M2C_UNK; +typedef s8 M2C_UNK8; +typedef s16 M2C_UNK16; +typedef s32 M2C_UNK32; +typedef s64 M2C_UNK64; + +/* Unknown field access, like `*(type_ptr) &expr->unk_offset` */ +#define M2C_FIELD(expr, type_ptr, offset) (*(type_ptr)((s8 *)(expr) + (offset))) + +/* Bitwise (reinterpret) cast */ +#define M2C_BITWISE(type, expr) ((type)(expr)) + +/* Unaligned reads */ +#define M2C_LWL(expr) (expr) +#define M2C_FIRST3BYTES(expr) (expr) +#define M2C_UNALIGNED32(expr) (expr) + +/* Unhandled instructions */ +#define M2C_ERROR(desc) (0) +#define M2C_TRAP_IF(cond) (0) +#define M2C_BREAK() (0) +#define M2C_SYNC() (0) + +#define GLUE_F64(a, b) (0.0) +#define MULT_HI(a, b) (0) +#define MULTU_HI(a, b) (0) +#define DMULT_HI(a, b) (0) +#define DMULTU_HI(a, b) (0) +#define CLZ(x) (0) +#define REVERSE_BITS(x) (0) +#define ROTATE_RIGHT(x, shift) (0) +#define ARM_RRX(x, carry) (0) +#define BSWAP32(x) (0) +#define BSWAP16(x) (0) +#define BSWAP16X2(x) (0) + +/* Carry/overflow bits from partially-implemented instructions */ +#define M2C_CARRY 0 +#define M2C_OVERFLOW(a) (0) + +/* Memcpy patterns */ +#define M2C_MEMCPY_ALIGNED memcpy +#define M2C_MEMCPY_UNALIGNED memcpy +#define M2C_STRUCT_COPY memcpy + +/* Sh2 control register loads/stores */ +#define M2C_LOAD_SR() (0) +#define M2C_LOAD_GBR() (0) +#define M2C_LOAD_VBR() (0) +#define M2C_STORE_SR(a) +#define M2C_STORE_GBR(a) +#define M2C_STORE_VBR(a) + +#define M2C_CMP_STR(a, b) (0) +#define M2C_TAS_B(a) (0) + +#endif diff --git a/packages/romdev-m2c/package.json b/packages/romdev-m2c/package.json new file mode 100644 index 00000000..61613ef4 --- /dev/null +++ b/packages/romdev-m2c/package.json @@ -0,0 +1,42 @@ +{ + "name": "romdev-m2c", + "version": "0.1.0", + "description": "m2c (MIPS/PowerPC/ARM/SuperH to C decompiler) ported to plain JavaScript ESM, for romdev. Output is byte-identical to upstream m2c at the pinned commit.", + "type": "module", + "main": "src/index.js", + "exports": { + ".": "./src/index.js", + "./m2c_macros.h": "./m2c_macros.h", + "./package.json": "./package.json" + }, + "bin": { + "romdev-m2c": "src/cli.js" + }, + "files": [ + "src", + "m2c_macros.h", + "LICENSE", + "NOTICE" + ], + "scripts": { + "test": "node --test 'test/**/*.test.mjs'" + }, + "engines": { + "node": ">=24" + }, + "license": "GPL-3.0-only", + "repository": { + "type": "git", + "url": "git+https://github.com/monteslu/romdev.git", + "directory": "packages/romdev-m2c" + }, + "homepage": "https://github.com/monteslu/romdev#readme", + "bugs": { + "url": "https://github.com/monteslu/romdev/issues" + }, + "author": "Luis Montes", + "dependencies": { + "romdev-pycparser": "0.1.0", + "@viz-js/viz": "3.31.0" + } +} diff --git a/packages/romdev-m2c/scripts/regen-candidates.mjs b/packages/romdev-m2c/scripts/regen-candidates.mjs new file mode 100644 index 00000000..3e4893b0 --- /dev/null +++ b/packages/romdev-m2c/scripts/regen-candidates.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node +// Regenerate recorded m2c candidates (romdev decomp workspaces: candidates//gen-N.{c,json}) +// with the JS port, using the exact args recorded in each sidecar, and compare byte-for-byte. +// Usage: node scripts/regen-candidates.mjs [--verbose] +import fs from "node:fs"; +import path from "node:path"; +import { decompile } from "../src/main.js"; + +const root = process.argv[2]; +const verbose = process.argv.includes("--verbose"); +if (!root) { + console.error("usage: regen-candidates.mjs "); + process.exit(2); +} + +// Same split as romdevtools src/decomp/m2c.js splitM2cOutput +function splitM2cOutput(text) { + const lines = text.split("\n"); + const declarations = []; + let i = 0; + for (; i < lines.length; i++) { + const l = lines[i].trim(); + if (!l) continue; + if (/^\?\s+\w+\s*\(.*\)\s*;/.test(l) || /^extern\s+\?/.test(l) || (/^extern\s+[^(]*;$/.test(l) && /\?/.test(l))) { + declarations.push(l); + continue; + } + break; + } + return { declarations, body: lines.slice(i).join("\n") }; +} + +const candDir = path.join(root, "candidates"); +let same = 0; +let differ = 0; +let skipped = 0; +const diffs = []; +for (const fn of fs.readdirSync(candDir).sort()) { + const dir = path.join(candDir, fn); + for (const f of fs.readdirSync(dir).filter((x) => /^gen-\d+\.json$/.test(x)).sort()) { + const meta = JSON.parse(fs.readFileSync(path.join(dir, f), "utf8")); + const cfile = path.join(dir, f.replace(/\.json$/, ".c")); + const args = (meta.args ?? []).slice(1); // drop m2c.py + const missing = args.filter((a, k) => (k === args.length - 1 || args[k - 1] === "--context") && !fs.existsSync(a)); + if (!fs.existsSync(cfile) || missing.length) { + skipped++; + if (verbose) console.log(`SKIP ${fn}/${f}: missing ${missing.join(", ") || cfile}`); + continue; + } + const r = await decompile(args); + const parsed = splitM2cOutput(r.stdout); + const text = parsed.body.trim() + "\n"; + const expected = fs.readFileSync(cfile, "utf8"); + const declsOk = JSON.stringify(parsed.declarations) === JSON.stringify(meta.declarations ?? parsed.declarations); + if (text === expected && declsOk) same++; + else { + differ++; + diffs.push(`${fn}/${f}${declsOk ? "" : " (declarations)"}`); + } + } +} +console.log(`candidates: ${same} identical, ${differ} different, ${skipped} skipped (inputs gone)`); +for (const d of diffs) console.log(` DIFF ${d}`); +process.exit(differ ? 1 : 0); diff --git a/packages/romdev-m2c/src/arch_arm.js b/packages/romdev-m2c/src/arch_arm.js new file mode 100644 index 00000000..7fa3e632 --- /dev/null +++ b/packages/romdev-m2c/src/arch_arm.js @@ -0,0 +1,1547 @@ +// Port of m2c/arch_arm.py +import { DecompFailure } from "./error.js"; +import { PyEnum, Target } from "./options.js"; +import { AsmSymbolicData, Label } from "./asm_file.js"; +import { + ARM_BARREL_SHIFTER_OPS, + AsmAddressMode, + AsmGlobalSymbol, + AsmInstruction, + AsmLiteral, + BinOp, + JumpTarget, + Macro, + Register, + RegisterList, + Writeback, + get_jump_target, +} from "./asm_instruction.js"; +import { AsmPattern, Replacement, SimpleAsmPattern, make_pattern } from "./asm_pattern.js"; +import { Instruction, InstructionMeta } from "./instruction.js"; +import { + Abi, + AbiArgSlot, + AddressMode, + ArgLoc, + Arch, + BinaryOp, + CarryBit, + ErrorExpr, + ExprStmt, + Literal, + SecondF64Half, + UnaryOp, + as_type, + as_f32, + as_f64, + format_hex, +} from "./translate.js"; +import { + condition_from_expr, + deref, + eval_arm_cmp, + fn_op, + fold_divmod, + fold_mul_chains, + handle_add_arm, + handle_add_double, + handle_add_float, + handle_add_real, + handle_arm_mov, + handle_bitinv, + handle_convert, + handle_la, + handle_load, + handle_or, + handle_shift_right, + handle_sll, + handle_sub, + handle_sub_arm, + handle_xor, + make_store, + make_store_real, + replace_bitand, + set_arm_flags_from_add, +} from "./evaluate.js"; +import { Type } from "./types.js"; +import { band, bxor, floordiv, format, has, int_, pyassert, pymod, shr } from "./py.js"; + +export const SUFFIXABLE_INSTRUCTIONS = new Set([ + "adc", "adr", "add", "and", "asr", "b", "bic", "bl", "blx", "bx", "cbnz", "cbz", "clz", "cmn", "cmp", "cpy", + "eor", "ldm", "ldr", "ldrb", "ldrh", "ldrsb", "ldrsh", "lsl", "lsr", "mla", "mls", "movimm.fictive", "mov", + "mul", "mvn", "neg", "nop", "orn", "orr", "pop", "push", "rbit", "rev", "rev16", "revsh", "ror", "rrx", "rsb", + "rsc", "sbc", "sdiv", "smlabb", "smlal", "smmla", "smmls", "smmul", "smulbb", "smull", "stm", "str", "strb", + "strh", "sub", "tablejmp.fictive", "teq", "tst", "udiv", "umlal", "umull", "vldm", "vldr", "vstm", "vstr", +]); + +export const LENGTH_THREE = new Set(["adc", "add", "and", "asr", "bic", "eor", "lsl", "lsr", "mul", "orn", "orr", "ror", "rsb", "rsc", "sbc", "sub"]); + +export const THUMB1_FLAG_SETTING = new Set(["adc", "add", "and", "asr", "bic", "eor", "lsl", "lsr", "mov", "mul", "mvn", "neg", "orr", "ror", "sbc", "sub"]); + +export const MAGIC_FUNCTIONS = { + __divsi3: ["sdiv", "001"], + _idiv: ["sdiv", "001"], + __udivsi3: ["udiv", "001"], + _uidiv: ["udiv", "001"], + __modsi3: ["smod.fictive", "001"], + __umodsi3: ["umod.fictive", "001"], + _s32_div_f: ["sdivmod.fictive", "01"], + _idivmod: ["sdivmod.fictive", "01"], + _u32_div_f: ["udivmod.fictive", "01"], + _uidivmod: ["udivmod.fictive", "01"], + __clzsi2: ["clz", "00"], + // Soft float emulation from fplib + _fadd: ["add.s.fictive", "001"], + _fsub: ["sub.s.fictive", "001"], + _frsub: ["sub.s.fictive", "010"], + _fmul: ["mul.s.fictive", "001"], + _fdiv: ["div.s.fictive", "001"], + _frdiv: ["div.s.fictive", "010"], + _fsqrt: ["sqrt.s.fictive", "00"], + _frnd: ["round.s.fictive", "00"], + _fflt: ["cvt.s.w.fictive", "00"], + _ffltu: ["cvt.s.u.fictive", "00"], + _ffix: ["cvt.w.s.fictive", "00"], + _ffixu: ["cvt.u.s.fictive", "00"], + _f2d: ["cvt.d.s.fictive", "00"], + _fls: ["c.lt.s.fictive", "01"], + _fgr: ["c.gt.s.fictive", "01"], + _fleq: ["c.le.s.fictive", "01"], + _fgeq: ["c.ge.s.fictive", "01"], + _feq: ["c.eq.s.fictive", "01"], + _fneq: ["c.neq.s.fictive", "01"], + _dadd: ["add.d.fictive", "002"], + _dsub: ["sub.d.fictive", "002"], + _drsub: ["sub.d.fictive", "020"], + _dmul: ["mul.d.fictive", "002"], + _ddiv: ["div.d.fictive", "002"], + _drdiv: ["div.d.fictive", "020"], + _dsqrt: ["sqrt.d.fictive", "00"], + _drnd: ["round.d.fictive", "00"], + _dflt: ["cvt.d.w.fictive", "00"], + _dfltu: ["cvt.d.u.fictive", "00"], + _dfix: ["cvt.w.d.fictive", "00"], + _dfixu: ["cvt.u.d.fictive", "00"], + _d2f: ["cvt.s.d.fictive", "00"], + _dls: ["c.lt.d.fictive", "02"], + _dgr: ["c.gt.d.fictive", "02"], + _dleq: ["c.le.d.fictive", "02"], + _dgeq: ["c.ge.d.fictive", "02"], + _deq: ["c.eq.d.fictive", "02"], + _dneq: ["c.neq.d.fictive", "02"], +}; + +const HI_REGS = new Set(["r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc"].map((r) => new Register(r))); + +export class Cc extends PyEnum {} +PyEnum.define(Cc, { + EQ: "eq", + NE: "ne", + CS: "cs", + CC: "cc", + MI: "mi", + PL: "pl", + VS: "vs", + VC: "vc", + HI: "hi", + LS: "ls", + GE: "ge", + LT: "lt", + GT: "gt", + LE: "le", + AL: "al", +}); + +export const CC_REGS = new Map([ + [Cc.EQ, new Register("z")], + [Cc.CS, new Register("c")], + [Cc.MI, new Register("n")], + [Cc.VS, new Register("v")], + [Cc.HI, new Register("hi")], + [Cc.GE, new Register("ge")], + [Cc.GT, new Register("gt")], +]); + +function cc_reg(cc) { + const r = CC_REGS.get(cc); + if (r === undefined) throw new Error(`KeyError: ${cc}`); + return r; +} + +const NEGATE = new Map([ + [Cc.EQ, Cc.NE], + [Cc.NE, Cc.EQ], + [Cc.CS, Cc.CC], + [Cc.CC, Cc.CS], + [Cc.MI, Cc.PL], + [Cc.PL, Cc.MI], + [Cc.VS, Cc.VC], + [Cc.VC, Cc.VS], + [Cc.HI, Cc.LS], + [Cc.LS, Cc.HI], + [Cc.GE, Cc.LT], + [Cc.LT, Cc.GE], + [Cc.GT, Cc.LE], + [Cc.LE, Cc.GT], +]); + +export function negate_cond(cc) { + const r = NEGATE.get(cc); + if (r === undefined) throw new Error(`KeyError: ${cc}`); + return r; +} + +const FACTOR = new Map([ + [Cc.EQ, [Cc.EQ, false]], + [Cc.NE, [Cc.EQ, true]], + [Cc.CS, [Cc.CS, false]], + [Cc.CC, [Cc.CS, true]], + [Cc.MI, [Cc.MI, false]], + [Cc.PL, [Cc.MI, true]], + [Cc.VS, [Cc.VS, false]], + [Cc.VC, [Cc.VS, true]], + [Cc.HI, [Cc.HI, false]], + [Cc.LS, [Cc.HI, true]], + [Cc.GE, [Cc.GE, false]], + [Cc.LT, [Cc.GE, true]], + [Cc.GT, [Cc.GT, false]], + [Cc.LE, [Cc.GT, true]], +]); + +export function factor_cond(cc) { + const r = FACTOR.get(cc); + if (r === undefined) throw new Error(`KeyError: ${cc}`); + return r; +} + +/** Returns [mnemonic, cc|null, set_flags, direction]. */ +export function parse_suffix(mnemonic) { + const ldm = mnemonic.startsWith("ldm") || mnemonic.startsWith("vldm"); + const stm = mnemonic.startsWith("stm") || mnemonic.startsWith("vstm"); + + const strip_cc = (mn) => { + for (const suffix of [...Cc.members.map((c) => c.value), "hs", "lo"]) { + if (mn.endsWith(suffix)) { + let cc; + if (suffix === "hs") cc = Cc.CS; + else if (suffix === "lo") cc = Cc.CC; + else cc = Cc.of(suffix); + return [mn.slice(0, -suffix.length), cc]; + } + } + return [mn, null]; + }; + + const strip_dir = (mn) => { + if (!ldm && !stm) return [mn, ""]; + if (["ia", "ib", "da", "db"].some((s) => mn.endsWith(s))) return [mn.slice(0, -2), mn.slice(-2)]; + if (["fa", "ea", "fd", "ed"].some((s) => mn.endsWith(s))) { + const tr = { fa: ["da", "ib"], ea: ["db", "ia"], fd: ["ia", "db"], ed: ["ib", "da"] }; + return [mn.slice(0, -2), tr[mn.slice(-2)][ldm ? 0 : 1]]; + } + return [mn, ""]; + }; + + // bls should be parsed as b + ls, not bl + s + let s_ok = !mnemonic.startsWith("b") || mnemonic.startsWith("bic"); + + let memsize = ""; + if (mnemonic.startsWith("str") || mnemonic.startsWith("ldr")) { + // ldrhs should be parsed as ldr + hs, not ldrh + s + s_ok = false; + for (const suffix of ["b", "h", "d"]) { + if (mnemonic.endsWith(suffix)) { + mnemonic = mnemonic.slice(0, -1); + memsize = suffix; + break; + } + } + if ((memsize === "b" || memsize === "h") && mnemonic.endsWith("s") && (!strip_cc(mnemonic)[1] || strip_cc(mnemonic.slice(0, -1))[1])) { + mnemonic = mnemonic.slice(0, -1); + memsize = "s" + memsize; + } + } + + const orig_mn = mnemonic; + for (const cc_is_last of [false, true]) { + let direction; + [mnemonic, direction] = strip_dir(orig_mn); + let cc = null; + let set_flags = ""; + if (cc_is_last) { + [mnemonic, cc] = strip_cc(mnemonic); + if (!direction) [mnemonic, direction] = strip_dir(mnemonic); + } + if (SUFFIXABLE_INSTRUCTIONS.has(mnemonic)) return [mnemonic + memsize, cc, set_flags, direction]; + if (mnemonic.endsWith("s") && s_ok) { + set_flags = "s"; + mnemonic = mnemonic.slice(0, -1); + if (SUFFIXABLE_INSTRUCTIONS.has(mnemonic)) return [mnemonic + memsize, cc, set_flags, direction]; + } + if (!cc_is_last) { + [mnemonic, cc] = strip_cc(mnemonic); + if (SUFFIXABLE_INSTRUCTIONS.has(mnemonic)) return [mnemonic + memsize, cc, set_flags, direction]; + } + } + return [orig_mn + memsize, null, "", ""]; +} + +export function get_ldm_stm_offset(i, num_regs, direction) { + if (direction === "ia") return 4 * i; + if (direction === "ib") return 4 * (i + 1); + if (direction === "da") return 4 * (i + 1 - num_regs); + if (direction === "db") return 4 * (i - num_regs); + pyassert(false, `bad ldm/stm direction ${direction}`); +} + +export function other_f64_reg(reg) { + const num = int_(reg.register_name.slice(1)); + return new Register(`r${num ^ 1}`); +} + +export function vreg_type(reg) { + const [tp] = reg.arm_regtype_index(); + if (tp === "s") return Type.reg32({ likely_float: true }); + else if (tp === "d") return Type.reg64({ likely_float: true }); + else if (tp === "q") return Type.reg128(); + pyassert(false, `invalid vldr target ${reg}`); +} + +/** Detect switch jumps of the form "add pc, pc, reg, lsl 2". */ +export class AddPcPcPattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (!(instr instanceof Instruction) || !instr.mnemonic.startsWith("add")) return null; + const [base, cc, set_flags] = parse_suffix(instr.mnemonic); + if ( + base !== "add" || + set_flags || + instr.args[0] !== new Register("pc") || + instr.args[1] !== new Register("pc") || + !(instr.args[2] instanceof BinOp) || + instr.args[2].op !== "lsl" || + instr.args[2].rhs !== new AsmLiteral(2) + ) { + return null; + } + let i = matcher.index + 1; + let seen_first = false; + const new_args = [instr.args[2].lhs]; + while (i < matcher.input.length) { + const ins2 = matcher.input[i]; + i += 1; + if (ins2 instanceof Label) continue; + if (!seen_first) { + seen_first = true; + continue; + } + if (ins2.mnemonic === "pop" && ins2.args[0] instanceof RegisterList && ins2.args[0].regs.includes(new Register("pc"))) { + new_args.push(new AsmGlobalSymbol("_m2c_ret")); + } else if (ins2.mnemonic === "b") { + pyassert(ins2.args[0] instanceof AsmGlobalSymbol); + new_args.push(ins2.args[0]); + } else break; + } + const cc_str = cc !== null ? cc.value : ""; + const jump_ins = new AsmInstruction("tablejmp.fictive" + cc_str, new_args); + return new Replacement([jump_ins], 1); + } +} + +/** Detect switch jumps emitted by MWCC for Thumb. */ +export class ShortJumpTablePattern extends AsmPattern { + pattern = make_pattern("adds $x, $x, $x", "add $x, $x, $pc", "ldrh $x, [$x, 6]", "movs $x, $x, lsl 0x10", "movs $x, $x, asr 0x10", "add $pc, $pc, $x", ".label:"); + + match(matcher) { + const m = matcher.try_match(this.pattern); + if (!m) return null; + const label = m.labels.get(".label").names[0]; + const ent = matcher.asm_data.values.get(label) ?? null; + if (ent === null) return null; + const new_args = [m.regs.get("x")]; + for (const data of ent.data) { + if ( + !(data instanceof AsmSymbolicData) || + !(data.data instanceof BinOp) || + data.data.rhs !== new AsmLiteral(2) || + !(data.data.lhs instanceof BinOp) || + data.data.lhs.rhs !== new AsmGlobalSymbol(label) + ) { + break; + } + new_args.push(data.data.lhs.lhs); + } + const jump_ins = new AsmInstruction("tablejmp.fictive", new_args); + return new Replacement([jump_ins], this.pattern.length - 1); + } +} + +function intersects(a, setb) { + for (const x of a) if (setb.has(x)) return true; + return false; +} + +export class InstructionEffects { + constructor() { + this.inputs = new Set(); + this.outputs = new Set(); + this.is_effectful = false; + this.has_load = false; + } + can_move_before(instr) { + const outputs = [...instr.outputs, ...instr.clobbers]; + if (intersects([...instr.inputs, ...outputs], this.outputs)) return false; + if (intersects(outputs, this.inputs)) return false; + if (this.is_effectful && (instr.is_effectful || instr.is_load)) return false; + if (this.has_load && instr.is_effectful) return false; + return true; + } + add(instr) { + for (const x of [...instr.outputs, ...instr.clobbers]) this.outputs.add(x); + for (const x of instr.inputs) this.inputs.add(x); + if (instr.is_effectful) this.is_effectful = true; + if (instr.is_load) this.has_load = true; + } +} + +/** Replace conditionally executed instructions by branches. */ +export class ConditionalInstrPattern extends AsmPattern { + match(matcher) { + let matched_cc = null; + let i = 0; + const if_instrs = []; + const else_instrs = []; + const before_instrs = []; + const after_instrs = []; + const mid_set = new InstructionEffects(); + const after_set = new InstructionEffects(); + let moved_before_streak = 0; + let moved_after_streak = 0; + const label1 = `._m2c_cc_${matcher.index}`; + const label2 = `._m2c_cc2_${matcher.index}`; + let flag_check = null; + while (matcher.index + i < matcher.input.length) { + const instr = matcher.input[matcher.index + i]; + if (!(instr instanceof Instruction)) break; + const [base, cc, set_flags, direction] = parse_suffix(instr.mnemonic); + if (cc === null) { + if (matched_cc === null) return null; + if (instr.is_jump()) break; + if (mid_set.can_move_before(instr) && !after_instrs.length) { + before_instrs.push(instr); + moved_before_streak += 1; + } else { + after_set.add(instr); + after_instrs.push(instr); + moved_after_streak += 1; + } + i += 1; + continue; + } + const outputs = [...instr.outputs, ...instr.clobbers]; + if (!after_set.can_move_before(instr)) break; + if (after_instrs.length && instr.is_jump()) break; + mid_set.add(instr); + const new_instr = new AsmInstruction(base + set_flags + direction, instr.args); + if (matched_cc === null) { + if (base === "b") break; + matched_cc = cc; + } + if (cc !== matched_cc && cc !== negate_cond(matched_cc)) break; + if (flag_check !== null) if_instrs.push(flag_check); + flag_check = null; + if (matched_cc === cc) if_instrs.push(new_instr); + else else_instrs.push(new_instr); + i += 1; + moved_before_streak = 0; + moved_after_streak = 0; + if (instr.is_jump()) break; + if (outputs.includes(cc_reg(factor_cond(matched_cc)[0]))) { + if (matched_cc === cc && !else_instrs.length) { + const b_mn = "b" + negate_cond(matched_cc).value; + flag_check = new AsmInstruction(b_mn, [new AsmGlobalSymbol(label1)]); + } else break; + } + } + if (matched_cc === null) return null; + + i -= moved_before_streak + moved_after_streak; + before_instrs.splice(before_instrs.length - moved_before_streak); + after_instrs.splice(after_instrs.length - moved_after_streak); + + const b_mn = "b" + negate_cond(matched_cc).value; + if (else_instrs.length) { + return new Replacement( + [ + ...before_instrs, + new AsmInstruction(b_mn, [new AsmGlobalSymbol(label1)]), + ...if_instrs, + new AsmInstruction("b", [new AsmGlobalSymbol(label2)]), + Label.new(label1), + ...else_instrs, + Label.new(label2), + ...after_instrs, + ], + i, + ); + } + return new Replacement([...before_instrs, new AsmInstruction(b_mn, [new AsmGlobalSymbol(label1)]), ...if_instrs, Label.new(label1), ...after_instrs], i); + } +} + +/** Replace negated registers in address modes by neg instructions. */ +export class NegatedRegAddrModePattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (!(instr instanceof Instruction)) return null; + if (!instr.args.length || !(instr.args[instr.args.length - 1] instanceof AsmAddressMode)) return null; + const last = instr.args[instr.args.length - 1]; + const addend = last.addend; + const inner = addend instanceof BinOp && addend.op !== "-" ? addend.lhs : addend; + if (!(inner instanceof BinOp) || inner.op !== "-") return null; + const temp = Register.fictive("neg"); + let new_addend; + if (addend instanceof BinOp && addend.op !== "-") new_addend = new BinOp(addend.op, temp, addend.rhs); + else new_addend = temp; + const new_args = [...instr.args]; + new_args[new_args.length - 1] = new AsmAddressMode(last.base, new_addend, last.writeback); + return new Replacement([new AsmInstruction("rsb", [temp, inner.rhs, new AsmLiteral(0)]), new AsmInstruction(instr.mnemonic, new_args)], 1); + } +} + +/** Replace barrel shifted registers in address modes by additional instructions. */ +export class ShiftedRegAddrModePattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (!(instr instanceof Instruction)) return null; + if (!instr.args.length || !(instr.args[instr.args.length - 1] instanceof AsmAddressMode)) return null; + const last = instr.args[instr.args.length - 1]; + const addend = last.addend; + if (!(addend instanceof BinOp) || !ARM_BARREL_SHIFTER_OPS.includes(addend.op)) return null; + const temp = Register.fictive(addend.op); + const new_args = [...instr.args]; + new_args[new_args.length - 1] = new AsmAddressMode(last.base, temp, last.writeback); + return new Replacement([new AsmInstruction("mov", [temp, addend]), new AsmInstruction(instr.mnemonic, new_args)], 1); + } +} + +/** Replace writebacks in address modes by additional instructions. */ +export class AddrModeWritebackPattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (!(instr instanceof Instruction) || !instr.args.length) return null; + const addr = instr.args[instr.args.length - 1]; + if (!(addr instanceof AsmAddressMode) || addr.writeback === null) return null; + const new_args = [...instr.args]; + new_args[new_args.length - 1] = new AsmAddressMode(addr.base, new AsmLiteral(0), null); + if (instr.args[0] === addr.base) { + throw new DecompFailure("Writeback of same register as is being loaded/stored, " + `for instruction: ${instr}`); + } + if (addr.writeback === Writeback.PRE) { + return new Replacement([new AsmInstruction("add", [addr.base, addr.base, addr.addend]), new AsmInstruction(instr.mnemonic, new_args)], 1); + } + return new Replacement([new AsmInstruction(instr.mnemonic, new_args), new AsmInstruction("add", [addr.base, addr.base, addr.addend])], 1); + } +} + +/** Replace register addends in address modes by a separate add instruction. */ +export class RegRegAddrModePattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (!(instr instanceof Instruction) || !instr.args.length) return null; + const arg = instr.args[instr.args.length - 1]; + if (!(arg instanceof AsmAddressMode) || !(arg.addend instanceof Register)) return null; + pyassert(arg.writeback === null); + const temp = Register.fictive("mem_loc"); + const new_args = [...instr.args]; + new_args[new_args.length - 1] = new AsmAddressMode(temp, new AsmLiteral(0), null); + return new Replacement([new AsmInstruction("add", [temp, arg.base, arg.addend]), new AsmInstruction(instr.mnemonic, new_args)], 1); + } +} + +/** Replace barrel shifted registers by additional instructions. */ +export class ShiftedRegPattern extends AsmPattern { + static _sets_flags(base, set_flags) { + return Boolean(base === "tst" || base === "teq" || (["mov", "mvn", "and", "eor", "orr", "orn", "bic"].includes(base) && set_flags)); + } + + static _get_literal_carry(base, arg) { + if (!(arg instanceof AsmLiteral)) return null; + // Carry = bit 31 if the constant is greater than 255 and can be + // produced by shifting an 8-bit value + let value = band(arg.value, 0xffffffff); + if (value >= 0x100 && value < band(value, -value) * 0x100) return shr(value, 31); + if (base === "mov" || base === "mvn") value = bxor(value, 0xffffffff); + if (value >= 0x100 && value < band(value, -value) * 0x100) return shr(value, 31); + return null; + } + + static sets_flags_based_on_barrel_shifter(base, set_flags, args) { + if (!args.length) return false; + const arg = args[args.length - 1]; + return ( + ShiftedRegPattern._sets_flags(base, set_flags) && + (ShiftedRegPattern._get_literal_carry(base, arg) !== null || (arg instanceof BinOp && ARM_BARREL_SHIFTER_OPS.includes(arg.op))) + ); + } + + match(matcher) { + const instr = matcher.input[matcher.index]; + if (!(instr instanceof Instruction) || !instr.args.length) return null; + const [base, , set_flags] = parse_suffix(instr.mnemonic); + const arg = instr.args[instr.args.length - 1]; + + const literal_carry = ShiftedRegPattern._get_literal_carry(base, arg); + if (literal_carry !== null) { + if (!ShiftedRegPattern._sets_flags(base, set_flags)) return null; + return new Replacement([instr, new AsmInstruction("setcarryi.fictive", [new AsmLiteral(literal_carry)])], 1); + } + + if (!(arg instanceof BinOp) || !ARM_BARREL_SHIFTER_OPS.includes(arg.op)) return null; + + const temp = Register.fictive(arg.op); + // (upstream builds the 3-arg form and pops the last arg for rrx; AsmInstruction + // is interned here, so build the final arg list directly) + const shift_args = arg.op === "rrx" ? [temp, arg.lhs] : [temp, arg.lhs, arg.rhs]; + const shift_ins = new AsmInstruction(arg.op, shift_args); + const new_instrs = [shift_ins, new AsmInstruction(instr.mnemonic, [...instr.args.slice(0, -1), temp])]; + if (ShiftedRegPattern._sets_flags(base, set_flags)) new_instrs.push(new AsmInstruction("setcarry.fictive", [temp])); + return new Replacement(new_instrs, 1); + } +} + +export class PopAndReturnPattern extends SimpleAsmPattern { + pattern = make_pattern("pop {x}", "add $sp, $sp, N?", "bx $x"); + replace(m) { + return new Replacement([new AsmInstruction("bx", [new Register("lr")])], m.body.length); + } +} + +export class OldThumbBlxPattern extends SimpleAsmPattern { + pattern = make_pattern("mov $lr, $pc", "bx $x"); + replace(m) { + return new Replacement([new AsmInstruction("blx", [m.regs.get("x")])], m.body.length); + } +} + +export class IndirectTailCallPattern extends SimpleAsmPattern { + pattern = make_pattern("bx $x"); + replace(m) { + if (m.regs.get("x") === new Register("lr")) return null; + return new Replacement([new AsmInstruction("blx", [m.regs.get("x")]), new AsmInstruction("bx", [new Register("lr")])], m.body.length); + } +} + +/** `return fn(...);` may be optimized to perform a `b fn` instead of `bl fn; bx lr`. */ +export class TailCallPattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (instr instanceof Instruction && instr.mnemonic === "b" && instr.args[0] instanceof AsmGlobalSymbol && !matcher.is_local_label(instr.args[0].symbol_name)) { + return new Replacement([new AsmInstruction("bl", instr.args), new AsmInstruction("bx", [new Register("lr")])], 1); + } + return null; + } +} + +/** Replace bl by b when used for intra-function jumps. */ +export class BlBranchPattern extends AsmPattern { + match(matcher) { + const is_local_bl = (instr) => instr.mnemonic === "bl" && instr.args[0] instanceof AsmGlobalSymbol && matcher.is_local_label(instr.args[0].symbol_name); + + const instr = matcher.input[matcher.index]; + if (instr instanceof Instruction && is_local_bl(instr)) { + return new Replacement([new AsmInstruction("b", instr.args)], 1, [new Register("lr")]); + } + + if (matcher.index + 2 >= matcher.input.length) return null; + const instr2 = matcher.input[matcher.index + 1]; + const label = matcher.input[matcher.index + 2]; + if ( + instr instanceof Instruction && + instr2 instanceof Instruction && + label instanceof Label && + is_local_bl(instr2) && + instr.jump_target instanceof JumpTarget && + label.names.includes(instr.jump_target.target) && + instr.is_conditional + ) { + const [base, cc] = parse_suffix(instr.mnemonic); + if (base === "b" && cc !== null) { + const b_mn = "b" + negate_cond(cc).value; + return new Replacement([new AsmInstruction(b_mn, instr2.args)], 2, [new Register("lr")]); + } + } + return null; + } +} + +export class MagicFuncPattern extends SimpleAsmPattern { + pattern = make_pattern("bl"); + replace(m) { + const ins = m.body[0]; + pyassert(ins instanceof Instruction); + pyassert(ins.args[0] instanceof AsmGlobalSymbol); + let target = ins.args[0].symbol_name; + if (target.startsWith("_call_via_")) { + const reg_name = target.slice(10); + let reg = has(ArmArch.prototype.aliased_regs, reg_name) ? ArmArch.prototype.aliased_regs[reg_name] : null; + if (reg === null && ArmArch.prototype.all_regs.includes(new Register(reg_name))) reg = new Register(reg_name); + if (reg !== null) return new Replacement([new AsmInstruction("blx", [reg])], 1); + } + if (target.startsWith("__aeabi_")) target = target.slice(7); + if (has(MAGIC_FUNCTIONS, target)) { + const [mn, arg_str] = MAGIC_FUNCTIONS[target]; + const args = [...arg_str].map((x) => new Register("r" + x)); + return new Replacement([new AsmInstruction(mn, args)], 1, []); + } + return null; + } +} + +export class ArmArch extends Arch { + missing_return() { + return [this.parse("bx", [new Register("lr")], InstructionMeta.missing())]; + } + + normalize_instruction(instr, asm_state) { + if (instr.mnemonic.endsWith(".n") || instr.mnemonic.endsWith(".w")) instr = new AsmInstruction(instr.mnemonic.slice(0, -2), instr.args); + if (asm_state.is_thumb && !asm_state.is_unified) { + if (instr.mnemonic.length > 3 && instr.mnemonic.endsWith("s")) { + throw new DecompFailure("Missing '.syntax unified' marker"); + } + if (THUMB1_FLAG_SETTING.has(instr.mnemonic) && instr.args.every((arg) => !HI_REGS.has(arg))) { + instr = new AsmInstruction(instr.mnemonic + "s", instr.args); + } + } + return this.normalize_instruction_real(instr); + } + + normalize_instruction_real(instr) { + let [base, cc, set_flags, direction] = parse_suffix(instr.mnemonic); + if (cc === Cc.AL) { + cc = null; + instr = new AsmInstruction(base + set_flags + direction, instr.args); + } + const cc_str = cc ? cc.value : ""; + const suffix = cc_str + set_flags + direction; + const args = instr.args; + if (args.length === 3) { + if (base === "lsl" && args[2] === new AsmLiteral(0)) return new AsmInstruction("mov" + suffix, args.slice(0, 2)); + if (base === "add" && !set_flags && args[2] === new AsmLiteral(0)) return new AsmInstruction("mov" + suffix, args.slice(0, 2)); + if (["asr", "lsl", "lsr", "ror"].includes(base)) return new AsmInstruction("mov" + suffix, [args[0], new BinOp(base, args[1], args[2])]); + } + if (args.length === 2) { + if (instr.mnemonic === "mov" && args[0] === args[1] && args[1] === new Register("r8")) return new AsmInstruction("nop", []); + if ( + base === "ldr" && + args[0] instanceof Register && + args[1] instanceof AsmAddressMode && + args[1].base === new Register("sp") && + args[1].addend === new AsmLiteral(4) && + args[1].writeback === Writeback.POST + ) { + return new AsmInstruction("pop" + suffix, [new RegisterList([args[0]])]); + } + if (base === "ldr" && args[1] instanceof Macro && args[1].macro_name === "eqsign") { + const mn = args[1].argument instanceof AsmLiteral ? "movimm.fictive" : "adr"; + return new AsmInstruction(mn + suffix, [args[0], args[1].argument]); + } + if ( + base === "str" && + args[0] instanceof Register && + args[1] instanceof AsmAddressMode && + args[1].base === new Register("sp") && + args[1].addend === new AsmLiteral(-4) && + args[1].writeback === Writeback.PRE + ) { + return new AsmInstruction("push" + suffix, [new RegisterList([args[0]])]); + } + if (base === "cpy") return new AsmInstruction("mov" + suffix, args); + if (base === "neg") return new AsmInstruction("rsb" + suffix, [...args, new AsmLiteral(0)]); + if (base === "rrx") return new AsmInstruction("mov" + suffix, [args[0], new BinOp(base, args[1], new AsmLiteral(1))]); + if (["stm", "ldm", "vstm", "vldm"].includes(base) && !direction) return this.normalize_instruction_real(new AsmInstruction(instr.mnemonic + "ia", args)); + const sp_excl = new AsmAddressMode(new Register("sp"), new AsmLiteral(0), Writeback.PRE); + if ((base === "stm" || base === "vstm") && direction === "db" && args[0] === sp_excl) { + const v = base === "vstm" ? "v" : ""; + return new AsmInstruction(v + "push" + cc_str, [args[1]]); + } + if ((base === "ldm" || base === "vldm") && direction === "ia" && args[0] === sp_excl) { + const v = base === "vldm" ? "v" : ""; + return new AsmInstruction(v + "pop" + cc_str, [args[1]]); + } + if (LENGTH_THREE.has(base)) return this.normalize_instruction_real(new AsmInstruction(instr.mnemonic, [args[0], ...args])); + } + if (instr.mnemonic.startsWith("it")) return new AsmInstruction("nop", []); + return instr; + } + + parse(mnemonic, args, meta) { + const cls = this; + let inputs = []; + let clobbers = []; + let outputs = []; + let jump_target = null; + let function_target = null; + let is_conditional = false; + let is_return = false; + let is_load = false; + let is_store = false; + let is_effectful = true; + let eval_fn = null; + + const instr_str = String(new AsmInstruction(mnemonic, args)); + + let [base, cc, set_flags, direction] = parse_suffix(mnemonic); + let cc_negated; + if (cc !== null) [cc, cc_negated] = factor_cond(cc); + else cc_negated = false; + + const get_inputs = (starti) => { + const ret = []; + for (let arg of args.slice(starti)) { + if (arg instanceof AsmAddressMode) { + ret.push(arg.base); + arg = arg.addend; + } + if (arg instanceof BinOp) { + if (arg.rhs instanceof Register) ret.push(arg.rhs); + arg = arg.lhs; + } + if (arg instanceof BinOp && arg.op === "-" && arg.lhs === new AsmLiteral(0)) arg = arg.rhs; + if (arg instanceof Register) ret.push(arg); + } + return ret; + }; + + if (base === "b") { + pyassert(args.length === 1); + jump_target = get_jump_target(args[0]); + if (cc !== null) { + is_conditional = true; + eval_fn = (s, a) => { + let cond = condition_from_expr(a.regs.get(cc_reg(cc))); + if (cc_negated) cond = cond.negated(); + s.set_branch_condition(cond); + }; + } + } else if (base === "cbz" || base === "cbnz") { + pyassert(args.length === 2); + pyassert(args[0] instanceof Register); + inputs = [args[0]]; + jump_target = get_jump_target(args[1]); + is_conditional = true; + eval_fn = (s, a) => { + const op = base === "cbz" ? "==" : "!="; + s.set_branch_condition(BinaryOp.icmp(a.reg(0), op, new Literal(0))); + }; + } else if (base === "bx" && args[0] === new Register("lr")) { + pyassert(args.length === 1); + inputs = [new Register("lr")]; + is_return = true; + } else if (base === "pop") { + pyassert(args.length === 1); + pyassert(args[0] instanceof RegisterList); + outputs = [...args[0].regs]; + if (args[0].regs.includes(new Register("pc"))) is_return = true; + } else if (base === "blx" && args[0] instanceof Register) { + inputs = [...cls.argument_regs]; + inputs.push(args[0]); + outputs = [...cls.all_return_regs]; + clobbers = [...cls.temp_regs]; + function_target = args[0]; + eval_fn = (s, a) => s.make_function_call(a.reg(0), outputs); + } else if (base === "bl" || base === "blx") { + pyassert(args.length === 1); + inputs = [...cls.argument_regs]; + outputs = [...cls.all_return_regs]; + clobbers = [...cls.temp_regs]; + function_target = args[0]; + eval_fn = (s, a) => s.make_function_call(a.sym_imm(0), outputs); + } else if (base === "ldr" && args[0] === new Register("pc")) { + pyassert(!set_flags); + inputs = get_inputs(1); + outputs = [...cls.all_return_regs]; + is_return = true; + function_target = args[1]; + eval_fn = (s, a) => { + const target = handle_load(a, Type.reg32({ likely_float: false })); + s.make_function_call(target, outputs); + }; + } else if (base === "tablejmp.fictive") { + pyassert(args.length >= 1 && args[0] instanceof Register); + const targets = []; + for (const arg of args.slice(1)) { + pyassert(arg instanceof AsmGlobalSymbol); + targets.push(new JumpTarget(arg.symbol_name)); + } + inputs = [args[0]]; + jump_target = targets; + is_conditional = true; + eval_fn = (s, a) => s.set_switch_expr(a.reg(0), true); + } else if (has(cls.instrs_no_flags, base)) { + pyassert(!set_flags); + pyassert(args[0] instanceof Register); + outputs = [args[0]]; + inputs = get_inputs(1); + is_effectful = false; + is_load = base.startsWith("ldr") || base === "vldr"; + + if (base.startsWith("cvt.")) { + pyassert(args.length === 2 && args[1] instanceof Register); + const mn_parts = base.split("."); + if (mn_parts[1] === "d") outputs.push(other_f64_reg(args[0])); + if (mn_parts[2] === "d") inputs.push(other_f64_reg(args[1])); + } else if (base.endsWith(".d.fictive")) { + for (const reg of args.slice(1)) { + pyassert(reg instanceof Register); + inputs.push(reg, other_f64_reg(reg)); + } + outputs.push(other_f64_reg(args[0])); + } + + eval_fn = (s, a) => { + const target = a.reg_ref(0); + s.set_reg(target, cls.instrs_no_flags[base](a)); + if (outputs.length === 2) s.set_reg(other_f64_reg(target), new SecondF64Half()); + }; + } else if (has(cls.instrs_divmod, base)) { + pyassert(!set_flags); + outputs = [new Register("r0"), new Register("r1")]; + inputs = get_inputs(0); + is_effectful = false; + eval_fn = (s, a) => { + const [div, mod] = cls.instrs_divmod[base](a); + s.set_reg_real(new Register("r0"), div, { function_return: true }); + s.set_reg_real(new Register("r1"), mod, { function_return: true }); + }; + } else if (base === "ldm") { + pyassert(!set_flags); + pyassert(["ia", "ib", "da", "db"].includes(direction)); + pyassert(args[1] instanceof RegisterList); + const reg_list = args[1]; + outputs = [...args[1].regs]; + let writeback = false; + let base_reg; + if (args[0] instanceof Register) base_reg = args[0]; + else { + pyassert(args[0] instanceof AsmAddressMode); + pyassert(args[0].addend === new AsmLiteral(0)); + pyassert(args[0].writeback === Writeback.PRE); + base_reg = args[0].base; + if (outputs.includes(base_reg)) { + // pass + } else { + outputs.push(base_reg); + writeback = true; + } + } + inputs = [base_reg]; + is_effectful = false; + is_load = true; + + eval_fn = (s, a) => { + const loads = []; + for (let i = 0; i < reg_list.regs.length; i++) { + const offset = get_ldm_stm_offset(i, reg_list.regs.length, direction); + const target = new AddressMode(offset, base_reg); + loads.push(deref(target, a.regs, a.stack_info, { size: 4 })); + } + reg_list.regs.forEach((r, k) => { + if (k < loads.length) s.set_reg(r, as_type(loads[k], Type.reg32({ likely_float: false }), true)); + }); + if (writeback) { + const imm = new Literal(4 * reg_list.regs.length); + const op = direction === "ia" || direction === "ib" ? "+" : "-"; + s.set_reg(base_reg, BinaryOp.intptr(a.regs.get(base_reg), op, imm)); + } + }; + } else if (base === "stm") { + pyassert(!set_flags); + pyassert(["ia", "ib", "da", "db"].includes(direction)); + pyassert(args[1] instanceof RegisterList); + const reg_list = args[1]; + inputs = [...args[1].regs]; + let writeback = false; + let base_reg; + if (args[0] instanceof Register) base_reg = args[0]; + else { + pyassert(args[0] instanceof AsmAddressMode); + pyassert(args[0].addend === new AsmLiteral(0)); + pyassert(args[0].writeback === Writeback.PRE); + base_reg = args[0].base; + outputs.push(base_reg); + writeback = true; + } + inputs.push(base_reg); + is_store = true; + + eval_fn = (s, a) => { + reg_list.regs.forEach((r, i) => { + const offset = get_ldm_stm_offset(i, reg_list.regs.length, direction); + const target = new AddressMode(offset, base_reg); + const store = make_store_real(a.regs.get(r), a.regs.get_raw(r), target, a.regs, a.stack_info, Type.reg32({ likely_float: false })); + if (store !== null) s.store_memory(store, r); + }); + if (writeback) { + const imm = new Literal(4 * reg_list.regs.length); + const op = direction === "ia" || direction === "ib" ? "+" : "-"; + s.set_reg(base_reg, BinaryOp.intptr(a.regs.get(base_reg), op, imm)); + } + }; + } else if (base === "mov" && args[0] === new Register("pc")) { + pyassert(args.length === 2 && args[1] instanceof Register); + inputs.push(args[1]); + if (args[1] === new Register("lr")) is_return = true; + else { + jump_target = args[1]; + is_conditional = true; + eval_fn = (s, a) => s.set_switch_expr(a.reg(1)); + } + } else if (has(cls.instrs_store, base)) { + pyassert(args[0] instanceof Register); + inputs = [args[0]]; + is_store = true; + if (args[1] instanceof AsmAddressMode) inputs.push(args[1].base); + eval_fn = (s, a) => { + const store = cls.instrs_store[base](a); + if (store !== null) s.store_memory(store, a.reg_ref(0)); + }; + } else if (has(cls.instrs_nz_flags, base)) { + if (base === "mov" || base === "mvn") pyassert(args.length === 2); + else if (base === "mla") pyassert(args.length === 4); + else pyassert(args.length === 3); + pyassert(args[0] instanceof Register); + outputs = [args[0]]; + inputs = get_inputs(1); + if (set_flags) { + outputs.push(new Register("n"), new Register("z")); + clobbers = [new Register("hi"), new Register("ge"), new Register("gt")]; + } + is_effectful = false; + + eval_fn = (s, a) => { + let val = cls.instrs_nz_flags[base](a); + val = s.set_reg(a.reg_ref(0), val); + if (set_flags) { + if (base === "mov" || base === "mul" || base === "mla") { + const sval = as_type(val, Type.s32(), true, { unify: false }); + s.set_reg(new Register("n"), BinaryOp.scmp(sval, "<", new Literal(0))); + } else { + const top_bit = BinaryOp.int(val, "&", new Literal(2 ** 31)); + s.set_reg(new Register("n"), BinaryOp.icmp(top_bit, "!=", new Literal(0))); + } + s.set_reg(new Register("z"), BinaryOp.icmp(val, "==", new Literal(0))); + } + }; + } else if (has(cls.instrs_mul_full, base)) { + pyassert(args.length === 4); + pyassert(args[0] instanceof Register); + pyassert(args[1] instanceof Register); + outputs = [args[0], args[1]]; + inputs = get_inputs(2); + if (set_flags) { + outputs.push(new Register("n"), new Register("z")); + clobbers = [new Register("hi"), new Register("ge"), new Register("gt")]; + } + is_effectful = false; + + eval_fn = (s, a) => { + let [hi, lo] = cls.instrs_mul_full[base](a); + lo = s.set_reg(a.reg_ref(0), lo); + hi = s.set_reg(a.reg_ref(1), hi); + if (set_flags) { + const shi = as_type(hi, Type.s32(), true, { unify: false }); + s.set_reg(new Register("n"), BinaryOp.scmp(shi, "<", new Literal(0))); + s.set_reg(new Register("z"), new BinaryOp(BinaryOp.icmp(lo, "==", new Literal(0)), "&&", BinaryOp.icmp(hi, "==", new Literal(0)), { type: Type.boolean() })); + } + }; + } else if (base === "smlal" || base === "umlal") { + pyassert(args.length === 4); + pyassert(args[0] instanceof Register); + pyassert(args[1] instanceof Register); + outputs = [args[0], args[1], new Register(base)]; + inputs = get_inputs(0); + if (set_flags) { + outputs.push(new Register("n"), new Register("z")); + clobbers = [new Register("hi"), new Register("ge"), new Register("gt")]; + } + is_effectful = false; + + eval_fn = (s, a) => { + const signed = base === "smlal"; + const tp = signed ? Type.sintish() : Type.uintish(); + const tp64 = signed ? Type.s64() : Type.u64(); + const lhs = as_type(a.reg(2), tp, true); + const rhs = as_type(a.reg(3), tp, true); + const orig = BinaryOp.int(a.reg(0), "+", BinaryOp.int(a.reg(1), "<<", new Literal(32))); + const mul = BinaryOp.int(lhs, "*", rhs); + let mlal = as_type(BinaryOp.int(orig, "+", mul), tp64, true); + mlal = s.set_reg(new Register(base), mlal); + const upper = BinaryOp.int(mlal, ">>", new Literal(32)); + const lo = as_type(mlal, Type.int_of_size(32), false); + const hi = as_type(upper, Type.int_of_size(32), false); + s.set_reg(a.reg_ref(0), lo); + s.set_reg(a.reg_ref(1), hi); + if (set_flags) { + const as_s64 = as_type(mlal, Type.s64(), true, { unify: false }); + s.set_reg(new Register("n"), BinaryOp.scmp(as_s64, "<", new Literal(0))); + s.set_reg(new Register("z"), BinaryOp.icmp(mlal, "==", new Literal(0))); + } + }; + } else if (base === "tst" || base === "teq") { + pyassert(args.length === 2); + inputs = get_inputs(0); + outputs = [new Register("n"), new Register("z")]; + clobbers = [new Register("hi"), new Register("ge"), new Register("gt")]; + is_effectful = false; + + eval_fn = (s, a) => { + const lhs = a.reg(0); + const rhs = a.reg_or_imm(1); + let val; + if (base === "tst") { + val = BinaryOp.int(lhs, "&", rhs); + s.set_reg(new Register("z"), BinaryOp.icmp(val, "==", new Literal(0))); + } else { + val = BinaryOp.int(lhs, "^", rhs); + s.set_reg(new Register("z"), BinaryOp.icmp(lhs, "==", rhs)); + } + const top_bit = BinaryOp.int(val, "&", new Literal(2 ** 31)); + s.set_reg(new Register("n"), BinaryOp.icmp(top_bit, "!=", new Literal(0))); + }; + } else if (mnemonic === "setcarryi.fictive") { + pyassert(args.length === 1 && args[0] instanceof AsmLiteral); + const imm = args[0].value; + outputs = [new Register("c"), new Register("hi")]; + inputs = imm ? [new Register("z")] : []; + is_effectful = false; + + eval_fn = (s, a) => { + s.set_reg(new Register("c"), new Literal(imm)); + if (imm === 0) s.set_reg(new Register("hi"), new Literal(0)); + else { + const z = condition_from_expr(a.regs.get(new Register("z"))); + s.set_reg(new Register("hi"), z.negated()); + } + }; + } else if (mnemonic === "setcarry.fictive") { + pyassert(args.length === 1 && args[0] instanceof Register); + outputs = [new Register("c"), new Register("hi")]; + inputs = [new Register("z")]; + is_effectful = false; + + eval_fn = (s, a) => { + const c = s.set_reg(new Register("c"), new CarryBit(a.reg(0))); + const z = condition_from_expr(a.regs.get(new Register("z"))); + const hi = new BinaryOp(c, "&&", z.negated(), { type: Type.boolean() }); + s.set_reg(new Register("hi"), hi); + }; + } else if (has(cls.instrs_add, base)) { + pyassert(args.length === 3 && args[0] instanceof Register); + outputs = [args[0]]; + if (set_flags) outputs.push(...cls.flag_regs); + inputs = get_inputs(1); + if (base === "adc") inputs.push(new Register("c")); + is_effectful = false; + + eval_fn = (s, a) => { + let val = cls.instrs_add[base](a); + val = s.set_reg(a.reg_ref(0), val); + if (set_flags) set_arm_flags_from_add(s, val); + }; + } else if (has(cls.instrs_sub, base)) { + pyassert(args.length === 3 && args[0] instanceof Register); + outputs = [args[0]]; + if (set_flags) outputs.push(...cls.flag_regs); + inputs = get_inputs(1); + if (base === "sbc" || base === "rsc") inputs.push(new Register("c")); + is_effectful = false; + + eval_fn = (s, a) => { + let val = cls.instrs_sub[base](a); + if (val instanceof BinaryOp) val = fold_divmod(val); + val = fold_mul_chains(val); + val = s.set_reg(a.reg_ref(0), val); + if (set_flags) { + s.set_reg(new Register("z"), BinaryOp.icmp(val, "==", new Literal(0, { type: val.type }))); + let sval = as_type(val, Type.s32(), true, { unify: false }); + s.set_reg(new Register("n"), BinaryOp.scmp(sval, "<", new Literal(0))); + const v = fn_op("M2C_OVERFLOW", [sval], Type.boolean()); + s.set_reg(new Register("v"), v); + const uval = as_type(val, Type.u32(), true, { unify: false }); + sval = as_type(val, Type.s32(), true, { unify: false }); + const s64u = as_type(uval, Type.s64(), false, { unify: false }); + const s64s = as_type(sval, Type.s64(), false, { unify: false }); + s.set_reg(new Register("c"), BinaryOp.scmp(s64u, ">=", new Literal(0))); + s.set_reg(new Register("hi"), BinaryOp.scmp(s64u, ">", new Literal(0))); + s.set_reg(new Register("ge"), BinaryOp.scmp(s64s, ">=", new Literal(0))); + s.set_reg(new Register("gt"), BinaryOp.scmp(s64s, ">", new Literal(0))); + } + }; + } else if (base === "cmp") { + pyassert(args.length === 2 && args[0] instanceof Register); + outputs = [...cls.flag_regs]; + inputs = get_inputs(0); + is_effectful = false; + eval_fn = (s, a) => eval_arm_cmp(s, a.reg(0), a.reg_or_imm(1)); + } else if (base === "cmn") { + pyassert(args.length === 2 && args[0] instanceof Register); + outputs = [...cls.flag_regs]; + inputs = get_inputs(0); + is_effectful = false; + eval_fn = (s, a) => { + const lhs = a.reg(0); + const rhs = a.reg_or_imm(1); + if (rhs instanceof Literal && band(rhs.value, 0xffffffff) !== 0x80000000) eval_arm_cmp(s, lhs, new Literal(-rhs.value)); + else set_arm_flags_from_add(s, handle_add_real(lhs, rhs, a)); + }; + } else if (has(cls.instrs_float_comp, base)) { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + if (mnemonic.includes(".d.")) inputs = [args[0], other_f64_reg(args[0]), args[1], other_f64_reg(args[1])]; + else inputs = [args[0], args[1]]; + + let [cmp_cc, handler] = cls.instrs_float_comp[base]; + let fc_negated; + [cmp_cc, fc_negated] = factor_cond(cmp_cc); + const creg = cc_reg(cmp_cc); + + clobbers = cls.flag_regs.filter((r) => r !== creg); + outputs = [new Register("r0"), creg]; + is_effectful = false; + + eval_fn = (s, a) => { + const cond = handler(a); + s.set_reg_real(new Register("r0"), cond, { function_return: true }); + s.set_reg(creg, fc_negated ? cond.negated() : cond); + }; + // (upstream rebinds cc_negated here; the outer `cc` stays as parsed) + cc_negated = fc_negated; + } else if (cls.instrs_ignore.has(base)) { + is_effectful = false; + } else { + let maybe_dest_first; + if (args.length && args[0] instanceof Register && base !== "bx") { + inputs = args.slice(1).filter((r) => r instanceof Register); + outputs = [args[0]]; + maybe_dest_first = true; + } else maybe_dest_first = false; + + eval_fn = (s, a) => { + const error = new ErrorExpr(`unknown instruction: ${instr_str}`); + if (maybe_dest_first) s.set_reg_real(a.reg_ref(0), error, { emit_exactly_once: true }); + else s.write_statement(new ExprStmt(error)); + }; + } + + if (cc !== null) inputs.push(cc_reg(cc)); + + if (ShiftedRegPattern.sets_flags_based_on_barrel_shifter(base, set_flags, args)) outputs.push(new Register("c"), new Register("hi")); + + return new Instruction({ + mnemonic, + args, + meta, + inputs, + clobbers, + outputs, + jump_target, + function_target, + is_conditional, + is_return, + is_store, + is_load, + is_effectful, + eval_fn, + }); + } + + default_function_abi_candidate_slots() { + return [0, 1, 2, 3].map((i) => new AbiArgSlot(new ArgLoc(null, i, new Register(`r${i}`)), Type.any_reg())); + } + + is_likely_partial_offset(addend) { + return addend < 0x1000000 && pymod(addend, 0x100) === 0; + } + + arg_name(loc) { + if (loc.offset !== null) return `arg${format_hex(floordiv(loc.offset, 4) + 4)}`; + pyassert(loc.reg !== null); + return `arg${loc.reg.register_name.slice(1)}`; + } + + /** Compute stack positions/registers used by a function according to the agbcc ABI. */ + function_abi(fn_sig, likely_regs, { for_call }) { + void for_call; + const known_slots = []; + let candidate_slots = []; + if (fn_sig.params_known) { + let offset = 0; + if (fn_sig.return_type.is_struct() && fn_sig.return_type.get_parameter_size_align_bytes()[0] > 4) { + known_slots.push(new AbiArgSlot(new ArgLoc(null, 0, new Register("r0")), Type.ptr(fn_sig.return_type), { name: "__return__", comment: "return" })); + offset = 4; + } + + for (const param of fn_sig.params) { + const param_type = param.type.decay(); + let [size, align] = param_type.get_parameter_size_align_bytes(); + size = band(size + 3, ~3); + offset = band(offset + align - 1, -align); + const name = param.name; + for (let i = floordiv(offset, 4); i < floordiv(offset + size, 4); i++) { + const unk_offset = 4 * i - offset; + let reg2 = null; + let stack_loc = null; + if (i < 4) reg2 = new Register(`r${i}`); + else stack_loc = (i - 4) * 4; + let name2, sub_type, comment; + if (size > 4) { + name2 = name ? `${name}_unk${format(unk_offset, "X")}` : null; + sub_type = Type.any(); + comment = `${param_type}+${format(unk_offset, "#x")}`; + } else { + pyassert(unk_offset === 0); + name2 = name; + sub_type = param_type; + comment = null; + } + known_slots.push(new AbiArgSlot(new ArgLoc(stack_loc, i, reg2), sub_type, { name: name2, comment })); + } + offset += size; + } + + if (fn_sig.is_variadic) { + for (let i = floordiv(offset, 4); i < 4; i++) candidate_slots.push(new AbiArgSlot(new ArgLoc(null, i, new Register(`r${i}`)), Type.any_reg())); + } + } else { + candidate_slots = this.default_function_abi_candidate_slots(); + } + + const valid_extra_regs = new Set(); + for (const slot of known_slots) if (slot.loc.reg !== null) valid_extra_regs.add(slot.loc.reg); + const possible_slots = []; + + let lasti = -1; + for (let i = 0; i < 4; i++) { + if (!likely_regs.has(new Register(`r${i}`))) break; + lasti = i; + } + for (let i = lasti; i > 0; i--) { + if (likely_regs.get(new Register(`r${i}`))) likely_regs.set(new Register(`r${i - 1}`), true); + } + + for (const slot of candidate_slots) { + const reg = slot.loc.reg; + if (reg === null || !likely_regs.has(reg)) continue; + + let require = null; + if (slot === candidate_slots[0]) { + // pass + } else if (reg === new Register("r1")) require = ["r0"]; + else if (reg === new Register("r2")) require = ["r1"]; + else if (reg === new Register("r3")) require = ["r2"]; + if (require && !require.some((r) => valid_extra_regs.has(new Register(r)))) continue; + + valid_extra_regs.add(reg); + + if (!likely_regs.get(reg)) continue; + + possible_slots.push(slot); + } + + return new Abi({ arg_slots: known_slots, possible_slots }); + } + + function_return(expr) { + return new Map([ + [new Register("r0"), as_type(expr, Type.intptr(), true, { unify: false })], + [new Register("r1"), fn_op("SECOND_REG", [expr], Type.reg32({ likely_float: false }))], + ]); + } +} + +{ + const argument_regs = ["r0", "r1", "r2", "r3"].map((r) => new Register(r)); + const simple_temp_regs = [ + new Register("r12"), + ...Array.from({ length: 16 }, (_, i) => new Register(`s${i}`)), + ...Array.from({ length: 8 }, (_, i) => new Register(`d${i}`)), + ...Array.from({ length: 4 }, (_, i) => new Register(`q${i}`)), + ]; + const flag_regs = ["n", "z", "c", "v", "hi", "ge", "gt"].map((r) => new Register(r)); + const temp_regs = [...argument_regs, ...simple_temp_regs, ...flag_regs]; + const saved_regs = [ + new Register("lr"), + ...Array.from({ length: 8 }, (_, i) => new Register(`r${i + 4}`)), + ...Array.from({ length: 16 }, (_, i) => new Register(`s${i + 16}`)), + ...Array.from({ length: 8 }, (_, i) => new Register(`d${i + 8}`)), + ...Array.from({ length: 4 }, (_, i) => new Register(`q${i + 4}`)), + ]; + const stack_pointer_reg = new Register("sp"); + const R = (n) => new Register(n); + + Object.assign(ArmArch.prototype, { + arch: Target.ArchEnum.ARM, + re_comment: String.raw`^[ \t]*#.*|[@;].*`, + supports_dollar_regs: false, + home_space_size: 0, + stack_pointer_reg, + frame_pointer_regs: [R("r7"), R("r11")], + return_address_reg: R("lr"), + base_return_regs: [[R("r0"), false]], + all_return_regs: [R("r0"), R("r1")], + argument_regs, + simple_temp_regs, + flag_regs, + temp_regs, + saved_regs, + all_regs: [...saved_regs, ...temp_regs, stack_pointer_reg, R("pc")], + aliased_regs: { + a1: R("r0"), + a2: R("r1"), + a3: R("r2"), + a4: R("r3"), + v1: R("r4"), + v2: R("r5"), + v3: R("r6"), + v4: R("r7"), + v5: R("r8"), + v6: R("r9"), + v7: R("r10"), + v8: R("r11"), + wr: R("r7"), + sb: R("r9"), + tr: R("r9"), + sl: R("r10"), + fp: R("r11"), + ip: R("r12"), + r13: R("sp"), + r14: R("lr"), + r15: R("pc"), + }, + asm_patterns: [ + new AddPcPcPattern(), + new ShortJumpTablePattern(), + new ConditionalInstrPattern(), + new NegatedRegAddrModePattern(), + new ShiftedRegAddrModePattern(), + new ShiftedRegPattern(), + new AddrModeWritebackPattern(), + new RegRegAddrModePattern(), + new PopAndReturnPattern(), + new OldThumbBlxPattern(), + new IndirectTailCallPattern(), + new TailCallPattern(), + new BlBranchPattern(), + new MagicFuncPattern(), + ], + instrs_ignore: new Set(["push", "vpush", "vpop", "nop"]), + instrs_no_flags: { + // Bit-fiddling + clz: (a) => fn_op("CLZ", [a.reg(1)], Type.intish()), + rbit: (a) => fn_op("REVERSE_BITS", [a.reg(1)], Type.intish()), + rev: (a) => fn_op("BSWAP32", [a.reg(1)], Type.intish()), + rev16: (a) => fn_op("BSWAP16X2", [a.reg(1)], Type.intish()), + revsh: (a) => fn_op("BSWAP16", [a.reg(1)], Type.s16()), + // Shifts + lsl: (a) => handle_sll(a, { arm: true }), + asr: (a) => handle_shift_right(a, { arm: true, signed: true }), + lsr: (a) => handle_shift_right(a, { arm: true, signed: false }), + ror: (a) => fn_op("ROTATE_RIGHT", [a.reg(1), a.reg_or_imm(2)], Type.intish()), + rrx: (a) => fn_op("ARM_RRX", [a.reg(1), a.regs.get(new Register("c"))], Type.intish()), + // Immediate movs + adr: (a) => handle_la(a), + "movimm.fictive": (a) => a.full_imm(1), + // Loading instructions + ldr: (a) => handle_load(a, Type.reg32({ likely_float: false })), + ldrb: (a) => handle_load(a, Type.u8()), + ldrsb: (a) => handle_load(a, Type.s8()), + ldrh: (a) => handle_load(a, Type.u16()), + ldrsh: (a) => handle_load(a, Type.s16()), + vldr: (a) => handle_load(a, vreg_type(a.reg_ref(0))), + // Arithmetic + smulbb: (a) => BinaryOp.int(a.reg(1), "*", a.reg(2)), + smlabb: (a) => handle_add_real(a.reg(3), BinaryOp.int(a.reg(1), "*", a.reg(2)), a), + sdiv: (a) => BinaryOp.sint(a.reg(1), "/", a.reg(2)), + udiv: (a) => BinaryOp.uint(a.reg(1), "/", a.reg(2)), + "smod.fictive": (a) => BinaryOp.sint(a.reg(1), "%", a.reg(2)), + "umod.fictive": (a) => BinaryOp.uint(a.reg(1), "%", a.reg(2)), + // Floating point arithmetic + "add.s.fictive": (a) => handle_add_float(a), + "sub.s.fictive": (a) => BinaryOp.f32(a.reg(1), "-", a.reg(2)), + "div.s.fictive": (a) => BinaryOp.f32(a.reg(1), "/", a.reg(2)), + "mul.s.fictive": (a) => BinaryOp.f32(a.reg(1), "*", a.reg(2)), + "sqrt.s.fictive": (a) => fn_op("sqrtf", [as_f32(a.reg(1))], Type.f32()), + "round.s.fictive": (a) => fn_op("roundf", [as_f32(a.reg(1))], Type.f32()), + "add.d.fictive": (a) => handle_add_double(a), + "sub.d.fictive": (a) => BinaryOp.f64(a.dreg(1), "-", a.dreg(2)), + "div.d.fictive": (a) => BinaryOp.f64(a.dreg(1), "/", a.dreg(2)), + "mul.d.fictive": (a) => BinaryOp.f64(a.dreg(1), "*", a.dreg(2)), + "sqrt.d.fictive": (a) => fn_op("sqrt", [as_f64(a.dreg(1))], Type.f64()), + "round.d.fictive": (a) => fn_op("round", [as_f64(a.dreg(1))], Type.f64()), + // Floating point conversions + "cvt.d.s.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.f32()), + "cvt.d.w.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.intish()), + "cvt.d.u.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.u32()), + "cvt.s.d.fictive": (a) => handle_convert(a.dreg(1), Type.f32(), Type.f64()), + "cvt.s.w.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.intish()), + "cvt.s.u.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.u32()), + "cvt.w.d.fictive": (a) => handle_convert(a.dreg(1), Type.s32(), Type.f64()), + "cvt.w.s.fictive": (a) => handle_convert(a.reg(1), Type.s32(), Type.f32()), + "cvt.u.d.fictive": (a) => handle_convert(a.dreg(1), Type.u32(), Type.f64()), + "cvt.u.s.fictive": (a) => handle_convert(a.reg(1), Type.u32(), Type.f32()), + }, + instrs_float_comp: { + "c.eq.s.fictive": [Cc.EQ, (a) => BinaryOp.fcmp(a.reg(0), "==", a.reg(1))], + "c.lt.s.fictive": [Cc.CC, (a) => BinaryOp.fcmp(a.reg(0), "<", a.reg(1))], + "c.ge.s.fictive": [Cc.CS, (a) => BinaryOp.fcmp(a.reg(0), ">=", a.reg(1))], + "c.le.s.fictive": [Cc.LS, (a) => BinaryOp.fcmp(a.reg(0), "<=", a.reg(1))], + "c.gt.s.fictive": [Cc.HI, (a) => BinaryOp.fcmp(a.reg(0), ">", a.reg(1))], + "c.neq.s.fictive": [Cc.NE, (a) => BinaryOp.fcmp(a.reg(0), "==", a.reg(1)).negated()], + "c.eq.d.fictive": [Cc.EQ, (a) => BinaryOp.dcmp(a.dreg(0), "==", a.dreg(1))], + "c.lt.d.fictive": [Cc.CC, (a) => BinaryOp.dcmp(a.dreg(0), "<", a.dreg(1))], + "c.ge.d.fictive": [Cc.CS, (a) => BinaryOp.dcmp(a.dreg(0), ">=", a.dreg(1))], + "c.le.d.fictive": [Cc.LS, (a) => BinaryOp.dcmp(a.dreg(0), "<=", a.dreg(1))], + "c.gt.d.fictive": [Cc.HI, (a) => BinaryOp.dcmp(a.dreg(0), ">", a.dreg(1))], + "c.neq.d.fictive": [Cc.NE, (a) => BinaryOp.dcmp(a.dreg(0), "==", a.dreg(1)).negated()], + }, + instrs_divmod: { + "sdivmod.fictive": (a) => [BinaryOp.sint(a.reg(0), "/", a.reg(1)), BinaryOp.sint(a.reg(0), "%", a.reg(1))], + "udivmod.fictive": (a) => [BinaryOp.uint(a.reg(0), "/", a.reg(1)), BinaryOp.uint(a.reg(0), "%", a.reg(1))], + }, + instrs_nz_flags: { + mov: (a) => handle_arm_mov(a), + mul: (a) => BinaryOp.int(a.reg(1), "*", a.reg(2)), + mla: (a) => BinaryOp.int(BinaryOp.int(a.reg(1), "*", a.reg(2)), "+", a.reg(3)), + mvn: (a) => handle_bitinv(a.reg_or_imm(1)), + and: (a) => replace_bitand(BinaryOp.int(a.reg(1), "&", a.reg_or_imm(2))), + orr: (a) => handle_or(a.reg(1), a.reg_or_imm(2), { is_arm: true }), + eor: (a) => handle_xor(a.reg(1), a.reg_or_imm(2)), + bic: (a) => BinaryOp.int(a.reg(1), "&", UnaryOp.int("~", a.reg_or_imm(2))), + orn: (a) => BinaryOp.int(a.reg(1), "|", UnaryOp.int("~", a.reg_or_imm(2))), + }, + instrs_mul_full: { + smull: (a) => [fold_divmod(BinaryOp.int(a.reg(2), "MULT_HI", a.reg(3))), BinaryOp.int(a.reg(2), "*", a.reg(3))], + umull: (a) => [fold_divmod(BinaryOp.int(a.reg(2), "MULTU_HI", a.reg(3))), BinaryOp.int(a.reg(2), "*", a.reg(3))], + }, + instrs_store: { + str: (a) => make_store(a, Type.reg32({ likely_float: false })), + strb: (a) => make_store(a, Type.int_of_size(8)), + strh: (a) => make_store(a, Type.int_of_size(16)), + vstr: (a) => make_store(a, vreg_type(a.reg_ref(0))), + }, + instrs_add: { + add: (a) => handle_add_arm(a), + adc: (a) => handle_add_real(handle_add_arm(a), a.regs.get(new Register("c")), a), + }, + instrs_sub: { + sub: (a) => handle_sub_arm(a), + rsb: (a) => handle_sub(a.reg_or_imm(2), a.reg(1)), + sbc: (a) => handle_add_real(handle_sub(a.reg(1), a.reg_or_imm(2)), condition_from_expr(a.regs.get(new Register("c"))).negated(), a), + rsc: (a) => handle_add_real(handle_sub(a.reg_or_imm(2), a.reg(1)), condition_from_expr(a.regs.get(new Register("c"))).negated(), a), + }, + }); +} + +/** Arch variant that follows the APCS ABI used on Gameboy Advance. */ +export class ArmGbaArch extends ArmArch {} +ArmGbaArch.prototype.base_struct_align = 4; diff --git a/packages/romdev-m2c/src/arch_mips.js b/packages/romdev-m2c/src/arch_mips.js new file mode 100644 index 00000000..e7cdf558 --- /dev/null +++ b/packages/romdev-m2c/src/arch_mips.js @@ -0,0 +1,1134 @@ +// Port of m2c/arch_mips.py +import { DecompFailure } from "./error.js"; +import { Target } from "./options.js"; +import { Label } from "./asm_file.js"; +import { AsmAddressMode, AsmGlobalSymbol, AsmInstruction, AsmLiteral, Register, get_jump_target } from "./asm_instruction.js"; +import { Instruction, InstructionMeta, StackLocation } from "./instruction.js"; +import { AsmPattern, Replacement, SimpleAsmPattern, make_pattern } from "./asm_pattern.js"; +import { + Abi, + AbiArgSlot, + Arch, + ArgLoc, + BinaryOp, + Cast, + CommentStmt, + ErrorExpr, + ExprStmt, + Literal, + SecondF64Half, + UnaryOp, + as_f32, + as_f64, + as_intish, + as_s64, + as_type, + as_u32, + as_u64, + format_hex, +} from "./translate.js"; +import { + condition_from_expr, + error_stmt, + fn_op, + fold_divmod, + fold_mul_chains, + handle_add, + handle_add_double, + handle_add_float, + handle_add_real, + handle_addi_mips, + handle_bgez, + handle_conditional_move, + handle_convert, + handle_la, + handle_load, + handle_lw, + handle_lwl, + handle_lwr, + handle_or, + handle_shift_right, + handle_sltiu, + handle_sltu, + handle_swl, + handle_swr, + handle_xor, + imm_add_32, + load_upper, + make_store, + void_fn_op, +} from "./evaluate.js"; +import { Type } from "./types.js"; +import { band, floordiv, format, has, int_, pyassert } from "./py.js"; + +const R = (n) => new Register(n); + +const LENGTH_TWO = new Set(["neg", "negu", "not", "neg.s", "abs.s", "sqrt.s", "neg.d", "abs.d", "sqrt.d"]); +const LENGTH_THREE = new Set([ + "slt", "slti", "sltu", "sltiu", "add", "addi", "addiu", "addu", "sub", "subu", "daddi", "daddiu", "dsubu", + "add.s", "sub.s", "div.s", "mul.s", "add.d", "sub.d", "div.d", "mul.d", "ori", "and", "or", "nor", "xor", + "andi", "xori", "sll", "sllv", "srl", "srlv", "sra", "srav", "dsll", "dsll32", "dsllv", "dsrl", "dsrl32", + "dsrlv", "dsra", "dsra32", "dsrav", "div", "divu", "ddiv", "ddivu", +]); + +export function other_f64_reg(reg) { + pyassert(reg.is_float(), "tried to get complement reg of non-floating point register"); + const num = int_(reg.register_name.slice(1)); + return R(`f${num ^ 1}`); +} + +class DivPattern extends SimpleAsmPattern { + pattern = make_pattern("bnez $q, .A", "*", "break", ".A:", "li $at, -1", "bne $q, $at, .B", "li $at, 0x80000000", "bne $p, $at, .B", "nop", "break", ".B:"); + replace(m) { + return new Replacement([m.body[1]], m.body.length - 1); + } +} + +class DivuPattern extends SimpleAsmPattern { + pattern = make_pattern("bnez $q, .A", "nop", "break", ".A:"); + replace(m) { + return new Replacement([], m.body.length - 1); + } +} + +/** Modulo by power of two. */ +class ModP2Pattern1 extends SimpleAsmPattern { + pattern = make_pattern("bgez $i, .A", "andi $o, $i, N", "beqz $o, .A", "nop", "addiu $o, $o, (-1 - N)", ".A:"); + replace(m) { + const val = band(m.literals.get("N"), 0xffff) + 1; + if (band(val, val - 1)) return null; + const mod = new AsmInstruction("mod.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(val)]); + return new Replacement([mod], m.body.length - 1); + } +} + +/** Modulo by power of two where the mask is too big to fit an andi. */ +class ModP2Pattern2 extends SimpleAsmPattern { + pattern = make_pattern("li $at, HI", "addiu $at, $at, LO?", "bgez $i, .A", "and $o, $i, $at", "beqz $o, .A", "addiu $at, $at, 1", "subu $o, $o, $at", ".A:"); + replace(m) { + let val = band(m.literals.get("HI"), 0xffffffff) + 1; + if (m.literals.has("LO")) val += band(m.literals.get("LO") + 0x8000, 0xffff) - 0x8000; + if (!val || band(val, val - 1)) return null; + const mod = new AsmInstruction("mod.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(val)]); + return new Replacement([mod], m.body.length - 1); + } +} + +/** Division by power of two where input reg != output reg. */ +class DivP2Pattern1 extends SimpleAsmPattern { + pattern = make_pattern("bgez $i, .A", "sra $o, $i, N", "addiu $at, $i, ((1 << N) - 1)", "sra $o, $at, N", ".A:"); + replace(m) { + const shift = band(m.literals.get("N"), 0x1f); + const div = new AsmInstruction("div.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(2 ** shift)]); + return new Replacement([div], m.body.length - 1); + } +} + +/** Division by power of two where input reg = output reg. */ +class DivP2Pattern2 extends AsmPattern { + pattern1 = make_pattern("bgez $x, .A", "move $at, $x", "addiu $at, $x, M", ".A:", "sra $x, $at, N"); + pattern2 = make_pattern("bgez $x, .A", "nop", "addiu $x, $x, M", ".A:", "sra $x, $x, N"); + pattern3 = make_pattern("bltzl $x, .A", "addiu $x, $x, M", ".A:", "sra $x, $x, N"); + match(matcher) { + for (const pattern of [this.pattern1, this.pattern2, this.pattern3]) { + const m = matcher.try_match(pattern); + if (!m) continue; + const shift = band(m.literals.get("N"), 0x1f); + if (m.literals.get("M") !== 2 ** shift - 1) continue; + const div = new AsmInstruction("div.fictive", [m.regs.get("x"), m.regs.get("x"), new AsmLiteral(2 ** shift)]); + return new Replacement([div], m.body.length); + } + return null; + } +} + +class Div2S16Pattern extends SimpleAsmPattern { + pattern = make_pattern("sll $i, $i, N", "sra $o, $i, N", "srl $i, $i, 0x1f", "addu $o, $o, $i", "sra $o, $o, 1"); + replace(m) { + const div = new AsmInstruction("div.fictive", [m.regs.get("o"), m.regs.get("o"), new AsmLiteral(2)]); + return new Replacement([m.body[0], m.body[1], div], m.body.length); + } +} + +class Div2S32Pattern1 extends SimpleAsmPattern { + pattern = make_pattern("srl $t, $i, 0x1f", "addu $t, $i, $t", "sra $o, $t, 1"); + replace(m) { + if (m.regs.get("t") === m.regs.get("i")) return null; + const div = new AsmInstruction("div.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(2)]); + return new Replacement([div], m.body.length); + } +} + +class Div2S32Pattern2 extends SimpleAsmPattern { + pattern = make_pattern("srl $t, $i, 0x1f", "addu $i, $i, $t", "sra $o, $i, 1"); + replace(m) { + if (m.regs.get("t") === m.regs.get("i")) return null; + const div = new AsmInstruction("div.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(2)]); + return new Replacement([div], m.body.length); + } +} + +class UtfPattern extends SimpleAsmPattern { + pattern = make_pattern("bgez $x, .A", "cvt.s.w $o, $i", "li $at, 0x4f800000", "mtc1", "nop", "add.s", ".A:"); + replace(m) { + const new_instr = new AsmInstruction("cvt.s.u.fictive", [m.regs.get("o"), m.regs.get("i")]); + return new Replacement([new_instr], m.body.length - 1); + } +} + +class FtuPattern extends SimpleAsmPattern { + pattern = make_pattern( + "cfc1 $o, $31", "nop", "andi", "andi?", "*", "*", "li?", "mtc1", "mtc1?", "li", "*", "ctc1", "nop", "*", + "cfc1", "nop", "andi", "andi?", "bnez", "nop", "mfc1", "li", "b", "or", ".A:", "b", "li", "*", "*", "nop", "bltz", "nop", + ); + replace(m) { + const sub = m.body.find((x) => x instanceof Instruction && x.mnemonic.startsWith("sub")); + if (sub === undefined) throw new Error("StopIteration"); + const parts = sub.mnemonic.split("."); + const fmt = parts[parts.length - 1]; + const args = [m.regs.get("o"), sub.args[1]]; + const new_instr = fmt === "s" ? new AsmInstruction("cvt.u.s.fictive", args) : new AsmInstruction("cvt.u.d.fictive", args); + return new Replacement([new_instr], m.body.length); + } +} + +class Mips1DoubleLoadStorePattern extends AsmPattern { + lwc_pattern = make_pattern("lwc1", "lwc1"); + swc_pattern = make_pattern("swc1", "swc1"); + match(matcher) { + if (matcher.arch instanceof MipseeArch) return null; + const m = matcher.try_match(this.lwc_pattern) || matcher.try_match(this.swc_pattern); + if (!m) return null; + const [a, b] = m.body; + pyassert(a instanceof Instruction); + pyassert(b instanceof Instruction); + let [ra, ma] = a.args; + let [rb, mb] = b.args; + if (!(ra instanceof Register && ra.is_float() && other_f64_reg(ra) === rb && ma instanceof AsmAddressMode && mb instanceof AsmAddressMode && ma.base === mb.base)) return null; + const num = int_(ra.register_name.slice(1)); + if (num % 2 === 1) { + [ra, rb] = [rb, ra]; + [ma, mb] = [mb, ma]; + } + if (ma.addend instanceof AsmLiteral && mb.addend instanceof AsmLiteral && ma.addend.value !== mb.addend.value + 4) return null; + const new_mn = a.mnemonic === "lwc1" ? "ldc1" : "sdc1"; + const new_instr = new AsmInstruction(new_mn, [ra, mb]); + return new Replacement([new_instr], m.body.length); + } +} + +class GccSqrtPatternJal extends SimpleAsmPattern { + pattern = make_pattern("sqrt.s $o, $i", "c.eq.s", "nop?", "bc1t", "*", "jal sqrtf", "nop", "mov.s $o, $f0?"); + replace(m) { + return new Replacement([m.body[0], m.wildcard_items[0]], m.body.length); + } +} + +class GccSqrtPatternJalr extends SimpleAsmPattern { + pattern = make_pattern("sqrt.s $o, $i", "c.eq.s", "nop?", "bc1t", "*", "lui $x, %hi(sqrtf)", "addiu $x, $x, %lo(sqrtf)", "jalr $ra, $x", "nop", "mov.s $o, $f0?"); + replace(m) { + return new Replacement([m.body[0], m.wildcard_items[0]], m.body.length); + } +} + +class TrapuvPattern extends SimpleAsmPattern { + pattern = make_pattern("li $x, 0xfffa0000", "move $y, $sp", "addiu $sp, $sp, N", "ori $x, $x, 0x5a5a", ".loop:", "addiu $y, $y, -8", "sw $x, ($y)", "bne $y, $sp, .loop", "sw $x, 4($y)"); + replace(m) { + const new_instr = new AsmInstruction("trapuv.fictive", []); + return new Replacement([m.body[2], new_instr], m.body.length); + } +} + +/** Strip PIC .cpload pattern at the top of functions. */ +class SetGpPattern extends AsmPattern { + pattern = make_pattern("*", "addiu $gp, $gp, _", "addu $gp, $gp, $t9"); + match(matcher) { + if (matcher.index !== 0) return null; + const m = matcher.try_match(this.pattern); + if (m === null) return null; + const nop = new AsmInstruction("nop", []); + return new Replacement([nop], m.body.length); + } +} + +/** IDO unrolled memcpy, used e.g. for struct copies. */ +class MemcpyPatternBase extends AsmPattern { + match(matcher) { + let m = null; + let pattern = null; + for (const p of [this.pattern_mips1, this.pattern_mips2]) { + m = matcher.try_match(p); + pattern = p; + if (m) break; + } + if (!m) return null; + + let e_src = null; + let i_src = null; + for (let i = matcher.index - 1; i >= 0; i--) { + const item = matcher.input[i]; + if (item instanceof Label) break; + if (!i_src && item.outputs.includes(m.regs.get("i"))) i_src = item; + if (!e_src && item.outputs.includes(m.regs.get("e"))) e_src = item; + } + if (e_src === null || e_src.mnemonic !== "addiu") return null; + if (e_src.args[1] !== m.regs.get("i") && (i_src === null || i_src.mnemonic !== "move" || i_src.args[1] !== e_src.args[1])) return null; + pyassert(e_src.args[2] instanceof AsmLiteral); + let length = e_src.args[2].value; + + const added_length = length; + const m2 = matcher.try_match([...pattern, ...this.epilogue1]); + if (m2) { + m = m2; + length += 4; + const m3 = matcher.try_match([...pattern, ...this.epilogue1, ...this.epilogue2]); + if (m3) { + m = m3; + length += 4; + } + } + + const from_reg = R("from"); + const to_reg = R("to"); + const from_offset = new AsmLiteral(m.literals.get("N")); + const to_offset = new AsmLiteral(m.literals.get("M")); + const added_len_arg = new AsmLiteral(added_length); + const len_arg = new AsmLiteral(length); + return new Replacement( + [ + m.body[0], + new AsmInstruction("addiu", [from_reg, m.regs.get("i"), from_offset]), + new AsmInstruction("addiu", [to_reg, m.regs.get("o"), to_offset]), + new AsmInstruction(this.instruction_name, [to_reg, from_reg, len_arg]), + new AsmInstruction("addiu", [m.regs.get("o"), m.regs.get("o"), added_len_arg]), + new AsmInstruction("addiu", [m.regs.get("i"), m.regs.get("i"), added_len_arg]), + ...m.wildcard_items, + new AsmInstruction("nop", []), + ], + m.body.length, + ); + } +} + +class AlignedMemcpyPattern extends MemcpyPatternBase { + pattern_mips1 = make_pattern(".loop:", "lw $a, N($i)", "addiu $i, $i, 12", "sw $a, M($o)", "lw $b, (N-8)($i)", "addiu $o, $o, 12", "sw $b, (M-8)($o)", "lw $c, (N-4)($i)", "bne $i, $e, .loop", "sw $c, (M-4)($o)"); + pattern_mips2 = make_pattern(".loop:", "lw $a, N($i)", "addiu $i, $i, 12", "addiu $o, $o, 12", "sw $a, MM($o)", ".eq M, MM+12", "lw $b, (N-8)($i)", "sw $b, (M-8)($o)", "lw $c, (N-4)($i)", "bne $i, $e, .loop", "sw $c, (M-4)($o)"); + epilogue1 = make_pattern("lw $x, N($i)", "*", "sw $x, M($o)"); + epilogue2 = make_pattern("lw $y, (N+4)($i)", "*", "sw $y, (M+4)($o)"); + instruction_name = "memcpy.aligned.fictive"; +} + +class UnalignedMemcpyPattern extends MemcpyPatternBase { + pattern_mips1 = make_pattern( + ".loop:", "lwl $a, N($i)", "lwr $a, (N+3)($i)", "addiu $i, $i, 12", "swl $a, M($o)", "swr $a, (M+3)($o)", "lwl $b, (N-8)($i)", "lwr $b, (N-5)($i)", + "addiu $o, $o, 12", "swl $b, (M-8)($o)", "swr $b, (M-5)($o)", "lwl $c, (N-4)($i)", "lwr $c, (N-1)($i)", "nop", "swl $c, (M-4)($o)", "bne $i, $e, .loop", "swr $c, (M-1)($o)", + ); + pattern_mips2 = make_pattern( + ".loop:", "lwl $a, N($i)", "lwr $a, (N+3)($i)", "addiu $i, $i, 12", "addiu $o, $o, 12", "swl $a, MM($o)", ".eq M, MM+12", "swr $a, (M-9)($o)", "lwl $b, (N-8)($i)", + "lwr $b, (N-5)($i)", "swl $b, (M-8)($o)", "swr $b, (M-5)($o)", "lwl $c, (N-4)($i)", "lwr $c, (N-1)($i)", "swl $c, (M-4)($o)", "bne $i, $e, .loop", "swr $c, (M-1)($o)", + ); + epilogue1 = make_pattern("lwl $x, N($i)", "lwr $x, (N+3)($i)", "*", "swl $x, M($o)", "swr $x, (M+3)($o)"); + epilogue2 = make_pattern("lwl $y, (N+4)($i)", "lwr $y, (N+7)($i)", "*", "swl $y, (M+4)($o)", "swr $y, (M+7)($o)"); + instruction_name = "memcpy.unaligned.fictive"; +} + +/** Remove additions of $gp used for position-independent jump tables. */ +class GpJumpPattern extends SimpleAsmPattern { + pattern = make_pattern("addu $x, $x, $gp", "jr $x"); + replace(m) { + return new Replacement([m.body[1]], m.body.length); + } +} + +/** Some PS2 compilers emit ori for small stack additions instead of addiu. */ +class OriSpPattern extends SimpleAsmPattern { + pattern = make_pattern("ori $x, $sp, N"); + replace(m) { + const n = m.literals.get("N"); + if (0 <= n && n < 16 && m.regs.get("x") !== R("sp")) { + const ins = new AsmInstruction("addiu", [m.regs.get("x"), R("sp"), new AsmLiteral(n)]); + return new Replacement([ins], m.body.length); + } + return null; + } +} + +/** `return fn(...);` may be optimized to a `j fn`. */ +class TailCallPattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (instr instanceof Instruction && instr.mnemonic === "j" && instr.args[0] instanceof AsmGlobalSymbol && !matcher.is_local_label(instr.args[0].symbol_name)) { + return new Replacement( + [new AsmInstruction("jal", instr.args), new AsmInstruction("nop", []), new AsmInstruction("jr", [R("ra")]), new AsmInstruction("nop", [])], + 1, + ); + } + return null; + } +} + +const regs = (names) => names.map(R); + +export class MipsArch extends Arch { + missing_return() { + const meta = InstructionMeta.missing(); + return [this.parse("jr", [R("ra")], meta), this.parse("nop", [], meta)]; + } + + normalize_instruction(instr, asm_state) { + const args = instr.args; + const zero = R("zero"); + if (args.length === 3) { + if (instr.mnemonic === "sll" && args[0] === zero && args[1] === zero) return new AsmInstruction("nop", []); + if (instr.mnemonic === "or" && args[2] === zero) return new AsmInstruction("move", args.slice(0, 2)); + if (instr.mnemonic === "addu" && args[2] === zero) return new AsmInstruction("move", args.slice(0, 2)); + if (instr.mnemonic === "daddu" && args[2] === zero) return new AsmInstruction("move", args.slice(0, 2)); + if (instr.mnemonic === "nor" && args[1] === zero) return new AsmInstruction("not", [args[0], args[2]]); + if (instr.mnemonic === "nor" && args[2] === zero) return new AsmInstruction("not", [args[0], args[1]]); + if (instr.mnemonic === "addiu" && args[2] === new AsmLiteral(0)) return new AsmInstruction("move", args.slice(0, 2)); + if (instr.mnemonic === "paddub" && args[2] === zero) return new AsmInstruction("move", args.slice(0, 2)); + if (instr.mnemonic === "ori" && args[1] === zero && args[2] instanceof AsmLiteral) { + return new AsmInstruction("li", [args[0], new AsmLiteral(band(args[2].value, 0xffff))]); + } + if (instr.mnemonic === "addiu" && args[1] === zero && args[2] instanceof AsmLiteral) { + return new AsmInstruction("li", [args[0], new AsmLiteral(band(args[2].value + 0x8000, 0xffff) - 0x8000)]); + } + if (instr.mnemonic === "beq" && args[0] === zero && args[1] === zero) return new AsmInstruction("b", [args[2]]); + if (["bne", "beq", "beql", "bnel"].includes(instr.mnemonic) && args[1] === zero) { + const mn = instr.mnemonic.slice(0, 3) + "z" + instr.mnemonic.slice(3); + return new AsmInstruction(mn, [args[0], args[2]]); + } + } + if (args.length === 2) { + if (instr.mnemonic === "beqz" && args[0] === zero) return new AsmInstruction("b", [args[1]]); + if (instr.mnemonic === "lui" && args[1] instanceof AsmLiteral) return new AsmInstruction("li", [args[0], new AsmLiteral(band(args[1].value, 0xffff) * 0x10000)]); + if (instr.mnemonic === "jalr" && args[0] !== R("ra")) throw new DecompFailure("Two-argument form of jalr is not supported."); + if (["mult", "multu", "dmult", "dmultu", "madd", "maddu"].includes(instr.mnemonic)) return new AsmInstruction(instr.mnemonic, [zero, ...args]); + if (LENGTH_THREE.has(instr.mnemonic)) return this.normalize_instruction(new AsmInstruction(instr.mnemonic, [args[0], ...args]), asm_state); + } + if (args.length === 1) { + if (instr.mnemonic === "jalr") return new AsmInstruction("jalr", [R("ra"), args[0]]); + if (LENGTH_TWO.has(instr.mnemonic)) return this.normalize_instruction(new AsmInstruction(instr.mnemonic, [args[0], ...args]), asm_state); + } + return instr; + } + + parse(mnemonic, args, meta) { + let inputs = []; + let clobbers = []; + let outputs = []; + let jump_target = null; + let function_target = null; + let has_delay_slot = false; + let is_branch_likely = false; + let is_conditional = false; + let is_return = false; + let is_load = false; + let is_store = false; + let eval_fn = null; + const cls = this; + + const instr_str = String(new AsmInstruction(mnemonic, args)); + + const memory_sizes = { b: 1, h: 2, w: 4, d: 8, q: 16 }; + const c1 = mnemonic.slice(1, 2); + const size = has(memory_sizes, c1) ? memory_sizes[c1] : null; + + const alt_mult_pipeline = mnemonic.endsWith("1"); + const base_mult_mnemonic = alt_mult_pipeline ? mnemonic.slice(0, -1) : mnemonic; + const lo_reg = alt_mult_pipeline ? R("lo1") : R("lo"); + const hi_reg = alt_mult_pipeline ? R("hi1") : R("hi"); + + const make_memory_access = (arg) => { + pyassert(size !== null); + if (arg instanceof AsmAddressMode && arg.base === cls.stack_pointer_reg) { + const loc = StackLocation.from_offset(arg.addend); + if (loc === null) return []; + const at = (d) => new StackLocation(loc.offset + d, loc.symbolic_offset); + if (size === 16) return [loc, at(4), at(8), at(12)]; + if (size === 8) return [loc, at(4)]; + pyassert(size <= 4); + return [loc]; + } + return []; + }; + + const unreachable_eval = () => { + throw new DecompFailure(`Instruction ${instr_str} should be replaced before eval`); + }; + + if (mnemonic === "jr" && args[0] === R("ra")) { + pyassert(args.length === 1); + inputs = [R("ra")]; + is_return = true; + has_delay_slot = true; + } else if (mnemonic === "jr") { + pyassert(args.length === 1 && args[0] instanceof Register); + inputs.push(args[0]); + jump_target = args[0]; + is_conditional = true; + has_delay_slot = true; + eval_fn = (s, a) => s.set_switch_expr(a.reg(0)); + } else if (mnemonic === "jal" || mnemonic === "bal") { + pyassert(args.length === 1); + inputs = [...cls.argument_regs]; + outputs = [...cls.all_return_regs]; + clobbers = [...cls.temp_regs]; + function_target = args[0]; + has_delay_slot = true; + eval_fn = (s, a) => s.make_function_call(a.sym_imm(0), outputs); + } else if (mnemonic === "jalr") { + pyassert(args.length === 2 && args[0] === R("ra") && args[1] instanceof Register); + inputs = [...cls.argument_regs]; + inputs.push(args[1]); + outputs = [...cls.all_return_regs]; + clobbers = [...cls.temp_regs]; + function_target = args[1]; + has_delay_slot = true; + eval_fn = (s, a) => s.make_function_call(a.reg(1), outputs); + } else if (mnemonic === "b" || mnemonic === "j") { + pyassert(args.length === 1); + jump_target = get_jump_target(args[0]); + has_delay_slot = true; + } else if (["beql", "bnel", "beqzl", "bnezl", "bgezl", "bgtzl", "blezl", "bltzl", "bc1tl", "bc1fl"].includes(mnemonic)) { + if (mnemonic === "beql" || mnemonic === "bnel") { + pyassert(args.length === 3 && args[0] instanceof Register && args[1] instanceof Register); + inputs.push(args[0]); + inputs.push(args[1]); + } else if (mnemonic === "bc1tl" || mnemonic === "bc1fl") { + pyassert(args.length === 1); + inputs.push(R("condition_bit")); + } else { + pyassert(args.length === 2 && args[0] instanceof Register); + inputs.push(args[0]); + } + jump_target = get_jump_target(args[args.length - 1]); + has_delay_slot = true; + is_branch_likely = true; + is_conditional = true; + eval_fn = unreachable_eval; + } else if (["beq", "bne", "beqz", "bnez", "bgez", "bgtz", "blez", "bltz", "bc1t", "bc1f"].includes(mnemonic)) { + if (mnemonic === "beq" || mnemonic === "bne") { + pyassert(args.length === 3 && args[0] instanceof Register && args[1] instanceof Register); + inputs = [args[0], args[1]]; + } else if (mnemonic === "bc1t" || mnemonic === "bc1f") { + pyassert(args.length === 1); + inputs = [R("condition_bit")]; + } else { + pyassert(args.length === 2 && args[0] instanceof Register); + inputs = [args[0]]; + } + jump_target = get_jump_target(args[args.length - 1]); + has_delay_slot = true; + is_conditional = true; + eval_fn = (s, a) => { + let cond; + if (mnemonic === "bc1t" || mnemonic === "bc1f") { + cond = condition_from_expr(a.regs.get(R("condition_bit"))); + if (mnemonic === "bc1f") cond = cond.negated(); + } else cond = cls.instrs_branches[mnemonic](a); + s.set_branch_condition(cond); + }; + } else if (mnemonic === "mfc0") { + pyassert(args.length === 2 && args[0] instanceof Register); + outputs = [args[0]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(0), new ErrorExpr(`mfc0 ${a.raw_arg(1)}`)); + } else if (mnemonic === "mtc0") { + pyassert(args.length === 2 && args[0] instanceof Register); + inputs = [args[0]]; + eval_fn = (s) => s.write_statement(error_stmt(instr_str)); + } else if (has(cls.instrs_no_dest, mnemonic)) { + pyassert(!args.some((a) => a instanceof AsmAddressMode)); + inputs = args.filter((r) => r instanceof Register); + eval_fn = (s, a) => s.write_statement(cls.instrs_no_dest[mnemonic](a)); + } else if (has(cls.instrs_store, mnemonic)) { + pyassert(args[0] instanceof Register); + outputs = make_memory_access(args[1]); + inputs = [args[0]]; + is_store = true; + if (mnemonic === "sdc1") inputs.push(other_f64_reg(args[0])); + else if ((mnemonic === "sd" || mnemonic === "sq") && outputs.length) { + const n = outputs.length; + const base = inputs; + inputs = []; + for (let k = 0; k < n; k++) inputs.push(...base); + } + if (args[1] instanceof AsmAddressMode) inputs.push(args[1].base); + eval_fn = (s, a) => { + const store = cls.instrs_store[mnemonic](a); + if (store !== null) s.store_memory(store, a.reg_ref(0)); + }; + } else if (mnemonic === "mtc1") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + inputs = [args[0]]; + outputs = [args[1]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(1), a.reg(0)); + } else if (has(cls.instrs_destination_first, mnemonic)) { + pyassert(args[0] instanceof Register); + outputs = [args[0]]; + const mn_parts = mnemonic.split("."); + if (["add.d", "sub.d", "neg.d", "abs.d", "sqrt.d", "div.d", "mul.d", "mov.d"].includes(mnemonic)) { + pyassert(2 <= args.length && args.length <= 3); + for (const reg of args.slice(1)) { + pyassert(reg instanceof Register); + inputs.push(reg, other_f64_reg(reg)); + } + outputs.push(other_f64_reg(args[0])); + } else if (mn_parts[0] === "cvt" || mn_parts[0] === "trunc") { + pyassert(args.length === 2 && args[1] instanceof Register); + if (mn_parts[2] === "d") inputs = [args[1], other_f64_reg(args[1])]; + else inputs = [args[1]]; + if (mn_parts[1] === "d") outputs.push(other_f64_reg(args[0])); + } else if (mnemonic.startsWith("l") && size !== null) { + pyassert(args.length === 2); + is_load = true; + inputs = make_memory_access(args[1]); + if (args[1] instanceof AsmAddressMode) inputs.push(args[1].base); + if (mnemonic === "lwr") inputs.push(args[0]); + else if (mnemonic === "ldc1") outputs.push(other_f64_reg(args[0])); + } else if (mnemonic === "la" && args[1] instanceof AsmAddressMode) { + inputs = [args[1].base]; + } else if (base_mult_mnemonic === "mfhi") { + pyassert(args.length === 1); + inputs = [hi_reg]; + } else if (base_mult_mnemonic === "mflo") { + pyassert(args.length === 1); + inputs = [lo_reg]; + } else if (mnemonic === "movn" || mnemonic === "movz") { + pyassert(args.length === 3 && args[1] instanceof Register && args[2] instanceof Register); + inputs = [args[0], args[1], args[2]]; + } else { + pyassert(!args.some((a) => a instanceof AsmAddressMode)); + inputs = args.slice(1).filter((r) => r instanceof Register); + } + eval_fn = (s, a) => { + const target = a.reg_ref(0); + s.set_reg(target, cls.instrs_destination_first[mnemonic](a)); + if (outputs.length === 2) s.set_reg(other_f64_reg(target), new SecondF64Half()); + }; + } else if (has(cls.instrs_float_comp, mnemonic)) { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + if (mnemonic.endsWith(".d")) inputs = [args[0], other_f64_reg(args[0]), args[1], other_f64_reg(args[1])]; + else inputs = [args[0], args[1]]; + outputs = [R("condition_bit")]; + eval_fn = (s, a) => s.set_reg(R("condition_bit"), cls.instrs_float_comp[mnemonic](a)); + } else if (has(cls.instrs_hi_lo, base_mult_mnemonic)) { + pyassert(args.length === 3 && args[0] instanceof Register && args[1] instanceof Register && args[2] instanceof Register); + inputs = [args[1], args[2]]; + if (base_mult_mnemonic === "madd" || base_mult_mnemonic === "maddu") inputs.push(lo_reg); + outputs = [hi_reg, lo_reg]; + if (args[0] !== R("zero")) outputs.push(args[0]); + eval_fn = (s, a) => { + const [hi, lo] = cls.instrs_hi_lo[base_mult_mnemonic](a, lo_reg); + s.set_reg(hi_reg, hi); + s.set_reg(lo_reg, lo); + const copy_lo_to = a.reg_ref(0); + if (copy_lo_to !== R("zero")) s.set_reg(copy_lo_to, lo); + }; + } else if (base_mult_mnemonic === "mtlo" || base_mult_mnemonic === "mthi") { + pyassert(args.length === 1 && args[0] instanceof Register); + inputs = [args[0]]; + const output_reg = base_mult_mnemonic === "mthi" ? hi_reg : lo_reg; + outputs = [output_reg]; + eval_fn = (s, a) => s.set_reg(output_reg, a.reg(0)); + } else if (cls.instrs_ignore.has(mnemonic)) { + // pass + } else { + let maybe_dest_first; + if (args.length && args[0] instanceof Register) { + inputs = args.slice(1).filter((r) => r instanceof Register); + outputs = [args[0]]; + maybe_dest_first = true; + } else maybe_dest_first = false; + eval_fn = (s, a) => { + const error = new ErrorExpr(`unknown instruction: ${instr_str}`); + if (maybe_dest_first) s.set_reg_real(a.reg_ref(0), error, { emit_exactly_once: true }); + else s.write_statement(new ExprStmt(error)); + }; + } + + return new Instruction({ + mnemonic, + args, + meta, + inputs, + clobbers, + outputs, + jump_target, + function_target, + has_delay_slot, + is_branch_likely, + is_conditional, + is_return, + is_load, + is_store, + eval_fn, + }); + } + + arg_name(loc) { + pyassert(loc.offset !== null); + return `arg${floordiv(loc.offset, 4)}`; + } + + default_function_abi_candidate_slots() { + return [ + new AbiArgSlot(new ArgLoc(0, 0, R("f12")), Type.floatish()), + new AbiArgSlot(new ArgLoc(4, 1, R("f13")), Type.floatish()), + new AbiArgSlot(new ArgLoc(4, 2, R("f14")), Type.floatish()), + new AbiArgSlot(new ArgLoc(12, 3, R("f15")), Type.floatish()), + new AbiArgSlot(new ArgLoc(0, 4, R("a0")), Type.intptr()), + new AbiArgSlot(new ArgLoc(4, 5, R("a1")), Type.any_reg()), + new AbiArgSlot(new ArgLoc(8, 6, R("a2")), Type.any_reg()), + new AbiArgSlot(new ArgLoc(12, 7, R("a3")), Type.any_reg()), + ]; + } + + /** Compute stack positions/registers used by a function according to the o32 ABI. */ + function_abi(fn_sig, likely_regs, { for_call }) { + const known_slots = []; + let candidate_slots = []; + if (fn_sig.params_known) { + let offset = 0; + let only_floats = true; + if (fn_sig.return_type.is_struct()) { + known_slots.push(new AbiArgSlot(new ArgLoc(0, 0, R("a0")), Type.ptr(fn_sig.return_type), { name: "__return__", comment: "return" })); + offset = 4; + only_floats = false; + } + fn_sig.params.forEach((param, ind) => { + const param_type = param.type.decay(); + let [size, align] = param_type.get_parameter_size_align_bytes(); + size = band(size + 3, -4); + only_floats = only_floats && param_type.is_float(); + offset = band(offset + align - 1, -align); + const name = param.name; + let reg2; + if (ind < 2 && only_floats) { + reg2 = R(ind === 0 ? "f12" : "f14"); + const is_double = param_type.is_float() && param_type.get_size_bits() === 64; + known_slots.push(new AbiArgSlot(new ArgLoc(offset, floordiv(offset, 4), reg2), param_type, { name })); + if (is_double && !for_call) { + const name2 = name ? `${name}_lo` : null; + reg2 = R(ind === 0 ? "f13" : "f15"); + known_slots.push(new AbiArgSlot(new ArgLoc(offset + 4, floordiv(offset, 4) + 1, reg2), Type.any_reg(), { name: name2 })); + } + } else { + for (let i = floordiv(offset, 4); i < floordiv(offset + size, 4); i++) { + const unk_offset = 4 * i - offset; + reg2 = i < 4 ? R(`a${i}`) : null; + let name2, sub_type, comment; + if (size > 4) { + name2 = name ? `${name}_unk${format(unk_offset, "X")}` : null; + sub_type = Type.any(); + comment = `${param_type}+${format(unk_offset, "#x")}`; + } else { + pyassert(unk_offset === 0); + name2 = name; + sub_type = param_type; + comment = null; + } + known_slots.push(new AbiArgSlot(new ArgLoc(4 * i, i, reg2), sub_type, { name: name2, comment })); + } + } + offset += size; + }); + if (fn_sig.is_variadic) { + for (let i = floordiv(offset, 4); i < 4; i++) candidate_slots.push(new AbiArgSlot(new ArgLoc(i * 4, i, R(`a${i}`)), Type.any_reg())); + } + } else { + candidate_slots = this.default_function_abi_candidate_slots(); + } + + const valid_extra_regs = new Set(known_slots.filter((slot) => slot.loc.reg !== null).map((slot) => slot.loc.reg)); + const possible_slots = []; + for (const slot of candidate_slots) { + const reg = slot.loc.reg; + if (reg === null || !likely_regs.has(reg)) continue; + let require = null; + if (slot === candidate_slots[0]) { + // pass + } else if (reg === R("f13") || reg === R("f14")) require = ["f12"]; + else if (reg === R("f15")) require = ["f14"]; + else if (reg === R("a1")) require = ["a0", "f12"]; + else if (reg === R("a2")) require = ["a1", "f13", "f14"]; + else if (reg === R("a3")) require = ["a2"]; + if (require && !require.some((r) => valid_extra_regs.has(R(r)))) continue; + valid_extra_regs.add(reg); + if ((reg === R("f13") || reg === R("f15")) && for_call) continue; + if (!likely_regs.get(reg)) continue; + possible_slots.push(slot); + } + return new Abi({ arg_slots: known_slots, possible_slots }); + } + + function_return(expr) { + return new Map([ + [R("f0"), new Cast(expr, { reinterpret: true, silent: true, type: Type.floatish() })], + [R("v0"), new Cast(expr, { reinterpret: true, silent: true, type: Type.intptr() })], + [R("v1"), as_u32(new Cast(expr, { reinterpret: true, silent: false, type: Type.u64() }))], + [R("f1"), new SecondF64Half()], + ]); + } +} + +{ + const argument_regs = regs(["a0", "a1", "a2", "a3", "f12", "f13", "f14", "f15"]); + const simple_temp_regs = regs([ + "v0", "v1", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f16", "f17", "f18", "f19", + ]); + const temp_regs = [...argument_regs, ...simple_temp_regs, ...regs(["at", "hi", "lo", "lo1", "hi1", "condition_bit"])]; + const saved_regs = regs(["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "ra", "31", "fp", "gp"]); + const stack_pointer_reg = R("sp"); + const aliased_gp_regs = { s8: R("fp"), r0: R("zero") }; + const o32abi_float_regs = {}; + const fnames = ["fv0", "fv0f", "fv1", "fv1f", "ft0", "ft0f", "ft1", "ft1f", "ft2", "ft2f", "ft3", "ft3f", "fa0", "fa0f", "fa1", "fa1f", "ft4", "ft4f", "ft5", "ft5f", "fs0", "fs0f", "fs1", "fs1f", "fs2", "fs2f", "fs3", "fs3f", "fs4", "fs4f", "fs5", "fs5f"]; + fnames.forEach((n, i) => (o32abi_float_regs[n] = R(`f${i}`))); + + const instrs_store = { + sb: (a) => make_store(a, Type.int_of_size(8)), + sh: (a) => make_store(a, Type.int_of_size(16)), + sw: (a) => make_store(a, Type.reg32({ likely_float: false })), + sd: (a) => make_store(a, Type.reg64({ likely_float: false })), + sq: (a) => make_store(a, Type.reg128()), + swl: (a) => handle_swl(a), + swr: (a) => handle_swr(a), + swc1: (a) => make_store(a, Type.reg32({ likely_float: true })), + sdc1: (a) => make_store(a, Type.reg64({ likely_float: true })), + }; + const instrs_branches = { + beq: (a) => BinaryOp.icmp(a.reg(0), "==", a.reg(1)), + bne: (a) => BinaryOp.icmp(a.reg(0), "!=", a.reg(1)), + beqz: (a) => BinaryOp.icmp(a.reg(0), "==", new Literal(0)), + bnez: (a) => BinaryOp.icmp(a.reg(0), "!=", new Literal(0)), + blez: (a) => BinaryOp.scmp(a.reg(0), "<=", new Literal(0)), + bgtz: (a) => BinaryOp.scmp(a.reg(0), ">", new Literal(0)), + bltz: (a) => handle_bgez(a).negated(), + bgez: (a) => handle_bgez(a), + }; + const trap = (op, cmp, imm) => (a) => void_fn_op("M2C_TRAP_IF", [BinaryOp[cmp](a.reg(0), op, imm ? a.s16_imm(1) : a.reg(1))]); + const instrs_no_dest = { + teq: trap("==", "icmp", false), + tne: trap("!=", "icmp", false), + tlt: trap("<", "scmp", false), + tltu: trap("<", "ucmp", false), + tge: trap(">=", "scmp", false), + tgeu: trap(">=", "ucmp", false), + teqi: trap("==", "icmp", true), + tnei: trap("!=", "icmp", true), + tlti: trap("<", "scmp", true), + tltiu: trap("<", "ucmp", true), + tgei: trap(">=", "scmp", true), + tgeiu: trap(">=", "ucmp", true), + break: (a) => void_fn_op("M2C_BREAK", a.count() >= 1 ? [a.s16_imm(0)] : []), + sync: () => void_fn_op("M2C_SYNC", []), + "trapuv.fictive": () => new CommentStmt("code compiled with -trapuv"), + "memcpy.aligned.fictive": (a) => void_fn_op("M2C_MEMCPY_ALIGNED", [a.reg(0), a.reg(1), a.s16_imm(2)]), + "memcpy.unaligned.fictive": (a) => void_fn_op("M2C_MEMCPY_UNALIGNED", [a.reg(0), a.reg(1), a.s16_imm(2)]), + }; + const fc = (op, neg) => (a) => { + const c = BinaryOp.fcmp(a.reg(0), op, a.reg(1)); + return neg ? c.negated() : c; + }; + const dc = (op, neg) => (a) => { + const c = BinaryOp.dcmp(a.dreg(0), op, a.dreg(1)); + return neg ? c.negated() : c; + }; + const instrs_float_comp = {}; + for (const [suf, mk] of [ + ["s", fc], + ["d", dc], + ]) { + Object.assign(instrs_float_comp, { + [`c.eq.${suf}`]: mk("==", false), + [`c.olt.${suf}`]: mk("<", false), + [`c.oge.${suf}`]: mk(">=", false), + [`c.ole.${suf}`]: mk("<=", false), + [`c.ogt.${suf}`]: mk(">", false), + [`c.neq.${suf}`]: mk("==", true), + [`c.uge.${suf}`]: mk("<", true), + [`c.ult.${suf}`]: mk(">=", true), + [`c.ugt.${suf}`]: mk("<=", true), + [`c.ule.${suf}`]: mk(">", true), + [`c.seq.${suf}`]: mk("==", false), + [`c.lt.${suf}`]: mk("<", false), + [`c.ge.${suf}`]: mk(">=", false), + [`c.le.${suf}`]: mk("<=", false), + [`c.gt.${suf}`]: mk(">", false), + [`c.sne.${suf}`]: mk("==", true), + [`c.nle.${suf}`]: mk("<=", true), + [`c.nlt.${suf}`]: mk("<", true), + [`c.nge.${suf}`]: mk(">=", true), + [`c.ngt.${suf}`]: mk(">", true), + }); + } + const madd = (name) => (a, lo_reg) => [new ErrorExpr(`${name} top half`), handle_add_real(a.regs.get(lo_reg), BinaryOp.int(a.reg(1), "*", a.reg(2)), a)]; + const instrs_hi_lo = { + div: (a) => [BinaryOp.sint(a.reg(1), "%", a.reg(2)), BinaryOp.sint(a.reg(1), "/", a.reg(2))], + divu: (a) => [BinaryOp.uint(a.reg(1), "%", a.reg(2)), BinaryOp.uint(a.reg(1), "/", a.reg(2))], + ddiv: (a) => [BinaryOp.s64(a.reg(1), "%", a.reg(2)), BinaryOp.s64(a.reg(1), "/", a.reg(2))], + ddivu: (a) => [BinaryOp.u64(a.reg(1), "%", a.reg(2)), BinaryOp.u64(a.reg(1), "/", a.reg(2))], + mult: (a) => [fold_divmod(BinaryOp.int(a.reg(1), "MULT_HI", a.reg(2))), BinaryOp.int(a.reg(1), "*", a.reg(2))], + multu: (a) => [fold_divmod(BinaryOp.int(a.reg(1), "MULTU_HI", a.reg(2))), BinaryOp.int(a.reg(1), "*", a.reg(2))], + dmult: (a) => [BinaryOp.int64(a.reg(1), "DMULT_HI", a.reg(2)), BinaryOp.int64(a.reg(1), "*", a.reg(2))], + dmultu: (a) => [BinaryOp.int64(a.reg(1), "DMULTU_HI", a.reg(2)), BinaryOp.int64(a.reg(1), "*", a.reg(2))], + madd: madd("madd"), + maddu: madd("maddu"), + }; + const sub = (a) => fold_mul_chains(fold_divmod(BinaryOp.intptr(a.reg(1), "-", a.reg(2)))); + const instrs_destination_first = { + slt: (a) => BinaryOp.scmp(a.reg(1), "<", a.reg(2)), + slti: (a) => BinaryOp.scmp(a.reg(1), "<", a.s16_imm(2)), + sltu: (a) => handle_sltu(a), + sltiu: (a) => handle_sltiu(a), + addi: (a) => handle_addi_mips(a), + addiu: (a) => handle_addi_mips(a), + add: (a) => handle_add(a), + addu: (a) => handle_add(a), + sub, + subu: sub, + negu: (a) => fold_mul_chains(UnaryOp.sint("-", a.reg(1))), + neg: (a) => fold_mul_chains(UnaryOp.sint("-", a.reg(1))), + "div.fictive": (a) => BinaryOp.sint(a.reg(1), "/", a.full_imm(2)), + "mod.fictive": (a) => BinaryOp.sint(a.reg(1), "%", a.full_imm(2)), + daddi: (a) => handle_addi_mips(a), + daddiu: (a) => handle_addi_mips(a), + daddu: (a) => handle_add(a), + dsubu: (a) => fold_mul_chains(BinaryOp.intptr(a.reg(1), "-", a.reg(2))), + dnegu: (a) => fold_mul_chains(new UnaryOp("-", as_s64(a.reg(1)), { type: Type.s64() })), + dneg: (a) => fold_mul_chains(new UnaryOp("-", as_s64(a.reg(1)), { type: Type.s64() })), + mfhi: (a) => a.regs.get(R("hi")), + mflo: (a) => a.regs.get(R("lo")), + mfhi1: (a) => a.regs.get(R("hi1")), + mflo1: (a) => a.regs.get(R("lo1")), + "add.s": (a) => handle_add_float(a), + "sub.s": (a) => BinaryOp.f32(a.reg(1), "-", a.reg(2)), + "neg.s": (a) => new UnaryOp("-", as_f32(a.reg(1)), { type: Type.f32() }), + "abs.s": (a) => fn_op("fabsf", [as_f32(a.reg(1))], Type.f32()), + "sqrt.s": (a) => fn_op("sqrtf", [as_f32(a.reg(1))], Type.f32()), + "div.s": (a) => BinaryOp.f32(a.reg(1), "/", a.reg(2)), + "mul.s": (a) => BinaryOp.f32(a.reg(1), "*", a.reg(2)), + "add.d": (a) => handle_add_double(a), + "sub.d": (a) => BinaryOp.f64(a.dreg(1), "-", a.dreg(2)), + "neg.d": (a) => new UnaryOp("-", as_f64(a.dreg(1)), { type: Type.f64() }), + "abs.d": (a) => fn_op("fabs", [as_f64(a.dreg(1))], Type.f64()), + "sqrt.d": (a) => fn_op("sqrt", [as_f64(a.dreg(1))], Type.f64()), + "div.d": (a) => BinaryOp.f64(a.dreg(1), "/", a.dreg(2)), + "mul.d": (a) => BinaryOp.f64(a.dreg(1), "*", a.dreg(2)), + "cvt.d.s": (a) => handle_convert(a.reg(1), Type.f64(), Type.f32()), + "cvt.d.w": (a) => handle_convert(a.reg(1), Type.f64(), Type.intish()), + "cvt.s.d": (a) => handle_convert(a.dreg(1), Type.f32(), Type.f64()), + "cvt.s.w": (a) => handle_convert(a.reg(1), Type.f32(), Type.intish()), + "cvt.w.d": (a) => handle_convert(a.dreg(1), Type.s32(), Type.f64()), + "cvt.w.s": (a) => handle_convert(a.reg(1), Type.s32(), Type.f32()), + "cvt.s.u.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.u32()), + "cvt.u.d.fictive": (a) => handle_convert(a.dreg(1), Type.u32(), Type.f64()), + "cvt.u.s.fictive": (a) => handle_convert(a.reg(1), Type.u32(), Type.f32()), + "trunc.w.s": (a) => handle_convert(a.reg(1), Type.s32(), Type.f32()), + "trunc.w.d": (a) => handle_convert(a.dreg(1), Type.s32(), Type.f64()), + ori: (a) => handle_or(a.reg(1), a.u16_imm(2)), + and: (a) => BinaryOp.int(a.reg(1), "&", a.reg(2)), + or: (a) => BinaryOp.int(a.reg(1), "|", a.reg(2)), + not: (a) => new UnaryOp("~", a.reg(1), { type: Type.intish() }), + nor: (a) => new UnaryOp("~", BinaryOp.int(a.reg(1), "|", a.reg(2)), { type: Type.intish() }), + xor: (a) => BinaryOp.int(a.reg(1), "^", a.reg(2)), + andi: (a) => BinaryOp.int(a.reg(1), "&", a.u16_imm(2)), + xori: (a) => handle_xor(a.reg(1), a.u16_imm(2)), + sll: (a) => fold_mul_chains(BinaryOp.int(a.reg(1), "<<", a.s16_imm(2))), + sllv: (a) => fold_mul_chains(BinaryOp.int(a.reg(1), "<<", a.reg(2))), + srl: (a) => fold_divmod(BinaryOp.ushift(a.reg(1), ">>", a.s16_imm(2))), + srlv: (a) => fold_divmod(BinaryOp.ushift(a.reg(1), ">>", a.reg(2))), + sra: (a) => handle_shift_right(a, { signed: true }), + srav: (a) => fold_divmod(BinaryOp.sshift(a.reg(1), ">>", a.reg(2))), + dsll: (a) => fold_mul_chains(BinaryOp.int64(a.reg(1), "<<", as_intish(a.s16_imm(2)))), + dsll32: (a) => fold_mul_chains(BinaryOp.int64(a.reg(1), "<<", imm_add_32(a.s16_imm(2)))), + dsllv: (a) => BinaryOp.int64(a.reg(1), "<<", as_intish(a.reg(2))), + dsrl: (a) => new BinaryOp(as_u64(a.reg(1)), ">>", as_intish(a.s16_imm(2)), { type: Type.u64() }), + dsrl32: (a) => new BinaryOp(as_u64(a.reg(1)), ">>", imm_add_32(a.s16_imm(2)), { type: Type.u64() }), + dsrlv: (a) => new BinaryOp(as_u64(a.reg(1)), ">>", as_intish(a.reg(2)), { type: Type.u64() }), + dsra: (a) => new BinaryOp(as_s64(a.reg(1)), ">>", as_intish(a.s16_imm(2)), { type: Type.s64() }), + dsra32: (a) => new BinaryOp(as_s64(a.reg(1)), ">>", imm_add_32(a.s16_imm(2)), { type: Type.s64() }), + dsrav: (a) => new BinaryOp(as_s64(a.reg(1)), ">>", as_intish(a.reg(2)), { type: Type.s64() }), + move: (a) => a.reg(1), + "move.fictive": (a) => a.reg(1), + mfc1: (a) => a.reg(1), + "mov.s": (a) => a.reg(1), + "mov.d": (a) => as_f64(a.dreg(1)), + movn: (a) => handle_conditional_move(a, true), + movz: (a) => handle_conditional_move(a, false), + cfc1: () => new ErrorExpr("cfc1"), + li: (a) => a.full_imm(1), + lui: (a) => load_upper(a), + la: (a) => handle_la(a), + lb: (a) => handle_load(a, Type.s8()), + lbu: (a) => handle_load(a, Type.u8()), + lh: (a) => handle_load(a, Type.s16()), + lhu: (a) => handle_load(a, Type.u16()), + lw: (a) => handle_lw(a), + ld: (a) => handle_load(a, Type.reg64({ likely_float: false })), + lq: (a) => handle_load(a, Type.reg128()), + lwu: (a) => handle_load(a, Type.u32()), + lwc1: (a) => handle_load(a, Type.reg32({ likely_float: true })), + ldc1: (a) => handle_load(a, Type.reg64({ likely_float: true })), + lwl: (a) => handle_lwl(a), + lwr: (a) => handle_lwr(a), + seb: (a) => as_type(a.reg(1), Type.s8(), false), + seh: (a) => as_type(a.reg(1), Type.s16(), false), + }; + + Object.assign(MipsArch.prototype, { + arch: Target.ArchEnum.MIPS, + re_comment: "[#;].*", + supports_dollar_regs: true, + has_delay_slots: true, + home_space_size: 0x10, + stack_pointer_reg, + frame_pointer_regs: [R("fp")], + return_address_reg: R("ra"), + base_return_regs: [ + [R("v0"), false], + [R("f0"), true], + ], + all_return_regs: regs(["v0", "v1", "f0", "f1"]), + argument_regs, + simple_temp_regs, + temp_regs, + saved_regs, + all_regs: [...saved_regs, ...temp_regs, stack_pointer_reg, R("zero")], + aliased_gp_regs, + o32abi_float_regs, + aliased_regs: { ...o32abi_float_regs, ...aliased_gp_regs }, + asm_patterns: [ + new DivPattern(), + new DivuPattern(), + new DivP2Pattern1(), + new DivP2Pattern2(), + new Div2S16Pattern(), + new Div2S32Pattern1(), + new Div2S32Pattern2(), + new ModP2Pattern1(), + new ModP2Pattern2(), + new UtfPattern(), + new FtuPattern(), + new Mips1DoubleLoadStorePattern(), + new GccSqrtPatternJal(), + new GccSqrtPatternJalr(), + new TrapuvPattern(), + new SetGpPattern(), + new AlignedMemcpyPattern(), + new UnalignedMemcpyPattern(), + new GpJumpPattern(), + new OriSpPattern(), + new TailCallPattern(), + ], + instrs_ignore: new Set(["ctc1", "nop"]), + instrs_store, + instrs_branches, + instrs_no_dest, + instrs_float_comp, + instrs_hi_lo, + instrs_destination_first, + }); +} + +export class MipseeArch extends MipsArch { + default_function_abi_candidate_slots() { + const out = []; + for (let i = 0; i < 8; i++) out.push(new AbiArgSlot(new ArgLoc(null, i, R(`a${i}`)), Type.intptr())); + for (let i = 0; i < 8; i++) out.push(new AbiArgSlot(new ArgLoc(null, 8 + i, R(`f${12 + i}`)), Type.floatish())); + return out; + } + + arg_name(loc) { + if (loc.offset !== null) return `arg_sp${format_hex(loc.offset)}`; + pyassert(loc.reg !== null); + const reg_num = int_(loc.reg.register_name.slice(1)); + if (loc.reg.register_name.startsWith("a")) return `arg${reg_num}`; + return `fparg${reg_num - 12}`; + } + + function_abi(fn_sig, likely_regs, { for_call }) { + void for_call; + const known_slots = []; + let candidate_slots = []; + const intptr_regs = this.argument_regs.filter((r) => r.register_name[0] !== "f"); + const float_regs = this.argument_regs.filter((r) => r.register_name[0] === "f"); + + if (fn_sig.params_known) { + let ind = 0; + let stack_offset = 0; + for (const param of fn_sig.params) { + const param_type = param.type.decay(); + let reg = null; + let offset = null; + const pool = param_type.is_float() ? float_regs : intptr_regs; + if (pool.length) reg = pool.shift(); + else { + offset = stack_offset; + stack_offset += 4; + } + known_slots.push(new AbiArgSlot(new ArgLoc(offset, ind, reg), param_type, { name: param.name })); + ind += 1; + } + if (fn_sig.is_variadic) { + for (const reg of intptr_regs) { + candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.intptr())); + ind += 1; + } + for (const reg of float_regs) { + candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.floatish())); + ind += 1; + } + } + } else { + candidate_slots = this.default_function_abi_candidate_slots(); + } + + const possible_slots = []; + const valid_extra_regs = new Set(known_slots.filter((slot) => slot.loc.reg !== null).map((slot) => slot.loc.reg)); + for (const slot of candidate_slots) { + const reg = slot.loc.reg; + if (reg === null || !likely_regs.has(reg)) continue; + if (slot === candidate_slots[0]) { + // pass + } else { + const regname = reg.register_name; + const prev_reg = R(`${regname[0]}${int_(regname.slice(1)) - 1}`); + if (this.argument_regs.includes(prev_reg) && !valid_extra_regs.has(prev_reg)) continue; + } + valid_extra_regs.add(reg); + if (!likely_regs.get(reg)) continue; + possible_slots.push(slot); + } + return new Abi({ arg_slots: known_slots, possible_slots }); + } +} + +{ + const argument_regs = regs(["a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19"]); + const simple_temp_regs = regs(["v0", "v1", "t4", "t5", "t6", "t7", "t8", "t9", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11"]); + const temp_regs = [...argument_regs, ...simple_temp_regs, ...regs(["at", "hi", "lo", "condition_bit"])]; + const saved_regs = regs(["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "ra", "31", "fp", "gp"]); + const stack_pointer_reg = R("sp"); + const aliased_gp_regs = { s8: R("fp"), r0: R("zero") }; + const eabi64_float_regs = {}; + ["fv0", "fv1", "ft0", "ft1", "ft2", "ft3", "ft4", "ft5", "ft6", "ft7", "ft8", "ft9", "fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7", "fs0", "fs1", "fs2", "fs3", "fs4", "fs5", "fs6", "fs7", "fs8", "fs9", "fs10", "fs11"].forEach( + (n, i) => (eabi64_float_regs[n] = R(`f${i}`)), + ); + const numeric_names = ["zero", "at", "v0", "v1", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "t0", "t1", "t2", "t3", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8", "t9", "k0", "k1", "gp", "sp", "fp", "ra"]; + const numeric_regs = {}; + numeric_names.forEach((n, i) => (numeric_regs[String(i)] = R(n))); + Object.assign(MipseeArch.prototype, { + stack_pointer_reg, + home_space_size: 0, + argument_regs, + simple_temp_regs, + temp_regs, + saved_regs, + all_regs: [...saved_regs, ...temp_regs, stack_pointer_reg, R("zero")], + aliased_gp_regs, + eabi64_float_regs, + numeric_regs, + aliased_regs: { ...eabi64_float_regs, ...aliased_gp_regs, ...numeric_regs }, + }); +} diff --git a/packages/romdev-m2c/src/arch_ppc.js b/packages/romdev-m2c/src/arch_ppc.js new file mode 100644 index 00000000..7e3704fe --- /dev/null +++ b/packages/romdev-m2c/src/arch_ppc.js @@ -0,0 +1,1298 @@ +// Port of m2c/arch_ppc.py +import { DecompFailure } from "./error.js"; +import { IrPattern } from "./ir_pattern.js"; +import { Target } from "./options.js"; +import { AsmAddressMode, AsmGlobalSymbol, AsmInstruction, AsmLiteral, BinOp, Macro, Register, get_jump_target } from "./asm_instruction.js"; +import { Instruction, InstructionMeta, StackLocation } from "./instruction.js"; +import { AsmPattern, Replacement, SimpleAsmPattern, make_pattern } from "./asm_pattern.js"; +import { + Abi, + AbiArgSlot, + AddressMode, + Arch, + ArgLoc, + BinaryOp, + Cast, + ErrorExpr, + ExprStmt, + Literal, + TernaryOp, + UnaryOp, + as_intish, + as_u32, + as_type, + format_hex, +} from "./translate.js"; +import { + add_imm, + carry_add_to, + carry_sub_from, + error_stmt, + fn_op, + fold_divmod, + fold_mul_chains, + handle_add, + handle_add_double, + handle_add_float, + handle_add_real, + handle_addi, + handle_addis, + handle_cmpnez, + handle_convert, + handle_load, + handle_loadx, + handle_or, + handle_rlwimi, + handle_rlwinm, + handle_rlwnm, + handle_shift_right, + handle_xor, + load_upper, + make_store, + make_storex, + void_fn_op, +} from "./evaluate.js"; +import { InstrRef } from "./flow_graph.js"; +import { Type } from "./types.js"; +import { band, has, int_, lstrip, pyassert, pyeq, repr, rstrip } from "./py.js"; + +/** + * For floating point, `x <= y` and `x >= y` use `cror` to OR together the `cr0_eq` + * bit with either `cr0_lt` or `cr0_gt`. + */ +class FcmpoCrorPattern extends SimpleAsmPattern { + pattern = make_pattern("fcmpo $cr0, $x, $y", "cror 2, N, 2"); + + replace(m) { + const fcmpo = m.body[0]; + pyassert(fcmpo instanceof Instruction); + if (m.literals.get("N") === 0) return new Replacement([new AsmInstruction("fcmpo.lte.fictive", fcmpo.args)], m.body.length); + else if (m.literals.get("N") === 1) return new Replacement([new AsmInstruction("fcmpo.gte.fictive", fcmpo.args)], m.body.length); + return null; + } +} + +/** Comparison results extracted as ints. */ +class MfcrPattern extends SimpleAsmPattern { + pattern = make_pattern("mfcr $x", "rlwinm $x, $x, N, 31, 31"); + + replace(m) { + const x = m.regs.get("x"); + const n = m.literals.get("N"); + let reg; + if (n === 1) reg = new Register("cr0_lt"); + else if (n === 2) reg = new Register("cr0_gt"); + else if (n === 3) reg = new Register("cr0_eq"); + else if (n === 4) reg = new Register("cr0_so"); + else return null; + return new Replacement([new AsmInstruction("move.fictive", [x, reg])], m.body.length); + } +} + +/** `return fn(...);` emitted as `b fn` instead of `bl fn; blr`. */ +class TailCallPattern extends AsmPattern { + match(matcher) { + if (matcher.index !== matcher.input.length - 1) return null; + const instr = matcher.input[matcher.index]; + if (instr instanceof Instruction && instr.mnemonic === "b" && instr.args[0] instanceof AsmGlobalSymbol && !matcher.is_local_label(instr.args[0].symbol_name)) { + return new Replacement([new AsmInstruction("bl", instr.args), new AsmInstruction("blr", [])], 1); + } + return null; + } +} + +/** Expand calls to MWCC's built-in `_{save,rest}{gpr,fpr}_` functions into register saves/restores. */ +class SaveRestoreRegsFnPattern extends AsmPattern { + match(matcher) { + const bl = matcher.input[matcher.index]; + if (!(bl instanceof Instruction) || bl.mnemonic !== "bl" || !(bl.args[0] instanceof AsmGlobalSymbol)) return null; + const parts = bl.args[0].symbol_name.split("_"); + if (parts.length !== 3 || parts[0]) return null; + let mnemonic, size, reg_prefix; + if (parts[1] === "savegpr" || parts[1] === "restgpr") { + mnemonic = parts[1] === "savegpr" ? "stw" : "lwz"; + size = 4; + reg_prefix = "r"; + } else if (parts[1] === "savefpr" || parts[1] === "restfpr") { + mnemonic = parts[1] === "savefpr" ? "stfd" : "lfd"; + size = 8; + reg_prefix = "f"; + } else return null; + + let addend = null; + for (let i = matcher.index - 1; i >= 0; i--) { + const instr = matcher.input[i]; + if ( + instr instanceof Instruction && + instr.mnemonic === "addi" && + instr.args[0] === new Register("r11") && + instr.args[1] === new Register("r1") && + instr.args[2] instanceof AsmLiteral + ) { + addend = instr.args[2].value; + break; + } + } + if (addend === null) return null; + + const regnum = int_(parts[2]); + const new_instrs = []; + for (let i = regnum; i < 32; i++) { + const reg = new Register(reg_prefix + String(i)); + const stack_pos = new AsmAddressMode(new Register("r1"), new AsmLiteral(size * (i - 32) + addend), null); + new_instrs.push(new AsmInstruction(mnemonic, [reg, stack_pos])); + } + return new Replacement(new_instrs, 1); + } +} + +/** Comparison against 0. */ +class CmpnezPattern1 extends IrPattern { + replacement = "cmpnez.fictive $o, $i"; + parts = ["addic $a, $i, -1", "subfe $o, $a, $i"]; +} + +class CmpnezPattern2 extends IrPattern { + replacement = "cmpnez.fictive $o, $i"; + parts = ["neg $a, $i", "or $b, $a, $i", "srwi $o, $b, 31"]; +} + +class CmplezPattern extends IrPattern { + replacement = "cmplez.fictive $o, $i"; + parts = ["cntlzw $a, $i", "li $b, 1", "rlwnm $o, $b, $a, 31, 31"]; +} + +class CmpgtzPattern extends IrPattern { + replacement = "cmpgtz.fictive $o, $i"; + parts = ["neg $a, $i", "andc $b, $a, $i", "srwi $o, $b, 31"]; +} + +class CmpnePattern extends IrPattern { + replacement = "cmpne.fictive $o, $x, $y"; + parts = ["subf $a, $x, $y", "subf $b, $y, $x", "or $c, $a, $b", "srwi $o, $c, 31"]; +} + +class CmplePattern extends IrPattern { + replacement = "cmple.fictive $o, $x, $y"; + parts = ["srawi $a, $y, 31", "srwi $b, $x, 31", "subfc $c, $x, $y", "adde $o, $a, $b"]; +} + +class CmpltPattern1 extends IrPattern { + replacement = "cmplt.fictive $o, $x, $y"; + parts = ["eqv $a, $y, $x", "subfc $b, $y, $x", "srwi $c, $a, 31", "addze $d, $c", "clrlwi $o, $d, 31"]; +} + +class CmpltPattern2 extends IrPattern { + replacement = "cmplt.fictive $o, $x, $y"; + parts = ["xor $a, $y, $x", "srawi $b, $a, 1", "and $c, $a, $y", "subf $d, $c, $b", "srwi $o, $d, 31"]; +} + +class CmpleuPattern1 extends IrPattern { + replacement = "cmpleu.fictive $o, $x, $y"; + parts = ["subf $a, $x, $y", "orc $b, $y, $x", "srwi $c, $a, 1", "subf $d, $c, $b", "srwi $o, $d, 31"]; +} + +class CmpleuPattern2 extends IrPattern { + replacement = "cmpleu.fictive $o, $x, $y"; + parts = ["li $a, -1", "subfc $b, $x, $y", "subfze $o, $a"]; +} + +class CmpltuPattern1 extends IrPattern { + replacement = "cmpltu.fictive $o, $x, $y"; + parts = ["subfc $a, $y, $x", "subfe $b, $a, $a", "neg $o, $b"]; +} + +class CmpltuPattern2 extends IrPattern { + replacement = "cmpltu.fictive $o, $x, $y"; + parts = ["xor $a, $y, $x", "cntlzw $b, $a", "slw $c, $y, $b", "srwi $o, $c, 31"]; +} + +/** Split decrement-$ctr-and-branch instructions into a pair of instructions. */ +class BranchCtrPattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (instr instanceof Instruction && (instr.mnemonic === "bdz" || instr.mnemonic === "bdnz")) { + const ctr = new Register("ctr"); + return new Replacement([new AsmInstruction("addi", [ctr, ctr, new AsmLiteral(-1)]), new AsmInstruction(instr.mnemonic + ".fictive", instr.args)], 1); + } + return null; + } +} + +class FloatishToUintPattern extends SimpleAsmPattern { + pattern = make_pattern("bl __cvt_fp2unsigned"); + + replace(m) { + return new Replacement([new AsmInstruction("cvt.u.d.fictive", [new Register("r3"), new Register("f1")])], m.body.length); + } +} + +class LoopStructCopyPattern extends AsmPattern { + loop_patterns = [ + // 4-aligned + make_pattern(".loop:", ".set W, 8", ".set B, 4", "lwz $a, 4($x)", "lwzu $b, 8($x)", "stw $a, 4($y)", "stwu $b, 8($y)", "bdnz .loop"), + make_pattern(".loop:", ".set W, 8", ".set B, 8", "lwzu $a, 8($x)", "lwz $b, 4($x)", "stwu $a, 8($y)", "stw $b, 4($y)", "bdnz .loop"), + // 2-aligned + make_pattern(".loop:", ".set W, 4", ".set B, 2", "lhz $a, 2($x)", "lhzu $b, 4($x)", "sth $a, 2($y)", "sthu $b, 4($y)", "bdnz .loop"), + make_pattern(".loop:", ".set W, 4", ".set B, 4", "lhzu $a, 4($x)", "lhz $b, 2($x)", "sthu $a, 4($y)", "sth $b, 2($y)", "bdnz .loop"), + // 1-aligned + make_pattern(".loop:", ".set W, 2", ".set B, 1", "lbz $a, 1($x)", "lbzu $b, 2($x)", "stb $a, 1($y)", "stbu $b, 2($y)", "bdnz .loop"), + make_pattern(".loop:", ".set W, 2", ".set B, 2", "lbzu $a, 2($x)", "lbz $b, 1($x)", "stbu $a, 2($y)", "stb $b, 1($y)", "bdnz .loop"), + ]; + + match(matcher) { + let m = null; + for (const pattern of this.loop_patterns) { + m = matcher.try_match(pattern); + if (m !== null) break; + } + if (m === null) return null; + const new_instr = new AsmInstruction("loopstructcopy.fictive", [ + m.regs.get("y"), + m.regs.get("x"), + m.regs.get("y"), + m.regs.get("x"), + new Register("ctr"), + new AsmLiteral(m.literals.get("W")), + new AsmLiteral(m.literals.get("B")), + new AsmLiteral(0), + new AsmLiteral(0), + ]); + return new Replacement([m.body[0], new_instr], m.body.length); + } +} + +/** Recognizing struct copy when it starts with lwz lwz stw stw. */ +class StructCopyPattern extends AsmPattern { + pattern = make_pattern("lwz $a, I($s)", "lwz $b, (I+4)($s)", "stw $a, I($d)", "stw $b, (I+4)($d)"); + + match(matcher) { + let m = matcher.try_match(this.pattern); + if (m === null) return null; + let i = 8; + const pattern_ext = [...this.pattern]; + for (;;) { + const pattern2 = make_pattern(`lwz $a, (I+${i})($s)`, `lwz $b, (I+${i + 4})($s)`, `stw $a, (I+${i})($d)`, `stw $b, (I+${i + 4})($d)`); + const m2 = matcher.try_match([...pattern_ext, ...pattern2]); + if (m2) { + m = m2; + i += 8; + pattern_ext.push(...pattern2); + } else break; + } + + const pattern_end_4b = make_pattern(`lwz $b, (I+${i})($s)`, `stw $b, (I+${i})($d)`); + let m_end = matcher.try_match([...pattern_ext, ...pattern_end_4b]); + if (m_end) { + m = m_end; + i += 4; + pattern_ext.push(...pattern_end_4b); + } + + const pattern_end_2b = make_pattern(`lhz $b, (I+${i})($s)`, `sth $b, (I+${i})($d)`); + m_end = matcher.try_match([...pattern_ext, ...pattern_end_2b]); + if (m_end) { + m = m_end; + i += 2; + pattern_ext.push(...pattern_end_2b); + } + + const pattern_end_1b = make_pattern(`lbz $b, (I+${i})($s)`, `stb $b, (I+${i})($d)`); + m_end = matcher.try_match([...pattern_ext, ...pattern_end_1b]); + if (m_end) { + m = m_end; + i += 1; + } + + return new Replacement([new AsmInstruction("structcopy.fictive", [m.regs.get("d"), m.regs.get("s"), new AsmLiteral(i)])], m.body.length); + } +} + +class FloatishToSintIrPattern extends IrPattern { + replacement = "fctiwz.fictive $i, $f"; + parts = ["fctiwz $t, $f", "stfd $t, (N-4)($r1)", "lwz $i, N($r1)"]; +} + +// Upstream mixes in CheckConstantMixin *after* IrPattern, so IrPattern.check +// (always true) wins in the MRO; the mixin's check is never used. + +class SintToDoubleIrPattern extends IrPattern { + replacement = "cvt.d.i.fictive $f, $i, K($k)"; + parts = ["lis $a, 0x4330", "stw $a, N($r1)", "xoris $b, $i, 0x8000", "stw $b, (N+4)($r1)", "lfd $d, N($r1)", "lfd $c, K($k)", "fsub $f, $d, $c"]; +} + +class UintToDoubleIrPattern extends IrPattern { + replacement = "cvt.d.u.fictive $f, $i, K($k)"; + parts = ["lis $a, 0x4330", "stw $a, N($r1)", "stw $i, (N+4)($r1)", "lfd $d, N($r1)", "lfd $c, K($k)", "fsub $f, $d, $c"]; +} + +class SintToFloatIrPattern extends IrPattern { + replacement = "cvt.s.i.fictive $f, $i, K($k)"; + parts = ["lis $a, 0x4330", "stw $a, N($r1)", "xoris $b, $i, 0x8000", "stw $b, (N+4)($r1)", "lfd $d, N($r1)", "lfd $c, K($k)", "fsubs $f, $d, $c"]; +} + +class UintToFloatIrPattern extends IrPattern { + replacement = "cvt.s.u.fictive $f, $i, K($k)"; + parts = ["lis $a, 0x4330", "stw $a, N($r1)", "stw $i, (N+4)($r1)", "lfd $d, N($r1)", "lfd $c, K($k)", "fsubs $f, $d, $c"]; +} + +class LoopStructCopySetupPattern extends IrPattern { + replacement = "loopstructcopy.fictive $a, $b, $x, $y, $z, W, B, B, T"; + parts = ["addi $a, $x, -B", "addi $b, $y, -B", "loopstructcopy.fictive $a, $b, $a, $b, $z, W, B, 0, 0"]; + + static _by_offset(refs) { + const ret = new Map(); + for (const ref of refs) { + if (!(ref instanceof InstrRef)) continue; + const ins = ref.instruction; + if (ins.args.length !== 2) continue; + const arg = ins.args[1]; + if (!(arg instanceof AsmAddressMode)) continue; + if (!(arg.addend instanceof AsmLiteral)) continue; + ret.set(arg.addend.value, ref); + } + return ret; + } + + check(m, arch, flow_graph) { + let offset = m.symbolic_args.get("B"); + pyassert(offset instanceof AsmLiteral); + offset = offset.value; + let tail_size = 0; + + const ref = m.body[2]; + pyassert(ref.instruction.mnemonic === "loopstructcopy.fictive"); + const dst = m.symbolic_registers.get("a"); + const src = m.symbolic_registers.get("b"); + const dst_refs_by_offset = LoopStructCopySetupPattern._by_offset(flow_graph.instr_uses.get(ref).get(dst)); + const src_refs_by_offset = LoopStructCopySetupPattern._by_offset(flow_graph.instr_uses.get(ref).get(src)); + + const tails = [ + ["lwz", "stw", 4], + ["lhz", "sth", 2], + ["lbz", "stb", 1], + ]; + for (const [load_mn, store_mn, width] of tails) { + const load = src_refs_by_offset.get(offset + tail_size) ?? null; + const store = dst_refs_by_offset.get(offset + tail_size) ?? null; + if (load === null || store === null || load.instruction.mnemonic !== load_mn || store.instruction.mnemonic !== store_mn) continue; + const temp_reg = load.instruction.args[0]; + pyassert(temp_reg instanceof Register); + if (!flow_graph.instr_uses.get(load).get(temp_reg).has(store)) continue; + tail_size += width; + load.instruction = load.instruction.replace({ in_pattern: true }); + store.replace_instruction(new AsmInstruction("nop", []), arch); + } + + m.symbolic_args.set("T", new AsmLiteral(tail_size)); + return true; + } +} + +const r = (names) => names.map((n) => new Register(n)); + +const argument_regs = r(["r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13"]); +const simple_temp_regs = r(["r11", "r12"]); +const temp_regs = [...argument_regs, ...simple_temp_regs, ...r(["r0", "f0", "cr0_gt", "cr0_lt", "cr0_eq", "cr0_so", "ctr"])]; +const saved_regs = r([ + "lr", + "r2", + "r13", + "r14", + "r15", + "r16", + "r17", + "r18", + "r19", + "r20", + "r21", + "r22", + "r23", + "r24", + "r25", + "r26", + "r27", + "r28", + "r29", + "r30", + "r31", + "f14", + "f15", + "f16", + "f17", + "f18", + "f19", + "f20", + "f21", + "f22", + "f23", + "f24", + "f25", + "f26", + "f27", + "f28", + "f29", + "f30", + "f31", +]); +const stack_pointer_reg = new Register("r1"); +const all_regs = [...saved_regs, ...temp_regs, stack_pointer_reg, ...r(["zero", "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7"])]; + +// List of all instructions where `$r0` as certain args is interpreted as `0` +// instead of the contents of `$r0`. The value is the affected argument index. +const INSTRS_R0_AS_ZERO = { + addi: 1, + addis: 1, + dcbf: 0, + dcbi: 0, + dcbst: 0, + dcbt: 0, + dcbtst: 0, + dcbz: 0, + dcbz_l: 0, + eciwx: 1, + ecowx: 1, + icbi: 0, + lbz: 1, + lbzx: 1, + lfd: 1, + lfdx: 1, + lfs: 1, + lfsx: 1, + lha: 1, + lhax: 1, + lhbrx: 1, + lhz: 1, + lhzx: 1, + lmw: 1, + lswi: 1, + lswx: 1, + lwarx: 1, + lwbrx: 1, + lwz: 1, + lwzx: 1, + psq_lx: 1, + psq_stx: 1, + stb: 1, + stbx: 1, + stfd: 1, + stfdx: 1, + stfiwx: 1, + stfs: 1, + stfsx: 1, + sth: 1, + sthbrx: 1, + sthx: 1, + stmw: 1, + stswi: 1, + stswx: 1, + stw: 1, + stwbrx: 1, + "stwcx.": 1, + stwx: 1, +}; + +const instrs_ignore = new Set(["nop", "stmw", "lmw", "crclr", "crset"]); + +const instrs_store = { + stb: (a) => make_store(a, Type.int_of_size(8)), + sth: (a) => make_store(a, Type.int_of_size(16)), + stw: (a) => make_store(a, Type.reg32({ likely_float: false })), + stbx: (a) => make_storex(a, Type.int_of_size(8)), + sthx: (a) => make_storex(a, Type.int_of_size(16)), + stwx: (a) => make_storex(a, Type.reg32({ likely_float: false })), + stfs: (a) => make_store(a, Type.f32()), + stfd: (a) => make_store(a, Type.f64()), + stfsx: (a) => make_storex(a, Type.f32()), + stfdx: (a) => make_storex(a, Type.f64()), + psq_st: () => null, +}; +const instrs_store_update = { + stbu: (a) => make_store(a, Type.int_of_size(8)), + sthu: (a) => make_store(a, Type.int_of_size(16)), + stwu: (a) => make_store(a, Type.reg32({ likely_float: false })), + stbux: (a) => make_storex(a, Type.int_of_size(8)), + sthux: (a) => make_storex(a, Type.int_of_size(16)), + stwux: (a) => make_storex(a, Type.reg32({ likely_float: false })), + stfsu: (a) => make_store(a, Type.f32()), + stfdu: (a) => make_store(a, Type.f64()), + stfsux: (a) => make_storex(a, Type.f32()), + stfdux: (a) => make_storex(a, Type.f64()), +}; +const instrs_load = { + lba: (a) => handle_load(a, Type.s8()), + lbz: (a) => handle_load(a, Type.u8()), + lha: (a) => handle_load(a, Type.s16()), + lhz: (a) => handle_load(a, Type.u16()), + lwz: (a) => handle_load(a, Type.reg32({ likely_float: false })), + lbax: (a) => handle_loadx(a, Type.s8()), + lbzx: (a) => handle_loadx(a, Type.u8()), + lhax: (a) => handle_loadx(a, Type.s16()), + lhzx: (a) => handle_loadx(a, Type.u16()), + lwzx: (a) => handle_loadx(a, Type.reg32({ likely_float: false })), + lfs: (a) => handle_load(a, Type.f32()), + lfd: (a) => handle_load(a, Type.f64()), + lfsx: (a) => handle_loadx(a, Type.f32()), + lfdx: (a) => handle_loadx(a, Type.f64()), + psq_l: () => new ErrorExpr("psq_l unimplemented"), +}; +const instrs_load_update = { + lbau: (a) => handle_load(a, Type.s8()), + lbzu: (a) => handle_load(a, Type.u8()), + lhau: (a) => handle_load(a, Type.s16()), + lhzu: (a) => handle_load(a, Type.u16()), + lwzu: (a) => handle_load(a, Type.reg32({ likely_float: false })), + lbaux: (a) => handle_loadx(a, Type.s8()), + lbzux: (a) => handle_loadx(a, Type.u8()), + lhaux: (a) => handle_loadx(a, Type.s16()), + lhzux: (a) => handle_loadx(a, Type.u16()), + lwzux: (a) => handle_loadx(a, Type.reg32({ likely_float: false })), + lfsu: (a) => handle_load(a, Type.f32()), + lfdu: (a) => handle_load(a, Type.f64()), + lfsux: (a) => handle_loadx(a, Type.f32()), + lfdux: (a) => handle_loadx(a, Type.f64()), +}; + +const instrs_branches = { + // The `!` indicates that the condition in the register is negated + beq: "cr0_eq", + bge: "!cr0_lt", + bgt: "cr0_gt", + ble: "!cr0_gt", + blt: "cr0_lt", + bne: "!cr0_eq", + bns: "!cr0_so", + bso: "cr0_so", + bdnz: "ctr", + bdz: "!ctr", + "bdnz.fictive": "ctr", + "bdz.fictive": "!ctr", +}; +const instrs_no_dest = { + sync: () => void_fn_op("M2C_SYNC", []), + isync: () => void_fn_op("M2C_SYNC", []), + "structcopy.fictive": (a) => void_fn_op("M2C_STRUCT_COPY", [a.reg(0), a.reg(1), a.full_imm(2)]), +}; + +const intish = () => ({ type: Type.intish() }); + +const instrs_dest_first_non_load = { + // Integer arithmetic + add: (a) => handle_add(a), + addc: (a) => handle_add(a), + adde: (a) => carry_add_to(handle_add(a)), + addze: (a) => carry_add_to(a.reg(1)), + addi: (a) => handle_addi(a.reg_ref(0), a.reg_ref(1), a.reg(1), a.s16_imm(2), a), + addic: (a) => handle_addi(a.reg_ref(0), a.reg_ref(1), a.reg(1), a.s16_imm(2), a), + addis: (a) => handle_addis(a), + subf: (a) => fold_divmod(BinaryOp.intptr(a.reg(2), "-", a.reg(1))), + subfc: (a) => fold_divmod(BinaryOp.intptr(a.reg(2), "-", a.reg(1))), + subfe: (a) => carry_sub_from(fold_divmod(BinaryOp.intptr(a.reg(2), "-", a.reg(1)))), + subfic: (a) => fold_divmod(BinaryOp.intptr(a.s16_imm(2), "-", a.reg(1))), + subfze: (a) => carry_sub_from(fold_mul_chains(UnaryOp.sint("-", a.reg(1)))), + neg: (a) => fold_mul_chains(UnaryOp.sint("-", a.reg(1))), + divw: (a) => BinaryOp.sint(a.reg(1), "/", a.reg(2)), + divwu: (a) => BinaryOp.uint(a.reg(1), "/", a.reg(2)), + mulli: (a) => BinaryOp.int(a.reg(1), "*", a.s16_imm(2)), + mullw: (a) => BinaryOp.int(a.reg(1), "*", a.reg(2)), + mulhw: (a) => fold_divmod(BinaryOp.int(a.reg(1), "MULT_HI", a.reg(2))), + mulhwu: (a) => fold_divmod(BinaryOp.int(a.reg(1), "MULTU_HI", a.reg(2))), + // Bit arithmetic + or: (a) => handle_or(a.reg(1), a.reg(2)), + orc: (a) => handle_or(a.reg(1), new UnaryOp("~", a.reg(2), intish())), + ori: (a) => handle_or(a.reg(1), a.u16_imm(2)), + oris: (a) => handle_or(a.reg(1), a.shifted_u16_imm(2)), + and: (a) => BinaryOp.int(a.reg(1), "&", a.reg(2)), + andc: (a) => BinaryOp.int(a.reg(1), "&", new UnaryOp("~", a.reg(2), intish())), + not: (a) => new UnaryOp("~", a.reg(1), intish()), + nor: (a) => new UnaryOp("~", BinaryOp.int(a.reg(1), "|", a.reg(2)), intish()), + xor: (a) => BinaryOp.int(a.reg(1), "^", a.reg(2)), + eqv: (a) => new UnaryOp("~", BinaryOp.int(a.reg(1), "^", a.reg(2)), intish()), + andi: (a) => BinaryOp.int(a.reg(1), "&", a.u16_imm(2)), + andis: (a) => BinaryOp.int(a.reg(1), "&", a.shifted_u16_imm(2)), + xori: (a) => handle_xor(a.reg(1), a.u16_imm(2)), + xoris: (a) => BinaryOp.int(a.reg(1), "^", a.shifted_u16_imm(2)), + "cmpnez.fictive": (a) => handle_cmpnez(a.reg(1)), + "cmpne.fictive": (a) => BinaryOp.icmp(a.reg(1), "!=", a.reg(2)), + "cmple.fictive": (a) => BinaryOp.scmp(a.reg(1), "<=", a.reg(2)), + "cmplez.fictive": (a) => BinaryOp.scmp(a.reg(1), "<=", new Literal(0)), + "cmplt.fictive": (a) => BinaryOp.scmp(a.reg(1), "<", a.reg(2)), + "cmpgtz.fictive": (a) => BinaryOp.scmp(a.reg(1), ">", new Literal(0)), + "cmpleu.fictive": (a) => BinaryOp.ucmp(a.reg(1), "<=", a.reg(2)), + "cmpltu.fictive": (a) => BinaryOp.ucmp(a.reg(1), "<", a.reg(2)), + rlwimi: (a) => handle_rlwimi(a.reg(0), a.reg(1), a.imm_value(2), a.imm_value(3), a.imm_value(4)), + rlwinm: (a) => handle_rlwinm(a.reg(1), a.imm_value(2), a.imm_value(3), a.imm_value(4)), + rlwnm: (a) => handle_rlwnm(a.reg(1), a.reg(2), a.imm_value(3), a.imm_value(4)), + slw: (a) => fold_mul_chains(BinaryOp.int(a.reg(1), "<<", as_intish(a.reg(2)))), + srw: (a) => fold_divmod(BinaryOp.ushift(a.reg(1), ">>", a.reg(2))), + sraw: (a) => fold_divmod(BinaryOp.sshift(a.reg(1), ">>", a.reg(2))), + srawi: (a) => handle_shift_right(a, { signed: true }), + extsb: (a) => as_type(a.reg(1), Type.s8(), false), + extsh: (a) => as_type(a.reg(1), Type.s16(), false), + cntlzw: (a) => new UnaryOp("CLZ", a.reg(1), intish()), + // Load Immediate + li: (a) => a.full_imm(1), + lis: (a) => load_upper(a), + // Move from Special Register + mflr: (a) => a.regs.get(new Register("lr")), + mfctr: (a) => a.regs.get(new Register("ctr")), + // Move pseudoinstructions + mr: (a) => a.reg(1), + "move.fictive": (a) => a.reg(1), + // Floating Point Arithmetic + fadd: (a) => handle_add_double(a), + fadds: (a) => handle_add_float(a), + fdiv: (a) => BinaryOp.f64(a.reg(1), "/", a.reg(2)), + fdivs: (a) => BinaryOp.f32(a.reg(1), "/", a.reg(2)), + fmul: (a) => BinaryOp.f64(a.reg(1), "*", a.reg(2)), + fmuls: (a) => BinaryOp.f32(a.reg(1), "*", a.reg(2)), + fsub: (a) => BinaryOp.f64(a.reg(1), "-", a.reg(2)), + fsubs: (a) => BinaryOp.f32(a.reg(1), "-", a.reg(2)), + fneg: (a) => new UnaryOp("-", a.reg(1), { type: Type.floatish() }), + fmr: (a) => a.reg(1), + frsp: (a) => handle_convert(a.reg(1), Type.f32(), Type.f64()), + fctiwz: (a) => handle_convert(a.reg(1), Type.sintish(), Type.floatish()), + "fctiwz.fictive": (a) => handle_convert(a.reg(1), Type.sintish(), Type.floatish()), + "cvt.u.d.fictive": (a) => handle_convert(a.reg(1), Type.uintish(), Type.floatish()), + "cvt.d.i.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.sintish()), + "cvt.d.u.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.uintish()), + "cvt.s.i.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.sintish()), + "cvt.s.u.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.uintish()), + // Floating Point Fused Multiply-{Add,Sub} + fmadd: (a) => BinaryOp.f64(BinaryOp.f64(a.reg(1), "*", a.reg(2)), "+", a.reg(3)), + fmadds: (a) => BinaryOp.f32(BinaryOp.f32(a.reg(1), "*", a.reg(2)), "+", a.reg(3)), + fnmadd: (a) => new UnaryOp("-", BinaryOp.f64(BinaryOp.f64(a.reg(1), "*", a.reg(2)), "+", a.reg(3)), { type: Type.f64() }), + fnmadds: (a) => new UnaryOp("-", BinaryOp.f32(BinaryOp.f32(a.reg(1), "*", a.reg(2)), "+", a.reg(3)), { type: Type.f32() }), + fmsub: (a) => BinaryOp.f64(BinaryOp.f64(a.reg(1), "*", a.reg(2)), "-", a.reg(3)), + fmsubs: (a) => BinaryOp.f32(BinaryOp.f32(a.reg(1), "*", a.reg(2)), "-", a.reg(3)), + fnmsub: (a) => new UnaryOp("-", BinaryOp.f64(BinaryOp.f64(a.reg(1), "*", a.reg(2)), "-", a.reg(3)), { type: Type.f64() }), + fnmsubs: (a) => new UnaryOp("-", BinaryOp.f32(BinaryOp.f32(a.reg(1), "*", a.reg(2)), "-", a.reg(3)), { type: Type.f32() }), + fabs: (a) => fn_op("fabs", [a.reg(1)], Type.floatish()), + fres: (a) => fn_op("__fres", [a.reg(1)], Type.floatish()), + frsqrte: (a) => fn_op("__frsqrte", [a.reg(1)], Type.floatish()), + fsel: (a) => new TernaryOp(BinaryOp.fcmp(a.reg(1), ">=", new Literal(0)), a.reg(2), a.reg(3), { type: Type.floatish() }), +}; +const instrs_destination_first = { ...instrs_dest_first_non_load, ...instrs_load }; + +const instrs_ppc_compare = { + // Integer (signed/unsigned) + cmpw: (a, op) => BinaryOp.sintptr_cmp(a.reg(1), op, a.reg(2)), + cmpwi: (a, op) => BinaryOp.sintptr_cmp(a.reg(1), op, a.s16_imm(2)), + cmplw: (a, op) => BinaryOp.uintptr_cmp(a.reg(1), op, a.reg(2)), + cmplwi: (a, op) => BinaryOp.uintptr_cmp(a.reg(1), op, a.s16_imm(2)), + // Floating point + fcmpo: (a, op) => BinaryOp.fcmp(a.reg(1), op, a.reg(2)), + fcmpu: (a, op) => BinaryOp.fcmp(a.reg(1), op, a.reg(2)), + "fcmpo.lte.fictive": (a, op) => BinaryOp.fcmp(a.reg(1), op !== "==" ? op : "<=", a.reg(2)), + "fcmpo.gte.fictive": (a, op) => BinaryOp.fcmp(a.reg(1), op !== "==" ? op : ">=", a.reg(2)), +}; + +const PPC_ATTRS = { + arch: Target.ArchEnum.PPC, + re_comment: String.raw`[#;].*`, + supports_dollar_regs: true, + home_space_size: 8, + stack_pointer_reg, + frame_pointer_regs: r(["r30"]), + return_address_reg: new Register("lr"), + base_return_regs: [ + [new Register("r3"), false], + [new Register("f1"), true], + ], + all_return_regs: r(["f1", "r3", "r4"]), + argument_regs, + simple_temp_regs, + temp_regs, + saved_regs, + all_regs, + aliased_regs: {}, + INSTRS_R0_AS_ZERO, + instrs_ignore, + instrs_store, + instrs_store_update, + instrs_load, + instrs_load_update, + instrs_branches, + instrs_no_dest, + instrs_dest_first_non_load, + instrs_destination_first, + instrs_ppc_compare, +}; + +export class PpcArch extends Arch { + constructor() { + super(); + Object.assign(this, PPC_ATTRS); + this.ir_patterns = [ + new LoopStructCopySetupPattern(), + new FloatishToSintIrPattern(), + new SintToDoubleIrPattern(), + new UintToDoubleIrPattern(), + new SintToFloatIrPattern(), + new UintToFloatIrPattern(), + new CmpnezPattern1(), + new CmpnezPattern2(), + new CmplezPattern(), + new CmpgtzPattern(), + new CmpnePattern(), + new CmplePattern(), + new CmpltPattern1(), + new CmpltPattern2(), + new CmpleuPattern1(), + new CmpleuPattern2(), + new CmpltuPattern1(), + new CmpltuPattern2(), + ]; + this.asm_patterns = [ + new FcmpoCrorPattern(), + new MfcrPattern(), + new TailCallPattern(), + new SaveRestoreRegsFnPattern(), + new LoopStructCopyPattern(), + new BranchCtrPattern(), + new FloatishToUintPattern(), + new StructCopyPattern(), + ]; + } + + missing_return() { + return [this.parse("blr", [], InstructionMeta.missing())]; + } + + normalize_instruction(instr, asm_state) { + // Remove +/- suffix, which indicates branch-(un)likely and can be ignored + if (instr.mnemonic.startsWith("b") && (instr.mnemonic.endsWith("+") || instr.mnemonic.endsWith("-"))) { + return this.normalize_instruction(new AsmInstruction(instr.mnemonic.slice(0, -1), instr.args), asm_state); + } + + const args = instr.args; + const base_mnemonic = rstrip(instr.mnemonic, "."); + const dot = instr.mnemonic.slice(base_mnemonic.length); + + const sub = (a, b) => (a instanceof AsmLiteral && b instanceof AsmLiteral ? new AsmLiteral(a.value - b.value) : new BinOp("-", a, b)); + const add = (a, b) => (a instanceof AsmLiteral && b instanceof AsmLiteral ? new AsmLiteral(a.value + b.value) : new BinOp("+", a, b)); + const make_dotted = (mn, a) => new AsmInstruction(mn + dot, a); + const lit = (v) => new AsmLiteral(v); + + const r0_index = has(this.INSTRS_R0_AS_ZERO, instr.mnemonic) ? this.INSTRS_R0_AS_ZERO[instr.mnemonic] : null; + if (r0_index !== null && args.length > r0_index) { + let r0_arg = args[r0_index]; + if (r0_arg === new Register("r0")) r0_arg = new Register("zero"); + else if (r0_arg instanceof AsmAddressMode && r0_arg.base === new Register("r0")) r0_arg = new AsmAddressMode(new Register("zero"), r0_arg.addend, r0_arg.writeback); + if (r0_arg !== args[r0_index]) { + const new_args = [...args]; + new_args[r0_index] = r0_arg; + return this.normalize_instruction(new AsmInstruction(instr.mnemonic, new_args), asm_state); + } + } + if (args.length === 4) { + if (base_mnemonic === "extlwi") return make_dotted("rlwinm", [...args.slice(0, 2), args[3], lit(0), sub(args[2], lit(1))]); + if (base_mnemonic === "extrwi") return make_dotted("rlwinm", [...args.slice(0, 2), add(args[2], args[3]), sub(lit(32), args[2]), lit(31)]); + if (base_mnemonic === "clrlslwi") { + const b = args[2]; + const n = args[3]; + return make_dotted("rlwinm", [...args.slice(0, 2), n, sub(b, n), sub(lit(31), n)]); + } + } + if (args.length === 3) { + if ( + instr.mnemonic === "addi" && + args[2] instanceof Macro && + (args[1] === new Register("r2") || args[1] === new Register("r13")) && + (args[2].macro_name === "sda2" || args[2].macro_name === "sda21") + ) { + return new AsmInstruction("li", [args[0], args[2].argument]); + } + if (["subi", "subis", "subic"].includes(base_mnemonic) && args[2] instanceof AsmLiteral) { + const mn = "add" + base_mnemonic.slice(3); + const negated = new AsmLiteral(-args[2].value); + return this.normalize_instruction(make_dotted(mn, [...args.slice(0, 2), negated]), asm_state); + } + if (["sub", "subo", "subc", "subco"].includes(base_mnemonic)) { + const mn = "subf" + base_mnemonic.slice(3); + return make_dotted(mn, [args[0], args[2], args[1]]); + } + if (base_mnemonic === "rotlwi") return make_dotted("rlwinm", [...args.slice(0, 2), args[2], lit(0), lit(31)]); + if (base_mnemonic === "rotrwi") return make_dotted("rlwinm", [...args.slice(0, 2), sub(lit(32), args[2]), lit(0), lit(31)]); + if (base_mnemonic === "slwi") return make_dotted("rlwinm", [...args.slice(0, 2), args[2], lit(0), sub(lit(31), args[2])]); + if (base_mnemonic === "srwi") return make_dotted("rlwinm", [...args.slice(0, 2), sub(lit(32), args[2]), args[2], lit(31)]); + if (base_mnemonic === "clrlwi") return make_dotted("rlwinm", [...args.slice(0, 2), lit(0), args[2], lit(31)]); + if (base_mnemonic === "clrrwi") return make_dotted("rlwinm", [...args.slice(0, 2), lit(0), lit(0), sub(lit(31), args[2])]); + } + if (args.length === 2) { + if (instr.mnemonic === "lis" && args[1] instanceof AsmLiteral) { + const val = lit(band(args[1].value, 0xffff) * 0x10000); + return new AsmInstruction("li", [args[0], val]); + } + if (instr.mnemonic === "lis" && args[1] instanceof Macro && args[1].macro_name === "ha" && args[1].argument instanceof AsmLiteral) { + let value = args[1].argument.value; + if (band(value, 0x8000)) value += 0x10000; + const val = lit(band(value, 0xffff0000)); + return new AsmInstruction("li", [args[0], val]); + } + if (instr.mnemonic.startsWith("cmp") && !instr.mnemonic.includes("fictive")) { + const cr0 = new Register("cr0"); + return new AsmInstruction(instr.mnemonic, [cr0, ...instr.args]); + } + } + return instr; + } + + parse(mnemonic, args, meta) { + const cls = this; + let inputs = []; + let clobbers = []; + let outputs = []; + let jump_target = null; + let function_target = null; + let is_conditional = false; + let is_return = false; + let is_load = false; + let is_store = false; + let eval_fn = null; + + const instr_str = String(new AsmInstruction(mnemonic, args)); + + const cr0_bits = r(["cr0_lt", "cr0_gt", "cr0_eq", "cr0_so"]); + + const memory_sizes = { b: 1, h: 2, w: 4, fs: 4, fd: 8 }; + let psq_imms = 0; + const size_key = rstrip(lstrip(mnemonic, "stl"), "azux"); + let size = has(memory_sizes, size_key) ? memory_sizes[size_key] : null; + if (mnemonic.startsWith("psq_l") || mnemonic.startsWith("psq_st")) { + psq_imms = 2; + size = 8; + } + + const make_memory_access = (arg, size) => { + pyassert(size !== null); + if (arg instanceof AsmAddressMode && arg.base === cls.stack_pointer_reg) { + const loc = StackLocation.from_offset(arg.addend); + if (loc === null) return []; + else if (size === 8) return [loc, new StackLocation(loc.offset + 4, loc.symbolic_offset)]; + else { + pyassert(size <= 4); + return [loc]; + } + } + return []; + }; + + const unreachable_eval = () => { + throw new DecompFailure(`Instruction ${instr_str} should be replaced before eval`); + }; + + const mn_nodot = rstrip(mnemonic, "."); + + if (mnemonic === "blr") { + // Return + pyassert(args.length === 0); + inputs = [new Register("lr")]; + is_return = true; + } else if (["beqlr", "bgelr", "bgtlr", "blelr", "bltlr", "bnelr", "bnglr", "bnllr", "bnslr", "bsolr"].includes(mnemonic)) { + // Conditional return + pyassert(args.length <= 1); + inputs = [...cr0_bits, new Register("lr")]; + is_return = true; + is_conditional = true; + eval_fn = unreachable_eval; + } else if (mnemonic === "bctr") { + // Jump table (switch) + pyassert(args.length === 0); + inputs = [new Register("ctr")]; + jump_target = new Register("ctr"); + is_conditional = true; + eval_fn = (s, a) => s.set_switch_expr(a.regs.get(new Register("ctr"))); + } else if (mnemonic === "bl") { + // Function call to label + pyassert(args.length === 1); + inputs = [...cls.argument_regs]; + outputs = [...cls.all_return_regs]; + clobbers = [...cls.temp_regs]; + function_target = args[0]; + eval_fn = (s, a) => s.make_function_call(a.sym_imm(0), outputs); + } else if (mnemonic === "bctrl" || mnemonic === "blrl") { + // Function call to pointer in special reg ($ctr or $lr) + pyassert(args.length === 0); + const reg = new Register(mnemonic.slice(1, -1)); + inputs = [...cls.argument_regs]; + inputs.push(reg); + outputs = [...cls.all_return_regs]; + clobbers = [...cls.temp_regs]; + function_target = reg; + eval_fn = (s, a) => s.make_function_call(a.regs.get(reg), outputs); + } else if (mnemonic === "b") { + // Unconditional jump + pyassert(args.length === 1); + jump_target = get_jump_target(args[0]); + } else if (has(cls.instrs_branches, mnemonic)) { + // Normal branch + pyassert(1 <= args.length && args.length <= 2); + const raw_name = cls.instrs_branches[mnemonic]; + const negated = raw_name.startsWith("!"); + const reg_name = lstrip(raw_name, "!"); + inputs = [new Register(reg_name)]; + jump_target = get_jump_target(args[args.length - 1]); + is_conditional = true; + eval_fn = (s, a) => { + let cond = a.cmp_reg(reg_name); + if (negated) cond = cond.negated(); + s.set_branch_condition(cond); + }; + } else if (has(cls.instrs_store, mnemonic)) { + pyassert(args[0] instanceof Register && size !== null); + is_store = true; + if (mnemonic.endsWith("x")) { + pyassert(args.length === 3 + psq_imms && args[1] instanceof Register && args[2] instanceof Register); + inputs = [args[0], args[1], args[2]]; + } else { + pyassert(args.length === 2 + psq_imms && args[1] instanceof AsmAddressMode); + outputs = make_memory_access(args[1], size); + inputs = new Array(outputs.length || 1).fill(args[0]); + inputs.push(args[1].base); + } + eval_fn = (s, a) => { + const store = cls.instrs_store[mnemonic](a); + if (store !== null) s.store_memory(store, a.reg_ref(0)); + }; + } else if (has(cls.instrs_store_update, mnemonic)) { + pyassert(args[0] instanceof Register && size !== null); + is_store = true; + if (mnemonic.endsWith("x")) { + pyassert(args.length === 3 + psq_imms && args[1] instanceof Register && args[2] instanceof Register); + inputs = [args[0], args[1], args[2]]; + outputs = [args[1]]; + eval_fn = (s, a) => { + const store = cls.instrs_store_update[mnemonic](a); + // Update the register in the second argument + const update = a.reg_ref(1); + const offset = a.reg(2); + s.set_reg(update, add_imm(update, a.regs.get(update), offset, a)); + if (store !== null) s.store_memory(store, a.reg_ref(0)); + }; + } else { + pyassert(args.length === 2 + psq_imms && args[1] instanceof AsmAddressMode); + inputs = [args[0], args[1].base]; + outputs = [...make_memory_access(args[1], size), args[1].base]; + eval_fn = (s, a) => { + const store = cls.instrs_store_update[mnemonic](a); + // Update the register in the second argument + const update = a.memory_ref(1); + if (!(update instanceof AddressMode)) throw new DecompFailure(`Unhandled store-and-update arg in ${instr_str}: ${repr(update)}`); + s.set_reg(update.base, add_imm(update.base, a.regs.get(update.base), new Literal(update.offset), a)); + if (store !== null) s.store_memory(store, a.reg_ref(0)); + }; + } + } else if (has(cls.instrs_load, mnemonic)) { + pyassert(args[0] instanceof Register && size !== null); + if (mnemonic.endsWith("x")) { + pyassert(args.length === 3 + psq_imms && args[1] instanceof Register && args[2] instanceof Register); + inputs = [args[1], args[2]]; + } else { + pyassert(args.length === 2 + psq_imms); + if (args[1] instanceof AsmAddressMode) inputs = [...make_memory_access(args[1], size), args[1].base]; + } + is_load = true; + outputs = [args[0]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(0), cls.instrs_load[mnemonic](a)); + } else if (has(cls.instrs_load_update, mnemonic)) { + pyassert(args[0] instanceof Register && size !== null); + is_load = true; + if (mnemonic.endsWith("x")) { + pyassert(args.length === 3 + psq_imms && args[1] instanceof Register && args[2] instanceof Register); + inputs = [args[1], args[2]]; + outputs = [args[0], args[1]]; + eval_fn = (s, a) => { + const target = a.reg_ref(0); + const val = cls.instrs_load_update[mnemonic](a); + s.set_reg(target, val); + // In `rD, rA, rB`, update `rA = rA + rB` + const update_reg = a.reg_ref(1); + const offset = a.reg(2); + if (update_reg === target) throw new DecompFailure(`Invalid instruction, rA and rD must be different in ${instr_str}`); + s.set_reg(update_reg, add_imm(update_reg, a.regs.get(update_reg), offset, a)); + }; + } else { + pyassert(args.length === 2 + psq_imms && args[1] instanceof AsmAddressMode); + inputs = [...make_memory_access(args[1], size), args[1].base]; + outputs = [args[0], args[1].base]; + eval_fn = (s, a) => { + const target = a.reg_ref(0); + const val = cls.instrs_load_update[mnemonic](a); + s.set_reg(target, val); + // In `rD, rA(N)`, update `rA = rA + N` + const update = a.memory_ref(1); + if (!(update instanceof AddressMode)) throw new DecompFailure(`Unhandled load-and-update arg in ${instr_str}: ${repr(update)}`); + const update_reg = update.base; + const offset = new Literal(update.offset); + if (update_reg === target) throw new DecompFailure(`Invalid instruction, rA and rD must be different in ${instr_str}`); + s.set_reg(update_reg, add_imm(update_reg, a.regs.get(update_reg), offset, a)); + }; + } + } else if (mnemonic === "stmw" || mnemonic === "lmw") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof AsmAddressMode && args[0].register_name[0] === "r"); + is_store = mnemonic === "stmw"; + let index = int_(args[0].register_name.slice(1)); + let offset = args[1].addend_as_literal(); + while (index <= 31) { + const reg = new Register(`r${index}`); + const mem = make_memory_access(new AsmAddressMode(args[1].base, new AsmLiteral(offset), null), 4); + if (mnemonic === "stmw") { + inputs.push(reg); + outputs.push(...mem); + } else { + outputs.push(reg); + inputs.push(...mem); + } + index += 1; + offset += 4; + } + inputs.push(args[1].base); + // TODO: These are only supported in function prologues/epilogues + eval_fn = null; + } else if (has(cls.instrs_no_dest, mnemonic)) { + pyassert(!args.some((x) => x instanceof AsmAddressMode)); + inputs = args.filter((x) => x instanceof Register); + eval_fn = (s, a) => s.write_statement(cls.instrs_no_dest[mnemonic](a)); + } else if (has(cls.instrs_destination_first, mn_nodot)) { + pyassert(args[0] instanceof Register); + outputs = [args[0]]; + if (mnemonic === "mflr") { + pyassert(args.length === 1); + inputs = [new Register("lr")]; + } else if (mnemonic === "mfctr") { + pyassert(args.length === 1); + inputs = [new Register("ctr")]; + } else if (mn_nodot === "rlwimi") { + const notRegAm = (x) => !(x instanceof Register || x instanceof AsmAddressMode); + pyassert(args.length === 5 && args[1] instanceof Register && notRegAm(args[2]) && notRegAm(args[3]) && notRegAm(args[4])); + inputs = [args[0], args[1]]; + } else if (mnemonic.startsWith("cvt.")) { + pyassert(args[1] instanceof Register); + if (args.length === 2) inputs = [args[1]]; + else { + pyassert(args[2] instanceof AsmAddressMode); + size = 8; + inputs = [...make_memory_access(args[2], size), args[1], args[2].base]; + } + } else { + pyassert(!args.some((x) => x instanceof AsmAddressMode)); + inputs = args.slice(1).filter((x) => x instanceof Register); + } + if (["adde", "addme", "addze", "subfe", "subfze"].includes(mn_nodot)) inputs.push(new Register("carry")); + if (["addc", "addic", "subfc", "subfic"].includes(mn_nodot)) outputs.push(new Register("carry")); + if (mnemonic.endsWith(".")) outputs.push(...cr0_bits); + + eval_fn = (s, a) => { + const target = a.reg_ref(0); + const val = cls.instrs_destination_first[mn_nodot](a); + const target_val = s.set_reg(target, val); + // Instructions ending in `.` update the condition reg + if (mnemonic.endsWith(".")) { + s.set_reg(new Register("cr0_eq"), BinaryOp.icmp(target_val, "==", new Literal(0, { type: target_val.type }))); + // Use manual casts for cr0_gt/cr0_lt so that the type of target_val is not modified + // until the resulting bit is .use()'d. + const target_s32 = new Cast(target_val, { reinterpret: true, silent: true, type: Type.s32() }); + s.set_reg(new Register("cr0_gt"), new BinaryOp(target_s32, ">", new Literal(0), { type: Type.s32() })); + s.set_reg(new Register("cr0_lt"), new BinaryOp(target_s32, "<", new Literal(0), { type: Type.s32() })); + s.set_reg(new Register("cr0_so"), fn_op("M2C_OVERFLOW", [target_val], Type.s32())); + } + if (outputs.includes(new Register("carry"))) { + s.set_reg(new Register("carry"), fn_op("M2C_CARRY", [target_val], Type.s32())); + } + }; + } else if (mnemonic === "mtctr" || mnemonic === "mtlr") { + pyassert(args.length === 1 && args[0] instanceof Register); + const dest_reg = new Register(mnemonic.slice(2)); + inputs = [args[0]]; + outputs = [dest_reg]; + eval_fn = (s, a) => s.set_reg(dest_reg, a.reg(0)); + } else if (mnemonic === "loopstructcopy.fictive") { + pyassert(args.length === 9); + for (let k = 0; k < 5; k++) pyassert(args[k] instanceof Register); + const width = args[5]; + const bias = args[6]; + const adj = args[7]; + const tail_size = args[8]; + inputs = [args[2], args[3], args[4]]; + outputs = [args[0], args[1]]; + eval_fn = (s, a) => { + pyassert(width instanceof AsmLiteral); + pyassert(bias instanceof AsmLiteral); + pyassert(adj instanceof AsmLiteral); + pyassert(tail_size instanceof AsmLiteral); + const tail = tail_size.value; + const offset = bias.value - adj.value; + let dst = a.reg(2); + let dst_out = dst; + let src = a.reg(3); + let src_out = src; + if (offset !== 0) { + dst = BinaryOp.int(dst, "+", new Literal(offset)); + src = BinaryOp.int(src, "+", new Literal(offset)); + } + if (adj.value !== 0) { + dst_out = BinaryOp.int(dst_out, "-", new Literal(adj.value)); + src_out = BinaryOp.int(src_out, "-", new Literal(adj.value)); + } + const count = a.reg(4); + let incr_size, copy_size; + if (count instanceof Literal) { + incr_size = new Literal(count.value * width.value); + copy_size = new Literal(count.value * width.value + tail); + } else { + incr_size = BinaryOp.int(count, "*", new Literal(width.value)); + copy_size = incr_size; + if (tail !== 0) copy_size = BinaryOp.int(copy_size, "+", new Literal(tail)); + } + s.write_statement(void_fn_op("M2C_STRUCT_COPY", [dst, src, copy_size])); + dst_out = handle_add_real(dst_out, incr_size, a); + src_out = handle_add_real(src_out, incr_size, a); + s.set_reg_real(a.reg_ref(0), dst_out, { function_return: true }); + s.set_reg_real(a.reg_ref(1), src_out, { function_return: true }); + }; + } else if (has(cls.instrs_ppc_compare, mnemonic)) { + pyassert(args.length === 3 && args[1] instanceof Register); + inputs = args.slice(1).filter((x) => x instanceof Register); + outputs = [...cr0_bits]; + eval_fn = (s, a) => { + const base_reg = a.reg_ref(0); + if (base_reg !== new Register("cr0")) { + const error = `"${instr_str}" is not supported, the first arg is not $cr0`; + s.write_statement(error_stmt(error)); + return; + } + s.set_reg(new Register("cr0_eq"), cls.instrs_ppc_compare[mnemonic](a, "==")); + s.set_reg(new Register("cr0_gt"), cls.instrs_ppc_compare[mnemonic](a, ">")); + s.set_reg(new Register("cr0_lt"), cls.instrs_ppc_compare[mnemonic](a, "<")); + s.set_reg(new Register("cr0_so"), new Literal(0)); + }; + } else if (cls.instrs_ignore.has(mnemonic)) { + // pass + } else { + // If the mnemonic is unsupported, guess if it is destination-first + let maybe_dest_first; + if (args.length && args[0] instanceof Register) { + inputs = args.slice(1).filter((x) => x instanceof Register); + outputs = [args[0]]; + maybe_dest_first = true; + } else maybe_dest_first = false; + if (mnemonic.endsWith(".")) outputs.push(...cr0_bits); + + eval_fn = (s, a) => { + const error = new ErrorExpr(`unknown instruction: ${instr_str}`); + if (mnemonic.endsWith(".")) { + // Unimplemented instructions that modify CR0 + s.set_reg(new Register("cr0_eq"), error); + s.set_reg(new Register("cr0_gt"), error); + s.set_reg(new Register("cr0_lt"), error); + s.set_reg(new Register("cr0_so"), error); + } + if (maybe_dest_first) s.set_reg_real(a.reg_ref(0), error, { emit_exactly_once: true }); + else s.write_statement(new ExprStmt(error)); + }; + } + + return new Instruction({ + mnemonic, + args, + meta, + inputs, + clobbers, + outputs, + jump_target, + function_target, + is_conditional, + is_return, + is_load, + is_store, + eval_fn, + }); + } + + arg_name(loc) { + if (loc.offset !== null) return `arg_sp${format_hex(loc.offset)}`; + pyassert(loc.reg !== null); + const reg_num = int_(loc.reg.register_name.slice(1)); + if (loc.reg.register_name.startsWith("r")) return `arg${reg_num - 3}`; + return `farg${reg_num - 1}`; + } + + // Duplicated by MipseeArch.function_abi + function_abi(fn_sig, likely_regs, { for_call }) { + void for_call; + const known_slots = []; + const candidate_slots = []; + + // $rX & $fX regs can be interspersed in function args, unlike in the MIPS O32 ABI + const intptr_regs = argument_regs.filter((x) => x.register_name[0] !== "f"); + const float_regs = argument_regs.filter((x) => x.register_name[0] === "f"); + + if (fn_sig.params_known) { + let ind = 0; + let stack_offset = 0; + for (const param of fn_sig.params) { + const param_type = param.type.decay(); + let reg = null; + let offset = null; + const pool = param_type.is_float() ? float_regs : intptr_regs; + if (pool.length) reg = pool.shift(); + else { + // Stack variable + offset = stack_offset; + stack_offset += 4; + } + known_slots.push(new AbiArgSlot(new ArgLoc(offset, ind, reg), param_type, { name: param.name })); + ind += 1; + } + if (fn_sig.is_variadic) { + for (const reg of intptr_regs) { + candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.intptr())); + ind += 1; + } + for (const reg of float_regs) { + candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.floatish())); + ind += 1; + } + } + } else { + argument_regs.forEach((reg, ind) => { + if (reg.register_name[0] !== "f") candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.intptr())); + else candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.floatish())); + }); + } + + const valid_extra_regs = new Set(known_slots.filter((slot) => slot.loc.reg !== null).map((slot) => slot.loc.reg)); + const possible_slots = []; + for (const slot of candidate_slots) { + const reg = slot.loc.reg; + if (reg === null || !likely_regs.has(reg)) continue; + + // Don't pass this register if lower numbered ones are undefined. + if (pyeq(slot, candidate_slots[0])) { + // For varargs, a subset of regs may be used. + } else { + // Only r3-r10/f1-f13 can be used for arguments + const regname = reg.register_name; + const prev_reg = new Register(`${regname[0]}${int_(regname.slice(1)) - 1}`); + if (argument_regs.includes(prev_reg) && !valid_extra_regs.has(prev_reg)) continue; + } + + valid_extra_regs.add(reg); + + if (!likely_regs.get(reg)) continue; + + possible_slots.push(slot); + } + + return new Abi({ arg_slots: known_slots, possible_slots }); + } + + function_return(expr) { + return new Map([ + [new Register("f1"), new Cast(expr, { reinterpret: true, silent: true, type: Type.floatish() })], + [new Register("r3"), new Cast(expr, { reinterpret: true, silent: true, type: Type.intptr() })], + [new Register("r4"), as_u32(new Cast(expr, { reinterpret: true, silent: false, type: Type.u64() }))], + ]); + } +} diff --git a/packages/romdev-m2c/src/arch_sh.js b/packages/romdev-m2c/src/arch_sh.js new file mode 100644 index 00000000..228bfde2 --- /dev/null +++ b/packages/romdev-m2c/src/arch_sh.js @@ -0,0 +1,975 @@ +// Port of m2c/arch_sh.py +/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */ +import { DecompFailure } from "./error.js"; +import { Target } from "./options.js"; +import { AsmSymbolicData } from "./asm_file.js"; +import { AsmAddressMode, AsmGlobalSymbol, AsmInstruction, AsmLiteral, BinOp, JumpTarget, Register, Writeback, get_jump_target } from "./asm_instruction.js"; +import { AsmPattern, Replacement, SimpleAsmPattern, make_pattern } from "./asm_pattern.js"; +import { get_literal_pool_symbol, get_literal_pool_symbolic_data } from "./flow_graph.js"; +import { Instruction, InstructionMeta, StackLocation } from "./instruction.js"; +import { IrPattern } from "./ir_pattern.js"; +import { Abi, AbiArgSlot, Arch, InstrArgs, ArgLoc, BinaryOp, CarryBit, Cast, ErrorExpr, ExprStmt, Literal, UnaryOp, as_s16, as_type, as_u16, as_u32, early_unwrap } from "./translate.js"; +import { + condition_from_expr, + fn_op, + fold_divmod, + fold_mul_chains, + fold_shift_right, + handle_add, + handle_add_real, + handle_addi, + handle_bitinv, + handle_load, + handle_loadx, + handle_or, + handle_sub, + handle_xor, + make_store, + make_storex, + void_fn_op, +} from "./evaluate.js"; +import { Type } from "./types.js"; +import { floordiv, format, has, int_, pyassert, pyeq } from "./py.js"; + +/** dataclasses.replace(instr_args, raw_args=...) */ +function with_raw_args(a, raw_args) { + return new InstrArgs(a.instruction_ref, raw_args, a.regs, a.stack_info); +} + +const MOV_TYPES = { + "mov.b": () => Type.s8(), + "mov.w": () => Type.s16(), + "mov.l": () => Type.reg32({ likely_float: false }), +}; +const MOV_STRIDES = { "mov.b": 1, "mov.w": 2, "mov.l": 4 }; + +function mov_type(mnemonic) { + if (!has(MOV_TYPES, mnemonic)) throw new Error(`KeyError: '${mnemonic}'`); + return MOV_TYPES[mnemonic](); +} +function mov_stride(mnemonic) { + if (!has(MOV_STRIDES, mnemonic)) throw new Error(`KeyError: '${mnemonic}'`); + return MOV_STRIDES[mnemonic]; +} + +const SH_STACK_POINTER_REG = new Register("r15"); + +export class FarJumpPattern extends AsmPattern { + pattern = make_pattern("mov.l $t,@-$r15", "mov.l _, $t", "jmp @$t", "mov.l @$r15+,$t"); + + match(matcher) { + const m = matcher.try_match(this.pattern); + if (m === null) return null; + const load = m.body[1]; + pyassert(load instanceof Instruction); + const target_name = get_literal_pool_symbol(load.args[0], m.asm_data); + if (target_name === null || !matcher.is_local_label(target_name)) return null; + return new Replacement([new AsmInstruction("bra", [new AsmGlobalSymbol(target_name)]), new AsmInstruction("nop", [])], m.body.length); + } +} + +export class JumpTablePattern extends AsmPattern { + pattern1 = make_pattern("mova _, $b", "mov.w @($b,$i),$i", "add $i, $b", "jmp @$b", "nop"); + + pattern2 = make_pattern("mova _, $b", "mov.w @($b,$i),$i", "add $i, $b", "bra .dispatch", "nop", "nop?", ".dispatch:", "jmp @$b", "nop"); + + match(matcher) { + for (const pattern of [this.pattern1, this.pattern2]) { + const m = matcher.try_match(pattern); + if (!m) continue; + + const mova = m.body[0]; + pyassert(mova instanceof Instruction); + pyassert(mova.args[0] instanceof AsmGlobalSymbol); + + const table_name = mova.args[0].symbol_name; + const table = m.asm_data.values.get(table_name) ?? null; + if (table === null) return null; + const targets = []; + for (const entry of table.data) { + if ( + !(entry instanceof AsmSymbolicData) || + !(entry.data instanceof BinOp) || + entry.data.op !== "-" || + !(entry.data.lhs instanceof AsmGlobalSymbol) || + entry.data.rhs !== new AsmGlobalSymbol(table_name) + ) { + return null; + } + targets.push(entry.data.lhs); + } + if (!targets.length) return null; + const jump = new AsmInstruction("tablejmp.doubled.fictive", [m.regs.get("i"), ...targets]); + return new Replacement([jump], m.body.length); + } + return null; + } +} + +export class BrafJumpTablePattern extends SimpleAsmPattern { + pattern = make_pattern("mova _, $b", "mov.w @($b,$i),$b", "braf $b", "nop", ".base:"); + + replace(m) { + const mova = m.body[0]; + pyassert(mova instanceof Instruction); + if (!(mova.args[0] instanceof AsmGlobalSymbol)) return null; + const table = m.asm_data.values.get(mova.args[0].symbol_name) ?? null; + if (table === null) return null; + const base = m.labels.get(".base"); + const targets = []; + for (const entry of table.data) { + if ( + !(entry instanceof AsmSymbolicData) || + !(entry.data instanceof BinOp) || + entry.data.op !== "-" || + !(entry.data.lhs instanceof AsmGlobalSymbol) || + !(entry.data.rhs instanceof AsmGlobalSymbol) || + !base.names.includes(entry.data.rhs.symbol_name) + ) { + return null; + } + targets.push(entry.data.lhs); + } + if (!targets.length) return null; + const jump = new AsmInstruction("tablejmp.doubled.fictive", [m.regs.get("i"), ...targets]); + return new Replacement([jump, base], m.body.length); + } +} + +export class BsrfCallPattern extends SimpleAsmPattern { + pattern = make_pattern("mov.l _,$r", "bsrf $r", "*", ".base:"); + + replace(m) { + const load = m.body[0]; + pyassert(load instanceof Instruction); + const delay = m.wildcard_items[0]; + if (!(delay instanceof Instruction)) return null; + const entry = get_literal_pool_symbolic_data(load.args[0], m.asm_data); + if ( + entry === null || + !(entry.data instanceof BinOp) || + entry.data.op !== "-" || + !(entry.data.lhs instanceof AsmGlobalSymbol) || + !(entry.data.rhs instanceof AsmGlobalSymbol) || + !m.labels.get(".base").names.includes(entry.data.rhs.symbol_name) + ) { + return null; + } + return new Replacement([new AsmInstruction("bsr", [entry.data.lhs]), delay, m.labels.get(".base")], m.body.length); + } +} + +export class NegateTPattern extends SimpleAsmPattern { + pattern = make_pattern("rotcl $r", "xor #1, $r", "rotcr $r"); + + replace(m) { + return new Replacement([new AsmInstruction("negatet.fictive", [])], m.body.length, []); + } +} + +export class Shar31Pattern extends SimpleAsmPattern { + pattern = make_pattern("shll $r", "subc $r, $r"); + + replace(m) { + const reg = m.regs.get("r"); + const temp = Register.fictive(reg.register_name); + return new Replacement( + [new AsmInstruction("move.fictive", [temp, reg]), new AsmInstruction("shll", [temp]), new AsmInstruction("shar.fictive", [reg, reg, new AsmLiteral(31)])], + m.body.length, + ); + } +} + +/** Replace writebacks in mov address modes by separate add instructions. */ +export class Sh2AddrModeWritebackPattern extends AsmPattern { + match(matcher) { + const instr = matcher.input[matcher.index]; + if (!(instr instanceof Instruction) || !instr.args.length) return null; + if (!["mov.b", "mov.w", "mov.l"].includes(instr.mnemonic)) return null; + + let addr, addr_arg; + if (instr.args[0] instanceof AsmAddressMode) { + addr = instr.args[0]; + addr_arg = 0; + } else if (instr.args[1] instanceof AsmAddressMode) { + addr = instr.args[1]; + addr_arg = 1; + } else return null; + + if (addr.writeback === null) return null; + if (addr.base === SH_STACK_POINTER_REG) return null; + + if (addr.base === instr.args[0] || addr.base === instr.args[1]) { + throw new DecompFailure("Writeback with base register also used as load/store value, " + `for instruction: ${instr}`); + } + + pyassert(addr.addend === new AsmLiteral(0)); + + const new_args = [...instr.args]; + new_args[addr_arg] = new AsmAddressMode(addr.base, addr.addend, null); + const stride = mov_stride(instr.mnemonic); + if (addr.writeback === Writeback.PRE) { + return new Replacement([new AsmInstruction("add", [new AsmLiteral(-stride), addr.base]), new AsmInstruction(instr.mnemonic, new_args)], 1); + } + return new Replacement([new AsmInstruction(instr.mnemonic, new_args), new AsmInstruction("add", [new AsmLiteral(stride), addr.base])], 1); + } +} + +export class Shar16Pattern extends IrPattern { + replacement = "shar16.fictive $i, $o"; + parts = ["swap.w $i, $t", "exts.w $t, $o"]; +} + +const R = (names) => names.map((r) => new Register(r)); + +const SH2_ARGUMENT_REGS = R(["r4", "r5", "r6", "r7"]); +const SH2_SIMPLE_TEMP_REGS = R(["r0", "r1", "r2", "r3"]); +const SH2_TEMP_REGS = [...SH2_ARGUMENT_REGS, ...SH2_SIMPLE_TEMP_REGS, new Register("condition_bit")]; +const SH2_SAVED_REGS = R(["r8", "r9", "r10", "r11", "r12", "r13", "r14", "pr"]); +const SH2_ALL_REGS = [...SH2_SAVED_REGS, ...SH2_TEMP_REGS, SH_STACK_POINTER_REG, ...R(["mach", "macl", "sr", "gbr", "vbr"])]; + +const SH2_INSTRS_COMPARE = { + "cmp/pl": (a) => BinaryOp.scmp(a.reg(0), ">", new Literal(0)), + "cmp/pz": (a) => BinaryOp.scmp(a.reg(0), ">=", new Literal(0)), + "cmp/eq": (a) => BinaryOp.icmp(a.reg(1), "==", a.reg_or_s8_imm(0)), + "cmp/ge": (a) => BinaryOp.scmp(a.reg(1), ">=", a.reg(0)), + "cmp/gt": (a) => BinaryOp.scmp(a.reg(1), ">", a.reg(0)), + "cmp/hi": (a) => BinaryOp.ucmp(a.reg(1), ">", a.reg(0)), + "cmp/hs": (a) => BinaryOp.ucmp(a.reg(1), ">=", a.reg(0)), + "cmp/str": (a) => fn_op("M2C_CMP_STR", [a.reg(1), a.reg(0)], Type.boolean()), + tst: (a) => + a.reg_ref(1) === a.raw_arg(0) + ? BinaryOp.icmp(a.reg(1), "==", new Literal(0)) + : BinaryOp.icmp(BinaryOp.intptr(a.reg(1), "&", a.reg_or_s8_imm(0)), "==", new Literal(0)), +}; + +const SH2_INSTRS_READ_MODIFY_WRITE = { + // sh2 format is src, dst + // add handler is dest, left, right + add: (a) => + a.raw_arg(0) instanceof Register + ? handle_add(with_raw_args(a, [a.raw_arg(1), a.raw_arg(1), a.raw_arg(0)])) + : handle_addi(a.reg_ref(1), a.reg_ref(1), a.reg(1), a.s8_imm(0), a), + sub: (a) => handle_sub(a.reg(1), a.reg(0)), + and: (a) => BinaryOp.int(a.reg(1), "&", a.reg_or_imm(0)), + or: (a) => handle_or(a.reg(1), a.reg_or_imm(0)), + xor: (a) => handle_xor(a.reg(1), a.reg_or_imm(0)), + xtrct: (a) => BinaryOp.uint(BinaryOp.ushift(a.reg(1), ">>", new Literal(16)), "|", BinaryOp.int(a.reg(0), "<<", new Literal(16))), +}; + +const SH2_INSTRS_SOURCE_DEST = { + not: (a) => handle_bitinv(a.reg(0)), + neg: (a) => UnaryOp.sint("-", a.reg(0)), + "exts.b": (a) => as_type(a.reg(0), Type.s8(), false), + "exts.w": (a) => as_type(a.reg(0), Type.s16(), false), + "extu.b": (a) => as_type(a.reg(0), Type.u8(), false), + "extu.w": (a) => as_type(a.reg(0), Type.u16(), false), + "swap.w": (a) => BinaryOp.int(BinaryOp.ushift(a.reg(0), "<<", new Literal(16)), "|", BinaryOp.ushift(a.reg(0), ">>", new Literal(16))), + "swap.b": (a) => + BinaryOp.uint( + BinaryOp.uint(BinaryOp.int(a.reg(0), "&", new Literal(0xffff0000)), "|", BinaryOp.int(BinaryOp.int(a.reg(0), "&", new Literal(0xff)), "<<", new Literal(8))), + "|", + BinaryOp.int(BinaryOp.ushift(a.reg(0), ">>", new Literal(8)), "&", new Literal(0xff)), + ), + "shar16.fictive": (a) => fold_shift_right(a.reg(0), 16, { signed: true }), +}; + +const SH2_INSTRS_INTRINSICS = { + "shar.fictive": (a) => fold_shift_right(a.reg(1), a.imm_value(2), { signed: true }), + "vshar.fictive": (a) => BinaryOp.sshift(a.reg(1), ">>", a.reg(2)), + "vshlr.fictive": (a) => BinaryOp.ushift(a.reg(1), ">>", a.reg(2)), + "vshl.fictive": (a) => BinaryOp.int(a.reg(1), "<<", a.reg(2)), + "divs.fictive": (a) => BinaryOp.sint(a.reg(1), "/", a.reg(2)), + "divu.fictive": (a) => BinaryOp.uint(a.reg(1), "/", a.reg(2)), +}; + +const SH2_INSTRS_MULTIPLY = { + "mul.l": (a) => BinaryOp.int(a.reg(1), "*", a.reg(0)), + muls: (a) => BinaryOp.sint(as_s16(a.reg(1)), "*", as_s16(a.reg(0))), + mulu: (a) => BinaryOp.uint(as_u16(a.reg(1)), "*", as_u16(a.reg(0))), +}; + +const SH2_INSTRS_SHIFT = { + shll: (a) => fold_mul_chains(BinaryOp.int(a.reg(0), "<<", new Literal(1)), { allow_sll_chains: true }), + shlr: (a) => fold_shift_right(a.reg(0), 1, { signed: false }), + shar: (a) => fold_shift_right(a.reg(0), 1, { signed: true }), + shll2: (a) => fold_mul_chains(BinaryOp.int(a.reg(0), "<<", new Literal(2)), { allow_sll_chains: true }), + shlr2: (a) => fold_shift_right(a.reg(0), 2, { signed: false }), + shll8: (a) => fold_mul_chains(BinaryOp.int(a.reg(0), "<<", new Literal(8)), { allow_sll_chains: true }), + shlr8: (a) => fold_shift_right(a.reg(0), 8, { signed: false }), + shll16: (a) => fold_mul_chains(BinaryOp.int(a.reg(0), "<<", new Literal(16)), { allow_sll_chains: true }), + shlr16: (a) => fold_shift_right(a.reg(0), 16, { signed: false }), + rotl: (a) => BinaryOp.uint(BinaryOp.ushift(a.reg(0), "<<", new Literal(1)), "|", BinaryOp.ushift(a.reg(0), ">>", new Literal(31))), + rotr: (a) => BinaryOp.uint(BinaryOp.ushift(a.reg(0), ">>", new Literal(1)), "|", BinaryOp.ushift(a.reg(0), "<<", new Literal(31))), +}; + +const SH2_ATTRS = { + arch: Target.ArchEnum.SH, + re_comment: String.raw`!.*`, + supports_dollar_regs: false, + supports_at_addressing: true, + asm_word_size: 2, + has_delay_slots: true, + home_space_size: 0, + stack_pointer_reg: SH_STACK_POINTER_REG, + frame_pointer_regs: [new Register("r14")], + return_address_reg: new Register("pr"), + base_return_regs: [[new Register("r0"), false]], + all_return_regs: [new Register("r0"), new Register("r1")], + argument_regs: SH2_ARGUMENT_REGS, + simple_temp_regs: SH2_SIMPLE_TEMP_REGS, + temp_regs: SH2_TEMP_REGS, + saved_regs: SH2_SAVED_REGS, + all_regs: SH2_ALL_REGS, + aliased_regs: {}, + instrs_compare: SH2_INSTRS_COMPARE, + instrs_read_modify_write: SH2_INSTRS_READ_MODIFY_WRITE, + instrs_source_dest: SH2_INSTRS_SOURCE_DEST, + instrs_intrinsics: SH2_INSTRS_INTRINSICS, + instrs_multiply: SH2_INSTRS_MULTIPLY, + instrs_shift: SH2_INSTRS_SHIFT, +}; + +const SH2_ASM_PATTERNS = () => [ + new FarJumpPattern(), + new JumpTablePattern(), + new BrafJumpTablePattern(), + new BsrfCallPattern(), + new Sh2AddrModeWritebackPattern(), + new NegateTPattern(), + new Shar31Pattern(), +]; + +export class Sh2Arch extends Arch { + constructor() { + super(); + // Python class attributes (set after super() so base-class constructors + // cannot shadow them with instance fields). + Object.assign(this, SH2_ATTRS); + this.asm_patterns = SH2_ASM_PATTERNS(); + this.ir_patterns = [new Shar16Pattern()]; + } + + static mov_type(mnemonic) { + return mov_type(mnemonic); + } + static mov_stride(mnemonic) { + return mov_stride(mnemonic); + } + mov_type(mnemonic) { + return mov_type(mnemonic); + } + mov_stride(mnemonic) { + return mov_stride(mnemonic); + } + + c_symbol_name(asm_name) { + if (asm_name.length >= 2 && asm_name[0] === "_" && (/^\p{L}$/u.test(asm_name[1]) || asm_name[1] === "_")) return asm_name.slice(1); + return asm_name; + } + + missing_return() { + const meta = InstructionMeta.missing(); + return [this.parse("rts", [], meta), this.parse("nop", [], meta)]; + } + + normalize_instruction(instr, asm_state) { + const map = { "muls.w": "muls", "mulu.w": "mulu" }; + const mnemonic = has(map, instr.mnemonic) ? map[instr.mnemonic] : instr.mnemonic; + return new AsmInstruction(mnemonic, instr.args); + } + + parse(mnemonic, args, meta) { + const cls = this; + let inputs = []; + let clobbers = []; + let outputs = []; + let is_return = false; + let is_load = false; + let is_store = false; + let has_delay_slot = false; + let is_conditional = false; + let jump_target = null; + let function_target = null; + let eval_fn = null; + + if (mnemonic === "rts") { + pyassert(args.length === 0); + inputs = [new Register("pr")]; + is_return = true; + has_delay_slot = true; + } else if (mnemonic === "nop") { + pyassert(args.length === 0); + } else if (["mov", "lds", "sts"].includes(mnemonic)) { + pyassert(args.length === 2 && args[1] instanceof Register); + outputs = [args[1]]; + if (args[0] instanceof Register) { + inputs = [args[0]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(1), a.reg(0)); + } else { + pyassert(args[0] instanceof AsmLiteral); + eval_fn = (s, a) => s.set_reg(a.reg_ref(1), a.s8_imm(0)); + } + } else if (mnemonic === "move.fictive") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + inputs = [args[1]]; + outputs = [args[0]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(0), a.reg(1)); + } else if (mnemonic === "mova") { + pyassert(args.length === 2 && args[0] instanceof AsmGlobalSymbol && args[1] === new Register("r0")); + outputs = [new Register("r0")]; + eval_fn = (s, a) => s.set_reg(new Register("r0"), a.full_imm(0)); + } else if (["mov.b", "mov.l", "mov.w"].includes(mnemonic)) { + pyassert(args.length === 2); + if (args[0] instanceof Register) { + pyassert(args[1] instanceof AsmAddressMode); + inputs = [args[0], args[1].base]; + if (args[1].addend instanceof Register) inputs.push(args[1].addend); + is_store = true; + if (args[1].writeback === null) { + eval_fn = (s, a) => { + const store_type = cls.mov_type(mnemonic); + const address = a.raw_arg(1); + pyassert(address instanceof AsmAddressMode); + let store; + if (address.addend instanceof Register) { + store = make_storex(with_raw_args(a, [a.raw_arg(0), address.base, address.addend]), store_type); + } else { + store = make_store(a, store_type); + } + if (store !== null) s.store_memory(store, a.reg_ref(0)); + }; + } else if (args[1].base === cls.stack_pointer_reg) { + pyassert(args[1].writeback === Writeback.PRE); + eval_fn = (s, a) => { + const source_raw = a.regs.get_raw(a.reg_ref(0)); + if (source_raw === null || !s.stack_info.should_save(source_raw, null)) s.push_subroutine_arg(a.reg(0)); + }; + } else { + // writeback on other registers is rewritten into an explicit + // add by Sh2AddrModeWritebackPattern, so no eval_fn is needed. + } + } else { + pyassert(args[1] instanceof Register); + if (args[0] instanceof AsmAddressMode) { + inputs = [args[0].base]; + if (args[0].addend instanceof Register) inputs.push(args[0].addend); + } + outputs = [args[1]]; + is_load = true; + const load_type = cls.mov_type(mnemonic); + if (args[0] instanceof AsmAddressMode && args[0].addend instanceof Register) { + const indexed_base = args[0].base; + const indexed_addend = args[0].addend; + eval_fn = (s, a) => s.set_reg(a.reg_ref(1), handle_loadx(with_raw_args(a, [a.raw_arg(1), indexed_base, indexed_addend]), load_type)); + } else { + eval_fn = (s, a) => s.set_reg(a.reg_ref(1), handle_load(with_raw_args(a, [a.raw_arg(1), a.raw_arg(0)]), load_type)); + } + } + } else if (mnemonic === "sts.l" || mnemonic === "stc.l") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof AsmAddressMode && args[1].writeback === Writeback.PRE); + const mem = args[1]; + inputs = [args[0], mem.base]; + is_store = true; + eval_fn = (s, a) => { + pyassert(args[0] === new Register("pr")); + pyassert(mem.base === cls.stack_pointer_reg); + }; + } else if (mnemonic === "lds.l" || mnemonic === "ldc.l") { + pyassert(args.length === 2 && args[0] instanceof AsmAddressMode && args[0].writeback === Writeback.POST && args[1] instanceof Register); + const mem = args[0]; + inputs = [mem.base]; + outputs = [args[1]]; + is_load = true; + eval_fn = (s, a) => { + pyassert(args[1] === new Register("pr")); + pyassert(mem.base === cls.stack_pointer_reg); + }; + } else if (mnemonic === "addc") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + const t_reg = new Register("condition_bit"); + inputs = [args[0], args[1], t_reg]; + outputs = [args[1], t_reg]; + eval_fn = (s, a) => { + let result = handle_add_real(a.reg(1), a.reg(0), a); + result = handle_add_real(result, a.regs.get(t_reg), a); + result = s.set_reg(a.reg_ref(1), result); + s.set_reg(t_reg, new CarryBit(result)); + }; + } else if (mnemonic === "subc") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + const t_reg = new Register("condition_bit"); + inputs = [args[0], args[1], t_reg]; + outputs = [args[1], t_reg]; + eval_fn = (s, a) => { + const lhs = a.reg(1); + const rhs = a.reg(0); + const carry = a.regs.get(t_reg); + const result = handle_sub(handle_sub(lhs, rhs), carry); + let borrow; + if (pyeq(carry, new Literal(0))) borrow = BinaryOp.ucmp(lhs, "<", rhs); + else if (pyeq(carry, new Literal(1))) borrow = BinaryOp.ucmp(lhs, "<=", rhs); + else { + borrow = new BinaryOp({ + left: BinaryOp.ucmp(lhs, "<", rhs), + op: "||", + right: new BinaryOp({ left: BinaryOp.icmp(lhs, "==", rhs), op: "&&", right: condition_from_expr(carry), type: Type.boolean() }), + type: Type.boolean(), + }); + } + s.set_reg(a.reg_ref(1), result); + s.set_reg(t_reg, borrow); + }; + } else if (mnemonic === "negc") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + const t_reg = new Register("condition_bit"); + inputs = [args[0], t_reg]; + outputs = [args[1], t_reg]; + eval_fn = (s, a) => { + const value = a.reg(0); + const carry = a.regs.get(t_reg); + const result = handle_sub(UnaryOp.int("-", value), carry); + let borrow; + if (pyeq(carry, new Literal(0))) borrow = BinaryOp.icmp(value, "!=", new Literal(0)); + else if (pyeq(carry, new Literal(1))) borrow = new Literal(1); + else { + borrow = new BinaryOp({ left: BinaryOp.icmp(value, "!=", new Literal(0)), op: "||", right: condition_from_expr(carry), type: Type.boolean() }); + } + s.set_reg(a.reg_ref(1), result); + s.set_reg(t_reg, borrow); + }; + } else if (has(cls.instrs_read_modify_write, mnemonic)) { + pyassert(args.length === 2 && args[1] instanceof Register); + inputs = [args[1]]; + if (args[0] instanceof Register) inputs.unshift(args[0]); + outputs = [args[1]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(1), cls.instrs_read_modify_write[mnemonic](a)); + } else if (has(cls.instrs_source_dest, mnemonic)) { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + inputs = [args[0]]; + outputs = [args[1]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(1), cls.instrs_source_dest[mnemonic](a)); + } else if (has(cls.instrs_intrinsics, mnemonic)) { + pyassert(args[0] instanceof Register); + inputs = args.slice(1).filter((arg) => arg instanceof Register); + outputs = [args[0]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(0), cls.instrs_intrinsics[mnemonic](a)); + } else if (has(cls.instrs_multiply, mnemonic)) { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + inputs = [args[0], args[1]]; + outputs = [new Register("macl")]; + eval_fn = (s, a) => s.set_reg(new Register("macl"), cls.instrs_multiply[mnemonic](a)); + } else if (mnemonic === "dmuls.l" || mnemonic === "dmulu.l") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + inputs = [args[0], args[1]]; + outputs = [new Register("mach"), new Register("macl")]; + const high_op = mnemonic === "dmuls.l" ? "MULT_HI" : "MULTU_HI"; + eval_fn = (s, a) => { + s.set_reg(new Register("mach"), fold_divmod(BinaryOp.int(a.reg(1), high_op, a.reg(0)))); + s.set_reg(new Register("macl"), BinaryOp.int(a.reg(1), "*", a.reg(0))); + }; + } else if (mnemonic === "clrmac") { + pyassert(!args.length); + outputs = [new Register("macl"), new Register("mach")]; + eval_fn = (s, a) => { + s.set_reg(new Register("macl"), new Literal(0)); + s.set_reg(new Register("mach"), new Literal(0)); + }; + } else if (mnemonic === "rotcl" || mnemonic === "rotcr") { + pyassert(args.length === 1 && args[0] instanceof Register); + const t_reg = new Register("condition_bit"); + inputs = [args[0], t_reg]; + outputs = [args[0], t_reg]; + eval_fn = (s, a) => { + const original = a.reg(0); + const carry_in = a.regs.get(t_reg); + let shifted, incoming_bit, carry_out; + if (mnemonic === "rotcl") { + shifted = BinaryOp.ushift(original, "<<", new Literal(1)); + incoming_bit = carry_in; + carry_out = new CarryBit(shifted); + } else { + shifted = BinaryOp.ushift(original, ">>", new Literal(1)); + incoming_bit = BinaryOp.uint(carry_in, "<<", new Literal(31)); + carry_out = BinaryOp.int(original, "&", new Literal(1)); + } + const result = pyeq(carry_in, new Literal(0)) ? shifted : BinaryOp.int(shifted, "|", incoming_bit); + s.set_reg(a.reg_ref(0), result); + s.set_reg(t_reg, carry_out); + }; + } else if (has(cls.instrs_shift, mnemonic)) { + pyassert(args.length === 1 && args[0] instanceof Register); + inputs = [args[0]]; + outputs = [args[0]]; + const sets_t = ["shll", "shlr", "shar", "rotl", "rotr"].includes(mnemonic); + if (sets_t) outputs.push(new Register("condition_bit")); + eval_fn = (s, a) => { + const original = a.reg(0); + s.set_reg(a.reg_ref(0), cls.instrs_shift[mnemonic](a)); + if (sets_t) { + let carry; + if (["shlr", "shar", "rotr"].includes(mnemonic)) { + carry = BinaryOp.intptr(original, "&", new Literal(1)); + } else { + const as_u32_ = as_type(original, Type.u32(), true, { unify: false }); + carry = BinaryOp.int(as_u32_, ">>", new Literal(31)); + } + s.set_reg(new Register("condition_bit"), carry); + } + }; + } else if (mnemonic === "dt") { + pyassert(args.length === 1 && args[0] instanceof Register); + inputs = [args[0]]; + outputs = [args[0], new Register("condition_bit")]; + eval_fn = (s, a) => { + const value = s.set_reg(a.reg_ref(0), BinaryOp.intptr(a.reg(0), "-", new Literal(1))); + s.set_reg(new Register("condition_bit"), BinaryOp.icmp(value, "==", new Literal(0))); + }; + } else if (has(cls.instrs_compare, mnemonic)) { + inputs = args.filter((arg) => arg instanceof Register); + outputs = [new Register("condition_bit")]; + eval_fn = (s, a) => s.set_reg(new Register("condition_bit"), cls.instrs_compare[mnemonic](a)); + } else if (["bf", "bf.s", "bt", "bt.s"].includes(mnemonic)) { + pyassert(args.length === 1); + inputs = [new Register("condition_bit")]; + jump_target = get_jump_target(args[0]); + is_conditional = true; + has_delay_slot = mnemonic.endsWith(".s"); + eval_fn = (s, a) => { + let condition = condition_from_expr(a.regs.get(new Register("condition_bit"))); + if (mnemonic.startsWith("bf")) condition = condition.negated(); + s.set_branch_condition(condition); + }; + } else if (mnemonic === "bsr") { + pyassert(args.length === 1); + inputs = [...cls.argument_regs]; + outputs = [...cls.all_return_regs]; + clobbers = [...cls.temp_regs]; + function_target = args[0]; + has_delay_slot = true; + eval_fn = (s, a) => s.make_function_call(a.sym_imm(0), outputs); + } else if (mnemonic === "bra") { + pyassert(args.length === 1); + jump_target = get_jump_target(args[0]); + has_delay_slot = true; + } else if (mnemonic === "jmp") { + pyassert(args.length === 1 && args[0] instanceof AsmAddressMode && args[0].addend === new AsmLiteral(0)); + inputs = [args[0].base]; + jump_target = args[0].base; + is_conditional = true; + has_delay_slot = true; + eval_fn = (s, a) => { + const address = a.raw_arg(0); + pyassert(address instanceof AsmAddressMode); + s.set_switch_expr(a.regs.get(address.base)); + }; + } else if (mnemonic === "jsr") { + pyassert(args.length === 1 && args[0] instanceof AsmAddressMode && args[0].addend === new AsmLiteral(0)); + const target_reg = args[0].base; + inputs = [...cls.argument_regs, target_reg]; + outputs = [...cls.all_return_regs]; + clobbers = [...cls.temp_regs]; + function_target = target_reg; + has_delay_slot = true; + eval_fn = (s, a) => s.make_function_call(a.regs.get(target_reg), outputs); + } else if (mnemonic === "tablejmp.doubled.fictive") { + pyassert(args.length >= 2 && args[0] instanceof Register); + const targets = []; + for (const arg of args.slice(1)) { + pyassert(arg instanceof AsmGlobalSymbol); + targets.push(new JumpTarget(arg.symbol_name)); + } + inputs = [args[0]]; + jump_target = targets; + is_conditional = true; + eval_fn = (s, a) => { + let index = a.reg(0); + const unwrapped = early_unwrap(index); + if (unwrapped instanceof BinaryOp && unwrapped.op === "*" && pyeq(early_unwrap(unwrapped.right), new Literal(2))) { + index = unwrapped.left; + } else { + index = BinaryOp.ushift(index, ">>", new Literal(1)); + } + s.set_switch_expr(index, true); + }; + } else if (mnemonic === "movt") { + pyassert(args.length === 1 && args[0] instanceof Register); + inputs = [new Register("condition_bit")]; + outputs = [args[0]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(0), a.regs.get(new Register("condition_bit"))); + } else if (mnemonic === "clrt" || mnemonic === "sett") { + pyassert(!args.length); + outputs = [new Register("condition_bit")]; + const val = mnemonic === "sett" ? 1 : 0; + eval_fn = (s, a) => s.set_reg(new Register("condition_bit"), new Literal(val)); + } else if (mnemonic === "negatet.fictive") { + pyassert(!args.length); + inputs = outputs = [new Register("condition_bit")]; + eval_fn = (s, a) => { + const condition = condition_from_expr(a.regs.get(new Register("condition_bit"))); + s.set_reg(new Register("condition_bit"), condition.negated()); + }; + } else if (mnemonic === "tas.b") { + pyassert(args.length === 1 && args[0] instanceof AsmAddressMode && args[0].addend === new AsmLiteral(0)); + const base = args[0].base; + const t_reg = new Register("condition_bit"); + inputs = [base]; + outputs = [t_reg]; + is_load = is_store = true; + eval_fn = (s, a) => { + const result = fn_op("M2C_TAS_B", [a.regs.get(base)], Type.intish()); + s.set_reg(t_reg, result); + }; + } else if (mnemonic === "stc") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + outputs = [args[1]]; + eval_fn = (s, a) => { + const fn_name = "M2C_LOAD_" + a.reg_ref(0).register_name.toUpperCase(); + s.set_reg(a.reg_ref(1), fn_op(fn_name, [], Type.u32())); + }; + } else if (mnemonic === "ldc") { + pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register); + inputs = [args[0]]; + eval_fn = (s, a) => { + const fn_name = "M2C_STORE_" + a.reg_ref(1).register_name.toUpperCase(); + s.write_statement(void_fn_op(fn_name, [a.reg(0)])); + }; + } else { + const instr_str = String(new AsmInstruction(mnemonic, args)); + eval_fn = (s, a) => { + const error = new ErrorExpr(`unknown instruction: ${instr_str}`); + s.write_statement(new ExprStmt(error)); + }; + } + + return new Instruction({ + mnemonic, + args, + meta, + inputs, + clobbers, + outputs, + eval_fn, + jump_target, + function_target, + is_conditional, + is_return, + is_load, + is_store, + has_delay_slot, + }); + } + + process_flowgraph(asm_data, flow_graph) { + // Find intrinsic functions and replace them by fake instructions (see upstream). + const seen = new Set(); + + const make_intrinsic_instruction = (fn_name) => { + const table = { + ___sdivsi3: "divs.fictive", + ___udivsi3: "divu.fictive", + ___ashrsi3: "vshar.fictive", + ___ashlsi3: "vshl.fictive", + ___lshrsi3: "vshlr.fictive", + }; + const mn = has(table, fn_name) ? table[fn_name] : null; + if (mn !== null) return new AsmInstruction(mn, [new Register("r0"), new Register("r4"), new Register("r5")]); + if (fn_name.startsWith("___ashiftrt_r4_")) { + const shift = int_(fn_name.slice("___ashiftrt_r4_".length)); + return new AsmInstruction("shar.fictive", [new Register("r4"), new Register("r4"), new AsmLiteral(shift)]); + } + return null; + }; + + const loc_from_mov_operand = (arg, stack_regs) => { + if (arg instanceof Register) return arg; + if (arg instanceof AsmAddressMode && stack_regs.has(arg.base) && arg.writeback === null) return StackLocation.from_offset(arg.addend); + return null; + }; + + const rec = (node, reg_sym_values, stack_regs) => { + if (seen.has(node)) return; + seen.add(node); + for (const ref of node.block.instruction_refs) { + const ins = ref.instruction; + if (ins.mnemonic === "mov" && ins.args[0] === this.stack_pointer_reg) { + pyassert(ins.args[1] instanceof Register); + stack_regs = new Set([...stack_regs, ins.args[1]]); + continue; + } + if (ins.mnemonic === "mov.l") { + const src = ins.args[0]; + const dst = ins.args[1]; + if (dst instanceof Register) { + const target = get_literal_pool_symbol(src, asm_data); + if (target !== null) { + const intrinsic = make_intrinsic_instruction(target); + if (intrinsic !== null) { + reg_sym_values.set(dst, intrinsic); + ref.instruction = ins.replace({ in_pattern: true }); + continue; + } + } + } + const src_loc = loc_from_mov_operand(src, stack_regs); + const dst_loc = loc_from_mov_operand(dst, stack_regs); + if (src_loc !== null && dst_loc !== null) { + if (reg_sym_values.has(src_loc)) { + reg_sym_values.set(dst_loc, reg_sym_values.get(src_loc)); + ref.instruction = ins.replace({ in_pattern: true }); + } else if (reg_sym_values.has(dst_loc)) { + reg_sym_values.delete(dst_loc); + } + continue; + } + } + if (ins.mnemonic === "jsr") { + pyassert(ins.function_target instanceof Register); + const new_ins = reg_sym_values.get(ins.function_target) ?? null; + if (new_ins !== null) { + ref.replace_instruction(new_ins, this); + ref.instruction.clobbers.length = 0; + continue; + } + } + for (const loc of [...ins.clobbers, ...ins.outputs]) { + if (loc instanceof Register) { + if (reg_sym_values.has(loc)) reg_sym_values.delete(loc); + if (stack_regs.has(loc) && loc !== this.stack_pointer_reg) { + stack_regs = new Set([...stack_regs].filter((r) => r !== loc)); + } + } + } + } + for (const child of node.children()) rec(child, new Map(reg_sym_values), stack_regs); + }; + + rec(flow_graph.entry_node(), new Map(), new Set([this.stack_pointer_reg])); + } + + arg_name(loc) { + if (loc.offset !== null) return `arg${floordiv(loc.offset, 4) + 4}`; + pyassert(loc.reg !== null); + const reg_num = int_(loc.reg.register_name.slice(1)); + return `arg${reg_num - 4}`; + } + + function_abi(fn_sig, likely_regs, { for_call }) { + void for_call; + const known_slots = []; + let candidate_slots = []; + const possible_slots = []; + + if (fn_sig.params_known) { + if (fn_sig.return_type.is_struct() && fn_sig.return_type.get_parameter_size_align_bytes()[0] > 8) { + known_slots.push(new AbiArgSlot(new ArgLoc(null, -1, new Register("r2")), Type.ptr(fn_sig.return_type), { name: "__return__", comment: "return" })); + } + + let reg_num = 0; + for (const param of fn_sig.params) { + const param_type = param.type.decay(); + const [size] = param_type.get_parameter_size_align_bytes(); + const size_regs = floordiv(size + 3, 4); + const name = param.name; + for (let i = reg_num; i < reg_num + size_regs; i++) { + const unk_offset = 4 * (i - reg_num); + const reg = i < 4 ? new Register(`r${i + 4}`) : null; + const stack_loc = reg !== null ? null : (i - 4) * 4; + let name2, sub_type, comment; + if (size_regs > 1) { + name2 = name ? `${name}_unk${format(unk_offset, "X")}` : null; + sub_type = Type.any(); + comment = `${param_type}+${format(unk_offset, "#x")}`; + } else { + pyassert(unk_offset === 0); + name2 = name; + sub_type = param_type; + comment = null; + } + known_slots.push(new AbiArgSlot(new ArgLoc(stack_loc, i, reg), sub_type, { name: name2, comment })); + } + reg_num += size_regs; + } + + if (fn_sig.is_variadic) { + for (let i = reg_num; i < 4; i++) candidate_slots.push(new AbiArgSlot(new ArgLoc(null, i, new Register(`r${i + 4}`)), Type.intptr())); + } + } else { + candidate_slots = [0, 1, 2, 3].map((i) => new AbiArgSlot(new ArgLoc(null, i, new Register(`r${i + 4}`)), Type.intptr())); + } + + let highest_likely = -1; + for (let i = 4; i < 8; i++) { + if (!likely_regs.has(new Register(`r${i}`))) break; + if (likely_regs.get(new Register(`r${i}`))) highest_likely = i; + } + + for (const slot of candidate_slots) { + pyassert(slot.loc.reg !== null); + if (int_(slot.loc.reg.register_name.slice(1)) <= highest_likely) possible_slots.push(slot); + } + + return new Abi({ arg_slots: known_slots, possible_slots }); + } + + function_return(expr) { + return new Map([ + [new Register("r0"), new Cast(expr, { reinterpret: true, silent: true, type: Type.intptr() })], + [new Register("r1"), as_u32(new Cast(expr, { reinterpret: true, silent: false, type: Type.u64() }))], + ]); + } +} + +const SH4_FP_ARGUMENT_REGS = [4, 5, 6, 7, 8, 9, 10, 11].map((i) => new Register(`fr${i}`)); +const SH4_FP_TEMP_REGS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((i) => new Register(`fr${i}`)); +const SH4_FP_SAVED_REGS = [12, 13, 14, 15].map((i) => new Register(`fr${i}`)); + +const SH4_ATTRS = { + base_return_regs: [ + [new Register("r0"), false], + [new Register("fr0"), true], + ], + all_return_regs: [new Register("r0"), new Register("r1"), new Register("fr0")], + fp_argument_regs: SH4_FP_ARGUMENT_REGS, + fp_temp_regs: SH4_FP_TEMP_REGS, + fp_saved_regs: SH4_FP_SAVED_REGS, + argument_regs: [...SH2_ARGUMENT_REGS, ...SH4_FP_ARGUMENT_REGS], + temp_regs: [...SH2_TEMP_REGS, ...SH4_FP_TEMP_REGS, new Register("fpul")], + saved_regs: [...SH2_SAVED_REGS, ...SH4_FP_SAVED_REGS], + all_regs: [...SH2_ALL_REGS, ...SH4_FP_TEMP_REGS, ...SH4_FP_SAVED_REGS, new Register("fpul"), new Register("fpscr")], + instrs_load_const: { + fldi0: (a) => new Literal(0x00000000, Type.f32()), + fldi1: (a) => new Literal(0x3f800000, Type.f32()), + }, +}; + +export class Sh4Arch extends Sh2Arch { + constructor() { + super(); + Object.assign(this, SH4_ATTRS); + } + + parse(mnemonic, args, meta) { + const cls = this; + const inputs = []; + const clobbers = []; + let outputs = []; + let eval_fn = null; + + if (has(cls.instrs_load_const, mnemonic)) { + pyassert(args.length === 1 && args[0] instanceof Register); + outputs = [args[0]]; + eval_fn = (s, a) => s.set_reg(a.reg_ref(0), cls.instrs_load_const[mnemonic](a)); + } + + if (eval_fn !== null) return new Instruction({ mnemonic, args, meta, inputs, clobbers, outputs, eval_fn }); + + return super.parse(mnemonic, args, meta); + } + + function_return(expr) { + const ret = Sh2Arch.prototype.function_return.call(this, expr); + ret.set(new Register("fr0"), new Cast(expr, { reinterpret: true, silent: true, type: Type.floatish() })); + return ret; + } +} diff --git a/packages/romdev-m2c/src/asm_file.js b/packages/romdev-m2c/src/asm_file.js new file mode 100644 index 00000000..f4f2509e --- /dev/null +++ b/packages/romdev-m2c/src/asm_file.js @@ -0,0 +1,779 @@ +// Port of m2c/asm_file.py +import fs from "node:fs"; +import path from "node:path"; +import { DecompFailure } from "./error.js"; +import { CodingStyle } from "./options.js"; +import { AsmGlobalSymbol, AsmLiteral, AsmState, RegFormatter, parse_arg, traverse_arg } from "./asm_instruction.js"; +import { Instruction, InstructionMeta, parse_instruction } from "./instruction.js"; +import { AssertionError, DefaultMap, IndexError, ValueError, band, format, int_, intern, isspace, pyassert, pymod, split_ws, str as pystr } from "./py.js"; +import { print } from "./io.js"; + +const RE_COMMA_OR_STRING = /,|"(?:\\.|[^\\"])*"/g; + +export class Label { + // Various pattern matching code assumes that there cannot be consecutive + // labels, and to deal with this we allow for consecutive labels to be + // merged together. As a consequence, we allow a Label to have more than one + // name. When we need a single name to refer to one, we use the first one. + constructor(names) { + this.names = names; + return intern(this, [names]); + } + static new(name) { + return new Label([name]); + } + toString() { + return this.names[0]; + } +} + +export class Function { + constructor({ name, body = [], reg_formatter = new RegFormatter() }) { + this.name = name; + this.body = body; + this.reg_formatter = reg_formatter; + } + new_label(name) { + const label = Label.new(name); + if (this.body.length && this.body[this.body.length - 1] === label) return; + this.body.push(label); + } + new_instruction(instruction) { + this.body.push(instruction); + } + bodyless_copy() { + return new Function({ name: this.name, reg_formatter: this.reg_formatter }); + } + toString() { + const body = this.body.map((item) => (item instanceof Instruction ? String(item) : ` ${item}:`)).join("\n"); + return `glabel ${this.name}\n${body}`; + } +} + +export class AsmSymbolicData { + constructor(data, size) { + this.data = data; + this.size = size; + } + as_symbol_without_addend() { + if (this.data instanceof AsmGlobalSymbol && this.size === 4) return this.data.symbol_name; + return null; + } +} + +export function concatBytes(a, b) { + const out = new Uint8Array(a.length + b.length); + out.set(a, 0); + out.set(b, a.length); + return out; +} + +export class AsmDataEntry { + constructor(sort_order, { data = [], is_string = false, is_readonly = false, is_bss = false, is_text = false, is_jtbl = false, used_as_literal = false } = {}) { + this.sort_order = sort_order; + this.data = data; + this.is_string = is_string; + this.is_readonly = is_readonly; + this.is_bss = is_bss; + this.is_text = is_text; + this.is_jtbl = is_jtbl; + // Mutable state: + this.used_as_literal = used_as_literal; + } + + /** Return the range of possible sizes, if padding were stripped. */ + size_range_bytes() { + let max_size = 0; + for (const x of this.data) { + if (x instanceof AsmSymbolicData) max_size += x.size; + else max_size += x.length; + } + let padding_size = 0; + if (this.data.length && this.data[this.data.length - 1] instanceof Uint8Array) { + pyassert(this.data.length === 1 || this.data[this.data.length - 2] instanceof AsmSymbolicData); + const last = this.data[this.data.length - 1]; + for (let i = last.length - 1; i >= 0; i--) { + if (last[i] !== 0) break; + padding_size += 1; + } + } + padding_size = Math.min(padding_size, 15); + pyassert(padding_size <= max_size); + if (max_size === padding_size && max_size !== 0) return [1, max_size]; + return [max_size - padding_size, max_size]; + } + + data_at_offset(offset, size) { + for (let data of this.data) { + const subsize = data instanceof Uint8Array ? data.length : data.size; + if (offset >= subsize) { + offset -= subsize; + continue; + } + if (data instanceof Uint8Array) { + data = data.slice(offset, offset + size); + if (data.length !== size) return null; + return data; + } else { + if (data.size !== size) return null; + return data; + } + } + return null; + } +} + +export class AsmData { + constructor({ values = new Map(), mentioned_labels = new Set() } = {}) { + this.values = values; + this.mentioned_labels = mentioned_labels; + } + merge_into(other) { + for (const [sym, value] of this.values) other.values.set(sym, value); + for (const label of this.mentioned_labels) other.mentioned_labels.add(label); + } + is_likely_char(c) { + return (0x20 <= c && c < 0x7f) || [0, 7, 8, 9, 10, 13, 27].includes(c); + } + detect_heuristic_strings() { + for (const ent of this.values.values()) { + if ( + ent.is_readonly && + ent.data.length === 1 && + ent.data[0] instanceof Uint8Array && + ent.data[0].length > 1 && + ent.data[0][0] !== 0 && + [...ent.data[0]].every((x) => this.is_likely_char(x)) + ) { + ent.is_string = true; + } + } + } +} + +export class AsmFile { + constructor(filename, reg_formatter) { + this.filename = filename; + this.reg_formatter = reg_formatter; + this.functions = []; + this.asm_data = new AsmData(); + this.current_function = null; + this.current_data = null; + } + new_function(name) { + this.current_function = new Function({ name, reg_formatter: this.reg_formatter }); + this.functions.push(this.current_function); + } + new_instruction(instruction) { + if (this.current_function === null) { + if (instruction.mnemonic === "nop") return; + throw new DecompFailure(`unsupported non-nop instruction outside of function (${instruction})`); + } + this.current_function.new_instruction(instruction); + this.current_data = null; + } + new_label(label_name) { + pyassert(this.current_function !== null); + this.current_function.new_label(label_name); + } + new_data_label(symbol_name, { is_readonly = false, is_bss = false, is_text = false } = {}) { + const sort_order = [this.filename, this.asm_data.values.size]; + this.current_data = new AsmDataEntry(sort_order, { is_readonly, is_bss, is_text }); + this.asm_data.values.set(symbol_name, this.current_data); + } + new_symbolic_data(data, size) { + if (this.current_data !== null) this.current_data.data.push(new AsmSymbolicData(data, size)); + for (const subexpr of traverse_arg(data)) { + if (subexpr instanceof AsmGlobalSymbol) this.asm_data.mentioned_labels.add(subexpr.symbol_name); + } + } + new_data_bytes(data, { is_string }) { + if (this.current_data === null) return; + const d = this.current_data.data; + if (!d.length && is_string) this.current_data.is_string = true; + if (d.length && d[d.length - 1] instanceof Uint8Array) d[d.length - 1] = concatBytes(d[d.length - 1], data); + else d.push(data); + } + toString() { + const functions_str = this.functions.map((f) => String(f)).join("\n\n"); + return `# ${this.filename}\n${functions_str}`; + } +} + +/** + * Split a string of comma-separated arguments, handling quotes. Mirrors + * Python's csv.reader(delimiter=",", doublequote=False, escapechar="\\", + * quotechar='"', skipinitialspace=True) on a single line. + */ +export function split_quotable_arg_list(args) { + if (args === "") return []; + const fields = []; + let field = ""; + let state = "START_FIELD"; + for (const c of args) { + switch (state) { + case "START_FIELD": + if (c === '"') state = "IN_QUOTED_FIELD"; + else if (c === "\\") state = "ESCAPED_CHAR"; + else if (c === " ") { + /* skipinitialspace */ + } else if (c === ",") { + fields.push(field); + field = ""; + } else { + field += c; + state = "IN_FIELD"; + } + break; + case "ESCAPED_CHAR": + field += c; + state = "IN_FIELD"; + break; + case "IN_FIELD": + if (c === "\\") state = "ESCAPED_CHAR"; + else if (c === ",") { + fields.push(field); + field = ""; + state = "START_FIELD"; + } else field += c; + break; + case "IN_QUOTED_FIELD": + if (c === "\\") state = "ESCAPE_IN_QUOTED_FIELD"; + else if (c === '"') state = "IN_FIELD"; + else field += c; + break; + case "ESCAPE_IN_QUOTED_FIELD": + field += c; + state = "IN_QUOTED_FIELD"; + break; + } + } + fields.push(field); + return fields.map((a) => a.trim()); +} + +export function split_arg_list(args) { + if (!args.includes('"')) return args.split(",").map((a) => a.trim()); + const commas = []; + for (const m of args.matchAll(RE_COMMA_OR_STRING)) if (m[0] === ",") commas.push(m.index); + const starts = [-1, ...commas]; + const ends = [...commas, args.length]; + return starts.map((a, i) => args.slice(a + 1, ends[i]).trim()); +} + +const utf8 = new TextEncoder(); + +export function parse_ascii_directive(line, z) { + // This is wrong wrt encodings; the assembler really operates on bytes and + // not chars. But for our purposes it should be good enough. + let in_quote = false; + let num_parts = 0; + const ret = []; + const chars = [...line]; + let i = 0; + const digits = "0123456789"; + while (i < chars.length) { + let c = chars[i]; + i += 1; + if (!in_quote) { + if (c === '"') { + in_quote = true; + num_parts += 1; + } + } else { + if (c === '"') { + in_quote = false; + if (z) ret.push(0); + continue; + } + if (c !== "\\") { + ret.push(...utf8.encode(c)); + continue; + } + if (i === chars.length) throw new DecompFailure("backslash at end of .ascii line not supported: " + line); + c = chars[i]; + i += 1; + const char_escapes = { b: 8, f: 12, n: 10, r: 13, t: 9, v: 11 }; + if (Object.prototype.hasOwnProperty.call(char_escapes, c)) ret.push(char_escapes[c]); + else if (c === "x") { + let value = 0; + while (i < chars.length && (digits + "abcdefABCDEF").includes(chars[i])) { + value = value * 16 + parseInt(chars[i], 16); + i += 1; + } + ret.push(value % 256); + } else if (digits.includes(c)) { + let it = 0; + let value = parseInt(c, 10); + while (i < chars.length && digits.includes(chars[i]) && it < 2) { + value = value * 8 + parseInt(chars[i], 10); + i += 1; + it += 1; + } + ret.push(value & 0xff); + } else { + ret.push(...utf8.encode(c)); + } + } + } + if (in_quote) throw new DecompFailure("unterminated string literal: " + line); + if (num_parts === 0) throw new DecompFailure(".ascii with no string: " + line); + return Uint8Array.from(ret); +} + +function add_warning(warnings, n) { + if (!warnings.includes(n)) warnings.push(n); +} + +function pyListRepr(arr) { + return "[" + arr.map((s) => `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`).join(", ") + "]"; +} + +export function parse_incbin(args, options, warnings) { + let filename, offset, size; + try { + if (args.length === 3) { + filename = args[0]; + offset = int_(args[1], 0); + size = int_(args[2], 0); + } else if (args.length === 1) { + filename = args[0]; + offset = 0; + size = -1; + } else throw new ValueError(); + } catch (e) { + if (e instanceof ValueError) throw new DecompFailure(`Could not parse asm_data .incbin directive: ${pyListRepr(args)}`); + throw e; + } + if (!options.incbin_dirs.length) { + add_warning(warnings, `Skipping .incbin directive for ${filename}, pass --incbin-dir to set a search directory`); + return null; + } + for (const incbin_dir of options.incbin_dirs) { + const full_path = path.join(incbin_dir, filename); + let data; + try { + const buf = fs.readFileSync(full_path); + data = size < 0 ? buf.subarray(offset) : buf.subarray(offset, offset + size); + data = new Uint8Array(data); + } catch { + continue; + } + if (size >= 0 && data.length !== size) { + add_warning(warnings, `Unable to read ${size} bytes from ${full_path} at ${format(offset, "#x")} (got ${data.length} bytes)`); + return null; + } + return data; + } + add_warning(warnings, `Unable to find ${filename} in any of ${options.incbin_dirs.length} search paths`); + return null; +} + +function check_ifdef(macro_name, asm_state, warnings, directive) { + if (!asm_state.defines.has(macro_name)) { + asm_state.defines.set(macro_name, null); + add_warning(warnings, `Note: assuming ${macro_name} is unset for ${directive}, ` + `pass -D${macro_name}/-U${macro_name} to set/unset explicitly.`); + } + return asm_state.defines.get(macro_name) !== null; +} + +function eval_cpp_if(expr, asm_state, warnings, directive) { + const token_re = /[a-zA-Z0-9_]+|&&|\|\||./gs; + const tokens = [...expr.matchAll(token_re)].map((m) => m[0]).filter((t) => !isspace(t)); + let i = 0; + const tok_at = (j) => { + if (j >= tokens.length) throw new IndexError("list index out of range"); + return tokens[j]; + }; + const parse1 = () => { + const tok = tok_at(i); + i += 1; + if (tok === "!") return !parse1(); + if (tok === "(") { + const r = parse3(); + pyassert(tok_at(i) === ")"); + i += 1; + return r; + } + if (tok === "defined") { + pyassert(tok_at(i) === "("); + const w = tok_at(i + 1); + pyassert(tok_at(i + 2) === ")"); + i += 3; + return check_ifdef(w, asm_state, warnings, directive); + } + if (/^\p{N}/u.test(tok)) return Boolean(int_(tok, 0)); + const value = asm_state.defines.get(tok) ?? null; + if (value === null) { + check_ifdef(tok, asm_state, warnings, directive); + return false; + } + if (!(value instanceof AsmLiteral)) throw new DecompFailure(`Unable to evaluate if condition: ${value}`); + return Boolean(value.value); + }; + const parse2 = () => { + let r = parse1(); + while (i < tokens.length && tokens[i] === "&&") { + i += 1; + r = parse1() && r; + } + return r; + }; + const parse3 = () => { + let r = parse2(); + while (i < tokens.length && tokens[i] === "||") { + i += 1; + r = parse2() || r; + } + return r; + }; + let ret; + try { + ret = parse3(); + pyassert(i === tokens.length); + } catch (e) { + if (e instanceof AssertionError || e instanceof IndexError || e instanceof ValueError) throw new DecompFailure(`Failed to parse #if condition: ${expr}`); + throw e; + } + return ret; +} + +/** Python float() on a string. */ +export function py_float(s) { + const t = s.trim().replace(/(?<=\d)_(?=\d)/g, ""); + if (/^[+-]?(inf|infinity)$/i.test(t)) return t.startsWith("-") ? -Infinity : Infinity; + if (/^[+-]?nan$/i.test(t)) return NaN; + if (!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(t)) throw new ValueError(`could not convert string to float: '${s}'`); + return Number(t); +} + +function intToBytes(v, size, big) { + let b = BigInt(v); + const out = new Uint8Array(size); + for (let k = 0; k < size; k++) { + out[big ? size - 1 - k : k] = Number(b & 0xffn); + b >>= 8n; + } + return out; +} + +/** Read a text file as Python's open(..., encoding="utf-8-sig") line iterator would. */ +export function read_lines(text) { + if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); + text = text.replace(/\r\n?/g, "\n"); + const lines = []; + let start = 0; + for (;;) { + const j = text.indexOf("\n", start); + if (j < 0) { + if (start < text.length) lines.push(text.slice(start)); + break; + } + lines.push(text.slice(start, j + 1)); + start = j + 1; + } + return lines; +} + +/** + * @param {{name:string, text:string}} f file name and contents + */ +export function parse_file(f, arch, options) { + const filename = path.basename(f.name); + const reg_formatter = new RegFormatter(); + const asm_file = new AsmFile(filename, reg_formatter); + let curr_section = ".text"; + const section_sizes = new DefaultMap(() => 0); + const warnings = []; + const preproc_defines = new Map(); + for (const [key, value] of options.preproc_defines) preproc_defines.set(key, value === null ? null : new AsmLiteral(value)); + // NULL is a non-standard but common asm macro that expands to 0 + preproc_defines.set("NULL", new AsmLiteral(0)); + const asm_state = new AsmState({ defines: preproc_defines, reg_formatter }); + + let ifdef_level = 0; + const ifdef_levels = []; + + const re_comment_replacer = (s) => (s[0] === '"' ? s : " "); + const re_whitespace_or_string = /\s+|"(?:\\.|[^\\"])*"/g; + const re_local_glabel = /^L(_.*_)?[0-9A-F]{7,8}/; + const re_local_label = /^(?:loc_|locret_|def_|lbl_|LAB_|switchD_|jump_|LF?[0-9]+$|_[0-9A-Fa-f]{7,8}(?:_.*)?$)/; + const re_label = /^(?:([a-zA-Z0-9_.$]+)|"([a-zA-Z0-9_.$<>@,-]+)"):/; + + const data_directives = { + ".word": arch.asm_word_size, + ".gpword": 4, + ".4byte": 4, + ".long": 4, + ".short": 2, + ".half": 2, + ".2byte": 2, + ".byte": 1, + }; + const LabelKind = { GLOBAL: "global", LOCAL: "local", JUMP_TARGET: "jump_target" }; + + let directive; + let line; + const fail_parse = () => { + throw new DecompFailure(`Could not parse asm_data ${directive} in ${curr_section}: ${line}`); + }; + const try_parse = (parser) => { + try { + return parser(); + } catch { + fail_parse(); + } + }; + const parse_int = (w) => { + const value = try_parse(() => parse_arg(w, arch, asm_state)); + if (!(value instanceof AsmLiteral)) fail_parse(); + return value.value; + }; + const pack = (fmt, val) => { + const little = !options.target.is_big_endian(); + if (fmt === "f") { + if (Number.isFinite(val) && Math.abs(val) > 3.4028235677973366e38) throw new Error("OverflowError: float too large to pack with f format"); + const dv = new DataView(new ArrayBuffer(4)); + dv.setFloat32(0, val, little); + return new Uint8Array(dv.buffer); + } + const dv = new DataView(new ArrayBuffer(8)); + dv.setFloat64(0, val, little); + return new Uint8Array(dv.buffer); + }; + const emit_bytes = (data, { is_string = false } = {}) => { + asm_file.new_data_bytes(data, { is_string }); + section_sizes.set(curr_section, section_sizes.get(curr_section) + data.length); + }; + const emit_word = (w, size) => { + const value = try_parse(() => parse_arg(w, arch, asm_state)); + if (value instanceof AsmLiteral) { + const ival = BigInt.asUintN(size * 8, BigInt(value.value)); + emit_bytes(intToBytes(ival, size, options.target.is_big_endian())); + } else { + asm_file.new_symbolic_data(value, size); + section_sizes.set(curr_section, section_sizes.get(curr_section) + size); + } + }; + + const re_comment_or_string = new RegExp(arch.re_comment + String.raw`|/\*.*?\*/|"(?:\\.|[^\\"])*"`, "g"); + const lines = read_lines(f.text); + for (let idx = 0; idx < lines.length; idx++) { + const lineno = idx + 1; + line = lines[idx]; + const emit_goto = options.goto_patterns.some((pattern) => line.includes(pattern)); + + // Convert C preprocessor directives into asm ones + let is_c_preproc_command = false; + const ws = split_ws(line); + if (ws.length && ["#ifdef", "#ifndef", "#else", "#if", "#elif", "#elifdef", "#elifndef", "#endif", "#define"].includes(ws[0])) { + is_c_preproc_command = true; + line = "." + line.slice(1); + } + + // Strip comments and whitespace (but not within strings) + line = line.replace(re_comment_or_string, re_comment_replacer); + line = line.replace(re_whitespace_or_string, re_comment_replacer); + line = line.trim(); + + const process_label = (label, { kind }) => { + if (curr_section === ".rodata") asm_file.new_data_label(label, { is_readonly: true }); + else if (curr_section === ".data") asm_file.new_data_label(label); + else if (curr_section === ".bss") asm_file.new_data_label(label, { is_bss: true }); + else if (curr_section === ".text") { + asm_file.new_data_label(label, { is_readonly: true, is_text: true }); + if (label.startsWith(".") || kind === LabelKind.JUMP_TARGET) { + if (asm_file.current_function !== null) asm_file.new_label(label); + } else if ((re_local_glabel.test(label) || (kind !== LabelKind.GLOBAL && re_local_label.test(label))) && asm_file.current_function !== null) { + asm_file.new_label(label); + } else { + asm_file.new_function(label); + } + } + }; + + // Check for labels + for (;;) { + const g = re_label.exec(line); + if (!g) break; + const label = g[1] || g[2]; + if (ifdef_level === 0) process_label(label, { kind: LabelKind.LOCAL }); + line = line.slice(g[0].length).trim(); + } + + if (!line) continue; + + if (line.includes("=") && !is_c_preproc_command) { + const k = line.indexOf("="); + const key = line.slice(0, k).trim(); + const value = line.slice(k + 1); + if (!key.includes(" ")) line = `.set ${key}, ${value}`; + } + + directive = split_ws(line)[0]; + if (directive.startsWith(".")) { + // Assembler directive. + const sp = line.indexOf(" "); + const args_str = sp < 0 ? "" : line.slice(sp + 1); + if (is_c_preproc_command) { + line = "#" + line.slice(1); + directive = split_ws(line)[0]; + } + if ([".ifdef", ".ifndef", "#ifdef", "#ifndef"].includes(directive)) { + let active = check_ifdef(args_str, asm_state, warnings, directive); + if (directive.slice(1) === "ifndef") active = !active; + const level = 1 - Number(active); + ifdef_level += level; + ifdef_levels.push(level); + } else if (directive === ".if") { + const parts = split_ws(line); + if (parts.length < 2) throw new IndexError("list index out of range"); + const macro_name = parts[1]; + let active; + if (macro_name === "0") active = false; + else if (macro_name === "1") active = true; + else { + active = true; + add_warning(warnings, `Note: ignoring .if ${macro_name} directive`); + } + const level = 1 - Number(active); + ifdef_level += level; + ifdef_levels.push(level); + } else if (directive === "#if") { + const active = eval_cpp_if(args_str, asm_state, warnings, directive); + const level = 1 - Number(active); + ifdef_level += level; + ifdef_levels.push(level); + } else if (["#elif", "#elifdef", "#elifndef", "#else", ".else"].includes(directive)) { + if (!ifdef_levels.length) throw new IndexError("pop from empty list"); + let level = ifdef_levels.pop(); + ifdef_level -= level; + if (level === 1) { + let active; + if (directive === "#elifdef") active = check_ifdef(args_str, asm_state, warnings, directive); + else if (directive === "#elifndef") active = !check_ifdef(args_str, asm_state, warnings, directive); + else if (directive === "#elif") active = eval_cpp_if(args_str, asm_state, warnings, directive); + else active = true; + level = 1 - Number(active); + } else level = 2; + ifdef_level += level; + ifdef_levels.push(level); + } else if (directive === ".endif" || directive === "#endif") { + if (!ifdef_levels.length) throw new IndexError("pop from empty list"); + ifdef_level -= ifdef_levels.pop(); + } else if (directive === ".macro") { + ifdef_level += 1; + } else if (directive === ".endm") { + ifdef_level -= 1; + } else if (directive === ".fn") { + const args = split_quotable_arg_list(args_str); + asm_file.new_function(args[0]); + } else if (ifdef_level === 0) { + if (directive === ".section") { + curr_section = split_ws(line)[1].split(",")[0]; + if ([".rdata", ".late_rodata", ".sdata2"].includes(curr_section)) curr_section = ".rodata"; + else if (curr_section === ".sdata") curr_section = ".data"; + else if (curr_section.startsWith(".text")) curr_section = ".text"; + } else if (directive === ".rdata" || directive === ".rodata" || directive === ".late_rodata") { + curr_section = ".rodata"; + } else if (directive === ".data") curr_section = ".data"; + else if (directive === ".bss") curr_section = ".bss"; + else if (directive === ".text") curr_section = ".text"; + else if (directive === ".set") { + const args = split_quotable_arg_list(args_str); + if (args.length === 1) { + // ".set noreorder" or similar, just ignore + } else if (args.length === 2) asm_state.defines.set(args[0], parse_arg(args[1], arch, asm_state)); + else throw new DecompFailure(`Could not parse ${directive}: ${line}`); + } else if (directive === "#define") { + const args = split_ws(args_str, 1); + if (args.length === 2) asm_state.defines.set(args[0], parse_arg(args[1], arch, asm_state)); + else asm_state.defines.set(args[0], new AsmLiteral(1)); + } else if (directive === ".syntax") { + if (args_str.trim() === "unified") asm_state.is_unified = true; + else if (args_str.trim() === "divided") asm_state.is_unified = false; + } else if (directive === ".thumb" || directive === ".thumb_func") asm_state.is_thumb = true; + else if (directive === ".arm") asm_state.is_thumb = false; + else if (directive === ".code") { + if (args_str.trim() === "16") asm_state.is_thumb = true; + else if (args_str.trim() === "32") asm_state.is_thumb = false; + } else if ([".rodata", ".data", ".bss", ".text"].includes(curr_section)) { + if (Object.prototype.hasOwnProperty.call(data_directives, directive)) { + const size = data_directives[directive]; + const args = split_arg_list(args_str); + for (const w of args) emit_word(w, size); + } else if (directive === ".rel") { + const args = split_arg_list(args_str); + pyassert(args.length === 2); + emit_word(args[1], 4); + } else if (directive === ".obj") { + const args = split_quotable_arg_list(args_str); + pyassert(args.length === 2); + const kind = args[1] === "local" ? LabelKind.LOCAL : LabelKind.GLOBAL; + process_label(args[0], { kind }); + } else if (directive === ".float") { + const args = split_arg_list(args_str); + for (const w of args) { + const fval = try_parse(() => py_float(w)); + emit_bytes(pack("f", fval)); + } + } else if (directive === ".double") { + const args = split_arg_list(args_str); + for (const w of args) { + const fval = try_parse(() => py_float(w)); + emit_bytes(pack("d", fval)); + } + } else if ([".asci", ".asciz", ".ascii", ".asciiz", ".string"].includes(directive)) { + const z = directive.endsWith("z") || directive === ".string"; + emit_bytes(parse_ascii_directive(line, z), { is_string: true }); + } else if ([".space", ".skip", ".align", ".balign", ".p2align"].includes(directive)) { + const args = split_arg_list(args_str); + let fill; + if (args.length === 2) fill = band(parse_int(args[1]), 0xff); + else if (args.length === 1) fill = 0; + else throw new DecompFailure(`Could not parse asm_data ${directive} in ${curr_section}: ${line}`); + let size = parse_int(args[0]); + if (directive === ".balign") size = pymod(-section_sizes.get(curr_section), size); + else if (directive === ".align" || directive === ".p2align") size = pymod(-section_sizes.get(curr_section), 2 ** size); + emit_bytes(new Uint8Array(Math.max(size, 0)).fill(fill)); + } else if (directive === ".incbin") { + const args = split_quotable_arg_list(args_str); + const data = parse_incbin(args, options, warnings); + if (data !== null) emit_bytes(data); + } + } + } + } else if (ifdef_level === 0) { + if (["jlabel", "alabel", "ehlabel"].includes(directive)) { + const sp = line.indexOf(" "); + const args_str = sp < 0 ? "" : line.slice(sp + 1); + const args = split_quotable_arg_list(args_str); + if (args.length) process_label(args[0], { kind: LabelKind.JUMP_TARGET }); + } else if ( + ["glabel", "dlabel", "arm_func_start", "thumb_func_start", "non_word_aligned_thumb_func_start", "ARM_FUNC_START", "THUMB_FUNC_START", "NON_WORD_ALIGNED_THUMB_FUNC_START"].includes(directive) + ) { + if (directive.toLowerCase().includes("thumb")) asm_state.is_thumb = true; + else if (directive.toLowerCase().includes("arm")) asm_state.is_thumb = false; + const sp = line.indexOf(" "); + const args_str = sp < 0 ? "" : line.slice(sp + 1); + const args = split_quotable_arg_list(args_str); + if (args.length) process_label(args[0], { kind: LabelKind.GLOBAL }); + } else if (["arm_func_end", "thumb_func_end", "ARM_FUNC_END", "THUMB_FUNC_END", "endlabel", "enddlabel", "nonmatching"].includes(directive)) { + // pass + } else if (curr_section === ".text") { + const meta = new InstructionMeta({ emit_goto, filename, lineno, synthetic: false }); + const ins = parse_instruction(line, meta, arch, asm_state); + asm_file.new_instruction(ins); + } + } + } + + if (warnings.length && options.coding_style.comment_style !== CodingStyle.CommentStyle.NONE) { + print("/*"); + print(warnings.join("\n")); + print("*/"); + } + return asm_file; +} + +export { pystr }; diff --git a/packages/romdev-m2c/src/asm_instruction.js b/packages/romdev-m2c/src/asm_instruction.js new file mode 100644 index 00000000..eeae94fc --- /dev/null +++ b/packages/romdev-m2c/src/asm_instruction.js @@ -0,0 +1,610 @@ +// Port of m2c/asm_instruction.py +/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */ +// Functions and classes useful for parsing an arbitrary assembly instruction. +import { DecompFailure, assert_never } from "./error.js"; +import { IndexError, band, bor, bxor, hex, int_, intern, isspace, pyassert, shl, shr, compare, repr } from "./py.js"; +import { PyEnum } from "./options.js"; + +export const ARM_BARREL_SHIFTER_OPS = ["lsl", "lsr", "asr", "ror", "rrx"]; +export const OP_PRECEDENCE = { "*": 0, "+": 1, "-": 1, "<<": 2, ">>": 2, "&": 3, "^": 4, "|": 5 }; +export const MAX_PRECEDENCE = 6; + +export class Register { + constructor(register_name) { + this.register_name = register_name; + return intern(this, [register_name]); + } + is_float() { + const name = this.register_name; + return Boolean(name) && name[0] === "f" && name !== "fp"; + } + arm_regtype_index() { + const index = { sp: 13, lr: 14, pc: 15 }[this.register_name]; + if (index !== undefined) return ["r", index]; + pyassert("rsdq".includes(this.register_name[0]), this.register_name); + return [this.register_name[0], int_(this.register_name.slice(1))]; + } + static fictive(name, suffix = "") { + return new Register(`${name}_fictive_${suffix}`); + } + toString() { + return `$${this.register_name}`; + } + __repr__() { + return `Register(register_name=${repr(this.register_name)})`; + } +} + +export class RegisterList { + constructor(regs) { + this.regs = regs; + return intern(this, [regs]); + } + toString() { + return "{" + this.regs.map((r) => String(r)).join(",") + "}"; + } +} + +export class AsmGlobalSymbol { + constructor(symbol_name) { + this.symbol_name = symbol_name; + if (new.target === AsmGlobalSymbol) return intern(this, [symbol_name]); + } + toString() { + return this.symbol_name; + } +} + +export class AsmSectionGlobalSymbol extends AsmGlobalSymbol { + constructor(symbol_name, section_name, addend) { + super(symbol_name); + this.section_name = section_name; + this.addend = addend; + return intern(this, [symbol_name, section_name, addend]); + } +} + +export function asm_section_global_symbol(section_name, addend) { + return new AsmSectionGlobalSymbol(`__${section_name}${hex(addend).slice(2).toUpperCase()}`, section_name, addend); +} + +export class Macro { + constructor(macro_name, argument) { + this.macro_name = macro_name; + this.argument = argument; + return intern(this, [macro_name, argument]); + } + toString() { + if (this.macro_name === "eqsign") return `=${this.argument}`; + return `%${this.macro_name}(${this.argument})`; + } +} + +export class AsmLiteral { + constructor(value) { + this.value = value; + return intern(this, [value]); + } + as_s16() { + return band(this.value + 0x8000, 0xffff) - 0x8000; + } + as_s8() { + return band(this.value + 0x80, 0xff) - 0x80; + } + toString() { + return hex(this.value); + } +} + +export class Writeback extends PyEnum {} +PyEnum.define(Writeback, { PRE: "pre", POST: "post" }); + +export class AsmAddressMode { + constructor(base, addend, writeback) { + this.base = base; + this.addend = addend; + this.writeback = writeback; + return intern(this, [base, addend, writeback]); + } + addend_as_literal() { + pyassert(this.addend instanceof AsmLiteral); + return this.addend.value; + } + toString() { + if (this.writeback !== null && this.writeback !== undefined) { + // (upstream bug preserved: the addend is not interpolated) + const add_str = this.addend !== new AsmLiteral(0) ? ", {self.addend}" : ""; + if (this.writeback === Writeback.PRE) return `[${this.base}${add_str}]!`; + return `[${this.base}]${add_str}`; + } + if (this.addend === new AsmLiteral(0)) return `(${this.base})`; + return `${this.addend}(${this.base})`; + } +} + +export class BinOp { + constructor(op, lhs, rhs) { + this.op = op; + this.lhs = lhs; + this.rhs = rhs; + return intern(this, [op, lhs, rhs]); + } + toString() { + return `${this.lhs} ${this.op} ${this.rhs}`; + } +} + +export class JumpTarget { + constructor(target) { + this.target = target; + return intern(this, [target]); + } + toString() { + return this.target; + } +} + +export class AsmInstruction { + constructor(mnemonic, args) { + this.mnemonic = mnemonic; + this.args = args; + return intern(this, [mnemonic, args]); + } + toString() { + if (!this.args.length) return this.mnemonic; + return `${this.mnemonic} ${this.args.map((a) => String(a)).join(", ")}`; + } +} + +/** Arch-specific information needed to parse asm. */ +export class ArchAsmParsing { + normalize_instruction(instr, asm_state) { + throw new Error("abstract"); + } +} +ArchAsmParsing.prototype.supports_at_addressing = false; +ArchAsmParsing.prototype.has_delay_slots = false; + +/** A fake arch that can parse asm in a naive fashion. */ +export class NaiveParsingArch extends ArchAsmParsing { + constructor() { + super(); + this.all_regs = []; + this.aliased_regs = {}; + this.supports_dollar_regs = true; + this.supports_at_addressing = true; + } + normalize_instruction(instr, asm_state) { + return instr; + } +} + +function aliased(arch, name) { + return Object.prototype.hasOwnProperty.call(arch.aliased_regs, name) ? arch.aliased_regs[name] : undefined; +} + +/** Converts register names used in input assembly to the internal register representation. */ +export class RegFormatter { + constructor() { + this.used_names = new Map(); + } + parse(reg_name, arch) { + return aliased(arch, reg_name) ?? new Register(reg_name); + } + parse_and_store(reg_name, arch) { + reg_name = reg_name.toLowerCase(); + const internal_reg = aliased(arch, reg_name) ?? new Register(reg_name); + const existing_reg_name = this.used_names.get(internal_reg); + if (existing_reg_name === undefined) this.used_names.set(internal_reg, reg_name); + else if (existing_reg_name !== reg_name) { + throw new DecompFailure(`Source uses multiple names for ${internal_reg} (${existing_reg_name}, ${reg_name})`); + } + return internal_reg; + } + format(reg) { + return this.used_names.get(reg) ?? reg.register_name; + } +} + +export class AsmState { + constructor({ defines = new Map(), reg_formatter = new RegFormatter(), is_thumb = false, is_unified = false, is_pattern = false } = {}) { + // null means "explicitly undefined" + this.defines = defines; + this.reg_formatter = reg_formatter; + this.is_thumb = is_thumb; + this.is_unified = is_unified; + this.is_pattern = is_pattern; + } +} + +const ASCII_LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; +const DIGITS = "0123456789"; +export const valid_word = ASCII_LETTERS + DIGITS + "_$."; + +const inStr = (c, s) => c !== undefined && s.includes(c); + +export function parse_word(elems, valid = valid_word) { + let ret = ""; + while (elems.length && inStr(elems[0], valid)) ret += elems.shift(); + return ret; +} + +export function parse_quoted(elems, quote_char) { + let ret = ""; + while (elems.length && elems[0] !== quote_char) { + if (elems[0] === "\\") { + elems.shift(); + if (!elems.length) break; + } + ret += elems.shift(); + } + return ret; +} + +export function parse_number(number_str) { + if (number_str[0] === "0") pyassert(number_str.length === 1 || "xX".includes(number_str[1])); + return int_(number_str, 0); +} + +export function constant_fold(arg, asm_state) { + if (arg instanceof AsmGlobalSymbol) { + const value = asm_state.defines.get(arg.symbol_name); + if (value !== undefined && value !== null) return constant_fold(value, asm_state); + } + if (!(arg instanceof BinOp)) return arg; + const lhs = constant_fold(arg.lhs, asm_state); + const rhs = constant_fold(arg.rhs, asm_state); + if (lhs instanceof AsmLiteral && rhs instanceof AsmLiteral) { + switch (arg.op) { + case "+": return new AsmLiteral(lhs.value + rhs.value); + case "-": return new AsmLiteral(lhs.value - rhs.value); + case "*": return new AsmLiteral(lhs.value * rhs.value); + case ">>": return new AsmLiteral(shr(lhs.value, rhs.value)); + case "<<": return new AsmLiteral(shl(lhs.value, rhs.value)); + case "&": return new AsmLiteral(band(lhs.value, rhs.value)); + case "|": return new AsmLiteral(bor(lhs.value, rhs.value)); + case "^": return new AsmLiteral(bxor(lhs.value, rhs.value)); + } + } + return new BinOp(arg.op, lhs, rhs); +} + +/** If `arg` is an AsmGlobalSymbol whose name matches a known or aliased register, convert it. */ +export function replace_bare_reg(arg, arch, asm_state) { + if (arg instanceof AsmGlobalSymbol) { + const reg_name = arg.symbol_name.toLowerCase(); + if (arch.all_regs.includes(new Register(reg_name)) || aliased(arch, reg_name) !== undefined) { + return asm_state.reg_formatter.parse_and_store(reg_name, arch); + } + } + return arg; +} + +export function get_jump_target(label) { + pyassert(label instanceof AsmGlobalSymbol, "invalid branch target"); + return new JumpTarget(label.symbol_name); +} + +// Main parser. +export function parse_arg_elems(arg_elems, arch, asm_state, { top_level, do_constant_fold = true, do_replace_bare_reg = true, precedence_cap = MAX_PRECEDENCE }) { + let value = null; + const supports_dollar_regs = arch.supports_dollar_regs || asm_state.is_pattern; + + const consume_ws = () => { + while (arg_elems.length && isspace(arg_elems[0])) arg_elems.shift(); + }; + const expect = (n) => { + pyassert(arg_elems.length, `Expected one of ${repr([...n])}, but reached end of string`); + const g = arg_elems.shift(); + pyassert(n.includes(g), `Expected one of ${repr([...n])}, got ${g} (rest: ${repr(arg_elems)})`); + return g; + }; + const parse_sh_register = () => { + const word = parse_word(arg_elems); + if (word.startsWith("$") && supports_dollar_regs) return asm_state.reg_formatter.parse_and_store(word.slice(1), arch); + const reg = replace_bare_reg(new AsmGlobalSymbol(word), arch, asm_state); + pyassert(reg instanceof Register); + return reg; + }; + + for (;;) { + consume_ws(); + if (!arg_elems.length) break; + const tok = arg_elems[0]; + if (tok === ",") { + break; + } else if (tok === "$" && supports_dollar_regs) { + // Register. + pyassert(value === null); + const word = parse_word(arg_elems); + const reg = word.slice(1); + if (reg.includes("$")) value = new AsmGlobalSymbol(word); + else value = asm_state.reg_formatter.parse_and_store(reg, arch); + } else if (tok === "#") { + // ARM immediate. + pyassert(value === null); + expect("#"); + } else if (tok === "{") { + // ARM register list. + pyassert(value === null); + arg_elems.shift(); + const li = []; + for (;;) { + consume_ws(); + if (li.length) { + if (expect(",}") === "}") break; + consume_ws(); + } + let word = parse_word(arg_elems); + const reg1 = asm_state.reg_formatter.parse_and_store(word, arch); + consume_ws(); + if (arg_elems[0] !== "-") { + if (arg_elems.length === 0) throw new IndexError("list index out of range"); + li.push(reg1); + continue; + } + arg_elems.shift(); + consume_ws(); + word = parse_word(arg_elems); + const reg2 = asm_state.reg_formatter.parse_and_store(word, arch); + const [tp1, ind1] = reg1.arm_regtype_index(); + const [tp2, ind2] = reg2.arm_regtype_index(); + pyassert(tp1 === tp2); + for (let i = ind1; i < ind2 + 1; i++) li.push(asm_state.reg_formatter.parse(`${tp1}${i}`, arch)); + } + consume_ws(); + if (arg_elems.length && arg_elems[0] === "^") expect("^"); + if (li.length > 1) { + const keyed = li.map((r, i) => [r.arm_regtype_index(), i, r]); + keyed.sort((a, b) => compare(a[0], b[0]) || a[1] - b[1]); + li.splice(0, li.length, ...keyed.map((k) => k[2])); + } + value = new RegisterList(li); + } else if (tok === ".") { + // Either a jump target (i.e. a label), or a section reference. + pyassert(value === null); + arg_elems.shift(); + const word = parse_word(arg_elems); + if (["data", "sdata", "rodata", "rdata", "bss", "sbss", "text"].includes(word)) value = asm_section_global_symbol(word, 0); + else value = new AsmGlobalSymbol("." + word); + } else if (tok === "%") { + // A MIPS reloc macro, e.g. %hi(...) or %lo(...). + pyassert(value === null); + arg_elems.shift(); + const macro_name = parse_word(arg_elems); + pyassert(macro_name); + expect("("); + const m = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false, do_replace_bare_reg: false }); + expect(")"); + value = new Macro(macro_name, m); + } else if (tok === ")" || tok === "]") { + break; + } else if (DIGITS.includes(tok)) { + // Try a number. + pyassert(value === null); + const word = parse_word(arg_elems, valid_word); + value = new AsmLiteral(parse_number(word)); + } else if (tok === "-" && value === null) { + // Negated number, or ARM negated register. + expect("-"); + consume_ws(); + const word = parse_word(arg_elems, valid_word); + pyassert(word); + if (DIGITS.includes(word[0])) value = new AsmLiteral(-parse_number(word)); + else { + const val = replace_bare_reg(new AsmGlobalSymbol(word), arch, asm_state); + value = new BinOp("-", new AsmLiteral(0), val); + } + } else if (tok === "(") { + if (value !== null && !top_level) break; + // Address mode or binary operation. + expect("("); + let rhs = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false, do_constant_fold: false }); + expect(")"); + if (rhs instanceof BinOp) { + pyassert(value === null); + value = constant_fold(rhs, asm_state); + } else { + if (rhs === new AsmLiteral(0)) rhs = new Register("zero"); + if (rhs instanceof AsmGlobalSymbol) { + pyassert(value === null); + value = constant_fold(rhs, asm_state); + } else { + pyassert(top_level); + pyassert(rhs instanceof Register); + value = constant_fold(value || new AsmLiteral(0), asm_state); + value = new AsmAddressMode(rhs, value, null); + } + } + } else if (tok === "[") { + // ARM address mode + pyassert(value === null); + expect("["); + const val = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false }); + pyassert(val instanceof Register); + let addend = null; + if (expect(",]") === ",") { + addend = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false }); + if (expect(",]") === ",") { + consume_ws(); + const op = parse_word(arg_elems).toLowerCase(); + pyassert(ARM_BARREL_SHIFTER_OPS.includes(op)); + let shift; + if (op === "rrx") shift = new AsmLiteral(1); + else shift = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false }); + addend = new BinOp(op, addend, constant_fold(shift, asm_state)); + expect("]"); + } + } + consume_ws(); + let writeback = null; + if (arg_elems.length && arg_elems[0] === "!") { + expect("!"); + writeback = Writeback.PRE; + } else if (arg_elems.length && arg_elems[0] === ",") { + expect(","); + pyassert(addend === null); + addend = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false }); + writeback = Writeback.POST; + } + if (addend === null) addend = new AsmLiteral(0); + value = new AsmAddressMode(val, addend, writeback); + } else if (tok === "!") { + // ARM writeback indicator + expect("!"); + if (value !== null) value = replace_bare_reg(value, arch, asm_state); + pyassert(value instanceof Register); + value = new AsmAddressMode(value, new AsmLiteral(0), Writeback.PRE); + } else if (tok === '"') { + // Quoted global symbol. + expect('"'); + pyassert(value === null); + const word = parse_quoted(arg_elems, '"'); + value = new AsmGlobalSymbol(word); + expect('"'); + } else if (valid_word.includes(tok)) { + // Global symbol. + pyassert(value === null); + const word = parse_word(arg_elems); + value = new AsmGlobalSymbol(word); + + const op = word.toLowerCase(); + if (top_level && ARM_BARREL_SHIFTER_OPS.includes(op)) { + consume_ws(); + if (arg_elems.length && !",)@".includes(arg_elems[0])) { + const shift = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false }); + value = new BinOp(op, new AsmLiteral(0), shift); + pyassert(!arg_elems.length); + } else if (op === "rrx") { + value = new BinOp(op, new AsmLiteral(0), new AsmLiteral(1)); + pyassert(!arg_elems.length); + } + } + } else if ("<>+-*&|^".includes(tok)) { + // Binary operators + pyassert(value instanceof AsmLiteral || value instanceof AsmGlobalSymbol || value instanceof BinOp); + const op = "<>".includes(tok) ? tok + tok : tok; + const precedence = OP_PRECEDENCE[op]; + if (precedence >= precedence_cap) break; + for (const c of op) expect(c); + if (op === "-" && arg_elems[0] === "_") { + const reloc_name = parse_word(arg_elems); + if (reloc_name !== "_SDA_BASE_" && reloc_name !== "_SDA2_BASE_") { + throw new DecompFailure(`Unexpected symbol ${reloc_name} in subtraction expression`); + } + value = new Macro("sda21", value); + } else { + const rhs = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false, do_replace_bare_reg: false, precedence_cap: precedence }); + if (op === "+" && rhs instanceof AsmLiteral && value instanceof AsmSectionGlobalSymbol) { + value = asm_section_global_symbol(value.section_name, value.addend + rhs.value); + } else { + value = new BinOp(op, value, rhs); + } + } + } else if (tok === "@") { + if (value === null && arch.supports_at_addressing) { + // SuperH indirect addressing: @Rn, @-Rn, @Rn+, and @(disp,Rn). + expect("@"); + if (arg_elems.length && arg_elems[0] === "(") { + expect("("); + const addend = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false }); + expect(","); + consume_ws(); + const base = parse_sh_register(); + expect(")"); + value = new AsmAddressMode(base, addend, null); + continue; + } + let sh_writeback = null; + if (arg_elems.length && arg_elems[0] === "-") { + expect("-"); + sh_writeback = Writeback.PRE; + } + const base = parse_sh_register(); + if (arg_elems.length && arg_elems[0] === "+") { + pyassert(sh_writeback === null); + expect("+"); + sh_writeback = Writeback.POST; + } + value = new AsmAddressMode(base, new AsmLiteral(0), sh_writeback); + } else { + // A relocation (e.g. (...)@ha or (...)@l). + if (!top_level) break; + arg_elems.shift(); + const reloc_name = parse_word(arg_elems); + pyassert(["h", "ha", "l", "sda2", "sda21"].includes(reloc_name)); + pyassert(value); + value = new Macro(reloc_name, value); + } + } else if (tok === "=") { + // ARM reference to symbol + pyassert(top_level); + pyassert(!value); + expect("="); + const ref = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false, do_constant_fold: true }); + value = new Macro("eqsign", ref); + } else { + pyassert(false, `Unknown token ${tok} in ${repr(arg_elems)}`); + } + } + + pyassert(value !== null); + if (do_constant_fold) value = constant_fold(value, asm_state); + if (do_replace_bare_reg) value = replace_bare_reg(value, arch, asm_state); + return value; +} + +export function parse_args(args, arch, asm_state) { + const arg_elems = [...args.trim()]; + const output = []; + while (arg_elems.length) { + const ret = parse_arg_elems(arg_elems, arch, asm_state, { top_level: true }); + if (ret instanceof BinOp && ARM_BARREL_SHIFTER_OPS.includes(ret.op)) { + pyassert(output.length); + output[output.length - 1] = new BinOp(ret.op, output[output.length - 1], ret.rhs); + continue; + } + output.push(ret); + if (arg_elems.length) { + const comma = arg_elems.shift(); + pyassert(comma === ","); + } + } + return output; +} + +export function parse_arg(arg, arch, asm_state) { + const chars = [...arg]; + const value = parse_arg_elems(chars, arch, asm_state, { top_level: false, do_replace_bare_reg: false }); + if (chars.length) throw new Error(`Failed to parse value: ${arg}`); + return value; +} + +export function parse_asm_instruction(line, arch, asm_state) { + line = line.trim(); + const i = line.indexOf(" "); + const mnemonic = i < 0 ? line : line.slice(0, i); + const args_str = i < 0 ? "" : line.slice(i + 1); + const args = parse_args(args_str, arch, asm_state); + const instr = new AsmInstruction(mnemonic.toLowerCase(), args); + return arch.normalize_instruction(instr, asm_state); +} + +export function* traverse_arg(arg) { + yield arg; + if (arg instanceof Register || arg instanceof AsmLiteral || arg instanceof AsmGlobalSymbol) { + // pass + } else if (arg instanceof RegisterList) { + for (const reg of arg.regs) yield reg; + } else if (arg instanceof AsmAddressMode) { + yield arg.base; + yield* traverse_arg(arg.addend); + } else if (arg instanceof Macro) { + yield* traverse_arg(arg.argument); + } else if (arg instanceof BinOp) { + yield* traverse_arg(arg.lhs); + yield* traverse_arg(arg.rhs); + } else { + assert_never(arg); + } +} diff --git a/packages/romdev-m2c/src/asm_pattern.js b/packages/romdev-m2c/src/asm_pattern.js new file mode 100644 index 00000000..f29a9e36 --- /dev/null +++ b/packages/romdev-m2c/src/asm_pattern.js @@ -0,0 +1,275 @@ +// Port of m2c/asm_pattern.py +/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */ +import { Label } from "./asm_file.js"; +import { + ARM_BARREL_SHIFTER_OPS, + AsmAddressMode, + AsmGlobalSymbol, + AsmInstruction, + AsmLiteral, + AsmState, + BinOp, + Macro, + NaiveParsingArch, + Register, + RegisterList, + parse_asm_instruction, +} from "./asm_instruction.js"; +import { Instruction, InstructionMeta } from "./instruction.js"; +import { DefaultMap, pyassert, rstrip, shl } from "./py.js"; +import { print } from "./io.js"; + +/** Python str.isupper(). */ +export function isupper(s) { + return s !== s.toLowerCase() && s === s.toUpperCase(); +} + +export function make_pattern(...parts) { + const ret = []; + for (let part of parts) { + const optional = part.endsWith("?"); + part = rstrip(part, "?"); + if (part === "*") ret.push([null, optional]); + else if (part.endsWith(":")) ret.push([Label.new(part.slice(0, -1)), optional]); + else { + const ins = parse_asm_instruction(part, new NaiveParsingArch(), new AsmState()); + ret.push([ins, optional]); + } + } + return ret; +} + +export class Replacement { + constructor(new_body, num_consumed, clobbers = null) { + this.new_body = new_body; + this.num_consumed = num_consumed; + this.clobbers = clobbers; + } +} + +export class AsmMatch { + constructor(body, wildcard_items, regs, literals, labels, asm_data) { + this.body = body; + this.wildcard_items = wildcard_items; + this.regs = regs; // Map + this.literals = literals; // Map + this.labels = labels; // Map + this.asm_data = asm_data; + } +} + +export class AsmPattern { + match(matcher) { + throw new Error("abstract"); + } +} + +export class SimpleAsmPattern extends AsmPattern { + // subclasses define `pattern` and replace(m) + match(matcher) { + const m = matcher.try_match(this.pattern); + if (!m) return null; + return this.replace(m); + } +} + +export class TryMatchState { + constructor() { + this.symbolic_registers = new Map(); + this.symbolic_labels_def = new Map(); + this.symbolic_labels_uses = new DefaultMap(() => new Set()); + this.symbolic_literals = new Map(); + this.wildcard_items = []; + } + match_var(var_map, key, value) { + if (var_map.has(key)) { + if (var_map.get(key) !== value) return false; + } else var_map.set(key, value); + return true; + } + match_reg(actual, exp) { + if (exp.register_name.length <= 1) return this.match_var(this.symbolic_registers, exp.register_name, actual); + return exp.register_name === actual.register_name; + } + match_label_def(key, defn) { + pyassert(!this.symbolic_labels_def.has(key)); + this.symbolic_labels_def.set(key, defn); + const uses = this.symbolic_labels_uses.get(key); + for (const u of uses) if (!defn.names.includes(u)) return false; + return true; + } + match_label_use(key, use) { + const defn = this.symbolic_labels_def.get(key) ?? null; + if (defn !== null && !defn.names.includes(use)) return false; + this.symbolic_labels_uses.get(key).add(use); + return true; + } + eval_math(e) { + if (e instanceof AsmLiteral) return e.value; + if (e instanceof BinOp) { + if (e.op === "+") return this.eval_math(e.lhs) + this.eval_math(e.rhs); + if (e.op === "-") return this.eval_math(e.lhs) - this.eval_math(e.rhs); + if (e.op === "<<") return shl(this.eval_math(e.lhs), this.eval_math(e.rhs)); + pyassert(false, `bad binop in math pattern: ${e}`); + } else if (e instanceof AsmGlobalSymbol) { + pyassert(this.symbolic_literals.has(e.symbol_name), `undefined variable in math pattern: ${e.symbol_name}`); + return this.symbolic_literals.get(e.symbol_name); + } else { + pyassert(false, `bad pattern part in math pattern: ${e}`); + } + } + match_arg(a, e) { + if (e instanceof AsmLiteral) return a instanceof AsmLiteral && a.value === e.value; + if (e instanceof Register) return a instanceof Register && this.match_reg(a, e); + if (e instanceof AsmGlobalSymbol) { + if (e.symbol_name.startsWith(".")) return a instanceof AsmGlobalSymbol && this.match_label_use(e.symbol_name, a.symbol_name); + else if (isupper(e.symbol_name)) return a instanceof AsmLiteral && this.match_var(this.symbolic_literals, e.symbol_name, a.value); + else if (e.symbol_name === "_") return true; + else return a instanceof AsmGlobalSymbol && a.symbol_name === e.symbol_name; + } + if (e instanceof AsmAddressMode) { + return a instanceof AsmAddressMode && this.match_reg(a.base, e.base) && this.match_arg(a.addend, e.addend) && a.writeback === e.writeback; + } + if (e instanceof BinOp) { + if (ARM_BARREL_SHIFTER_OPS.includes(e.op)) { + return a instanceof BinOp && a.op === e.op && this.match_arg(a.lhs, e.lhs) && this.match_arg(a.rhs, e.rhs); + } + return a instanceof AsmLiteral && a.value === this.eval_math(e); + } + if (e instanceof Macro) return a instanceof Macro && a.macro_name === e.macro_name && this.match_arg(a.argument, e.argument); + if (e instanceof RegisterList) { + return a instanceof RegisterList && a.regs.length === e.regs.length && a.regs.every((ar, i) => this.match_reg(ar, e.regs[i])); + } + pyassert(false, `bad pattern part: ${e}`); + } + match_one(actual, exp) { + if (exp === null) { + this.wildcard_items.push(actual); + return true; + } + if (exp instanceof Label) { + pyassert(exp.names.length === 1); + return actual instanceof Label && this.match_label_def(exp.names[0], actual); + } + if (!(actual instanceof Instruction)) return false; + const ins = actual; + if (ins.mnemonic !== exp.mnemonic) return false; + if (exp.args.length) { + if (ins.args.length !== exp.args.length) return false; + for (let i = 0; i < ins.args.length; i++) if (!this.match_arg(ins.args[i], exp.args[i])) return false; + } + return true; + } + match_meta(ins) { + if (ins.mnemonic === ".eq") { + const res = this.eval_math(ins.args[1]); + return this.match_arg(new AsmLiteral(res), ins.args[0]); + } else if (ins.mnemonic === ".set") { + const sym = ins.args[0]; + pyassert(sym instanceof AsmGlobalSymbol); + pyassert(isupper(sym.symbol_name)); + this.symbolic_literals.set(sym.symbol_name, this.eval_math(ins.args[1])); + return true; + } else if (ins.mnemonic === ".forget") { + const arg = ins.args[0]; + if (arg instanceof Register) this.symbolic_registers.delete(arg.register_name); + else pyassert(false, ".forget arg of unsupported type"); + return true; + } else { + pyassert(false, ins.mnemonic); + } + } +} + +export class AsmMatcher { + constructor(arch, asm_data, input, labels) { + this.arch = arch; + this.asm_data = asm_data; + this.input = input; + this.labels = labels; + this.output = []; + this.index = 0; + } + try_match(pattern) { + const state = new TryMatchState(); + const start_index = this.index; + let index = this.index; + for (const [pat, optional] of pattern) { + if (pat instanceof AsmInstruction && pat.mnemonic[0] === ".") { + if (!state.match_meta(pat) && !optional) return null; + } else if (index < this.input.length && state.match_one(this.input[index], pat)) { + index += 1; + } else if (!optional) return null; + } + return new AsmMatch(this.input.slice(start_index, index), state.wildcard_items, state.symbolic_registers, state.symbolic_literals, state.symbolic_labels_def, this.asm_data); + } + derived_meta() { + for (const part of this.input.slice(this.index)) if (part instanceof Instruction) return part.meta.derived(); + return InstructionMeta.missing(); + } + is_local_label(name) { + return this.labels.has(name); + } + apply(repl, arch) { + const repl_writes = []; + let final_instr = null; + for (let part of repl.new_body) { + if (part instanceof AsmInstruction) part = arch.parse(part.mnemonic, part.args, this.derived_meta()); + if (part instanceof Instruction) { + repl_writes.push(...part.outputs); + repl_writes.push(...part.clobbers); + final_instr = part; + } + this.output.push(part); + } + if (repl.clobbers === null) { + for (const part of this.input.slice(this.index, this.index + repl.num_consumed)) { + if (part instanceof Instruction) { + for (const arg of [...part.outputs, ...part.clobbers]) { + pyassert(final_instr !== null); + if (!repl_writes.includes(arg) && !final_instr.clobbers.includes(arg)) final_instr.clobbers.push(arg); + } + } + } + } else if (repl.clobbers.length) { + pyassert(final_instr !== null); + final_instr.clobbers.push(...repl.clobbers); + } + this.index += repl.num_consumed; + } +} + +function label_names(body) { + const s = new Set(); + for (const item of body) if (item instanceof Label) for (const name of item.names) s.add(name); + return s; +} + +/** Detect and simplify asm standard patterns emitted by known compilers. */ +export function simplify_patterns(body, patterns, asm_data, arch, { debug_patterns }) { + let labels = label_names(body); + for (const pattern of patterns) { + const matcher = new AsmMatcher(arch, asm_data, body, labels); + let matched_any = false; + while (matcher.index < matcher.input.length) { + const m = pattern.match(matcher); + if (m) { + matcher.apply(m, arch); + matched_any = true; + } else { + matcher.output.push(matcher.input[matcher.index]); + matcher.index += 1; + } + } + if (!matched_any) continue; + body = matcher.output; + labels = label_names(body); + if (debug_patterns) { + print(`Rewrote asm using ${pattern.constructor.name}:`); + print(); + for (const part of body) print(String(part)); + print(); + } + } + return body; +} diff --git a/packages/romdev-m2c/src/c_types.js b/packages/romdev-m2c/src/c_types.js new file mode 100644 index 00000000..141b50a0 --- /dev/null +++ b/packages/romdev-m2c/src/c_types.js @@ -0,0 +1,759 @@ +// Port of m2c/c_types.py +// This file handles variable types, function signatures and struct layouts +// based on a C AST. Based on the pycparser library. +import fs from "node:fs"; +import { c_ast as ca, CGenerator, CParser, ParseError } from "romdev-pycparser"; +import { DecompFailure } from "./error.js"; +import { DefaultMap, ValueError, band, bnot, bor, bxor, count, deepcopy, floordiv, hex, int_, pyassert, pymod, rstrip, shl, shr } from "./py.js"; +import { print, popts } from "./io.js"; + +const { ArrayDecl, FuncDecl, IdentifierType, PtrDecl, TypeDecl } = ca; + +/** Arch-specific information needed to extract types from C. */ +export class ArchC {} +ArchC.prototype.base_struct_align = 1; + +export class StructField { + constructor(type, size, name) { + this.type = type; + this.size = size; + this.name = name; + } +} + +export class BitField { + constructor(width, name) { + this.width = width; + this.name = name; + } +} + +export class Struct { + constructor({ type, fields, bitfields, has_bitfields, size, align }) { + this.type = type; + this.fields = fields; // Map + this.bitfields = bitfields; // Map + this.has_bitfields = has_bitfields; + this.size = size; + this.align = align; + } +} + +export class Array_ { + constructor(subtype, subctype, subsize, dim) { + this.subtype = subtype; + this.subctype = subctype; + this.subsize = subsize; + this.dim = dim; + } +} + +export class Param { + constructor(type, name) { + this.type = type; + this.name = name; + } +} + +export class Function { + constructor({ type, ret_type, params, is_variadic }) { + this.type = type; + this.ret_type = ret_type; + this.params = params; + this.is_variadic = is_variadic; + } +} + +export class Enum { + constructor(tag, names) { + this.tag = tag; + this.names = names; // Map + } +} + +export class TypeMap { + static VERSION = 10; + constructor({ source_hash, base_struct_align, cparser_scope = null }) { + this.source_hash = source_hash; + this.base_struct_align = base_struct_align; + this.cparser_scope = cparser_scope; + this.typedefs = new Map(); // name -> [CType, align] + this.var_types = new Map(); + this.vars_with_initializers = new Set(); + this.functions = new Map(); + this.structs = new Map(); // str | ca.Struct/Union -> Struct + this.struct_typedefs = new Map(); + this.pragma_packs = new Map(); + this.enums = new Map(); + this.enum_values = new Map(); + } +} + +export function to_c(node) { + return new CGenerator().visit(node); +} + +export function basic_type(names) { + const idtype = new IdentifierType(names); + return new TypeDecl(null, [], [], idtype); +} + +export function pointer(type) { + return new PtrDecl([], type); +} + +export function get_align_override(decl, typemap) { + const aligns = []; + for (const attr of decl.gcc_attributes) { + if (attr.name === "packed") aligns.push(1); + if (attr.name === "aligned") { + let align_to; + if (!attr.args || !attr.args.length) align_to = 0x10; + else align_to = parse_constant_int(attr.args[0], typemap); + aligns.push(align_to); + } + } + if (decl instanceof ca.Decl) { + for (const alignas of decl.align) { + let align_to; + if (alignas.alignment instanceof ca.Typename) { + const [, tp_align] = parse_struct_member(alignas.alignment.type, "referenced in _Alignas", typemap, { allow_unsized: false }); + align_to = get_align_override(alignas.alignment, typemap) || tp_align; + } else align_to = parse_constant_int(alignas.alignment, typemap); + aligns.push(align_to); + } + } + let align = 0; + for (const align_to of aligns) { + if (align_to <= 0 || band(align_to, align_to - 1) !== 0) throw new DecompFailure(`Alignment ${align_to} is not a power of two`); + align = Math.max(align, align_to); + } + return align; +} + +export function has_128bit_attr(attrs) { + return attrs.some((attr) => attr.name === "mode" && attr.args && attr.args.length && attr.args[0] instanceof ca.ID && attr.args[0].name === "TI"); +} + +export function resolve_typedefs(type, typemap) { + if (type instanceof TypeDecl) { + if (type.type instanceof IdentifierType && type.type.names.length === 1 && typemap.typedefs.has(type.type.names[0])) { + const [t, align_override] = typemap.typedefs.get(type.type.names[0]); + const [t2, base_align_override] = resolve_typedefs(t, typemap); + return [t2, align_override || base_align_override]; + } + if (type.type instanceof ca.Typeof) { + const typeof_ = type.type; + if (typeof_.expr instanceof ca.Typename) { + return [typeof_.expr.type, get_align_override(typeof_.expr, typemap)]; + } else { + const expr = typeof_.expr; + if (expr instanceof ca.UnaryOp && expr.op === "sizeof") { + const size_t = new ca.IdentifierType(["unsigned", "int"]); + return [new TypeDecl(null, [], [], size_t), 0]; + } + throw new DecompFailure("typeof() is not supported"); + } + } + } + return [type, 0]; +} + +export function type_of_var_decl(decl) { + pyassert(!(decl.type instanceof ca.Struct || decl.type instanceof ca.Union || decl.type instanceof ca.Enum), "decls that declare variables have CType types"); + return decl.type; +} + +/** Get the CType of a global Decl, stripping names of function parameters. */ +export function type_from_global_decl(decl) { + const tp = type_of_var_decl(decl); + if (!(tp instanceof ca.FuncDecl) || !tp.args) return tp; + const anonymize_param = (param) => { + param = deepcopy(param); + param.name = null; + set_decl_name(param); + return new ca.Typename(null, param.quals, null, [], type_of_var_decl(param)); + }; + const new_params = tp.args.params.map((param) => (param instanceof ca.Decl ? anonymize_param(param) : param)); + return new ca.FuncDecl(new ca.ParamList(new_params), tp.type); +} + +function namesEq(names, arr) { + return names.length === arr.length && names.every((n, i) => n === arr[i]); +} + +export function is_void(type) { + return type instanceof ca.TypeDecl && type.type instanceof ca.IdentifierType && namesEq(type.type.names, ["void"]); +} + +export function primitive_size(type) { + if (type instanceof ca.Enum) return 4; + const names = type.names; + if (names.includes("double")) return 8; + if (names.includes("float")) return 4; + if (names.includes("__int128")) return 16; + if (names.includes("short")) return 2; + if (names.includes("char")) return 1; + if (names.includes("void")) return 0; + if (names.filter((n) => n === "long").length === 2) return 8; + return 4; +} + +/** Returns [start, stop] (Python range) or null. */ +export function primitive_range(type) { + let bits = 8 * primitive_size(type); + let signed = true; + if (!(type instanceof ca.Enum)) { + const names = type.names; + if (names.includes("double") || names.includes("float") || names.includes("void")) return null; + if (names.includes("unsigned")) signed = false; + } + if (signed) { + bits -= 1; + return [-(2 ** bits), 2 ** bits]; + } + return [0, 2 ** bits]; +} + +/** Return true if `type` represents an unknown type, or undetermined struct padding. */ +export function is_unk_type(type, typemap) { + if (type instanceof ArrayDecl && type.type instanceof TypeDecl && type.type.type instanceof IdentifierType && type.type.declname !== null && type.type.declname !== undefined && namesEq(type.type.type.names, ["char"])) { + const declname = type.type.declname; + if (declname.startsWith("unk_") || declname.startsWith("pad")) return true; + } + for (;;) { + if (type instanceof TypeDecl && type.type instanceof IdentifierType && type.type.names.length === 1 && typemap.typedefs.has(type.type.names[0])) { + const type_name = type.type.names[0]; + if (type_name.startsWith("UNK_") || type_name.startsWith("M2C_UNK")) return true; + type = typemap.typedefs.get(type_name)[0]; + } else if (type instanceof PtrDecl || type instanceof ArrayDecl) type = type.type; + else return false; + } +} + +export function parse_function(fn) { + if (!(fn instanceof FuncDecl)) return null; + const params = []; + let is_variadic = false; + let has_void = false; + if (fn.args) { + for (const arg of fn.args.params) { + if (arg instanceof ca.EllipsisParam) is_variadic = true; + else if (arg instanceof ca.Decl) params.push(new Param(type_of_var_decl(arg), arg.name)); + else if (arg instanceof ca.ID) throw new DecompFailure("K&R-style function header is not supported: " + to_c(fn)); + else { + pyassert(arg instanceof ca.Typename); + if (is_void(arg.type)) has_void = true; + else params.push(new Param(arg.type, null)); + } + } + } + let maybe_params = params; + if (!params.length && !has_void && !is_variadic) maybe_params = null; + const ret_type = is_void(fn.type) ? null : fn.type; + return new Function({ type: fn, ret_type, params: maybe_params, is_variadic }); +} + +export function divmod_towards_zero(lhs, rhs, op) { + if (rhs < 0) { + rhs = -rhs; + lhs = -lhs; + } + if (lhs < 0) return -divmod_towards_zero(-lhs, rhs, op); + if (op === "/") return floordiv(lhs, rhs); + return pymod(lhs, rhs); +} + +export function parse_constant_int(expr, typemap) { + if (expr instanceof ca.Constant) { + try { + return int_(rstrip(expr.value, "lLuU"), 0); + } catch (e) { + if (e instanceof ValueError) throw new DecompFailure(`Failed to parse ${to_c(expr)} as an int literal`); + throw e; + } + } + if (expr instanceof ca.ID) { + if (typemap.enum_values.has(expr.name)) return typemap.enum_values.get(expr.name); + } + if (expr instanceof ca.BinaryOp) { + const op = expr.op; + const lhs = parse_constant_int(expr.left, typemap); + if (op === "&&" && lhs === 0) return 0; + if (op === "||" && lhs !== 0) return 1; + const rhs = parse_constant_int(expr.right, typemap); + if (op === "+") return lhs + rhs; + if (op === "-") return lhs - rhs; + if (op === "*") return lhs * rhs; + if (op === "<<") return shl(lhs, rhs); + if (op === ">>") return shr(lhs, rhs); + if (op === "&") return band(lhs, rhs); + if (op === "|") return bor(lhs, rhs); + if (op === "^") return bxor(lhs, rhs); + if (op === ">=") return lhs >= rhs ? 1 : 0; + if (op === "<=") return lhs <= rhs ? 1 : 0; + if (op === ">") return lhs > rhs ? 1 : 0; + if (op === "<") return lhs < rhs ? 1 : 0; + if (op === "==") return lhs === rhs ? 1 : 0; + if (op === "!=") return lhs !== rhs ? 1 : 0; + if (op === "&&" || op === "||") return rhs !== 0 ? 1 : 0; + if (op === "/" || op === "%") { + if (rhs === 0) throw new DecompFailure(`Division by zero when evaluating expression ${to_c(expr)}`); + return divmod_towards_zero(lhs, rhs, op); + } + } + if (expr instanceof ca.TernaryOp) { + const cond = parse_constant_int(expr.cond, typemap) !== 0; + return parse_constant_int(cond ? expr.iftrue : expr.iffalse, typemap); + } + if (expr instanceof ca.ExprList) { + const last_expr = expr.exprs[expr.exprs.length - 1]; + if (!(last_expr instanceof ca.Typename)) return parse_constant_int(last_expr, typemap); + } + if (expr instanceof ca.UnaryOp && !(expr.expr instanceof ca.Typename)) { + const sub = parse_constant_int(expr.expr, typemap); + if (expr.op === "+") return sub; + if (expr.op === "-") return -sub; + if (expr.op === "~") return bnot(sub); + if (expr.op === "!") return sub === 0 ? 1 : 1; + } + if (expr instanceof ca.UnaryOp && expr.expr instanceof ca.Typename) { + const [size, align] = parse_struct_member(expr.expr.type, `referenced in ${expr.op}`, typemap, { allow_unsized: false }); + if (expr.op === "sizeof") return size; + if (expr.op === "_Alignof") return get_align_override(expr.expr, typemap) || align; + } + if (expr instanceof ca.Cast) { + const value = parse_constant_int(expr.expr, typemap); + const [type] = resolve_typedefs(expr.to_type.type, typemap); + if (type instanceof ca.TypeDecl && (type.type instanceof ca.Enum || type.type instanceof ca.IdentifierType)) { + const rng = primitive_range(type.type); + if (rng !== null) { + const [start, stop] = rng; + const width = stop - start; + if (Number.isSafeInteger(width) && Number.isSafeInteger(value - start)) return start + pymod(value - start, width); + return Number(BigInt(start) + (((BigInt(value) - BigInt(start)) % BigInt(width)) + BigInt(width)) % BigInt(width)); + } + } + } + throw new DecompFailure(`Failed to evaluate expression ${to_c(expr)} at compile time; only simple arithmetic is supported for now`); +} + +/** Parse an enum and compute the values of all its enumerators. */ +export function parse_enum(enum_, typemap) { + if (enum_.values === null || enum_.values === undefined) return; + const typemap_enum = new Enum(enum_.name, new Map()); + typemap.enums.set(enum_, typemap_enum); + if (enum_.name !== null && enum_.name !== undefined && !typemap.enums.has(enum_.name)) typemap.enums.set(enum_.name, typemap_enum); + let next_value = 0; + for (const enumerator of enum_.values.enumerators) { + let value; + if (enumerator.value) value = parse_constant_int(enumerator.value, typemap); + else value = next_value; + next_value = value + 1; + typemap.enum_values.set(enumerator.name, value); + typemap_enum.names.set(value, enumerator.name); + } +} + +export function get_struct(struct, typemap) { + if (struct.name) return typemap.structs.get(struct.name) ?? null; + return typemap.structs.get(struct) ?? null; +} + +export class UndefinedStructError extends DecompFailure { + constructor(message) { + super(message); + this.name = "UndefinedStructError"; + } +} + +export function parse_struct(struct, typemap) { + const existing = get_struct(struct, typemap); + if (existing) return existing; + if (struct.decls === null || struct.decls === undefined) { + throw new UndefinedStructError(`Tried to use struct ${struct.name ?? "None"} before it is defined (does it have a definition?).`); + } + const ret = do_parse_struct(struct, typemap); + if (struct.name) typemap.structs.set(struct.name, ret); + typemap.structs.set(struct, ret); + return ret; +} + +/** Returns [size, align, DetailedStructMember]. */ +export function parse_struct_member(type, field_name, typemap, { allow_unsized }) { + let align_override; + [type, align_override] = resolve_typedefs(type, typemap); + if (type instanceof PtrDecl) return [4, align_override || 4, null]; + if (type instanceof ArrayDecl) { + let dim; + if (type.dim !== null && type.dim !== undefined) dim = parse_constant_int(type.dim, typemap); + else dim = 1; + const [size, align, substr] = parse_struct_member(type.type, field_name, typemap, { allow_unsized: false }); + return [size * dim, align_override || align, new Array_(substr, type.type, size, dim)]; + } + if (type instanceof FuncDecl) { + pyassert(allow_unsized, "Struct can not contain a function"); + return [0, 0, null]; + } + const inner_type = type.type; + if (inner_type instanceof ca.Struct || inner_type instanceof ca.Union) { + const substr = parse_struct(inner_type, typemap); + return [substr.size, align_override || substr.align, substr]; + } + if (inner_type instanceof ca.Enum) parse_enum(inner_type, typemap); + pyassert(!(inner_type instanceof ca.Typeof), "handled by resolve_typedefs"); + const size = primitive_size(inner_type); + if (size === 0 && !allow_unsized) throw new DecompFailure(`Field ${field_name} cannot be void`); + return [size, align_override || size, null]; +} + +function do_parse_struct(struct, typemap) { + const is_union = struct instanceof ca.Union; + pyassert(struct.decls !== null && struct.decls !== undefined, "enforced by caller"); + + const fields = new DefaultMap(() => []); + const bitfields = new DefaultMap(() => []); + let union_size = 0; + let offset = 0; + let bit_offset = 0; + let has_bitfields = false; + let align = get_align_override(struct, typemap) || typemap.base_struct_align; + const pack_struct = struct.gcc_attributes.some((attr) => attr.name === "packed"); + const pragma_pack = typemap.pragma_packs.get(struct) ?? 0; + + const flush_bitfields = () => { + if (!is_union && bit_offset !== 0) { + bit_offset = 0; + offset += 1; + } + }; + + for (const decl of struct.decls) { + if (is_union) pyassert(offset === 0); + if (!(decl instanceof ca.Decl)) continue; + + let pack_decl; + if (pack_struct || decl.gcc_attributes.some((attr) => attr.name === "packed")) pack_decl = get_align_override(decl, typemap) || 1; + else pack_decl = 0; + if (pragma_pack && (!pack_decl || pack_decl > pragma_pack)) pack_decl = pragma_pack; + + const type = decl.type; + if (type instanceof ca.Struct || type instanceof ca.Union) { + if (type.decls === null || type.decls === undefined) continue; + const substruct = parse_struct(type, typemap); + const subalign = pack_decl || get_align_override(decl, typemap) || substruct.align; + if (type.name !== null && type.name !== undefined) { + // Struct defined within another; parse_struct already registered it. + } else { + flush_bitfields(); + align = Math.max(align, subalign); + offset = band(offset + subalign - 1, -subalign); + for (const [off, sfields] of substruct.fields) for (const field of sfields) fields.get(offset + off).push(field); + if (is_union) union_size = Math.max(union_size, substruct.size); + else offset += substruct.size; + } + continue; + } + + if (type instanceof ca.Enum) { + parse_enum(type, typemap); + continue; + } + + const field_name = `${struct.name ?? "None"}.${decl.name ?? "None"}`; + if (decl.bitsize !== null && decl.bitsize !== undefined) { + has_bitfields = true; + const width = parse_constant_int(decl.bitsize, typemap); + const [ssize, salign, substr] = parse_struct_member(type, field_name, typemap, { allow_unsized: false }); + if (ssize !== salign || substr !== null) throw new DecompFailure(`Bitfield ${field_name} is not of primitive type`); + if (get_align_override(decl, typemap)) throw new DecompFailure(`Alignment directive not supported for bitfield ${field_name}`); + align = Math.max(align, salign); + if (width === 0) continue; + if (width > ssize * 8) throw new DecompFailure(`Width of bitfield ${field_name} exceeds its type`); + if (floordiv(offset, ssize) !== floordiv(offset + floordiv(bit_offset + width - 1, 8), ssize) && !pack_decl) { + bit_offset = 0; + offset = band(offset + ssize, -ssize); + } + if (decl.name !== null && decl.name !== undefined) bitfields.get(offset * 8 + bit_offset).push(new BitField(width, decl.name)); + if (is_union) union_size = Math.max(union_size, ssize); + else { + bit_offset += width; + offset += floordiv(bit_offset, 8); + bit_offset &= 7; + } + continue; + } + + if (decl.name === null || decl.name === undefined) continue; + + flush_bitfields(); + let [ssize, salign] = parse_struct_member(type, field_name, typemap, { allow_unsized: false }); + salign = pack_decl || Math.max(salign, get_align_override(decl, typemap)); + align = Math.max(align, salign); + offset = band(offset + salign - 1, -salign); + fields.get(offset).push(new StructField(type, ssize, decl.name)); + if (is_union) union_size = Math.max(union_size, ssize); + else offset += ssize; + } + + flush_bitfields(); + + let ctype; + if (typemap.struct_typedefs.has(struct)) ctype = typemap.struct_typedefs.get(struct); + else if (struct.name && typemap.struct_typedefs.has(struct.name)) ctype = typemap.struct_typedefs.get(struct.name); + else ctype = new TypeDecl(null, [], [], struct); + + let size = is_union ? union_size : offset; + size = band(size + align - 1, -align); + return new Struct({ type: ctype, fields: new Map(fields), bitfields: new Map(bitfields), has_bitfields, size, align }); +} + +/** Add built-in typedefs to the source code. */ +export function add_builtin_typedefs(source) { + const typedefs = { + u8: "unsigned char", + s8: "char", + u16: "unsigned short", + s16: "short", + u32: "unsigned int", + s32: "int", + u64: "unsigned long long", + s64: "long long", + f32: "float", + f64: "double", + }; + const line = Object.entries(typedefs) + .map(([k, v]) => `typedef ${v} ${k};`) + .join(" "); + return line + "\n" + source; +} + +export function strip_comments(text) { + const pattern = /\/\/.*?$|\/\*[\s\S]*?\*\/|'(?:\\[\s\S]|[^\\'])*'|"(?:\\[\s\S]|[^\\"])*"/gm; + return text.replace(pattern, (s) => (s.startsWith("/") ? " " + "\n".repeat(count(s, "\n")) : s)); +} + +export function process_ifdef(text) { + const pattern = /^[ \t]*#if(?n?)def[ \t]+M2C\s+(?[\s\S]*?)(?:^[ \t]*#else\s+(?[\s\S]*?))?^[ \t]*#endif[\s\S]*?$/gm; + return text.replace(pattern, (...args) => { + const groups = args[args.length - 1]; + const whole = args[0]; + let ret; + if (groups.neg === "n") ret = groups.else_body || ""; + else ret = groups.if_body; + return ret + "\n".repeat(Math.max(0, count(whole, "\n") - count(ret, "\n"))); + }); +} + +/** Strip macro definitions from C source (m2c does not run the preprocessor). */ +export function strip_macro_defs(text) { + const pattern = /^[ \t]*#[ \t]*(?:define|undef)[ \t](\\\n|.)*/gm; + return text.replace(pattern, (m) => "\n".repeat(count(m, "\n"))); +} + +export function remove_backslashes_at_eol(text) { + const string_pat = /'(?:\\[\s\S]|[^\\'])*'?|"(?:\\[\s\S]|[^\\"])*"?/g; + let continued_string_start_ind = -1; + let continued_string_delim = ""; + return text.replace(/\\\n/gm, (match, ind) => { + const line_start = text.lastIndexOf("\n", ind - 1) + 1; + let prev_line = text.slice(line_start, ind); + if (line_start === continued_string_start_ind) prev_line = continued_string_delim + prev_line; + const strings = (prev_line + "$").match(string_pat) ?? []; + if (strings.length && strings[strings.length - 1].endsWith("$")) { + const delim = strings[strings.length - 1][0]; + continued_string_start_ind = ind + 2; + continued_string_delim = delim; + if (delim === "'") return ""; + return delim + "\n" + delim; + } + continued_string_start_ind = -1; + return "\n"; + }); +} + +export function parse_c(source, initial_scope) { + const c_parser = new CParser(); + c_parser.clex.filename = ""; + c_parser.clex.reset_lineno(); + if (initial_scope !== null) c_parser._scope_stack = [new Map(initial_scope)]; + c_parser._last_yielded_token = null; + let ast; + try { + ast = c_parser.cparser.parse(source, c_parser.clex); + } catch (e) { + if (e instanceof ParseError) { + let msg = String(e.message); + const coord = e.coord; + const i = msg.indexOf(": "); + msg = msg.slice(i + 2); + let posstr; + if (typeof coord === "string") posstr = " " + coord[0].toLowerCase() + coord.slice(1); + else { + const src = coord.source_line(); + posstr = ` at line ${coord.line - 1}, column ${coord.column}\n\n${src}`; + } + throw new DecompFailure(`Syntax error when parsing C context.\n${msg}${posstr}`); + } + throw e; + } + return [ast, new Map(c_parser._scope_stack[0])]; +} + +/** + * Build the TypeMap for the given context files. + * + * Upstream has two caches, and neither changes the output, so the port parses + * every time (`--no-cache` / use_cache is accepted and ignored): + * - an lru_cache on _build_typemap keyed by (paths, arch object, use_cache). + * main.run() makes a fresh arch object per run, so it never hits across runs. + * - a pickle of the finished TypeMap beside each context ("foo.c.m2c"), reused + * when sha256(parent hash + source) matches. A hit returns the same TypeMap a + * fresh parse builds (object identity inside it is preserved by pickle), and + * upstream's own test runner relies on this: it runs the gba cases with + * --no-cache and the rest with the cache, against the same expected outputs, + * all of which the port reproduces without a cache. The one observable side + * effect, a "Warning: Unable to write cache file" line when the context's + * directory is read-only, exists only because of the file write, so it is not + * reproduced. Parsing a 160 KB decomp context takes about 0.15 s in the port, + * and Python's .m2c pickles cannot be read from JS anyway. + */ +export function build_typemap(source_paths, arch, use_cache) { + void use_cache; + const sources = source_paths.map((p) => fs.readFileSync(p, "utf8")); + return _build_typemap(source_paths, sources, arch); +} + +function _build_typemap(source_paths, sources, arch) { + const typemap = new TypeMap({ source_hash: `root:${TypeMap.VERSION},${arch.base_struct_align}`, base_struct_align: arch.base_struct_align }); + + for (let source of sources) { + if (source.charCodeAt(0) === 0xfeff) source = source.slice(1); + source = source.replace(/\r\n?/g, "\n"); + source = add_builtin_typedefs(source); + source = strip_comments(source); + source = process_ifdef(source); + source = strip_macro_defs(source); + source = remove_backslashes_at_eol(source); + + const [ast, result_scope] = parse_c(source, typemap.cparser_scope); + typemap.cparser_scope = result_scope; + + for (const item of ast.ext) { + if (item instanceof ca.Typedef) { + let [target, align] = resolve_typedefs(item.type, typemap); + align = get_align_override(item, typemap) || align; + if (has_128bit_attr(item.gcc_attributes) && target instanceof TypeDecl && target.type instanceof ca.IdentifierType) { + const sign = target.type.names.includes("unsigned") ? ["unsigned"] : []; + target = basic_type([...sign, "__int128"]); + } + typemap.typedefs.set(item.name, [target, align]); + if (item.type instanceof TypeDecl && (item.type.type instanceof ca.Struct || item.type.type instanceof ca.Union) && !get_align_override(item, typemap)) { + const typedef = basic_type([item.name]); + if (item.type.type.name) typemap.struct_typedefs.set(item.type.type.name, typedef); + typemap.struct_typedefs.set(item.type.type, typedef); + } + } + if (item instanceof ca.FuncDef) { + pyassert(item.decl.name !== null && item.decl.name !== undefined, "cannot define anonymous function"); + const fn = parse_function(type_of_var_decl(item.decl)); + pyassert(fn !== null); + typemap.functions.set(item.decl.name, fn); + } + if (item instanceof ca.Decl && item.type instanceof FuncDecl) { + pyassert(item.name !== null && item.name !== undefined, "cannot define anonymous function"); + const fn = parse_function(item.type); + pyassert(fn !== null); + typemap.functions.set(item.name, fn); + } + } + + let cur_pack = 0; + const pack_stack = []; + + class Visitor extends ca.NodeVisitor { + visit_Pragma(node) { + const parts = node.string.split("("); + if (parts.length >= 2 && parts[0].trim() === "pack") { + const args = parts[1].split(")")[0].split(","); + const arg = args[0].trim(); + if (!arg) cur_pack = 0; + else if (args[0].trim() === "pop") { + if (!pack_stack.length) throw new Error("IndexError: pop from empty list"); + cur_pack = pack_stack.pop(); + } else if (args[0].trim() === "push") { + pack_stack.push(cur_pack); + if (args.length >= 2) cur_pack = int_(args[1], 0); + } else cur_pack = int_(args[0], 0); + } + } + visit_Struct(node) { + if (cur_pack) typemap.pragma_packs.set(node, cur_pack); + if (node.decls !== null && node.decls !== undefined) parse_struct(node, typemap); + } + visit_Union(node) { + if (cur_pack) typemap.pragma_packs.set(node, cur_pack); + if (node.decls !== null && node.decls !== undefined) parse_struct(node, typemap); + } + visit_Decl(node) { + if (node.name !== null && node.name !== undefined) { + typemap.var_types.set(node.name, type_from_global_decl(node)); + if (node.init !== null && node.init !== undefined) typemap.vars_with_initializers.add(node.name); + } + if (!(node.type instanceof FuncDecl)) this.visit(node.type); + } + visit_Enum(node) { + parse_enum(node, typemap); + } + visit_FuncDef(node) { + if (node.decl.name !== null && node.decl.name !== undefined) typemap.var_types.set(node.decl.name, type_from_global_decl(node.decl)); + } + } + new Visitor().visit(ast); + } + void source_paths; + return typemap; +} + +export function set_decl_name(decl) { + const name = decl.name; + let type = type_of_var_decl(decl); + while (!(type instanceof TypeDecl)) type = type.type; + type.declname = name; +} + +export function type_to_string(type, name = "") { + if (type instanceof TypeDecl && (type.type instanceof ca.Struct || type.type instanceof ca.Union || type.type instanceof ca.Enum)) { + let su; + if (type.type instanceof ca.Struct) su = "struct"; + else su = type.type instanceof ca.Union ? "union" : "enum"; + if (type.type.name) return `${su} ${type.type.name}`; + return `anon ${su}`; + } + const decl = new ca.Decl(name, [], [], [], [], [], deepcopy(type), null, null, null); + set_decl_name(decl); + return to_c(decl); +} + +export function dump_typemap(typemap) { + print("Variables:"); + for (const [v, type] of typemap.var_types) print(`${type_to_string(type, v)};`); + print(); + print("Functions:"); + for (const [name, fn] of typemap.functions) print(`${type_to_string(fn.type, name)};`); + print(); + print("Structs:"); + for (const [name_or_id, struct] of typemap.structs) { + if (typeof name_or_id !== "string") continue; + print(`${name_or_id}: size ${hex(struct.size)}, align ${struct.align}`); + for (const [offset, fields] of struct.fields) { + print(` ${hex(offset)}:`, popts({ end: "" })); + for (const field of fields) print(` ${field.name} (${type_to_string(field.type)})`, popts({ end: "" })); + print(); + } + } + print(); + print("Enums:"); + for (const [name, value] of typemap.enum_values) print(`${name}: ${value}`); + print(); +} diff --git a/packages/romdev-m2c/src/cli.js b/packages/romdev-m2c/src/cli.js new file mode 100755 index 00000000..b77c7459 --- /dev/null +++ b/packages/romdev-m2c/src/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node +// Command-line entry point taking the same flags as upstream m2c's CLI. +import { decompile } from "./main.js"; + +const r = await decompile(process.argv.slice(2)); +process.stdout.write(r.stdout); +process.stderr.write(r.stderr); +process.exitCode = r.code; diff --git a/packages/romdev-m2c/src/demangle_codewarrior.js b/packages/romdev-m2c/src/demangle_codewarrior.js new file mode 100644 index 00000000..c310dbad --- /dev/null +++ b/packages/romdev-m2c/src/demangle_codewarrior.js @@ -0,0 +1,525 @@ +// demangle_codewarrior.js - CodeWarrior C++ symbol demangler (port of +// m2c/demangle_codewarrior.py), supporting operators, templates (including +// literals), and arrays. +// +// CodeWarrior's symbol mangling and C++ ABI seems to be based on the +// Macintosh spec, section 3.4.1.2 (page 18) of +// https://mirror.informatimago.com/next/developer.apple.com/tools/mpw-tools/compilers/docs/abi_spec.pdf +// It deviates from this spec in a few key ways: +// - The in is an unterminated (no '_' separator) +// - Parameterized types use '<', ',' and '>' characters instead of the "__PT" prefix +// +// Like the rest of m2c this file is licensed under the GPL v3. It is based on +// `demangler.cs` by arookas, provided under the 3-clause BSD License: +// https://gist.github.com/arookas/0c0cd842c9ca836d7a9ed06a655b1a22 +// +// Copyright (c) 2017, arookas +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import { ValueError, pyassert, repr } from "./py.js"; + +// These substitutions are performed by the doldisasm.py decomp tool, and not by +// the CodeWarrior compiler directly. Undo them for convience. +const DOLDISASM_SUBSTITUTIONS = [ + ["<", "$$0"], + [">", "$$1"], + ["@", "$$2"], + ["\\", "$$3"], + [",", "$$4"], + ["-", "$$5"], +]; + +/** Minimal io.StringIO: read(n), tell(), seek(pos). */ +class StringIO { + constructor(s) { + this.s = s; + this.pos = 0; + } + read(n = -1) { + const start = this.pos; + const end = n < 0 ? this.s.length : Math.min(this.s.length, start + n); + this.pos = end; + return this.s.slice(start, end); + } + tell() { + return this.pos; + } + seek(p) { + this.pos = p; + } +} + +/** Read exactly `size` chars from `src`, or raise a ValueError. */ +function read_exact(src, size) { + const value = src.read(size); + if (value.length !== size) throw new ValueError(`Unable to read ${size} bytes; got ${repr(value)}`); + return value; +} + +/** Run fn, restoring the offset of `src` afterwards. */ +function peeking(src, fn) { + const ptr = src.tell(); + try { + return fn(); + } finally { + src.seek(ptr); + } +} + +/** Read up to `n` chars from `src` without advancing the offset. */ +function peek(src, n = 1) { + return peeking(src, () => src.read(n)); +} + +/** Wrap `s` in a StringIO for fn, and assert it was fully consumed after fn returns. */ +function as_stringio(s, fn) { + const buf = new StringIO(s); + const result = fn(buf); + const leftover = buf.read(); + if (leftover) throw new ValueError(`Unable to parse full input, leftover chars: ${repr(leftover)}`); + return result; +} + +// Python int(str) for base 10 (optional sign, digits); ValueError otherwise. +function pyInt(s) { + const t = s.trim(); + if (!/^[+-]?[0-9]+(_[0-9]+)*$/.test(t)) throw new ValueError(`invalid literal for int() with base 10: ${repr(s)}`); + return parseInt(t.replaceAll("_", ""), 10); +} + +/** + * The name of a C++ symbol, class, or namespace, optionally parameterized + * with `template_params`. + */ +export class CxxName { + constructor(name, template_params = null) { + this.name = name; + this.template_params = template_params; + } + static parse(src) { + // Numbers: either a template literal, or a length prefix + let number_str = ""; + while (CxxName.NUMBER_CHARS.has(peek(src))) number_str += read_exact(src, 1); + if (number_str === "") throw new ValueError("Unable to parse CxxName, input did not start with a number"); + const number = pyInt(number_str); + + // Check if the number represents a template literal + const p = peek(src); + if (p === "," || p === ">") return new CxxName(number_str); + + // Otherwise, it is the length of the name + if (number <= 0) throw new ValueError("length must be positive"); + const name = read_exact(src, number); + + // Simple case: plain identifier + if (!name.includes("<")) return new CxxName(name); + + // Otherwise, parse the template parameters between the `<...>` brackets + if (name[name.length - 1] !== ">") throw new ValueError("unpaired '<'"); + const idx = name.indexOf("<"); + const base_name = name.slice(0, idx); + const param_strs = name.slice(idx + 1); + + const template_params = as_stringio(param_strs, (buf) => { + const params = []; + for (;;) { + params.push(CxxType.parse(buf)); + const sep = read_exact(buf, 1); + if (sep === ">") break; + if (sep === ",") continue; + throw new ValueError(`Unexpected character while parsing CxxName: ${sep}`); + } + return params; + }); + return new CxxName(base_name, template_params); + } + __str__() { + if (this.template_params === null) return this.name; + return `${this.name}<${this.template_params.map((p) => p.__str__()).join(", ")}>`; + } + toString() { + return this.__str__(); + } +} +CxxName.NUMBER_CHARS = new Set("-0123456789"); + +const KIND_VALUES = { + CONST: "C", + POINTER: "P", + REFERENCE: "R", + SIGNED: "S", + UNSIGNED: "U", + ELLIPSIS: "e", + VOID: "v", + BOOL: "b", + CHAR: "c", + SHORT: "s", + INT: "i", + LONG: "l", + LONG_LONG: "x", + WIDE_CHAR: "w", + FLOAT: "f", + DOUBLE: "d", + LONG_DOUBLE: "r", + ARRAY: "A", + QUALIFIED: "Q", + FUNCTION: "F", + SYMBOL_REFERENCE: "&", +}; + +/** CxxTerm.Kind: an Enum whose members have .name and .value. */ +class Kind { + constructor(name, value) { + this.name = name; + this.value = value; + } + /** Kind(value) lookup, raising ValueError for an unknown value like Python's Enum. */ + static of(value) { + const k = Kind.byValue.get(value); + if (!k) throw new ValueError(`${repr(value)} is not a valid Kind`); + return k; + } +} +Kind.byValue = new Map(); +for (const [name, value] of Object.entries(KIND_VALUES)) { + const k = new Kind(name, value); + Kind[name] = k; + Kind.byValue.set(value, k); +} + +/** + * A part of a C++ type, like a token: usually a single letter of a mangled + * type, or an ARRAY / FUNCTION / QUALIFIED name / SYMBOL_REFERENCE. + */ +export class CxxTerm { + constructor(kind, { array_dim = null, function_params = null, function_return = null, qualified_name = null, symbol_reference = null } = {}) { + this.kind = kind; + this.array_dim = array_dim; + this.function_params = function_params; + this.function_return = function_return; + this.qualified_name = qualified_name; + this.symbol_reference = symbol_reference; + } + static parse(src) { + if (CxxName.NUMBER_CHARS.has(peek(src))) { + return new CxxTerm(Kind.QUALIFIED, { qualified_name: [CxxName.parse(src)] }); + } + const kind = Kind.of(read_exact(src, 1)); + if (kind === Kind.QUALIFIED) { + const count = pyInt(read_exact(src, 1)); + const qualified_name = []; + for (let i = 0; i < count; i++) qualified_name.push(CxxName.parse(src)); + return new CxxTerm(kind, { qualified_name }); + } + if (kind === Kind.FUNCTION) { + const function_params = []; + let function_return = null; + while (!["", "_", ",", ">"].includes(peek(src))) function_params.push(CxxType.parse(src)); + if (peek(src, 1) === "_") { + read_exact(src, 1); + function_return = CxxType.parse(src); + } + return new CxxTerm(kind, { function_params, function_return }); + } + if (kind === Kind.ARRAY) { + let array_dim = 0; + for (;;) { + const c = read_exact(src, 1); + if (c === "_") break; + array_dim = array_dim * 10 + pyInt(c); + } + return new CxxTerm(kind, { array_dim }); + } + if (kind === Kind.SYMBOL_REFERENCE) { + return new CxxTerm(kind, { symbol_reference: CxxSymbol.parse(src) }); + } + return new CxxTerm(kind); + } + __str__() { + if (this.kind === Kind.ARRAY) { + pyassert(this.array_dim !== null); + return `[${this.array_dim}]`; + } + if (this.kind === Kind.QUALIFIED) { + pyassert(this.qualified_name !== null); + const names = this.qualified_name.map((q) => q.__str__()); + const last = names[names.length - 1]; + if (Object.prototype.hasOwnProperty.call(CxxTerm.OPS, last)) { + names[names.length - 1] = "operator" + CxxTerm.OPS[last]; + } else if (last === "__ct") { + pyassert(names.length >= 2); + names[names.length - 1] = names[names.length - 2]; + } else if (last === "__dt") { + pyassert(names.length >= 2); + names[names.length - 1] = `~${names[names.length - 2]}`; + } + return names.join("::"); + } + if (this.kind === Kind.FUNCTION) { + pyassert(this.function_params !== null); + let prefix = ""; + if (this.function_return !== null) prefix = `${this.function_return.__str__()} (*) `; + const args = this.function_params.map((p) => p.__str__()).join(", "); + return `${prefix}(${args})`; + } + if (this.kind === Kind.SYMBOL_REFERENCE) { + pyassert(this.symbol_reference !== null); + return `&${this.symbol_reference.__str__()}`; + } + if (this.kind === Kind.POINTER) return "*"; + if (this.kind === Kind.REFERENCE) return "&"; + if (this.kind === Kind.LONG_LONG) return "long long"; + if (this.kind === Kind.LONG_DOUBLE) return "long double"; + if (this.kind === Kind.WIDE_CHAR) return "wchar_t"; + if (this.kind === Kind.ELLIPSIS) return "..."; + return this.kind.name.toLowerCase(); + } + toString() { + return this.__str__(); + } +} +CxxTerm.Kind = Kind; +CxxTerm.NONTERMINATING_KINDS = new Set([Kind.CONST, Kind.POINTER, Kind.REFERENCE, Kind.SIGNED, Kind.UNSIGNED, Kind.ARRAY]); +CxxTerm.OPS = { + __nw: " new", + __nwa: " new[]", + __dl: " delete", + __dla: " delete[]", + __pl: "+", + __mi: "-", + __ml: "*", + __dv: "/", + __md: "%", + __er: "^", + __adv: "/=", + __ad: "&", + __or: "|", + __co: "~", + __nt: "!", + __as: "=", + __lt: "<", + __gt: ">", + __apl: "+=", + __ami: "-=", + __amu: "*=", + __amd: "%=", + __aer: "^=", + __aad: "&=", + __aor: "|=", + __ls: "<<", + __rs: ">>", + __ars: ">>=", + __als: "<<=", + __eq: "==", + __ne: "!=", + __le: "<=", + __ge: ">=", + __aa: "&&", + __oo: "||", + __pp: "++", + __mm: "--", + __cl: "()", + __vc: "[]", + __rf: "->", + __cm: ",", + __rm: "->*", +}; + +/** + * A complete C++ type. The final element in `terms` is the primitive type; + * working from the end, each previous term modifies the type. + */ +export class CxxType { + constructor(terms = []) { + this.terms = terms; + } + static parse(src) { + const terms = []; + for (;;) { + const p = peek(src); + if (p === "," || p === ">") break; + const term = CxxTerm.parse(src); + terms.push(term); + if (!CxxTerm.NONTERMINATING_KINDS.has(term.kind)) break; + } + return new CxxType(terms); + } + __str__() { + return this.terms.slice().reverse().map((a) => a.__str__()).join(" ").trim(); + } + toString() { + return this.__str__(); + } +} + +/** A C++ symbol and its type. */ +export class CxxSymbol { + constructor(name, type) { + this.name = name; + this.type = type; + } + static parse(src) { + // Find the `base_name`: the prefix of `src` which usually represents the + // original, unmangled name, typically separated from the type information + // by the rightmost "__" (with many edge cases). + let strip_underscores = 0; + let template_depth = 0; + let base_name = peeking(src, () => src.read()); + peeking(src, () => { + let chars = ""; + for (;;) { + const c = src.read(1); + if (!c) break; + if ((c === "," || c === ">") && template_depth === 0) { + if (strip_underscores === 0) base_name = chars; + break; + } else if (c === "<") { + template_depth += 1; + } else if (c === ">") { + template_depth -= 1; + } + chars += c; + if (CxxSymbol.STATIC_FUNCTIONS.has(chars)) { + base_name = chars; + strip_underscores = 1; + break; + } else if (c === "_" && peek(src) === "_") { + const lookahead = peek(src, 2); + if (lookahead.length < 2 || "CFQ0123456789".includes(lookahead[1])) { + base_name = chars.slice(0, -1); + strip_underscores = 2; + } + } + } + }); + + read_exact(src, base_name.length + strip_underscores); + + if (CxxSymbol.STATIC_FUNCTIONS.has(base_name)) { + // `__sinit_Foo_cpp` is the static constructor for "Foo.cpp": + // "demangle" it into `void Foo_cpp::__sinit(void)`. + const type = as_stringio("Fv_v", (buf) => CxxType.parse(buf)); + return new CxxSymbol(new CxxTerm(Kind.QUALIFIED, { qualified_name: [new CxxName(src.read()), new CxxName(base_name)] }), type); + } + + // After the "__", the base_name is followed by the (optional) qualified class name, then the type. + let class_name = CxxType.parse(src); + let type; + if (!["", ",", ">"].includes(peek(src))) { + type = CxxType.parse(src); + } else { + pyassert(class_name !== null); + type = class_name; + class_name = null; + } + + const qualified_name = []; + if (class_name !== null) { + pyassert(class_name.terms.length === 1); + pyassert(class_name.terms[0].kind === Kind.QUALIFIED); + pyassert(class_name.terms[0].qualified_name !== null); + qualified_name.push(...class_name.terms[0].qualified_name); + } + as_stringio(String(base_name.length) + base_name, (buf) => qualified_name.push(CxxName.parse(buf))); + + const name = new CxxTerm(Kind.QUALIFIED, { qualified_name }); + return new CxxSymbol(name, type); + } + __str__() { + return `${this.name.__str__()} ${this.type.__str__()}`; + } + toString() { + return this.__str__(); + } +} +CxxSymbol.STATIC_FUNCTIONS = new Set(["__sinit", "__sterm"]); + +/** Parse a mangled CodeWarrior symbol. */ +export function parse(mangled) { + for (const [old, neu] of DOLDISASM_SUBSTITUTIONS) mangled = mangled.replaceAll(neu, old); + return as_stringio(mangled, (buf) => CxxSymbol.parse(buf)); +} + +/** Demangle `mangled`, returning it unchanged when it does not parse. */ +export function demangle(mangled) { + try { + return parse(mangled).__str__(); + } catch (e) { + if (e instanceof ValueError) return mangled; + throw e; + } +} + +/** The module's self-test table: [mangled, expected demangled]. */ +export const TEST_CASES = [ + // Unmangled, but with underscores + ["__foo_bar", "__foo_bar"], + // Namespacing + ["get__6FoobarFi", "Foobar::get (int)"], + // Constructor / Destructor + ["__ct__10FooBarFoosFP7ArgPtrsUsPCc", "FooBarFoos::FooBarFoos (ArgPtrs *, short unsigned, char const *)"], + ["__dt__10FooBarFoosFv", "FooBarFoos::~FooBarFoos (void)"], + // Overloaded operators + ["__dl__FPv", "operator delete (void *)"], + ["__nw__FUl", "operator new (long unsigned)"], + ["__eq__3FooCFRC3Foo", "Foo::operator== (Foo const &) const"], + // Namespacing & templated arguments + [ + "do__Q214GrandFooSystem8MiniFoosFUlPC3VecP3VecfUlUlPP8LateBazzUlUc", + "GrandFooSystem::MiniFoos::do (long unsigned, Vec const *, Vec *, float, long unsigned, long unsigned, LateBazz * *, long unsigned, char unsigned)", + ], + [ + "spin__11ThingieBaseFRCQ29MyLibrary8FVec3$$0f$$1RCQ29MyLibrary8FVec3$$0f$$1RCQ29MyLibrary8FVec3$$0f$$1", + "ThingieBase::spin (MyLibrary::FVec3 const &, MyLibrary::FVec3 const &, MyLibrary::FVec3 const &)", + ], + // Templated function names + ["function<&alpha,&beta,&GAMMA>__FR5Class_i", "function<&alpha, &beta, &GAMMA> int (*) (Class &)"], + ["function<&m0__5Class,&mf0__5ClassFi>__FR5Class_i", "function<&m0 Class, &Class::mf0 (int)> int (*) (Class &)"], + // Static functions + ["__sinit_Foo_cpp", "Foo_cpp::__sinit void (*) (void)"], + ["__sterm_Foo_cpp", "Foo_cpp::__sterm void (*) (void)"], + // Confusing function names (check that we split on the last valid "__") + ["foo__3BarFv", "Bar::foo (void)"], + ["foo__3BarFv__3BarFv", "Bar::foo__3BarFv (void)"], + ["foo__Q23Bar3BarFv__3BarFv", "Bar::foo__Q23Bar3BarFv (void)"], + ["copy__Q23std14__copy$$0Pv$$41$$40$$1FPPvPPvPPv", "std::__copy::copy (void * *, void * *, void * *)"], + ["__init__bar__9Bar$$03Foo$$1", "__init__bar Bar"], + ["bar__5__BarFv", "__Bar::bar (void)"], + // These examples we fail to demangle correctly + ["bar__5__FooFv", "bar__5__FooFv"], // should be "__Foo::bar (void)" + ["foo__Ul", "foo__Ul"], // should be "foo long unsigned" (or "long unsigned foo") +]; + +/** Run the self-test table; returns true when every case matches. */ +export function test() { + let all_pass = true; + for (const [mangled, demangled] of TEST_CASES) { + const output = demangle(mangled); + if (output !== demangled) all_pass = false; + } + return all_pass; +} diff --git a/packages/romdev-m2c/src/error.js b/packages/romdev-m2c/src/error.js new file mode 100644 index 00000000..e3448eb7 --- /dev/null +++ b/packages/romdev-m2c/src/error.js @@ -0,0 +1,17 @@ +// Port of m2c/error.py +import { repr } from "./py.js"; + +export class DecompFailure extends Error { + constructor(message) { + super(message); + this.name = "DecompFailure"; + this.message = message; + } + __str__() { + return this.message; + } +} + +export function assert_never(x) { + throw new Error(`Unreachable: ${repr(x)}`); +} diff --git a/packages/romdev-m2c/src/evaluate.js b/packages/romdev-m2c/src/evaluate.js new file mode 100644 index 00000000..66990898 --- /dev/null +++ b/packages/romdev-m2c/src/evaluate.js @@ -0,0 +1,988 @@ +// Port of m2c/evaluate.py +// Functions for evaluating assembly instructions and building Expression trees. +import { AsmSymbolicData } from "./asm_file.js"; +import { AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, Register } from "./asm_instruction.js"; +import { DecompFailure } from "./error.js"; +import { Target } from "./options.js"; +import { + AddressMode, + AddressOf, + ArrayAccess, + BinaryOp, + CarryBit, + Cast, + Condition, + ErrorExpr, + ExprCondition, + ExprStmt, + Expression, + FuncCall, + GlobalSymbol, + Literal, + Load3Bytes, + LocalVar, + Lwl, + StoreStmt, + StructAccess, + TernaryOp, + UnalignedLoad, + UnaryOp, + as_intish, + as_intptr, + as_type, + early_unwrap, + early_unwrap_ints, + var_for_expr, +} from "./translate.js"; +import { FunctionParam, FunctionSignature, StructDeclaration, Type } from "./types.js"; +import { normint, band, bit_length, bnot, bor, bxor, dcreplace, floordiv, format, pyassert, pyeq, pymod, pyround, shl, shr } from "./py.js"; + +export function error_stmt(msg) { + return new ExprStmt(new ErrorExpr(msg)); +} + +export function deref(arg, regs, stack_info, { size, store = false }) { + let offset; + let v; + if (arg instanceof Expression) { + offset = 0; + v = arg; + } else if (arg instanceof AddressMode) { + offset = arg.offset; + if (stack_info.is_stack_reg(arg.base)) return stack_info.get_stack_var(offset, { store }); + v = regs.get(arg.base); + } else { + offset = arg.offset; + v = stack_info.global_info.address_of_gsym(arg.sym.symbol_name); + } + + if (v instanceof Literal && pymod(v.value, 2 ** 16) === 0) { + v = new Literal(v.value + offset, { type: v.type }); + offset = 0; + } + + let uw_var = early_unwrap(v); + if (uw_var instanceof BinaryOp && uw_var.op === "+") { + for (const [base, addend] of [ + [uw_var.left, uw_var.right], + [uw_var.right, uw_var.left], + ]) { + const arch = stack_info.global_info.arch; + if (addend instanceof Literal && (arch.is_likely_partial_offset(addend.value) || (offset === 0 && addend.value >= 0))) { + offset += addend.value; + v = base; + uw_var = early_unwrap(v); + break; + } + } + } + if (uw_var instanceof AddressOf && uw_var.expr instanceof StructAccess) { + const base = uw_var.expr.struct_var; + const iaddend = uw_var.expr.offset; + const target = stack_info.global_info.target; + const arch = stack_info.global_info.arch; + if (arch.is_likely_partial_offset(iaddend) || target.compiler !== Target.CompilerEnum.IDO) { + offset += iaddend; + v = base; + uw_var = early_unwrap(v); + } + } + + v.type.unify(Type.ptr()); + stack_info.record_struct_access(v, offset); + let type = stack_info.unique_type_for("struct", [uw_var, offset], Type.any()); + + if (offset >= 0x200000) { + v = BinaryOp.int(new Literal(offset), "+", v); + offset = 0; + } + + const array_expr = array_access_from_add(v, offset, stack_info, { target_size: size, ptr: false }); + if (array_expr !== null) return array_expr; + let [field_path, field_type] = v.type.get_deref_field(offset, { target_size: size }); + if (field_path !== null) { + field_type.unify(type); + type = field_type; + } else field_path = null; + + return new StructAccess({ struct_var: v, offset, target_size: size, field_path, stack_info, type }); +} + +export function condition_from_expr(expr) { + const uw_expr = early_unwrap(expr); + if (uw_expr instanceof Condition && !(uw_expr instanceof BinaryOp && !uw_expr.is_comparison())) return uw_expr; + return new ExprCondition(expr, { type: expr.type }); +} + +export function imm_add_32(expr) { + if (expr instanceof Literal) return as_intish(new Literal(expr.value + 32)); + return BinaryOp.int(expr, "+", new Literal(32)); +} + +export function fn_op(fn_name, args, type) { + const fn_sig = new FunctionSignature({ + return_type: type, + params: args.map((arg) => new FunctionParam({ type: arg.type })), + params_known: true, + is_variadic: false, + }); + return new FuncCall({ function: new GlobalSymbol({ c_symbol_name: fn_name, type: Type.function(fn_sig) }), args, type }); +} + +export function void_fn_op(fn_name, args) { + const fn_call = fn_op(fn_name, args, Type.any_reg()); + fn_call.use(); + return new ExprStmt(fn_call); +} + +export function load_upper(args) { + pyassert(!(args.raw_arg(1) instanceof Literal), "normalize_instruction should convert lui/lis to li"); + const ref = args.hi_imm(1); + const stack_info = args.stack_info; + const source = stack_info.global_info.address_of_gsym(ref.sym.symbol_name); + const imm = new Literal(ref.offset); + return handle_addi_real(args.reg_ref(0), null, source, imm, args); +} + +export function handle_convert(expr, dest_type, source_type) { + const silent = dest_type.data().kind !== source_type.data().kind; + expr.type.unify(source_type); + return new Cast({ expr, type: dest_type, silent, reinterpret: false }); +} + +export function handle_la(args) { + const output_reg = args.reg_ref(0); + const target = args.memory_ref(1); + const stack_info = args.stack_info; + if (target instanceof AddressMode) return handle_addi(output_reg, target.base, args.regs.get(target.base), new Literal(target.offset), args); + const sym = stack_info.global_info.address_of_gsym(target.sym.symbol_name); + return add_imm(output_reg, sym, new Literal(target.offset), args); +} + +export function handle_lw(args) { + const ref = args.maybe_got_imm(1); + if (ref !== null) { + const sym = args.stack_info.global_info.address_of_gsym(ref.sym.symbol_name); + return add_imm(args.reg_ref(0), sym, new Literal(ref.offset), args); + } + return handle_load(args, Type.reg32({ likely_float: false })); +} + +export function handle_or(left, right, { is_arm = false } = {}) { + if (pyeq(left, right)) return left; + if (left instanceof Literal && left.value === 0) return right; + if (right instanceof Literal && right.value === 0) return left; + if (left instanceof Literal && right instanceof Literal) { + if ((band(left.value, 0xffff) === 0 && band(right.value, 0xffff0000) === 0) || (band(right.value, 0xffff) === 0 && band(left.value, 0xffff0000) === 0)) { + return new Literal({ value: bor(left.value, right.value) }); + } + } + const uw_left = early_unwrap(left); + if ( + is_arm && + uw_left instanceof BinaryOp && + uw_left.op === "|" && + uw_left.right instanceof Literal && + right instanceof Literal && + (pymod(uw_left.right.value, 0x100) === 0 || pymod(right.value, 0x100) === 0) + ) { + const imm = bor(uw_left.right.value, right.value); + return BinaryOp.int(uw_left.left, "|", new Literal(imm)); + } + return BinaryOp.int(left, "|", right); +} + +export function handle_bitinv(expr) { + if (expr instanceof Literal) return s32_literal(bnot(expr.value)); + return UnaryOp.int("~", expr); +} + +export function handle_sltu(args) { + const right = args.reg(2); + if (args.reg_ref(1) === new Register("zero")) { + const uw_right = early_unwrap(right); + if (uw_right instanceof BinaryOp && uw_right.op === "^") return BinaryOp.icmp(uw_right.left, "!=", uw_right.right); + return BinaryOp.icmp(right, "!=", new Literal(0)); + } + const left = args.reg(1); + return BinaryOp.ucmp(left, "<", right); +} + +export function handle_sltiu(args) { + const left = args.reg(1); + let right = args.s16_imm(2); + if (right instanceof Literal) { + const value = band(right.value, 0xffffffff); + if (value === 1) { + const uw_left = early_unwrap(left); + if (uw_left instanceof BinaryOp && uw_left.op === "^") return BinaryOp.icmp(uw_left.left, "==", uw_left.right); + return BinaryOp.icmp(left, "==", new Literal(0)); + } else right = new Literal(value); + } + return BinaryOp.ucmp(left, "<", right); +} + +export function handle_xor(left, right) { + if (right instanceof Literal && right.value === 1) { + const uw_left = early_unwrap(left); + if (uw_left instanceof BinaryOp && uw_left.is_comparison()) return uw_left.negated(); + } + return BinaryOp.int(left, "^", right); +} + +export function handle_addi_mips(args) { + const output_reg = args.reg_ref(0); + const source_reg = args.reg_ref(1); + const ref = args.maybe_gprel_imm(2); + if (ref !== null && source_reg === new Register("gp")) { + const sym = args.stack_info.global_info.address_of_gsym(ref.sym.symbol_name); + return add_imm(output_reg, sym, new Literal(ref.offset), args); + } + return handle_addi(output_reg, source_reg, args.reg(1), args.s16_imm(2), args); +} + +export function handle_addi(output_reg, source_reg, source, imm, args) { + if (pyeq(imm, new Literal(0))) return source; + const arm = args.stack_info.global_info.arch.arch === Target.ArchEnum.ARM; + const uw_source = early_unwrap(source); + if ( + uw_source instanceof BinaryOp && + uw_source.op === "+" && + uw_source.right instanceof Literal && + imm instanceof Literal && + (pymod(uw_source.right.value, 0x10000) === 0 || (arm && pymod(imm.value, 0x100) === 0)) + ) { + return add_imm(output_reg, uw_source.left, new Literal(imm.value + uw_source.right.value), args); + } + return handle_addi_real(output_reg, source_reg, source, imm, args); +} + +export function handle_sub_arm(args) { + const stack_info = args.stack_info; + const output_reg = args.reg_ref(0); + const source_reg = args.reg_ref(1); + const lhs = args.reg(1); + const rhs = args.reg_or_imm(2); + if (rhs instanceof Literal && stack_info.is_stack_reg(source_reg) && stack_info.is_stack_reg(output_reg)) return lhs; + return handle_sub(lhs, rhs); +} + +export function handle_sub(lhs, rhs) { + if (lhs instanceof Literal && rhs instanceof Literal) return s32_literal(lhs.value - rhs.value); + if (pyeq(rhs, new Literal(0))) return lhs; + return fold_mul_chains(fold_divmod(BinaryOp.intptr(lhs, "-", rhs))); +} + +export function handle_addis(args) { + const source_reg = args.reg_ref(1); + const source = args.reg(1); + const imm = args.shifted_u16_imm(2); + return handle_addi_real(args.reg_ref(0), source_reg, source, imm, args); +} + +export function handle_addi_real(output_reg, source_reg, source, imm, args) { + const stack_info = args.stack_info; + if (source_reg !== null && stack_info.is_stack_reg(source_reg)) { + pyassert(imm instanceof Literal); + if (stack_info.is_stack_reg(output_reg)) return source; + const v = stack_info.get_stack_var(imm.value, { store: false }); + if (v instanceof LocalVar) stack_info.add_local_var(v); + return new AddressOf(v, { type: v.type.reference() }); + } + return add_imm(output_reg, source, imm, args); +} + +export function add_imm(output_reg, source, imm, args) { + const stack_info = args.stack_info; + if (pyeq(imm, new Literal(0))) return source; + else if (source.type.is_pointer_or_array()) { + const dest_var = stack_info.get_planned_var(output_reg, args.instruction_ref); + const arch = stack_info.global_info.arch; + const inplace = dest_var !== null && var_for_expr(source) === dest_var; + if (imm instanceof Literal && !arch.is_likely_partial_offset(imm.value) && !inplace) { + const array_access = array_access_from_add(source, imm.value, stack_info, { target_size: null, ptr: true }); + if (array_access !== null) return array_access; + const [field_path, field_type] = source.type.get_deref_field(imm.value, { target_size: null }); + if (field_path !== null) { + return new AddressOf(new StructAccess({ struct_var: source, offset: imm.value, target_size: null, field_path, stack_info, type: field_type }), { type: field_type.reference() }); + } + } + if (imm instanceof Literal) { + const target = source.type.get_pointer_target(); + if (target) { + const target_size = target.get_size_bytes(); + if (target_size && pymod(imm.value, target_size) === 0) return new BinaryOp({ left: source, op: "+", right: as_intish(imm), type: source.type }); + } + } + return new BinaryOp({ left: source, op: "+", right: as_intish(imm), type: Type.ptr() }); + } else if (source instanceof Literal && imm instanceof Literal) { + return new Literal(source.value + imm.value); + } + return BinaryOp.intptr(source, "+", imm); +} + +export function handle_load(args, type) { + const size = type.get_size_bytes(); + pyassert(size !== null); + const output_reg = args.reg_ref(0); + const expr = deref(args.memory_ref(1), args.regs, args.stack_info, { size }); + + const load_rodata_constant = () => { + if (!(expr instanceof StructAccess)) return null; + const arch = args.stack_info.global_info.arch.arch; + const is_arm = arch === Target.ArchEnum.ARM; + const is_sh = arch === Target.ArchEnum.SH; + if (is_arm && args.raw_arg(1) instanceof AsmAddressMode) return null; + if (!is_arm && !is_sh && (!type.is_likely_float() || expr.offset !== 0)) return null; + const target = early_unwrap(expr.struct_var); + if (!(target instanceof AddressOf) || !(target.expr instanceof GlobalSymbol)) return null; + const ent = target.expr.asm_data_entry; + if (ent === null || !ent.is_readonly) return null; + const data = ent.data_at_offset(expr.offset, size); + if (data === null) return null; + if (data instanceof Uint8Array && [2, 4, 8].includes(size)) { + ent.used_as_literal = true; + const big = args.stack_info.global_info.target.is_big_endian(); + let v = 0n; + const bs = big ? [...data] : [...data].reverse(); + for (const b of bs) v = (v << 8n) | BigInt(b); + // Values beyond 2**53 stay BigInt (see normint) so 64-bit patterns keep every bit. + let val = normint(v); + if (type.is_signed() && (v >> BigInt(size * 8 - 1)) & 1n) val = normint(v - (1n << BigInt(size * 8))); + return new Literal({ value: val, type }); + } + if ((is_arm || is_sh) && ent.is_text && data instanceof AsmSymbolicData) { + let sym = data.data; + let addend = 0; + if (sym instanceof BinOp && (sym.op === "+" || sym.op === "-") && sym.rhs instanceof AsmLiteral) { + addend = sym.rhs.value * (sym.op === "-" ? -1 : 1); + sym = sym.lhs; + } + if (sym instanceof AsmGlobalSymbol) { + ent.used_as_literal = true; + let addr = args.stack_info.global_info.address_of_gsym(sym.symbol_name); + addr = add_imm(output_reg, addr, new Literal(addend), args); + return as_type(addr, type, true); + } + } + return null; + }; + + const c = load_rodata_constant(); + if (c !== null) return c; + return as_type(expr, type, true); +} + +export function deref_unaligned(arg, regs, stack_info, { store = false } = {}) { + return deref(arg, regs, stack_info, { size: 1, store }); +} + +export function handle_lwl(args) { + const ref = args.memory_ref(1); + const expr = deref_unaligned(ref, args.regs, args.stack_info); + let key; + if (ref instanceof AddressMode) key = [ref.offset, args.regs.get(ref.base)]; + else key = [ref.offset, ref.sym]; + return new Lwl(expr, key); +} + +export function handle_lwr(args) { + const uw_old_value = early_unwrap(args.reg(0)); + const ref = args.memory_ref(1); + const big = args.stack_info.global_info.target.is_big_endian(); + const delta = big ? -3 : 3; + let lwl_key; + if (ref instanceof AddressMode) lwl_key = [ref.offset + delta, args.regs.get(ref.base)]; + else lwl_key = [ref.offset + delta, ref.sym]; + if (uw_old_value instanceof Lwl && uw_old_value.key[0] === lwl_key[0]) { + let load_expr; + if (big) load_expr = uw_old_value.load_expr; + else load_expr = deref_unaligned(ref, args.regs, args.stack_info); + return new UnalignedLoad(load_expr); + } + if (pymod(ref.offset, 4) === 2 && big) { + const left_mem_ref = dcreplace(ref, { offset: ref.offset - 2 }); + const load_expr = deref_unaligned(left_mem_ref, args.regs, args.stack_info); + return new Load3Bytes(load_expr); + } + return new ErrorExpr("Unable to handle lwr; missing a corresponding lwl"); +} + +export function make_store(args, type) { + const size = type.get_size_bytes(); + pyassert(size !== null); + const stack_info = args.stack_info; + const source_reg = args.reg_ref(0); + const source_raw = args.regs.get_raw(source_reg); + let source_val; + if (type.is_likely_float() && size === 8) source_val = args.dreg(0); + else source_val = args.reg(0); + const target = args.memory_ref(1); + return make_store_real(source_val, source_raw, target, args.regs, stack_info, type); +} + +export function make_store_real(source_val, source_raw, target, regs, stack_info, type) { + const size = type.get_size_bytes(); + pyassert(size !== null); + const is_stack = target instanceof AddressMode && stack_info.is_stack_reg(target.base); + if (is_stack && source_raw !== null && stack_info.should_save(source_raw, target.offset)) return null; + const dest = deref(target, regs, stack_info, { size, store: true }); + dest.type.unify(type); + return new StoreStmt({ source: as_type(source_val, type, is_stack), dest }); +} + +export function make_storex(args, type) { + const size = type.get_size_bytes(); + pyassert(size !== null); + const source = args.reg(0); + const ptr = BinaryOp.intptr(args.reg(1), "+", args.reg(2)); + const dest = deref(ptr, args.regs, args.stack_info, { size, store: true }); + dest.type.unify(type); + return new StoreStmt({ source: as_type(source, type, false), dest }); +} + +export function handle_swl(args) { + let source = args.reg(0); + let target = args.memory_ref(1); + if (!(early_unwrap(source) instanceof UnalignedLoad)) source = new UnalignedLoad(source); + if (!args.stack_info.global_info.target.is_big_endian()) target = dcreplace(target, { offset: target.offset - 3 }); + const dest = deref_unaligned(target, args.regs, args.stack_info, { store: true }); + return new StoreStmt({ source, dest }); +} + +export function handle_swr(args) { + const expr = early_unwrap(args.reg(0)); + const target = args.memory_ref(1); + if (!(expr instanceof Load3Bytes)) return null; + const real_target = dcreplace(target, { offset: target.offset - 2 }); + const dest = deref_unaligned(real_target, args.regs, args.stack_info, { store: true }); + return new StoreStmt({ source: expr, dest }); +} + +export function handle_shift_right(args, { signed, arm = false }) { + const lhs = args.reg(1); + const shift = arm ? args.reg_or_imm(2) : args.s16_imm(2); + if (shift instanceof Literal && (shift.value === 16 || shift.value === 24)) { + const expr = early_unwrap(lhs); + const pow2 = shl(1, shift.value); + if (expr instanceof BinaryOp && expr.right instanceof Literal) { + let tp; + if (signed) tp = shift.value === 16 ? Type.s16() : Type.s8(); + else tp = shift.value === 16 ? Type.u16() : Type.u8(); + const rhs = expr.right.value; + if (expr.op === "<<" && rhs === shift.value) return as_type(expr.left, tp, false); + else if (expr.op === "<<" && rhs > shift.value) { + const new_shift = fold_mul_chains(BinaryOp.int(expr.left, "<<", new Literal(rhs - shift.value))); + return as_type(new_shift, tp, false); + } else if (expr.op === "*" && pymod(rhs, pow2) === 0 && rhs !== pow2) { + const mul = BinaryOp.int(expr.left, "*", new Literal({ value: floordiv(rhs, pow2) })); + return as_type(mul, tp, false); + } + } + } + if (signed) return fold_divmod(BinaryOp.sshift(lhs, ">>", shift)); + return BinaryOp.ushift(lhs, ">>", shift); +} + +export function handle_sll(args, { arm = false } = {}) { + const lhs = args.reg(1); + const rhs = arm ? args.reg_or_imm(2) : args.s16_imm(2); + if (lhs instanceof Literal && rhs instanceof Literal) return new Literal(shl(lhs.value, rhs.value)); + return fold_mul_chains(BinaryOp.int(lhs, "<<", as_intish(rhs))); +} + +export function handle_conditional_move(args, nonzero) { + const op = nonzero ? "!=" : "=="; + const val = args.reg(2); + const type = Type.any_reg(); + return new TernaryOp(BinaryOp.icmp(val, op, new Literal(0, { type: val.type })), as_type(args.reg(1), type, true), as_type(args.reg(0), type, true), type); +} + +/** Return a new BinaryOp instance if this one can be simplified to a single / or % op. */ +export function fold_divmod(original_expr) { + const mult_high_ops = ["MULT_HI", "MULTU_HI"]; + const possible_match_ops = [...mult_high_ops, "-", "+", ">>"]; + if (original_expr.is_floating() || !possible_match_ops.includes(original_expr.op)) return original_expr; + + let expr = original_expr; + let left_expr = early_unwrap_ints(expr.left); + let right_expr = early_unwrap_ints(expr.right); + let divisor_shift = 0; + + if (left_expr instanceof Literal && !(right_expr instanceof Literal)) [left_expr, right_expr] = [right_expr, left_expr]; + + if (left_expr instanceof BinaryOp && left_expr.op === ">>" && left_expr.right instanceof Literal && expr.op === "+" && right_expr instanceof CarryBit) { + const new_denom = shl(1, left_expr.right.value); + return BinaryOp.sint(left_expr.left, "/", new Literal(new_denom), { silent: true }); + } + + if (left_expr instanceof BinaryOp && left_expr.op === "/" && left_expr.right instanceof Literal && expr.op === ">>" && right_expr instanceof Literal) { + const new_denom = shl(left_expr.right.value, right_expr.value); + if (new_denom < 2 ** 32) return BinaryOp.int(left_expr.left, "/", new Literal(new_denom)); + } + + if (expr.op === "-" && right_expr instanceof BinaryOp && right_expr.op === "*") { + const div_expr = early_unwrap_ints(right_expr.left); + const mod_base = early_unwrap_ints(right_expr.right); + if (div_expr instanceof BinaryOp && pyeq(early_unwrap_ints(div_expr.left), left_expr)) { + const divisor = early_unwrap_ints(div_expr.right); + if ( + (div_expr.op === "/" && pyeq(divisor, mod_base)) || + (div_expr.op === ">>" && divisor instanceof Literal && mod_base instanceof Literal && shl(1, divisor.value) === mod_base.value) + ) { + return BinaryOp.int(left_expr, "%", right_expr.right); + } + } + } + + if ( + expr.op === "-" && + left_expr instanceof BinaryOp && + left_expr.op === ">>" && + pyeq(early_unwrap_ints(left_expr.right), new Literal(31)) && + right_expr instanceof BinaryOp && + right_expr.op === "/" && + right_expr.right instanceof Literal + ) { + [left_expr, right_expr] = [dcreplace(right_expr, { right: new Literal(-right_expr.right.value) }), left_expr]; + } + + if ( + expr.op === "+" && + left_expr instanceof BinaryOp && + left_expr.op === "/" && + left_expr.right instanceof Literal && + left_expr.right.value <= 2 ** 29 && + right_expr instanceof BinaryOp && + pyeq(early_unwrap_ints(right_expr.left), left_expr) && + right_expr.op === ">>" && + pyeq(early_unwrap_ints(right_expr.right), new Literal(31)) + ) { + return left_expr; + } + + if ( + expr.op === "-" && + left_expr instanceof BinaryOp && + left_expr.op === "/" && + left_expr.right instanceof Literal && + right_expr instanceof BinaryOp && + right_expr.op === ">>" && + pyeq(early_unwrap_ints(right_expr.right), new Literal(31)) + ) { + const div_expr = left_expr; + const shift_var_expr = early_unwrap_ints(right_expr.left); + const div_var_expr = early_unwrap_ints(div_expr.left); + if (pyeq(div_var_expr, shift_var_expr)) { + if (div_expr.right instanceof Literal && div_expr.right.value >= 2 ** 30) return BinaryOp.int(div_expr.left, div_expr.op, div_expr.right); + return div_expr; + } + if ( + shift_var_expr instanceof BinaryOp && + pyeq(early_unwrap_ints(div_expr.left), early_unwrap_ints(shift_var_expr.left)) && + shift_var_expr.op === "<<" && + shift_var_expr.right instanceof Literal + ) { + return div_expr; + } + } + + if (left_expr instanceof BinaryOp && expr.op === ">>" && right_expr instanceof Literal) { + divisor_shift += right_expr.value; + expr = left_expr; + left_expr = early_unwrap_ints(expr.left); + right_expr = early_unwrap_ints(expr.right); + if ( + left_expr instanceof BinaryOp && + left_expr.op === "MULT_HI" && + expr.op === "+" && + (pyeq(right_expr, early_unwrap_ints(left_expr.left)) || pyeq(right_expr, early_unwrap_ints(left_expr.right))) + ) { + expr = left_expr; + left_expr = early_unwrap_ints(expr.left); + right_expr = early_unwrap_ints(expr.right); + } + if (left_expr instanceof Literal && !(right_expr instanceof Literal)) [left_expr, right_expr] = [right_expr, left_expr]; + } + + if (mult_high_ops.includes(expr.op) && left_expr instanceof BinaryOp && left_expr.op === ">>" && left_expr.right instanceof Literal) { + divisor_shift += left_expr.right.value; + left_expr = early_unwrap_ints(left_expr.left); + } + + const round_div = (x, y) => { + if (y <= 1) return null; + const result = pyround(x / y); + if (x / (y + 1) <= result && result <= x / (y - 1)) return result; + return null; + }; + + if (mult_high_ops.includes(expr.op) && right_expr instanceof Literal) { + const denom = round_div(2 ** (32 + divisor_shift), right_expr.value); + if (denom !== null) return BinaryOp.int(left_expr, "/", new Literal(denom)); + } + return original_expr; +} + +/** Simplify an expression matching `CLZ(x) >> 5` into `x == 0`. */ +export function replace_clz_shift(expr) { + if (expr.is_floating() || expr.op !== ">>") return expr; + const left_expr = early_unwrap_ints(expr.left); + const right_expr = early_unwrap_ints(expr.right); + if (!(left_expr instanceof UnaryOp && left_expr.op === "CLZ" && right_expr instanceof Literal && right_expr.value === 5)) return expr; + const sub_expr = early_unwrap(left_expr.expr); + if (sub_expr instanceof BinaryOp && !sub_expr.is_floating() && sub_expr.op === "-") return BinaryOp.icmp(sub_expr.right, "==", sub_expr.left); + return BinaryOp.icmp(left_expr.expr, "==", new Literal(0, { type: left_expr.expr.type })); +} + +/** Simplify expressions using `&`. */ +export function replace_bitand(expr) { + if (!expr.is_floating() && expr.op === "&") { + if (pyeq(expr.right, new Literal(0))) return new Literal(0); + if (pyeq(expr.right, new Literal(0xff))) return as_type(expr.left, Type.u8(), false); + if (pyeq(expr.right, new Literal(0xffff))) return as_type(expr.left, Type.u16(), false); + } + return expr; +} + +/** Simplify an expression involving +, -, * and << to a single multiplication. */ +export function fold_mul_chains(expr, { allow_sll_chains = false } = {}) { + const fold = (expr, toplevel, allow_sll) => { + if (expr instanceof BinaryOp) { + if ((expr.op === "<<" || expr.op === "*") && expr.right instanceof Literal) { + const [lbase, lnum] = fold(expr.left, false, expr.op !== "<<"); + const rhs = expr.right.value; + if (expr.op === "<<" && (allow_sll || allow_sll_chains)) { + if (toplevel && lnum === 1 && !(1 <= rhs && rhs <= 4)) return [expr, 1]; + return [lbase, shl(lnum, rhs)]; + } + if (expr.op === "*" && (allow_sll || allow_sll_chains || pymod(rhs, 2) !== 0)) return [lbase, lnum * rhs]; + } + if ((expr.op === "+" || expr.op === "-") && toplevel) { + const [lbase, lnum] = fold(expr.left, false, expr.op !== "<<"); + const [rbase, rnum] = fold(expr.right, false, expr.op !== "<<"); + if (pyeq(early_unwrap(lbase), early_unwrap(rbase))) { + if (expr.op === "+") return [lbase, lnum + rnum]; + if (expr.op === "-") return [lbase, lnum - rnum]; + } + } + } + if (expr instanceof UnaryOp && expr.op === "-" && !toplevel) { + const [base, num] = fold(expr.expr, false, true); + return [base, -num]; + } + const uw_expr = early_unwrap(expr); + if (uw_expr !== expr) { + const [base, num] = fold(uw_expr, false, allow_sll); + if (num !== 1) return [base, num]; + } + return [expr, 1]; + }; + + const [base, num] = fold(expr, true, true); + if (num === 1) return expr; + if (allow_sll_chains && num > 16 && band(num, num - 1) === 0) return BinaryOp.int(base, "<<", new Literal(bit_length(num) - 1)); + return BinaryOp.int(base, "*", new Literal(num)); +} + +export function fold_shift_right(expr, shift, { signed }) { + const inner = early_unwrap_ints(expr); + if (inner instanceof BinaryOp && inner.op === ">>" && inner.type.is_signed() === signed && inner.right instanceof Literal && inner.right.value + shift < 32) { + expr = inner.left; + shift += inner.right.value; + } + let ret; + if (signed) ret = BinaryOp.sshift(expr, ">>", new Literal(shift)); + else ret = BinaryOp.ushift(expr, ">>", new Literal(shift)); + return fold_divmod(ret); +} + +/** Given `expr` of the form `a + (imm * b + Y)` and an `offset` X, try to create `a->unk(X + Y)[b]`. */ +export function array_access_from_add(expr, offset, stack_info, { target_size, ptr }) { + expr = early_unwrap(expr); + if (!(expr instanceof BinaryOp) || expr.op !== "+") return null; + let base = expr.left; + let addend = expr.right; + if (addend.type.is_pointer_or_array() && !base.type.is_pointer_or_array()) [base, addend] = [addend, base]; + + if (addend instanceof Literal) return null; + + let uw_addend = early_unwrap(addend); + if (uw_addend instanceof BinaryOp && uw_addend.op === "+") { + if (uw_addend.right instanceof Literal) { + offset += uw_addend.right.value; + addend = uw_addend.left; + } else if (uw_addend.left instanceof Literal) { + offset += uw_addend.left.value; + addend = uw_addend.right; + } + } + + let index = addend; + let scale = 1; + uw_addend = early_unwrap(addend); + if (uw_addend instanceof BinaryOp && (uw_addend.op === "*" || uw_addend.op === "<<") && uw_addend.right instanceof Literal) { + index = uw_addend.left; + scale = uw_addend.right.value; + if (uw_addend.op === "<<") scale = shl(1, scale); + } + + if (scale < 0) { + scale = -scale; + index = UnaryOp.sint("-", index); + } + + let target_type = base.type.get_pointer_target(); + if (target_type === null) return null; + + const uw_base = early_unwrap(base); + const typepool = stack_info.global_info.typepool; + + if (scale > 1 && offset === 0 && uw_base instanceof AddressOf && target_type.get_size_bytes() === null) { + let inner_type = null; + if (uw_base.expr instanceof GlobalSymbol && uw_base.expr.potential_array_dim(scale)[1] !== 0) { + // pass + } else if (scale === 2) inner_type = Type.int_of_size(16); + else if (scale === 4) inner_type = Type.reg32({ likely_float: false }); + else if (typepool.unk_inference && uw_base.expr instanceof GlobalSymbol) { + const struct_name = `_struct_${uw_base.expr.c_symbol_name}_0x${format(scale, "X")}`; + let struct = typepool.get_struct_by_tag_name(struct_name, stack_info.global_info.typemap); + if (struct === null) struct = StructDeclaration.unknown(typepool, scale, struct_name); + else if (struct.size !== scale) throw new DecompFailure(`sizeof(struct ${struct_name}) != ${format(scale, "#x")}`); + inner_type = Type.struct(struct); + } + if (inner_type !== null) { + uw_base.expr.type.unify(Type.array(inner_type, null)); + target_type.unify(inner_type); + } + } + + if (target_type.get_size_bytes() === scale) { + // base[index] + } else { + const [sub_path, sub_type, remaining_offset] = base.type.get_deref_field(offset, { target_size: scale, exact: false }); + if (sub_path === null || sub_path.length < 2 || sub_path[sub_path.length - 1] !== 0) return null; + sub_path.pop(); + base = new StructAccess({ struct_var: base, offset: offset - remaining_offset, target_size: null, field_path: sub_path, stack_info, type: sub_type }); + offset = remaining_offset; + target_type = sub_type; + } + + let ret = new ArrayAccess(base, index, { type: target_type }); + const ret_ref = new AddressOf(ret, { type: ret.type.reference() }); + const [field_path, field_type] = ret_ref.type.get_deref_field(offset, { target_size }); + if (offset !== 0 || (target_size !== null && target_size !== scale)) { + ret = new StructAccess({ struct_var: ret_ref, offset, target_size, field_path, stack_info, type: field_type }); + } + if (ptr) ret = new AddressOf(ret, { type: ret.type.reference() }); + return ret; +} + +export function handle_add(args) { + const output_reg = args.reg_ref(0); + const lhs = args.reg(1); + const rhs = args.reg(2); + if (rhs instanceof Literal) return fold_mul_chains(handle_addi_real(output_reg, args.reg_ref(1), lhs, rhs, args)); + if (lhs instanceof Literal) return fold_mul_chains(handle_addi_real(output_reg, args.reg_ref(2), rhs, lhs, args)); + return handle_add_real(lhs, rhs, args); +} + +export function handle_add_arm(args) { + if (args.raw_arg(2) instanceof Register) return handle_add(args); + return handle_addi(args.reg_ref(0), args.reg_ref(1), args.reg(1), args.full_imm(2), args); +} + +export function handle_add_real(lhs, rhs, args) { + const stack_info = args.stack_info; + if (pyeq(lhs, new Literal(0))) return rhs; + if (pyeq(rhs, new Literal(0))) return lhs; + let type = Type.intptr(); + if (lhs.type.is_pointer_or_array()) type = Type.ptr(); + else if (rhs.type.is_pointer_or_array()) type = Type.ptr(); + const expr = new BinaryOp({ left: as_intptr(lhs), op: "+", right: as_intptr(rhs), type }); + let folded_expr = fold_mul_chains(expr); + if (folded_expr instanceof BinaryOp) folded_expr = fold_divmod(folded_expr); + if (folded_expr !== expr) return folded_expr; + const array_expr = array_access_from_add(expr, 0, stack_info, { target_size: null, ptr: true }); + if (array_expr !== null) return array_expr; + return expr; +} + +export function handle_add_float(args) { + if (args.reg_ref(1) === args.reg_ref(2)) { + const two = new Literal(1 << 30, { type: Type.f32() }); + return BinaryOp.f32(two, "*", args.reg(1)); + } + return BinaryOp.f32(args.reg(1), "+", args.reg(2)); +} + +export function handle_add_double(args) { + if (args.reg_ref(1) === args.reg_ref(2)) { + const two = new Literal(2 ** 62, { type: Type.f64() }); + return BinaryOp.f64(two, "*", args.dreg(1)); + } + return BinaryOp.f64(args.dreg(1), "+", args.dreg(2)); +} + +export function fold_shift_bgez(expr) { + const uw_expr = early_unwrap(expr); + if (!(uw_expr instanceof BinaryOp) || !(uw_expr.right instanceof Literal)) return null; + const value = uw_expr.right.value; + let shift; + if (uw_expr.op === "<<") shift = value; + else if (uw_expr.op === "*" && value > 0 && band(value, value - 1) === 0) shift = bit_length(value) - 1; + else return null; + const bitand = BinaryOp.int(uw_expr.left, "&", new Literal(shl(1, 31 - shift))); + return new UnaryOp("!", bitand, { type: Type.boolean() }); +} + +export function handle_bgez(args) { + const expr = args.reg(0); + return fold_shift_bgez(expr) || BinaryOp.scmp(expr, ">=", new Literal(0)); +} + +export function rlwi_mask(mask_begin, mask_end) { + const bits_upto = (m) => shl(1, 32 - m) - 1; + const all_ones = 0xffffffff; + let mask; + if (mask_begin <= mask_end) mask = bits_upto(mask_begin) - bits_upto(mask_end + 1); + else mask = bxor(bits_upto(mask_end + 1) - bits_upto(mask_begin), all_ones); + return mask; +} + +export function handle_rlwinm(source, shift, mask_begin, mask_end, simplify = true) { + const all_ones = 0xffffffff; + const mask = rlwi_mask(mask_begin, mask_end); + const left_shift = shift; + const right_shift = 32 - shift; + const left_mask = band(shl(all_ones, left_shift), mask); + const right_mask = band(shr(all_ones, right_shift), mask); + + simplify = simplify && !(left_mask && right_mask); + + if (source instanceof Literal) { + const upper_value = band(shl(source.value, left_shift), mask); + const lower_value = band(shr(source.value, right_shift), mask); + return new Literal(bor(upper_value, lower_value)); + } + + let upper_bits; + if (left_mask === 0) upper_bits = null; + else { + upper_bits = source; + if (left_shift !== 0) upper_bits = BinaryOp.int(upper_bits, "<<", new Literal(left_shift)); + if (simplify) upper_bits = fold_mul_chains(upper_bits); + if (left_mask !== band(shl(all_ones, left_shift), all_ones)) { + upper_bits = BinaryOp.int(upper_bits, "&", new Literal(left_mask)); + if (simplify) upper_bits = replace_bitand(upper_bits); + } + } + + let lower_bits; + if (right_mask === 0) lower_bits = null; + else { + lower_bits = BinaryOp.uint(source, ">>", new Literal(right_shift)); + if (simplify) lower_bits = replace_clz_shift(fold_divmod(lower_bits)); + if (right_mask !== band(shr(all_ones, right_shift), all_ones)) { + lower_bits = BinaryOp.int(lower_bits, "&", new Literal(right_mask)); + if (simplify) lower_bits = replace_bitand(lower_bits); + } + } + + if (upper_bits === null && lower_bits === null) return new Literal(0); + else if (upper_bits === null) { + pyassert(lower_bits !== null); + return lower_bits; + } else if (lower_bits === null) return upper_bits; + return BinaryOp.int(upper_bits, "|", lower_bits); +} + +export function handle_rlwimi(base, source, shift, mask_begin, mask_end) { + const mask_literal = new Literal(rlwi_mask(mask_begin, mask_end)); + const mask = new UnaryOp("~", mask_literal, { type: Type.u32() }); + const masked_base = BinaryOp.int(base, "&", mask); + if (pyeq(source, new Literal(0))) return masked_base; + const inserted = handle_rlwinm(source, shift, mask_begin, mask_end, false); + if (pyeq(inserted, mask_literal)) return BinaryOp.int(base, "|", inserted); + return BinaryOp.int(masked_base, "|", inserted); +} + +export function handle_rlwnm(source, shift_source, mask_begin, mask_end) { + const mask = rlwi_mask(mask_begin, mask_end); + const shift = BinaryOp.int(shift_source, "&", new Literal(0x1f)); + const upper_bits = BinaryOp.int(BinaryOp.int(source, "<<", shift), "&", new Literal(mask)); + const lower_bits = BinaryOp.int(BinaryOp.int(source, ">>", BinaryOp.int(new Literal(32), "-", shift)), "&", new Literal(mask)); + return BinaryOp.int(upper_bits, "|", lower_bits); +} + +export function handle_cmpnez(source) { + let uw_source = early_unwrap(source); + if (uw_source instanceof UnaryOp && uw_source.op === "-") { + source = uw_source.expr; + uw_source = early_unwrap(source); + } + if (uw_source instanceof BinaryOp && (uw_source.op === "-" || uw_source.op === "^")) return BinaryOp.icmp(uw_source.right, "!=", uw_source.left); + return BinaryOp.icmp(source, "!=", new Literal(0)); +} + +export function handle_loadx(args, type) { + const size = type.get_size_bytes(); + pyassert(size !== null); + const ptr = BinaryOp.intptr(args.reg(1), "+", args.reg(2)); + const expr = deref(ptr, args.regs, args.stack_info, { size }); + return as_type(expr, type, true); +} + +export function handle_arm_mov(args) { + const dest = args.reg_ref(0); + const source = args.raw_arg(1); + const value = args.reg_or_imm(1); + if (source instanceof Register && args.stack_info.is_stack_reg(source) && !args.stack_info.is_stack_reg(dest)) return handle_addi_real(dest, source, value, new Literal(0), args); + return value; +} + +export function eval_arm_cmp(s, lhs, rhs) { + s.set_reg(new Register("z"), BinaryOp.icmp(lhs, "==", rhs)); + const sub = BinaryOp.intptr(lhs, "-", rhs); + const sval = as_type(sub, Type.s32(), true, { unify: false }); + s.set_reg(new Register("n"), BinaryOp.scmp(sval, "<", new Literal(0))); + const v = fn_op("M2C_OVERFLOW", [sval], Type.boolean()); + s.set_reg(new Register("v"), v); + const ulhs = as_type(lhs, Type.u32(), true, { unify: false }); + const slhs = as_type(lhs, Type.s32(), true, { unify: false }); + const urhs = as_type(rhs, Type.u32(), true, { unify: false }); + const srhs = as_type(rhs, Type.s32(), true, { unify: false }); + s.set_reg(new Register("c"), BinaryOp.ucmp(ulhs, ">=", urhs)); + s.set_reg(new Register("hi"), BinaryOp.ucmp(ulhs, ">", urhs)); + s.set_reg(new Register("ge"), BinaryOp.scmp(slhs, ">=", srhs)); + s.set_reg(new Register("gt"), BinaryOp.scmp(slhs, ">", srhs)); +} + +export function set_arm_flags_from_add(s, val) { + s.set_reg(new Register("z"), BinaryOp.icmp(val, "==", new Literal(0, { type: val.type }))); + const sval = as_type(val, Type.s32(), true, { unify: false }); + s.set_reg(new Register("n"), BinaryOp.scmp(sval, "<", new Literal(0))); + s.set_reg(new Register("c"), new CarryBit(val)); + const v = fn_op("M2C_OVERFLOW", [sval], Type.boolean()); + s.set_reg(new Register("v"), v); + const u64val = as_type(val, Type.u64(), false, { unify: false }); + const p32 = new Literal(2 ** 32); + s.set_reg(new Register("hi"), BinaryOp.ucmp(u64val, ">", p32)); + const s64val = as_type(val, Type.s64(), false, { unify: false }); + s.set_reg(new Register("ge"), BinaryOp.scmp(s64val, ">=", new Literal(0))); + s.set_reg(new Register("gt"), BinaryOp.scmp(s64val, ">", new Literal(0))); +} + +export function carry_add_to(expr) { + return fold_divmod(BinaryOp.intptr(expr, "+", new CarryBit())); +} + +export function carry_sub_from(expr) { + return BinaryOp.intptr(expr, "-", new UnaryOp("!", new CarryBit(), { type: Type.intish() })); +} + +export function s32_literal(value) { + return new Literal(band(value + 0x80000000, 0xffffffff) - 0x80000000); +} + +export { ArrayAccess }; diff --git a/packages/romdev-m2c/src/flow_graph.js b/packages/romdev-m2c/src/flow_graph.js new file mode 100644 index 00000000..0b593a31 --- /dev/null +++ b/packages/romdev-m2c/src/flow_graph.js @@ -0,0 +1,1267 @@ +// Port of m2c/flow_graph.py +/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */ +import { DecompFailure } from "./error.js"; +import { Target } from "./options.js"; +import { AsmSymbolicData, Function, Label } from "./asm_file.js"; +import { AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, JumpTarget, Macro, Register } from "./asm_instruction.js"; +import { ArchAsm, Instruction } from "./instruction.js"; +import { simplify_patterns } from "./asm_pattern.js"; +import { DefaultMap, ValueError, intern, pyassert, lstrip, sorted, compare, shallowcopy } from "./py.js"; +import { print } from "./io.js"; + +export class ArchFlowGraph extends ArchAsm { + process_flowgraph(asm_data, flow_graph) {} + simplify_ir(asm_data, flow_graph, { debug_patterns }) {} +} + +ArchFlowGraph.prototype.asm_patterns = []; + +/** Reference acts as a pointer to either a specific Instruction, or one of the function's bounds */ +export class Reference {} + +/** Reference to a Location's value before the start of a function (e.g. constants, args) */ +export class PrologueRef extends Reference { + constructor(location) { + super(); + this.location = location; + return intern(this, [location]); + } +} + +/** Reference to return values of a function */ +export class EpilogueRef extends Reference { + constructor(location) { + super(); + this.location = location; + return intern(this, [location]); + } +} + +/** Pointer to an Instruction as part of a Block. */ +export class InstrRef extends Reference { + constructor(instruction, block) { + super(); + this.instruction = instruction; + this.block = block; + } + /** Add `asm` into the parent assembly before this instruction. */ + add_instruction_before(asm, arch) { + const instr = arch.parse(asm.mnemonic, asm.args, this.instruction.meta.derived()); + const ref = new InstrRef(instr, this.block); + const index = this.block.instruction_refs.indexOf(this); + if (index < 0) throw new ValueError("x not in list"); + this.block.instruction_refs.splice(index, 0, ref); + return ref; + } + /** Replace the existing instruction with `new_asm`. */ + replace_instruction(new_asm, arch) { + const old_instr = this.instruction; + const new_instr = arch.parse(new_asm.mnemonic, new_asm.args, old_instr.meta.derived()); + for (const loc of [...old_instr.outputs, ...old_instr.clobbers]) { + if (!new_instr.clobbers.includes(loc)) new_instr.clobbers.push(loc); + } + this.instruction = new_instr; + } +} + +export class Block { + constructor(index, label, approx_label_name, instruction_refs = [], is_safeguard = false, block_info = null) { + this.index = index; + this.label = label; + this.approx_label_name = approx_label_name; + this.instruction_refs = instruction_refs; + this.is_safeguard = is_safeguard; + // block_info is actually an Optional[BlockInfo], set by translate.js + this.block_info = block_info; + } + get instructions() { + return this.instruction_refs.map((r) => r.instruction); + } + add_block_info(block_info) { + pyassert(this.block_info === null); + this.block_info = block_info; + } + clone() { + const ret = shallowcopy(this); + ret.instruction_refs = this.instruction_refs.map((ref) => new InstrRef(ref.instruction.clone(), ret)); + return ret; + } + toString() { + const name = `${this.index} (${this.approx_label_name})`; + const inst_str = this.instructions.map((instr) => " " + String(instr)).join("\n"); + return `# ${name}\n${inst_str}\n`; + } +} + +export class BlockBuilder { + constructor() { + this._curr_index = 0; + this._curr_label = null; + this._last_label_name = "initial"; + this._label_counter = 0; + this._curr_instructions = []; + this._blocks = []; + } + new_block() { + if (this._curr_instructions.length === 0) return null; + let label_name = this._last_label_name; + if (this._label_counter > 0) label_name += `.${this._label_counter}`; + const block = new Block(this._curr_index, this._curr_label, label_name); + for (const i of this._curr_instructions) block.instruction_refs.push(new InstrRef(i, block)); + this._blocks.push(block); + this._curr_index += 1; + this._curr_label = null; + this._label_counter += 1; + this._curr_instructions = []; + return block; + } + add_instruction(instruction) { + this._curr_instructions.push(instruction); + } + set_label(label) { + pyassert(!this._curr_label, "Cannot have two labels in a row ({label} vs {self._curr_label})"); + this._curr_label = label; + this._last_label_name = label.names[0]; + this._label_counter = 0; + } + is_empty() { + return !this._blocks.length && !this._curr_instructions.length; + } + get_blocks() { + return this._blocks; + } +} + +function verify_no_trailing_delay_slot(fn) { + let last_ins = null; + for (const item of fn.body) if (item instanceof Instruction) last_ins = item; + if (last_ins && last_ins.has_delay_slot) throw new DecompFailure(`Last instruction is missing a delay slot:\n${last_ins}`); +} + +export function invert_mips_branch_mnemonic(mnemonic) { + const inverses = { beq: "bne", bne: "beq", beqz: "bnez", bnez: "beqz", bgez: "bltz", bgtz: "blez", blez: "bgtz", bltz: "bgez", bc1t: "bc1f", bc1f: "bc1t" }; + if (!Object.prototype.hasOwnProperty.call(inverses, mnemonic)) throw new Error(`KeyError: '${mnemonic}'`); + return inverses[mnemonic]; +} + +export function internal_label(base, related = "") { + // (upstream computes `rel` but does not use it) + void (related ? lstrip(related, ".") + "_" : ""); + return `._m2c_${related}${base}`; +} + +function normalize_gcc_likely_branches(fn, arch) { + const new_function = fn.bodyless_copy(); + const new_body = new_function.body; + fn.body.forEach((item, i) => { + if (item instanceof Instruction && item.is_branch_likely && item.jump_target instanceof JumpTarget && i + 2 < fn.body.length) { + const ins = fn.body[i + 1]; + const label = fn.body[i + 2]; + if (ins instanceof Instruction && label instanceof Label && label.names.includes(item.jump_target.target)) { + const mn_inverted = invert_mips_branch_mnemonic(item.mnemonic.slice(0, -1)); + new_body.push(arch.parse(mn_inverted, item.args, item.meta.derived())); + new_body.push(arch.parse("nop", [], item.meta.derived())); + return; + } + } + new_body.push(item); + }); + return new_function; +} + +function iterOf(arr) { + const it = arr[Symbol.iterator](); + return { + next_or_throw() { + const r = it.next(); + if (r.done) throw new Error("StopIteration"); + return r.value; + }, + *[Symbol.iterator]() { + for (;;) { + const r = it.next(); + if (r.done) return; + yield r.value; + } + }, + }; +} + +function normalize_ido_likely_branches(fn, asm_data, arch) { + const seen_instrs = new Set(); + const label_names = new Map(); + const label_prev_instr = new Map(); + const label_before_instr = new Map(); + const instr_before_instr = new Map(); + let prev_instr = null; + let prev_label = null; + let prev_item = null; + for (const item of fn.body) { + if (item instanceof Instruction) { + pyassert(!seen_instrs.has(item)); + seen_instrs.add(item); + if (prev_label !== null) { + label_before_instr.set(item, prev_label.names[0]); + prev_label = null; + } + if (prev_item instanceof Instruction) instr_before_instr.set(item, prev_item); + prev_instr = item; + } else if (item instanceof Label) { + for (const name of item.names) { + label_prev_instr.set(name, prev_instr); + label_names.set(name, new Set(item.names)); + } + prev_label = item; + prev_instr = null; + } + prev_item = item; + } + + const untouched_targets = new Set(); + const addAll = (set, other) => { + for (const x of other ?? []) set.add(x); + }; + + const may_transform_branch = (item, next_item, before_target, pre = false) => { + if (!item.has_delay_slot) return false; + if (before_target === next_item) return false; + if (String(before_target) !== String(next_item)) return false; + const next_mn = next_item.mnemonic; + if (!item.is_branch_likely && next_mn === "nop") return false; + if (arch.arch === Target.ArchEnum.SH) { + pyassert(item.jump_target instanceof JumpTarget); + const label = item.jump_target.target; + if (!(next_mn.startsWith("cmp/") || next_mn === "tst")) return false; + if (untouched_targets.has(label) && !pre) return false; + } else { + if (!item.is_branch_likely && item.mnemonic !== "b") return false; + } + if (!item.is_conditional) { + const before_before_target = instr_before_instr.get(before_target) ?? null; + if (before_before_target !== null && before_before_target.has_delay_slot) return false; + } + return true; + }; + + if (arch.arch === Target.ArchEnum.SH) { + for (const label of asm_data.mentioned_labels) addAll(untouched_targets, label_names.get(label)); + for (let i = 0; i + 1 < fn.body.length; i++) { + const item = fn.body[i]; + const next_item = fn.body[i + 1]; + if (!(item instanceof Instruction)) continue; + if (Array.isArray(item.jump_target)) { + for (const target of item.jump_target) addAll(untouched_targets, label_names.get(target.target)); + } else if (item.jump_target instanceof JumpTarget) { + const before_target = label_prev_instr.get(item.jump_target.target) ?? null; + if (next_item instanceof Instruction && before_target !== null && may_transform_branch(item, next_item, before_target, true)) continue; + addAll(untouched_targets, label_names.get(item.jump_target.target)); + } + } + } + + const insert_label_before = new Map(); + const new_body = []; + const body_iter = iterOf(fn.body); + for (const item of body_iter) { + if (!(item instanceof Instruction) || !(item.jump_target instanceof JumpTarget)) { + new_body.push([item, item]); + continue; + } + const next_item = body_iter.next_or_throw(); + const before_target = label_prev_instr.get(item.jump_target.target) ?? null; + if (next_item instanceof Instruction && before_target !== null && may_transform_branch(item, next_item, before_target)) { + if (!label_before_instr.has(before_target)) { + const new_label = internal_label("before", item.jump_target.target); + label_before_instr.set(before_target, new_label); + insert_label_before.set(before_target, new_label); + } + const new_target = label_before_instr.get(before_target); + const mn = item.mnemonic; + const mn_unlikely = item.is_branch_likely ? mn.slice(0, -1) : mn; + const new_item = arch.parse(mn_unlikely, [...item.args.slice(0, -1), new AsmGlobalSymbol(new_target)], item.meta.derived()); + let new_next_item; + if (item.is_conditional && !item.is_branch_likely) new_next_item = next_item; + else new_next_item = arch.parse("nop", [], new_item.meta.derived()); + new_body.push([item, new_item]); + new_body.push([next_item, new_next_item]); + } else { + new_body.push([item, item]); + new_body.push([next_item, next_item]); + } + } + + const new_function = fn.bodyless_copy(); + for (const [orig_item, new_item] of new_body) { + if (orig_item instanceof Instruction && insert_label_before.has(orig_item)) new_function.new_label(insert_label_before.get(orig_item)); + new_function.body.push(new_item); + } + return new_function; +} + +function minimize_labels(fn, asm_data) { + const labels_used = new Set(); + for (const label of fn.body) if (label instanceof Label) for (const name of label.names) if (asm_data.mentioned_labels.has(name)) labels_used.add(name); + for (const item of fn.body) { + if (item instanceof Instruction) { + if (item.jump_target instanceof JumpTarget) labels_used.add(item.jump_target.target); + if (item.function_target instanceof AsmGlobalSymbol) labels_used.add(item.function_target.symbol_name); + } + } + const new_function = fn.bodyless_copy(); + let cur_label = []; + for (const item of fn.body) { + if (item instanceof Label) cur_label.push(...item.names.filter((name) => labels_used.has(name))); + else { + if (cur_label.length) { + new_function.body.push(new Label(cur_label)); + cur_label = []; + } + new_function.body.push(item); + } + } + if (cur_label.length) new_function.body.push(new Label(cur_label)); + return new_function; +} + +function simplify_standard_patterns(fn, asm_data, arch, debug_patterns) { + const new_body = simplify_patterns(fn.body, arch.asm_patterns, asm_data, arch, { debug_patterns }); + const new_function = fn.bodyless_copy(); + new_function.body.push(...new_body); + return new_function; +} + +function build_blocks(fn, asm_data, arch, { fragment, debug_patterns }) { + if (!fragment) { + if (arch.has_delay_slots) { + verify_no_trailing_delay_slot(fn); + fn = minimize_labels(fn, asm_data); + if (arch.arch === Target.ArchEnum.MIPS) fn = normalize_gcc_likely_branches(fn, arch); + fn = normalize_ido_likely_branches(fn, asm_data, arch); + } + fn = minimize_labels(fn, asm_data); + fn = simplify_standard_patterns(fn, asm_data, arch, debug_patterns); + fn = minimize_labels(fn, asm_data); + } + + const block_builder = new BlockBuilder(); + const body_iter = iterOf(fn.body); + const branch_likely_counts = new Map(); + let cond_return_target = null; + + const process_delay_slots = (item) => { + if (item instanceof Label) { + block_builder.new_block(); + block_builder.set_label(item); + return; + } + if (!item.has_delay_slot) { + process_no_delay_slots(item); + return; + } + const process_after = []; + let next_item = body_iter.next_or_throw(); + + if (next_item instanceof Label) { + const label = next_item; + next_item = body_iter.next_or_throw(); + pyassert(next_item instanceof Instruction, "Cannot have two labels in a row"); + if (item.is_branch_likely || item.function_target !== null) { + let msg = [ + `Label ${label} refers to a delay slot; this is currently not supported.`, + "Please modify the assembly to work around it (e.g. copy the instruction", + "to all jump sources and move the label, or add a nop to the delay slot).", + ]; + if (label.names[0].includes("_before")) { + msg = msg.concat([ + "", + "This label was auto-generated as the target for a branch-likely", + "instruction (e.g. beql); you can also try to turn that into a non-likely", + "branch if that's equivalent in this context, i.e., if it's okay to", + "execute its delay slot unconditionally.", + ]); + } + throw new DecompFailure(msg.join("\n")); + } else if (next_item.outputs.every((x) => !next_item.inputs.includes(x)) && !next_item.is_store) { + process_after.push(label); + process_after.push(next_item.clone()); + } else { + pyassert(item.jump_target instanceof JumpTarget, "has delay slot and isn't a call"); + const target = item.jump_target.target; + const temp_label = internal_label("skip", label.names[0]); + const meta = item.meta.derived(); + const nop = arch.parse("nop", [], meta); + block_builder.add_instruction(arch.parse(item.mnemonic, [...item.args.slice(0, -1), new AsmGlobalSymbol(temp_label)], item.meta)); + block_builder.add_instruction(nop); + block_builder.new_block(); + block_builder.add_instruction(arch.parse("b", [new AsmGlobalSymbol(label.names[0])], item.meta.derived())); + block_builder.add_instruction(nop.clone()); + block_builder.new_block(); + block_builder.set_label(Label.new(temp_label)); + block_builder.add_instruction(arch.parse("b", [new AsmGlobalSymbol(target)], item.meta.derived())); + block_builder.add_instruction(next_item.clone()); + block_builder.new_block(); + block_builder.set_label(label); + block_builder.add_instruction(next_item); + return; + } + } + + if (next_item.has_delay_slot) throw new DecompFailure(`Two delay slot instructions in a row is not supported:\n${item}\n${next_item}`); + + if (item.is_branch_likely) { + pyassert(item.jump_target instanceof JumpTarget); + const target = item.jump_target.target; + branch_likely_counts.set(target, (branch_likely_counts.get(target) ?? 0) + 1); + const index = branch_likely_counts.get(target); + const mn_inverted = invert_mips_branch_mnemonic(item.mnemonic.slice(0, -1)); + const temp_label = internal_label(`branchlikelyskip_${index}`, target); + const branch_not = arch.parse(mn_inverted, [...item.args.slice(0, -1), new AsmGlobalSymbol(temp_label)], item.meta.derived()); + const nop = arch.parse("nop", [], item.meta.derived()); + block_builder.add_instruction(branch_not); + block_builder.add_instruction(nop); + block_builder.new_block(); + block_builder.add_instruction(next_item); + block_builder.add_instruction(arch.parse("b", [new AsmGlobalSymbol(target)], item.meta.derived())); + block_builder.add_instruction(nop.clone()); + block_builder.new_block(); + block_builder.set_label(Label.new(temp_label)); + block_builder.add_instruction(nop.clone()); + } else if (item.function_target !== null) { + if (item.args.length >= 2 && (next_item.outputs.includes(item.args[1]) || next_item.clobbers.includes(item.args[1]))) { + throw new DecompFailure(`Instruction after ${item.mnemonic} clobbers its source\n` + "register, which is currently not supported.\n\n" + "Try rewriting the assembly to avoid that."); + } + block_builder.add_instruction(next_item); + block_builder.add_instruction(item); + } else { + block_builder.add_instruction(item); + block_builder.add_instruction(next_item); + } + + if (item.is_jump()) block_builder.new_block(); + + for (const it of process_after) process_delay_slots(it); + }; + + const process_no_delay_slots = (item) => { + if (item instanceof Label) { + block_builder.new_block(); + block_builder.set_label(item); + return; + } + if (item.is_conditional && Array.isArray(item.jump_target)) { + for (let i = 0; i < item.jump_target.length; i++) { + if (item.jump_target[i] === new JumpTarget("_m2c_ret")) { + if (cond_return_target === null) cond_return_target = internal_label("conditionalreturn"); + item.jump_target[i] = new JumpTarget(cond_return_target); + } + } + } + if (item.is_conditional && item.is_return) { + if (cond_return_target === null) cond_return_target = internal_label("conditionalreturn"); + pyassert(item.mnemonic.slice(-2) === "lr"); + const branch_instr = arch.parse(item.mnemonic.slice(0, -2), [new AsmGlobalSymbol(cond_return_target)], item.meta.derived()); + block_builder.add_instruction(branch_instr); + block_builder.new_block(); + return; + } + block_builder.add_instruction(item); + if (item.is_jump()) block_builder.new_block(); + }; + + if (arch.has_delay_slots && !fragment) { + for (const item of body_iter) process_delay_slots(item); + } else { + for (const item of body_iter) process_no_delay_slots(item); + } + + if (block_builder.is_empty()) throw new DecompFailure(`Function ${fn.name} contains no instructions. Maybe it is rodata?`); + + if (fragment) { + block_builder.new_block(); + return block_builder.get_blocks(); + } + + for (const instr of arch.missing_return()) block_builder.add_instruction(instr); + const emitted_block = block_builder.new_block(); + pyassert(emitted_block !== null); + emitted_block.is_safeguard = true; + + if (cond_return_target !== null) { + block_builder.set_label(Label.new(cond_return_target)); + for (const instr of arch.missing_return()) block_builder.add_instruction(instr); + block_builder.new_block(); + } + return block_builder.get_blocks(); +} + +function verify_no_duplicate_instructions(blocks) { + const seen = new Set(); + for (const block of blocks) { + for (const instr of block.instructions) { + pyassert(!seen.has(instr), "Instructions must be clone()ed if emitted twice"); + seen.add(instr); + } + } +} + +export class BaseNode { + constructor(block, emit_goto) { + this.block = block; + this.emit_goto = emit_goto; + this.parents = []; + this.dominators = new Set(); + this.immediate_dominator = null; + this.immediately_dominates = []; + this.postdominators = new Set(); + this.immediate_postdominator = null; + this.immediately_postdominates = []; + // This is only populated on the head node of the loop + this.loop = null; + } + name() { + return String(this.block.index); + } + children() { + throw new Error("abstract"); + } + __repr__() { + return `<${this.constructor.name}: ${this.name()}>`; + } +} + +export class BasicNode extends BaseNode { + constructor(block, emit_goto, successor, fake_successor = null) { + super(block, emit_goto); + this.successor = successor; + // Optional link to the TerminalNode, used to make infinite loops reducible. + this.fake_successor = fake_successor; + } + children() { + if (this.fake_successor !== null) return [this.successor, this.fake_successor]; + return [this.successor]; + } + toString() { + return [`${this.block}\n`, `# ${this.name()} -> ${this.successor.name()}`, this.loop ? " (loop)" : "", this.emit_goto ? " (goto)" : ""].join(""); + } +} + +export class ConditionalNode extends BaseNode { + constructor(block, emit_goto, conditional_edge, fallthrough_edge) { + super(block, emit_goto); + this.conditional_edge = conditional_edge; + this.fallthrough_edge = fallthrough_edge; + } + children() { + if (this.conditional_edge === this.fallthrough_edge) return [this.conditional_edge]; + return [this.conditional_edge, this.fallthrough_edge]; + } + toString() { + return [ + `${this.block}\n`, + `# ${this.name()} -> `, + `cond: ${this.conditional_edge.name()}`, + this.loop ? " (loop)" : "", + ", ", + `def: ${this.fallthrough_edge.name()}`, + this.emit_goto ? " (goto)" : "", + ].join(""); + } +} + +export class ReturnNode extends BaseNode { + constructor(block, emit_goto, index, terminal) { + super(block, emit_goto); + this.index = index; + this.terminal = terminal; + } + children() { + return [this.terminal]; + } + name() { + const name = super.name(); + return this.is_real() ? name : `${name}.${this.index}`; + } + is_real() { + return this.index === 0; + } + toString() { + return [`${this.block}\n`, `# ${this.name()} -> ret`, this.emit_goto ? " (goto)" : ""].join(""); + } +} + +export class SwitchNode extends BaseNode { + constructor(block, emit_goto, cases) { + super(block, emit_goto); + this.cases = cases; + } + children() { + const seen = new Set(); + const children = []; + for (const node of this.cases) { + if (!seen.has(node)) { + seen.add(node); + children.push(node); + } + } + return children; + } + toString() { + const targets = this.cases.map((c) => c.name()).join(", "); + return `${this.block}\n# ${this.name()} -> ${targets}`; + } +} + +/** A fictive node that acts as a common postdominator for every node in the flowgraph. */ +export class TerminalNode extends BaseNode { + static terminal() { + return new TerminalNode(new Block(-1, null, "", []), false); + } + children() { + return []; + } + toString() { + return "return"; + } +} + +export class NaturalLoop { + constructor(head, nodes = new Set(), backedges = new Set()) { + this.head = head; + this.nodes = nodes; + this.backedges = backedges; + } +} + +export function get_literal_pool_symbolic_data(arg, asm_data) { + let offset = 0; + if (arg instanceof BinOp && arg.op === "+" && arg.rhs instanceof AsmLiteral) { + offset = arg.rhs.value; + arg = arg.lhs; + } + if (!(arg instanceof AsmGlobalSymbol)) return null; + const ent = asm_data.values.get(arg.symbol_name) ?? null; + if (ent === null || !ent.is_text) return null; + const data = ent.data_at_offset(offset, 4); + if (!(data instanceof AsmSymbolicData)) return null; + return data; +} + +export function get_literal_pool_symbol(arg, asm_data) { + const data = get_literal_pool_symbolic_data(arg, asm_data); + if (data === null) return null; + return data.as_symbol_without_addend(); +} + +export function arm_jtbl_for_ldr(arg, asm_data) { + const jtbl_name = get_literal_pool_symbol(arg, asm_data); + if (jtbl_name === null) return null; + const ent = asm_data.values.get(jtbl_name) ?? null; + if (ent === null || !ent.is_text || !ent.data.length || !(ent.data[0] instanceof AsmSymbolicData) || ent.data[0].as_symbol_without_addend() === null) return null; + return jtbl_name; +} + +function build_graph_from_block(block, blocks, parent_blocks, nodes, asm_data, arch) { + for (const node of nodes) if (node.block === block) return node; + + let new_node; + const dummy_node = null; + const terminal_node = nodes[0]; + pyassert(terminal_node instanceof TerminalNode, "expected first node to be TerminalNode"); + + const find_block_by_label = (label) => { + for (const b of blocks) if (b.label && b.label.names.includes(label)) return b; + return null; + }; + const blockAt = (i) => { + if (i >= blocks.length) throw new Error("IndexError: list index out of range"); + return blocks[i]; + }; + + const jumps = block.instructions.filter((inst) => inst.is_jump()); + pyassert(jumps.length === 0 || jumps.length === 1, "too many jump instructions in one block"); + + if (jumps.length === 0) { + new_node = new BasicNode(block, false, dummy_node); + nodes.push(new_node); + const next_block = blockAt(block.index + 1); + new_node.successor = build_graph_from_block(next_block, blocks, [...parent_blocks, block], nodes, asm_data, arch); + } else if (jumps.length === 1) { + const jump = jumps[0]; + + if (jump.is_return) { + new_node = new ReturnNode(block, false, 0, terminal_node); + nodes.push(new_node); + return new_node; + } + + if (jump.jump_target instanceof Register) { + new_node = new SwitchNode(block, false, []); + nodes.push(new_node); + + const jtbl_names = new Set(); + for (const jtbl_block of [block, ...[...parent_blocks].reverse()]) { + for (const ins of jtbl_block.instructions) { + for (let arg of ins.args) { + if (arg instanceof AsmAddressMode) arg = arg.addend; + if ( + arg instanceof Macro && + (arg.macro_name === "lo" || arg.macro_name === "l") && + arg.argument instanceof AsmGlobalSymbol && + ["jtbl", "jpt_", "lbl_", "jumptable_"].some((prefix) => arg.argument.symbol_name.startsWith(prefix)) + ) { + jtbl_names.add(arg.argument.symbol_name); + } + if (ins.arch_mnemonic(arch) === "arm:ldr") { + const jtbl_name = arm_jtbl_for_ldr(arg, asm_data); + if (jtbl_name !== null) jtbl_names.add(jtbl_name); + } + } + } + if (jtbl_names.size) break; + } + if (jtbl_names.size > 1) { + throw new DecompFailure( + `Unable to determine jump table for ${jump.mnemonic} instruction ${jump.meta.loc_str()}.\n\n` + + `Found multiple candidates: ${sorted(jtbl_names).join(", ")}\n` + + "You can help m2c's analysis by putting a copy of the jump table\n" + + "setup instructions within the same block as the jump instruction.", + ); + } + if (!jtbl_names.size) { + let help_text = ""; + if (arch.arch !== Target.ArchEnum.ARM) { + help_text = "\n\nThere must be a read of a variable before the instruction\n" + 'which has a name starting with with "jtbl"/"jpt_"/"lbl_"/"jumptable_".'; + } + throw new DecompFailure(`Unable to determine jump table for ${jump.mnemonic} instruction ${jump.meta.loc_str()}.${help_text}`); + } + + const jtbl_name = [...jtbl_names][0]; + if (!asm_data.values.has(jtbl_name)) { + throw new DecompFailure( + `Found ${jump.mnemonic} instruction ${jump.meta.loc_str()}, but the ` + + "corresponding jump table is not provided.\n" + + "\n" + + "Please include it in the input .s file(s), or in an additional file.\n", + ); + } + const jtbl_value = asm_data.values.get(jtbl_name); + jtbl_value.is_jtbl = true; + for (const entry of jtbl_value.data) { + if (entry instanceof Uint8Array) break; + const sym = entry.as_symbol_without_addend(); + if (sym === null) break; + const case_block = find_block_by_label(sym); + if (case_block === null) throw new DecompFailure(`Cannot find jtbl target ${sym}`); + const case_node = build_graph_from_block(case_block, blocks, [...parent_blocks, block], nodes, asm_data, arch); + new_node.cases.push(case_node); + } + return new_node; + } + + if (Array.isArray(jump.jump_target)) { + new_node = new SwitchNode(block, false, []); + nodes.push(new_node); + for (const jump_target of jump.jump_target) { + const case_block = find_block_by_label(jump_target.target); + if (case_block === null) throw new DecompFailure(`Cannot find jtbl target ${jump_target}`); + const case_node = build_graph_from_block(case_block, blocks, [...parent_blocks, block], nodes, asm_data, arch); + new_node.cases.push(case_node); + } + return new_node; + } + + const branch_label = jump.jump_target; + pyassert(branch_label instanceof JumpTarget); + const branch_block = find_block_by_label(branch_label.target); + if (branch_block === null) throw new DecompFailure(`Cannot find branch target ${branch_label.target}`); + + const emit_goto = jump.meta.emit_goto; + if (!jump.is_conditional) { + new_node = new BasicNode(block, emit_goto, dummy_node); + nodes.push(new_node); + new_node.successor = build_graph_from_block(branch_block, blocks, [...parent_blocks, block], nodes, asm_data, arch); + } else { + new_node = new ConditionalNode(block, emit_goto, dummy_node, dummy_node); + nodes.push(new_node); + const next_block = blockAt(block.index + 1); + new_node.conditional_edge = build_graph_from_block(branch_block, blocks, [...parent_blocks, block], nodes, asm_data, arch); + new_node.fallthrough_edge = build_graph_from_block(next_block, blocks, [...parent_blocks, block], nodes, asm_data, arch); + } + } + return new_node; +} + +function is_trivial_return_block(block, arch) { + for (const instr of block.instructions) { + if (instr.is_store || instr.function_target !== null) return false; + if ([...instr.inputs, ...instr.outputs].some((reg) => arch.all_return_regs.includes(reg))) return false; + } + return true; +} + +/** Return the set of nodes that can reach `end` with `without` removed. */ +function inv_reachable_without(end, without) { + const reachable = new Set(); + const stack = [end]; + while (stack.length) { + const node = stack.pop(); + if (node === without || reachable.has(node)) continue; + reachable.add(node); + stack.push(...node.parents); + } + return reachable; +} + +function build_nodes(fn, blocks, asm_data, arch, { fragment }) { + const terminal_node = TerminalNode.terminal(); + const graph = [terminal_node]; + if (fragment) blocks.push(terminal_node.block); + const entry_block = blocks[0]; + build_graph_from_block(entry_block, blocks, [], graph, asm_data, arch); + const terms = graph.filter((n) => n instanceof TerminalNode); + pyassert(terms.length === 1 && terms[0] === terminal_node); + terminal_node.block.index = Math.max(...graph.map((n) => n.block.index)) + 1; + graph.sort((a, b) => a.block.index - b.block.index); + return graph; +} + +function warn_on_safeguard_use(fn, nodes, arch) { + const node = nodes.find((n) => n.block.is_safeguard) ?? null; + if (node) { + const label = node.block.approx_label_name; + const return_instrs = arch.missing_return(); + print(`Warning: missing "${return_instrs[0]}" in last block of ${fn.name} (${label}).\n`); + } +} + +/** Check whether a given edge in the flow graph is an early return. */ +function is_premature_return(node, edge, nodes, arch) { + if (nodes.length < 3) return false; + const [antepenultimate_node, final_return_node, terminal_node] = nodes.slice(-3); + pyassert(terminal_node instanceof TerminalNode); + if (!(edge instanceof ReturnNode) || edge !== final_return_node) return false; + if (!is_trivial_return_block(edge.block, arch)) return false; + if (!(node instanceof BasicNode)) return false; + return node !== antepenultimate_node; +} + +/** For each jump to an early return node, create a duplicate return node for it to jump to. */ +function duplicate_premature_returns(nodes, arch) { + const extra_nodes = []; + let index = 0; + for (const node of nodes) { + if (node instanceof BasicNode && !node.emit_goto && is_premature_return(node, node.successor, nodes, arch)) { + pyassert(node.successor instanceof ReturnNode); + index += 1; + const n = new ReturnNode(node.successor.block.clone(), false, index, node.successor.terminal); + node.successor = n; + extra_nodes.push(n); + } + } + nodes.push(...extra_nodes); + nodes.sort((a, b) => a.block.index - b.block.index); + + const queue = [nodes[0]]; + const reachable_nodes = new Set(nodes.filter((n) => n instanceof TerminalNode)); + while (queue.length) { + const node = queue.pop(); + reachable_nodes.add(node); + for (const c of node.children()) if (!reachable_nodes.has(c) && !queue.includes(c)) queue.push(c); + } + return nodes.filter((n) => reachable_nodes.has(n)); +} + +/** Compute dominators, postdominators, and backedges for the set of nodes. */ +export function compute_relations(nodes) { + for (const node of nodes) node.parents = []; + for (const node of nodes) for (const child of node.children()) child.parents.push(node); + + const nnodes = nodes.length; + const index_of = new Map(nodes.map((n, i) => [n, i])); + const words = Math.ceil(nnodes / 32) || 1; + + const compute_dominators = (entry, parents, dominators, immediately_dominates, set_immediate_dominator) => { + // Bitsets as Uint32Array words (Python uses big ints). + const doms = new Map(); + nodes.forEach((n, i) => { + const bs = new Uint32Array(words); + if (n === entry) bs[i >>> 5] |= 1 << (i & 31); + else { + for (let w = 0; w < words; w++) bs[w] = 0xffffffff; + const extra = words * 32 - nnodes; + if (extra > 0) bs[words - 1] = 0xffffffff >>> extra; + } + doms.set(n, bs); + }); + let changes = true; + while (changes) { + changes = false; + nodes.forEach((node, i) => { + if (node === entry) return; + const nset = Uint32Array.from(doms.get(node)); + for (const parent of parents(node)) { + const p = doms.get(parent); + for (let w = 0; w < words; w++) nset[w] &= p[w]; + } + nset[i >>> 5] |= 1 << (i & 31); + const cur = doms.get(node); + let differ = false; + for (let w = 0; w < words; w++) if (nset[w] !== cur[w]) differ = true; + if (differ) { + for (let w = 0; w < words; w++) pyassert((nset[w] & cur[w]) >>> 0 === nset[w] >>> 0); + doms.set(node, nset); + changes = true; + } + }); + } + for (const n of nodes) { + const bitset = doms.get(n); + const nodeset = dominators(n); + nodeset.clear(); + for (let i = 0; i < nnodes; i++) if (bitset[i >>> 5] & (1 << (i & 31))) nodeset.add(nodes[i]); + } + for (const node of nodes) immediately_dominates(node).length = 0; + for (const node of nodes) { + const ds = [...dominators(node)].filter((d) => d !== node); + if (ds.length) { + let imdom = null; + let best = null; + for (const d of ds) { + const key = [dominators(d).size, d.block.index]; + if (best === null || compare(key, best) > 0) { + best = key; + imdom = d; + } + } + immediately_dominates(imdom).push(node); + set_immediate_dominator(node, imdom); + } else set_immediate_dominator(node, null); + } + for (const node of nodes) immediately_dominates(node).sort((x, y) => x.block.index - y.block.index); + }; + void index_of; + + const entry = nodes[0]; + const terminal = nodes[nodes.length - 1]; + pyassert(terminal instanceof TerminalNode); + + compute_dominators( + entry, + (n) => n.parents, + (n) => n.dominators, + (n) => n.immediately_dominates, + (node, imdom) => { + node.immediate_dominator = imdom; + }, + ); + compute_dominators( + terminal, + (n) => n.children(), + (n) => n.postdominators, + (n) => n.immediately_postdominates, + (node, impdom) => { + node.immediate_postdominator = impdom; + }, + ); + + for (const node of nodes) { + for (const child of node.children()) { + if (!node.dominators.has(child)) continue; + if (child.loop === null) child.loop = new NaturalLoop(child); + child.loop.nodes.add(child); + child.loop.nodes.add(node); + child.loop.backedges.add(node); + for (const parent of inv_reachable_without(node, child)) child.loop.nodes.add(parent); + } + } +} + +function reachable_backwards(start) { + const seen = new Set(); + const queue = [start]; + while (queue.length) { + const n = queue.pop(); + seen.add(n); + for (const p of n.parents) if (!seen.has(p) && !queue.includes(p)) queue.push(p); + } + return seen; +} + +function terminate_infinite_loops(nodes) { + const terminal_node = nodes[nodes.length - 1]; + pyassert(terminal_node instanceof TerminalNode); + for (;;) { + const seen = reachable_backwards(terminal_node); + const unterminated_nodes = nodes.filter((node) => !seen.has(node) && node instanceof BasicNode); + if (!unterminated_nodes.length) return; + unterminated_nodes[unterminated_nodes.length - 1].fake_successor = terminal_node; + compute_relations(nodes); + } +} + +/** A set of References, backed by a list to avoid non-determinism */ +export class RefSet { + constructor(refs = []) { + this.refs = refs; + } + static empty() { + return new RefSet([]); + } + is_empty() { + return this.refs.length === 0; + } + get length() { + return this.refs.length; + } + get_unique() { + if (this.refs.length === 1) return this.refs[0]; + return null; + } + add(ref) { + if (!this.refs.includes(ref)) this.refs.push(ref); + } + update(other) { + for (const ref of other.refs) this.add(ref); + } + remove(ref) { + const i = this.refs.indexOf(ref); + if (i < 0) throw new ValueError("list.remove(x): x not in list"); + this.refs.splice(i, 1); + } + copy() { + return new RefSet([...this.refs]); + } + has(ref) { + return this.refs.includes(ref); + } + [Symbol.iterator]() { + return this.refs[Symbol.iterator](); + } + equals(other) { + return this.refs.length === other.refs.length && this.refs.every((x) => other.has(x)); + } +} + +/** A map from Locations to RefSets. A missing key is equivalent to an empty RefSet. */ +export class LocationRefSetDict { + constructor(refs = new Map()) { + this.refs = refs; + } + get(loc) { + return this.refs.get(loc) ?? RefSet.empty(); + } + add(loc, ref) { + if (!this.has(loc)) this.refs.set(loc, new RefSet([ref])); + else this.refs.get(loc).add(ref); + } + remove(loc) { + this.refs.delete(loc); + } + copy() { + return new LocationRefSetDict(new Map(this.refs)); + } + items() { + return [...this.refs.entries()]; + } + is_empty() { + for (const v of this.refs.values()) if (v.refs.length) return false; + return true; + } + /** Python __contains__: the location maps to a non-empty RefSet */ + has(key) { + return this.get(key).refs.length > 0; + } + set(key, value) { + this.refs.set(key, value); + } +} + +export class FlowGraph { + constructor(nodes) { + this.nodes = nodes; + this.instr_inputs = new DefaultMap(() => new LocationRefSetDict()); + this.instr_uses = new DefaultMap(() => new LocationRefSetDict()); + } + entry_node() { + return this.nodes[0]; + } + terminal_node() { + const node = this.nodes[this.nodes.length - 1]; + pyassert(node instanceof TerminalNode); + return node; + } + /** A control flow graph is considered reducible or "well-structured" (see upstream docs). */ + is_reducible() { + const seen = new Set(); + const queue = [this.entry_node()]; + const incoming_edges = new Map(); + for (const n of this.nodes) { + const s = new Set(n.parents); + if (n.loop) for (const b of n.loop.backedges) s.delete(b); + incoming_edges.set(n, s); + } + while (queue.length) { + const n = queue.pop(); + seen.add(n); + for (const s of n.children()) { + if (s.loop !== null && s.loop.backedges.has(n)) continue; + const inc = incoming_edges.get(s); + if (!inc.has(n)) throw new Error(`KeyError: ${n.name()}`); + inc.delete(n); + if (!inc.size && !queue.includes(s)) queue.push(s); + } + } + for (const v of incoming_edges.values()) if (v.size) return false; + if (seen.size !== this.nodes.length) return false; + const seen2 = reachable_backwards(this.terminal_node()); + if (seen2.size !== this.nodes.length) return false; + return true; + } + reset_block_info() { + for (const node of this.nodes) node.block.block_info = null; + } + /** Update instr_inputs/instr_uses that `use` depends on `loc` from `src` */ + add_instruction_use({ use, loc, src }) { + this.instr_inputs.get(use).add(loc, src); + this.instr_uses.get(src).add(loc, use); + } + /** Remove all inputs for `ref` from instr_inputs/instr_uses */ + clear_instruction_inputs(ref) { + for (const [loc, uses] of this.instr_inputs.get(ref).items()) { + for (const use of uses) this.instr_uses.get(use).get(loc).remove(ref); + } + this.instr_inputs.delete(ref); + } + /** Verify that the instr_inputs & instr_uses dicts are consistent */ + validate_instruction_graph() { + const new_uses = new DefaultMap(() => new LocationRefSetDict()); + for (const [ref, inputs] of this.instr_inputs) { + for (const [reg, deps] of inputs.items()) for (const dep of deps) new_uses.get(dep).add(reg, ref); + } + for (const [ref, uses] of new_uses) { + for (const [reg, deps] of uses.items()) pyassert(deps.equals(this.instr_uses.get(ref).get(reg))); + } + } +} + +/** Return the RefSet of all of the places `loc` is assigned to, if it is a valid phi. */ +function phi_loc_sources(node, loc, imdom_srcs) { + pyassert(node.immediate_dominator !== null); + const seen = new Set(); + const stack = [...node.parents]; + const sources = new RefSet(); + while (stack.length) { + const n = stack.pop(); + if (seen.has(n)) continue; + seen.add(n); + if (n === node.immediate_dominator) { + if (imdom_srcs.is_empty()) return RefSet.empty(); + sources.update(imdom_srcs); + continue; + } + let broke = false; + const refs = n.block.instruction_refs; + for (let i = refs.length - 1; i >= 0; i--) { + const ref = refs[i]; + if (ref.instruction.outputs.includes(loc)) { + sources.add(ref); + broke = true; + break; + } + if (ref.instruction.clobbers.includes(loc)) return RefSet.empty(); + } + if (!broke) stack.push(...n.parents); + } + return sources; +} + +export function locs_clobbered_until_dominator(node) { + pyassert(node.immediate_dominator !== null); + const seen = new Set([node.immediate_dominator]); + const stack = [...node.parents]; + const clobbered = new Set(); + while (stack.length) { + const n = stack.pop(); + if (seen.has(n)) continue; + seen.add(n); + for (const instr of n.block.instructions) { + for (const o of instr.outputs) clobbered.add(o); + for (const c of instr.clobbers) clobbered.add(c); + } + stack.push(...n.parents); + } + return clobbered; +} + +function compute_flowgraph_inputs_uses(flow_graph, fn, arch, { print_warnings = false } = {}) { + const missing_regs = []; + + const process_node = (node, loc_srcs) => { + const add_use_sources = ({ use, input_loc }) => { + const sources = loc_srcs.get(input_loc); + for (const src of sources) flow_graph.add_instruction_use({ use, loc: input_loc, src }); + return sources; + }; + + for (const ref of node.block.instruction_refs) { + const ir = ref.instruction; + for (const inp of ir.inputs) { + const sources = add_use_sources({ use: ref, input_loc: inp }); + if (inp instanceof Register && sources.is_empty() && (ir.function_target === null || !arch.argument_regs.includes(inp))) { + missing_regs.push([inp, ref]); + } + } + for (const clob of [...ir.clobbers, ...ir.outputs]) if (loc_srcs.has(clob)) loc_srcs.remove(clob); + for (const out of ir.outputs) loc_srcs.add(out, ref); + } + + if (node instanceof TerminalNode) { + pyassert(!node.block.instruction_refs.length); + for (const reg of arch.all_return_regs) add_use_sources({ use: new EpilogueRef(reg), input_loc: reg }); + } + + for (const child of node.immediately_dominates) { + const child_loc_srcs = loc_srcs.copy(); + for (const loc of locs_clobbered_until_dominator(child)) { + const phi_reg_srcs = phi_loc_sources(child, loc, loc_srcs.get(loc)); + if (!phi_reg_srcs.is_empty()) child_loc_srcs.set(loc, phi_reg_srcs); + else if (child_loc_srcs.has(loc)) child_loc_srcs.remove(loc); + } + process_node(child, child_loc_srcs); + } + }; + + const entry_reg_srcs = new LocationRefSetDict(); + for (const r of arch.all_regs) entry_reg_srcs.refs.set(r, new RefSet([new PrologueRef(r)])); + + const entry_node = flow_graph.entry_node(); + process_node(entry_node, entry_reg_srcs); + + if (print_warnings && missing_regs.length) { + print("/*"); + print(`Warning: in ${fn.name}, regs were read before being written to:`); + for (const [reg, ref] of missing_regs) print(` ${reg} ${ref.instruction.meta.loc_str()}: ${ref.instruction}`); + print("*/"); + } +} + +/** + * Build the FlowGraph for the given Function. + * If `fragment` is true, do not treat the asm as a full function. + */ +export function build_flowgraph(fn, asm_data, arch, { fragment, print_warnings = false, debug_patterns = false }) { + const blocks = build_blocks(fn, asm_data, arch, { fragment, debug_patterns }); + verify_no_duplicate_instructions(blocks); + let nodes = build_nodes(fn, blocks, asm_data, arch, { fragment }); + warn_on_safeguard_use(fn, nodes, arch); + if (!fragment) nodes = duplicate_premature_returns(nodes, arch); + compute_relations(nodes); + if (!fragment) terminate_infinite_loops(nodes); + const flow_graph = new FlowGraph(nodes); + if (!fragment) arch.process_flowgraph(asm_data, flow_graph); + compute_flowgraph_inputs_uses(flow_graph, fn, arch, { print_warnings: print_warnings || fragment }); + if (!fragment) arch.simplify_ir(asm_data, flow_graph, { debug_patterns }); + return flow_graph; +} + +export { Function }; diff --git a/packages/romdev-m2c/src/if_statements.js b/packages/romdev-m2c/src/if_statements.js new file mode 100644 index 00000000..c9345a51 --- /dev/null +++ b/packages/romdev-m2c/src/if_statements.js @@ -0,0 +1,960 @@ +// Port of m2c/if_statements.py +/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */ +import { BasicNode, ConditionalNode, ReturnNode, SwitchNode, TerminalNode } from "./flow_graph.js"; +import { Target } from "./options.js"; +import { BinaryOp, CommaConditionExpr, Condition, Literal, SwitchControl, early_unwrap_ints, format_expr, get_block_info, simplify_condition } from "./translate.js"; +import { Type } from "./types.js"; +import { DefaultMap, dcinit, dcreplace, factory, format, lstrip, pyassert, pyeq, sorted } from "./py.js"; + +export class Context { + constructor({ flow_graph, fmt, options, is_void = true }) { + this.flow_graph = flow_graph; + this.fmt = fmt; + this.options = options; + this.is_void = is_void; + this.switch_nodes = new Map(); + this.case_nodes = new DefaultMap(() => []); + this.goto_nodes = new Set(); + this.emitted_nodes = new Set(); + this.has_warned = false; + } + add_switch(node) { + this.switch_nodes.set(node, 0); + return new SwitchIndex(this, node); + } +} + +export class IfElseStatement { + constructor(condition, if_body, else_body = null) { + this.condition = condition; + this.if_body = if_body; + this.else_body = else_body; + } + should_write() { + return true; + } + format(fmt) { + const space = fmt.indent(""); + const condition = simplify_condition(this.condition); + const cond_str = format_expr(condition, fmt); + const after_ifelse = fmt.coding_style.newline_after_if ? `\n${space}` : " "; + const before_else = fmt.coding_style.newline_before_else ? `\n${space}` : " "; + let if_str = fmt.indented(() => [`${space}if (${cond_str})${after_ifelse}{`, this.if_body.format(fmt), `${space}}`].join("\n")); + if (this.else_body !== null && !this.else_body.is_empty()) { + const sub_if = this.else_body.get_lone_if_statement(); + let else_str; + if (sub_if) { + const sub_if_str = lstrip(sub_if.format(fmt)); + else_str = `${before_else}else ${sub_if_str}`; + } else { + else_str = fmt.indented(() => [`${before_else}else${after_ifelse}{`, this.else_body.format(fmt), `${space}}`].join("\n")); + } + if_str = if_str + else_str; + } + return if_str; + } +} + +export class SwitchIndex { + constructor(context, node) { + this.context = context; + this.node = node; + } + equals(other) { + return other instanceof SwitchIndex && this.context === other.context && this.node === other.node; + } + to_comment(fmt) { + const index = this.context.switch_nodes.get(this.node); + if (this.context.switch_nodes.size === 1) return null; + return `switch ${index + 1}`; + } +} + +export class SwitchStatement { + constructor(jump, body, index) { + this.jump = jump; + this.body = body; + this.index = index; + } + should_write() { + return true; + } + format(fmt) { + const lines = []; + const comments = []; + const body_is_empty = this.body.is_empty(); + const comment = this.index.to_comment(fmt); + if (comment) comments.push(comment); + if (this.jump.is_irregular) comments.push("irregular"); + else if (this.jump.num_cases === null) comments.push("unable to parse jump table"); + else if (this.jump.jump_table !== null && body_is_empty) comments.push(`jump table: ${this.jump.jump_table.c_symbol_name}`); + const head = `switch (${format_expr(this.jump.control_expr, fmt)})`; + if (body_is_empty) lines.push(fmt.with_comments(`${head};`, comments)); + else { + if (fmt.coding_style.newline_after_if) { + lines.push(fmt.with_comments(`${head}`, comments)); + lines.push(fmt.indent("{")); + } else lines.push(fmt.with_comments(`${head} {`, comments)); + fmt.indented(fmt.coding_style.switch_indent_level, () => lines.push(this.body.format(fmt))); + lines.push(fmt.indent("}")); + } + return lines.join("\n"); + } +} + +export class SimpleStatement { + static __fields = [["contents"], ["comments", factory(() => [])], ["is_jump", false], ["indent", 0]]; + constructor(...args) { + dcinit(this, args); + } + should_write() { + return this.contents !== null || this.comments.length > 0; + } + format(fmt) { + let content; + if (this.contents === null) content = ""; + else if (typeof this.contents === "string") content = this.contents; + else content = this.contents.format(fmt); + const comments = []; + for (const c of this.comments) { + if (typeof c === "string") comments.push(c); + else { + const co = c(fmt); + if (co !== null) comments.push(co); + } + } + return fmt.with_comments(content, comments, { indent: this.indent }); + } + clear() { + this.contents = null; + this.comments = []; + } +} + +export class LabelStatement { + constructor(context, node) { + this.context = context; + this.node = node; + } + should_write() { + const cn = this.context.case_nodes.peek(this.node); + return this.context.goto_nodes.has(this.node) || Boolean(cn && cn.length); + } + format(fmt) { + const lines = []; + if (this.context.case_nodes.has(this.node)) { + for (const [index, case_label] of this.context.case_nodes.get(this.node)) { + const comment = index.to_comment(fmt); + const comments = comment ? [comment] : []; + lines.push(fmt.with_comments(`${case_label}:`, comments, { indent: -1 })); + } + } + if (this.context.goto_nodes.has(this.node)) lines.push(`${label_for_node(this.context, this.node)}:`); + return lines.join("\n"); + } +} + +export class DoWhileLoop { + constructor(body, condition) { + this.body = body; + this.condition = condition; + } + should_write() { + return true; + } + format(fmt) { + const space = fmt.indent(""); + const after_do = fmt.coding_style.newline_after_if ? `\n${space}` : " "; + const cond = format_expr(simplify_condition(this.condition), fmt); + return fmt.indented(() => [`${space}do${after_do}{`, this.body.format(fmt), `${space}} while (${cond});`].join("\n")); + } +} + +export class Body { + constructor(print_node_comment, statements = []) { + this.print_node_comment = print_node_comment; + this.statements = statements; + } + extend(other) { + this.print_node_comment = this.print_node_comment || other.print_node_comment; + this.statements.push(...other.statements); + } + add_node(node, comment_empty) { + const block_info = get_block_info(node); + const statements = block_info.statements_to_write(); + if (this.print_node_comment && (statements.length || comment_empty)) this.add_comment(`Node ${node.name()}`); + for (const item of statements) this.statements.push(new SimpleStatement(item)); + } + add_statement(statement) { + this.statements.push(statement); + } + add_comment(contents) { + this.add_statement(new SimpleStatement(null, { comments: [contents] })); + } + add_if_else(if_else) { + if (if_else.else_body === null || if_else.if_body.ends_in_jump()) { + this.statements.push(rewrite_if_ands(if_else.condition, if_else.if_body)); + if (if_else.else_body !== null) this.extend(if_else.else_body); + } else this.statements.push(if_else); + } + add_do_while_loop(do_while_loop) { + this.statements.push(do_while_loop); + } + add_switch(sw) { + this.add_statement(sw); + } + is_empty() { + return !this.statements.some((s) => s.should_write()); + } + ends_in_jump() { + for (let i = this.statements.length - 1; i >= 0; i--) { + const statement = this.statements[i]; + if (!statement.should_write()) continue; + return statement instanceof SimpleStatement && statement.is_jump; + } + return false; + } + get_lone_if_statement() { + let ret = null; + for (const statement of this.statements) { + if (statement.should_write()) { + if (!(statement instanceof IfElseStatement) || ret) return null; + ret = statement; + } + } + return ret; + } + elide_empty_returns() { + for (let i = this.statements.length - 1; i >= 0; i--) { + const statement = this.statements[i]; + if (statement instanceof SimpleStatement && statement.contents === "return;") statement.clear(); + if (!statement.should_write()) continue; + if (statement instanceof IfElseStatement) { + statement.if_body.elide_empty_returns(); + if (statement.else_body !== null) statement.else_body.elide_empty_returns(); + } + break; + } + } + format(fmt) { + return this.statements + .filter((s) => s.should_write()) + .map((s) => s.format(fmt)) + .join("\n"); + } +} + +/** Iterate through the left-heavy `&&`-joined subconditions, rewriting CommaConditionExprs into nested ifs. */ +export function rewrite_if_ands(condition, if_body) { + let outer_cond = condition; + const inner_conds = []; + while (outer_cond instanceof BinaryOp && outer_cond.left instanceof Condition && outer_cond.op === "&&" && outer_cond.right instanceof Condition) { + const cond = outer_cond.right; + outer_cond = outer_cond.left; + if (!(cond instanceof CommaConditionExpr)) inner_conds.push(cond); + else { + let inner_cond = cond.condition; + while (inner_conds.length) inner_cond = join_conditions(inner_cond, "&&", inner_conds.pop()); + const new_body = new Body(if_body.print_node_comment); + for (const stmt of cond.statements) new_body.add_statement(new SimpleStatement(stmt)); + new_body.add_if_else(new IfElseStatement(inner_cond, if_body, null)); + if_body = new_body; + condition = outer_cond; + } + } + return new IfElseStatement(condition, if_body, null); +} + +export function label_for_node(context, node) { + if (node.loop) return `loop_${node.block.index}`; + return `block_${node.block.index}`; +} + +/** Try to emit a node for the first time, together with a label for it. */ +export function emit_node(context, node, body) { + if (context.emitted_nodes.has(node)) { + if (!(node instanceof ReturnNode)) { + emit_goto(context, node, body); + return false; + } else body.add_comment(`Duplicate return node #${node.name()}. Try simplifying control flow for better match`); + } else { + body.add_statement(new LabelStatement(context, node)); + context.emitted_nodes.add(node); + } + body.add_node(node, true); + if (node instanceof ReturnNode) emit_return(context, node, body); + return true; +} + +export function emit_goto(context, target, body) { + pyassert(!(target instanceof TerminalNode), "cannot goto a TerminalNode"); + const label = label_for_node(context, target); + context.goto_nodes.add(target); + body.add_statement(new SimpleStatement(`goto ${label};`, { is_jump: true })); +} + +export function add_labels_for_switch(context, node, case_type, cases, default_node) { + pyassert(cases.length, "jtbl list must not be empty"); + const switch_index = context.add_switch(node); + const indexes = sorted(cases.map(([i]) => i)); + const use_hex = context.fmt.coding_style.hex_case || (Math.min(...indexes) >= 0 && Math.max(...indexes) > 50); + + const skipped_labels = []; + let emitted_label_count = 0; + + for (const [index, target] of cases) { + const enum_name = case_type.get_enum_name(index); + let case_label; + if (enum_name) case_label = `case ${enum_name}`; + else if (use_hex) { + if (index < 0) case_label = `case -0x${format(-index, "X")}`; + else case_label = `case 0x${format(index, "X")}`; + } else case_label = `case ${index}`; + + if (is_empty_goto(target, default_node) || is_empty_goto(target, node.immediate_postdominator)) skipped_labels.push([target, [switch_index, case_label]]); + else { + context.case_nodes.get(target).push([switch_index, case_label]); + emitted_label_count += 1; + } + } + + if (default_node !== null) { + context.case_nodes.get(default_node).push([switch_index, "default"]); + emitted_label_count += 1; + } + + if (emitted_label_count < 5) for (const [target, label] of skipped_labels) context.case_nodes.get(target).push(label); + return switch_index; +} + +/** If `node` is a switch bounds-check ConditionalNode, return the switch's control expression. */ +export function switch_guard_expr(node) { + if (!(node instanceof ConditionalNode)) return null; + const cond = get_block_info(node).branch_condition; + pyassert(cond !== null); + const switch_node = node.fallthrough_edge; + if (!(switch_node instanceof SwitchNode)) return null; + const switch_block_info = get_block_info(switch_node); + pyassert(switch_block_info.switch_control !== null); + if ( + switch_node.parents.length === 1 && + switch_node.parents[0] === node && + !switch_block_info.statements_to_write().length && + switch_block_info.switch_control.matches_guard_condition(cond) + ) { + return switch_block_info.switch_control.control_expr; + } + return null; +} + +/** Return true if `node` represents a jump to `end` without any other statements */ +export function is_empty_goto(node, end) { + if (end === null) return false; + const seen_nodes = new Set([node]); + for (;;) { + if (node === end) return true; + const block_info = get_block_info(node); + if (block_info.statements_to_write().length) return false; + if (node instanceof ReturnNode && end instanceof TerminalNode && block_info.return_value === null) return true; + else if (node instanceof BasicNode) { + node = node.successor; + if (seen_nodes.has(node)) return false; + seen_nodes.add(node); + } else return false; + } +} + +export function gather_any_comma_conditions(block_info) { + const branch_condition = block_info.branch_condition; + pyassert(branch_condition !== null); + const comma_statements = block_info.statements_to_write(); + if (comma_statements.length) { + pyassert(!(branch_condition instanceof CommaConditionExpr)); + return new CommaConditionExpr(comma_statements, branch_condition); + } + return branch_condition; +} + +/** Utility class for tracking possible switch control values across multiple conditional branches. */ +export class Bounds { + static __fields = [["lower", -(2 ** 31)], ["upper", 2 ** 32 - 1], ["holes", factory(() => new Set())]]; + constructor(...args) { + dcinit(this, args); + pyassert(this.lower <= this.upper); + } + without(hole) { + return dcreplace(this, { holes: new Set([...this.holes, hole]) }); + } + at_most(val) { + if (this.lower <= val && val <= this.upper) return dcreplace(this, { upper: val }); + else if (val > this.upper) return this; + return Bounds.empty(); + } + at_least(val) { + if (this.lower <= val && val <= this.upper) return dcreplace(this, { lower: val }); + else if (val < this.lower) return this; + return Bounds.empty(); + } + values({ max_count }) { + const values = []; + for (let i = this.lower; i < this.upper + 1; i++) { + if (!this.holes.has(i)) { + values.push(i); + if (values.length > max_count) return null; + } + } + return values; + } + static empty() { + return new Bounds({ lower: 0, upper: 0, holes: new Set([0]) }); + } +} + +/** Try to express the nodes in `chained_cond_nodes` as a single Condition. Returns [cond, if_node, else_node] or null. */ +export function try_make_if_condition(chained_cond_nodes, end) { + const start_node = chained_cond_nodes[0]; + let if_node = chained_cond_nodes[chained_cond_nodes.length - 1].fallthrough_edge; + let else_node = chained_cond_nodes[chained_cond_nodes.length - 1].conditional_edge; + pyassert(else_node !== null); + + const allowed_nodes = new Set([...chained_cond_nodes, if_node, else_node]); + const node_cond_edges = new Map(); + for (const node of chained_cond_nodes) { + if (!allowed_nodes.has(node.conditional_edge) || !allowed_nodes.has(node.fallthrough_edge)) return null; + allowed_nodes.delete(node); + const block_info = get_block_info(node); + let cond; + if (node === start_node) { + cond = block_info.branch_condition; + pyassert(cond instanceof Condition); + } else cond = gather_any_comma_conditions(block_info); + node_cond_edges.set(node, [cond, node.conditional_edge, node.fallthrough_edge]); + } + + for (;;) { + const node_parents = new Map(); + for (const node of node_cond_edges.keys()) node_parents.set(node, []); + for (const [node, edges] of node_cond_edges) { + for (const child of edges.slice(1)) { + if (child !== if_node && child !== else_node) { + pyassert(child instanceof ConditionalNode); + if (!node_parents.has(child)) throw new Error("KeyError: node"); + node_parents.get(child).push(node); + } + } + } + + let found = false; + for (const [child, parents] of node_parents) { + if (parents.length !== 1) continue; + const parent = parents[0]; + const [child_cond, child_if, child_else] = node_cond_edges.get(child); + let [parent_cond, parent_if, parent_else] = node_cond_edges.get(parent); + let cond; + if (parent_if === child_if && parent_else === child) { + parent_else = child_else; + cond = join_conditions(parent_cond, "||", child_cond); + } else if (parent_if === child_else && parent_else === child) { + parent_else = child_if; + cond = join_conditions(parent_cond, "||", child_cond.negated()); + } else if (parent_if === child && parent_else === child_if) { + parent_if = child_else; + cond = join_conditions(parent_cond, "&&", child_cond.negated()); + } else if (parent_if === child && parent_else === child_else) { + parent_if = child_if; + cond = join_conditions(parent_cond, "&&", child_cond); + } else continue; + node_cond_edges.set(parent, [cond, parent_if, parent_else]); + node_cond_edges.delete(child); + found = true; + break; + } + if (!found) break; + } + + if (node_cond_edges.size !== 1 || !node_cond_edges.has(start_node)) return null; + let [cond, left_node, right_node] = node_cond_edges.get(start_node); + + if (left_node === else_node && right_node === if_node) cond = cond.negated(); + else pyassert(left_node === if_node && right_node === else_node); + + if (else_node === end) else_node = null; + else if (if_node === end) { + cond = cond.negated(); + if_node = else_node; + else_node = null; + } + return [cond, if_node, else_node]; +} + +/** Look for irregular switch-like structures from nested ConditionalNodes & SwitchNodes. */ +export function try_build_irregular_switch(context, start, end) { + if (!(start instanceof ConditionalNode)) return null; + pyassert(start.postdominators.has(end)); + const start_block_info = get_block_info(start); + const control_expr0 = switch_guard_expr(start); + let var_expr = null; + + if (control_expr0 !== null) var_expr = control_expr0; + else if (start_block_info.branch_condition !== null) { + const start_cond = simplify_condition(start_block_info.branch_condition); + if (start_cond !== null && start_cond instanceof BinaryOp && start_cond.right instanceof Literal) var_expr = start_cond.left; + } + if (var_expr === null) return null; + + const uw_var_expr = early_unwrap_ints(var_expr); + const node_queue = [[start, new Bounds()]]; + const visited_nodes = new Set(); + const nodes_to_mark_emitted = new Set(); + const cases = new Map(); + let default_node = null; + let irregular_comparison_count = 0; + + while (node_queue.length) { + const [node, bounds] = node_queue.pop(); + if (visited_nodes.has(node) || node === end || node === default_node) continue; + visited_nodes.add(node); + const block_info = get_block_info(node); + + if (node !== start && block_info.statements_to_write().length) { + // pass + } else if (is_empty_goto(node, end)) { + nodes_to_mark_emitted.add(node); + if (node instanceof BasicNode) node_queue.push([node.successor, bounds]); + continue; + } else if (!node.dominators.has(start) || !node.postdominators.has(end)) { + // pass + } else if (node instanceof BasicNode) { + nodes_to_mark_emitted.add(node); + node_queue.push([node.successor, bounds]); + continue; + } else if (node instanceof ConditionalNode) { + const control_expr = switch_guard_expr(node); + if (control_expr !== null && pyeq(early_unwrap_ints(control_expr), uw_var_expr)) { + node_queue.push([node.fallthrough_edge, bounds]); + node_queue.push([node.conditional_edge, bounds]); + nodes_to_mark_emitted.add(node); + continue; + } + pyassert(block_info.branch_condition !== null); + const cond = simplify_condition(block_info.branch_condition); + if (cond instanceof BinaryOp && cond.right instanceof Literal && pyeq(early_unwrap_ints(cond.left), uw_var_expr)) { + const val = cond.right.value; + if (cond.op === "==") { + if (cases.has(val)) return null; + cases.set(val, node.conditional_edge); + node_queue.push([node.fallthrough_edge, bounds.without(val)]); + } else if (cond.op === "!=" && (node.block.index > node.conditional_edge.block.index || context.options.target.compiler !== Target.CompilerEnum.IDO)) { + if (cases.has(val)) return null; + cases.set(val, node.fallthrough_edge); + node_queue.push([node.conditional_edge, bounds.without(val)]); + } else if (cond.op === "<") { + node_queue.push([node.fallthrough_edge, bounds.at_least(val)]); + node_queue.push([node.conditional_edge, bounds.at_most(val - 1)]); + } else if (cond.op === ">=") { + node_queue.push([node.fallthrough_edge, bounds.at_most(val - 1)]); + node_queue.push([node.conditional_edge, bounds.at_least(val)]); + } else if (cond.op === "<=") { + node_queue.push([node.fallthrough_edge, bounds.at_least(val + 1)]); + node_queue.push([node.conditional_edge, bounds.at_most(val)]); + } else if (cond.op === ">") { + node_queue.push([node.fallthrough_edge, bounds.at_most(val)]); + node_queue.push([node.conditional_edge, bounds.at_least(val + 1)]); + } else return null; + irregular_comparison_count += 1; + nodes_to_mark_emitted.add(node); + continue; + } + } else if (node instanceof SwitchNode) { + if (block_info.switch_control === null) return null; + if (!pyeq(early_unwrap_ints(block_info.switch_control.control_expr), uw_var_expr)) return null; + let i = block_info.switch_control.offset; + for (const c of node.cases) { + if (cases.has(i)) return null; + cases.set(i, c); + i++; + } + nodes_to_mark_emitted.add(node); + irregular_comparison_count += 1; + continue; + } + + const values = bounds.values({ max_count: 1 }); + if (values && values.length && context.options.target.compiler !== Target.CompilerEnum.IDO) { + for (const value of values) { + if (cases.has(value)) return null; + cases.set(value, node); + } + nodes_to_mark_emitted.add(node); + continue; + } + + if (default_node !== null) return null; + if (node instanceof ReturnNode || (node.dominators.has(start) && node.postdominators.has(end))) default_node = node; + } + + if (irregular_comparison_count < 2 || nodes_to_mark_emitted.size < 3 || new Set(cases.values()).size < 2) return null; + + const switch_index = add_labels_for_switch(context, start, var_expr.type, [...cases.entries()], default_node); + const case_nodes = [...cases.values()]; + if (default_node !== null) case_nodes.push(default_node); + const sw = build_switch_statement(context, SwitchControl.irregular_from_expr(var_expr), case_nodes, switch_index, end); + for (const n of nodes_to_mark_emitted) context.emitted_nodes.add(n); + return sw; +} + +/** Output the subgraph between `start` and `end`, including the branch condition in `start`. */ +export function build_conditional_subgraph(context, start, end) { + let curr_node = start; + const chained_cond_nodes = []; + for (;;) { + pyassert(curr_node instanceof ConditionalNode); + chained_cond_nodes.push(curr_node); + curr_node = curr_node.fallthrough_edge; + if ( + !( + context.options.andor_detection && + curr_node instanceof ConditionalNode && + curr_node.postdominators.has(end) && + end !== curr_node && + !curr_node.loop && + curr_node.parents.every((p) => chained_cond_nodes.includes(p)) && + !switch_guard_expr(curr_node) + ) + ) { + break; + } + } + + let cond_result; + for (;;) { + pyassert(chained_cond_nodes.length); + cond_result = try_make_if_condition(chained_cond_nodes, end); + if (cond_result) break; + chained_cond_nodes.pop(); + } + const [cond, if_node, else_node] = cond_result; + + for (const n of chained_cond_nodes.slice(1)) context.emitted_nodes.add(n); + + let else_body = null; + if (else_node) else_body = build_flowgraph_between(context, else_node, end); + const if_body = build_flowgraph_between(context, if_node, end); + return new IfElseStatement(cond, if_body, else_body); +} + +export function join_conditions(left, op, right) { + pyassert(op === "&&" || op === "||"); + return new BinaryOp(left, op, right, { type: Type.boolean() }); +} + +export function emit_return(context, node, body) { + const ret_info = get_block_info(node); + const ret = ret_info.return_value; + if (ret !== null) { + const ret_str = format_expr(ret, context.fmt); + body.add_statement(new SimpleStatement(`return ${ret_str};`, { is_jump: true })); + context.is_void = false; + } else body.add_statement(new SimpleStatement("return;", { is_jump: true })); +} + +/** Helper for building both regular & irregular switch bodies. */ +export function build_switch_statement(context, jump, case_nodes, switch_index, end) { + const switch_body = new Body(context.options.debug); + + const remaining_labels = []; + // (Python closure semantics: the lambda reads `index` late, i.e. its final value.) + let index; + const end_labels = context.case_nodes.get(end); + for (const entry of end_labels) { + index = entry[0]; + const case_label = entry[1]; + if (index.equals(switch_index)) { + const comments = [(fmt) => index.to_comment(fmt)]; + switch_body.add_statement(new SimpleStatement(`${case_label}:`, { comments, indent: -1 })); + } else remaining_labels.push([index, case_label]); + } + if (remaining_labels.length !== context.case_nodes.get(end).length) { + switch_body.add_statement(new SimpleStatement("break;", { is_jump: true })); + context.case_nodes.set(end, remaining_labels); + } + + const uniq = [...new Set(case_nodes)]; + const sorted_cases = sorted(uniq, (node) => [node.block.index, case_nodes.indexOf(node)]); + const next_sorted_cases = [...sorted_cases.slice(1), null]; + for (let k = 0; k < sorted_cases.length; k++) { + const c = sorted_cases[k]; + const next_case = next_sorted_cases[k]; + if (context.emitted_nodes.has(c) || c === end) { + // pass + } else if (next_case !== null && !context.emitted_nodes.has(next_case) && next_case !== end && c.postdominators.has(next_case)) { + switch_body.extend(build_flowgraph_between(context, c, next_case)); + if (!switch_body.ends_in_jump()) switch_body.add_comment("fallthrough"); + } else { + switch_body.extend(build_flowgraph_between(context, c, end)); + if (!switch_body.ends_in_jump()) switch_body.add_statement(new SimpleStatement("break;", { is_jump: true })); + } + } + return new SwitchStatement(jump, switch_body, switch_index); +} + +function enumerate_from(arr, start) { + return arr.map((v, i) => [i + start, v]); +} + +/** Output the subgraph between `switch` and `end` (single jump table switches). */ +export function build_switch_between(context, sw, def, end) { + const switch_cases = [...sw.cases]; + if (def === end) def = null; + else if (def !== null) switch_cases.push(def); + const jump = get_block_info(sw).switch_control; + pyassert(jump !== null); + const switch_index = add_labels_for_switch(context, sw, jump.control_expr.type, enumerate_from(sw.cases, jump.offset), def); + return build_switch_statement(context, jump, switch_cases, switch_index, end); +} + +export function detect_loop(context, start, end) { + pyassert(start.loop); + let condition = null; + let new_end = null; + for (const node of start.loop.backedges) { + if (start.postdominators.has(node) && node instanceof ConditionalNode && node.fallthrough_edge === end) { + const block_info = get_block_info(node); + pyassert(block_info.branch_condition !== null); + condition = block_info.branch_condition; + new_end = node; + break; + } + } + if (!condition) return null; + const loop_body = build_flowgraph_between(context, start, new_end, true); + emit_node(context, new_end, loop_body); + return new DoWhileLoop(loop_body, condition); +} + +/** Output a section of a flow graph (start inclusive, end exclusive). */ +export function build_flowgraph_between(context, start, end, skip_loop_detection = false) { + let curr_start = start; + const body = new Body(context.options.debug); + + while (curr_start !== end) { + pyassert(!(curr_start instanceof TerminalNode)); + + if (!skip_loop_detection && curr_start.loop && !context.emitted_nodes.has(curr_start)) { + let imm_pdom = curr_start; + while (curr_start.loop.nodes.has(imm_pdom)) { + pyassert(imm_pdom.immediate_postdominator !== null); + imm_pdom = imm_pdom.immediate_postdominator; + } + const do_while_loop = detect_loop(context, curr_start, imm_pdom); + if (do_while_loop) { + body.add_do_while_loop(do_while_loop); + curr_start = imm_pdom; + continue; + } + } + + if (context.emitted_nodes.has(curr_start) && is_empty_goto(curr_start, end)) break; + + if (!emit_node(context, curr_start, body)) break; + + if (curr_start.emit_goto) { + emit_goto(context, curr_start, body); + const index = context.flow_graph.nodes.indexOf(curr_start); + const fallthrough = context.flow_graph.nodes[index + 1]; + if (curr_start instanceof ConditionalNode) pyassert(fallthrough === curr_start.fallthrough_edge); + curr_start = fallthrough; + continue; + } + + let curr_end = curr_start.immediate_postdominator; + pyassert(curr_end !== null); + + let irregular_switch = null; + if (context.options.switch_detection) irregular_switch = try_build_irregular_switch(context, curr_start, curr_end); + + if (irregular_switch !== null) body.add_switch(irregular_switch); + else if (switch_guard_expr(curr_start) !== null) { + pyassert(curr_start instanceof ConditionalNode, "checked by switch_guard_expr"); + const switch_node = curr_start.fallthrough_edge; + pyassert(switch_node instanceof SwitchNode, "checked by switch_guard_expr"); + const default_node = curr_start.conditional_edge; + context.emitted_nodes.add(switch_node); + if (curr_end === switch_node) { + curr_end = switch_node.immediate_postdominator; + pyassert(curr_start.postdominators.has(curr_end)); + } + body.add_switch(build_switch_between(context, switch_node, default_node, curr_end)); + } else if (curr_start instanceof SwitchNode) { + body.add_switch(build_switch_between(context, curr_start, null, curr_end)); + } else if (curr_start instanceof ConditionalNode) { + body.add_if_else(build_conditional_subgraph(context, curr_start, curr_end)); + } else if (curr_start instanceof BasicNode && curr_start.fake_successor === curr_end) { + curr_end = curr_start.successor; + } else { + const ch = curr_start.children(); + pyassert( + ch.length === 1 && ch[0] === curr_end, + `While emitting flowgraph between ${start.name()}:${end.name()}, ` + `skipped nodes while stepping from ${curr_start.name()} to ${curr_end.name()}.`, + ); + } + curr_start = curr_end; + } + return body; +} + +/** Naive procedure for generating output with only gotos for control flow. */ +export function build_naive(context, nodes) { + const body = new Body(context.options.debug); + + const emit_goto_or_early_return = (node, b) => { + if (node instanceof ReturnNode && !node.is_real()) emit_node(context, node, b); + else emit_goto(context, node, b); + }; + const emit_successor = (node, cur_index) => { + if (cur_index + 1 < nodes.length && nodes[cur_index + 1] === node && !(node instanceof ReturnNode && !node.is_real())) return; + emit_goto_or_early_return(node, body); + }; + + nodes.forEach((node, i) => { + if (node instanceof ReturnNode) { + if (node.is_real()) emit_node(context, node, body); + } else if (node instanceof BasicNode) { + emit_node(context, node, body); + emit_successor(node.successor, i); + } else if (node instanceof SwitchNode) { + const jump = get_block_info(node).switch_control; + pyassert(jump !== null); + const index = add_labels_for_switch(context, node, jump.control_expr.type, enumerate_from(node.cases, jump.offset), null); + emit_node(context, node, body); + body.add_switch(new SwitchStatement(jump, new Body(false), index)); + } else if (node instanceof ConditionalNode) { + emit_node(context, node, body); + const if_body = new Body(true); + emit_goto_or_early_return(node.conditional_edge, if_body); + const block_info = get_block_info(node); + pyassert(block_info.branch_condition !== null); + body.add_if_else(new IfElseStatement(block_info.branch_condition, if_body, null)); + emit_successor(node.fallthrough_edge, i); + } else { + pyassert(node instanceof TerminalNode); + } + }); + return body; +} + +export function build_body(context, options) { + const start_node = context.flow_graph.entry_node(); + const terminal_node = context.flow_graph.terminal_node(); + const is_reducible = context.flow_graph.is_reducible(); + + let body; + if (options.ifs && is_reducible) { + body = build_flowgraph_between(context, start_node, terminal_node); + body.elide_empty_returns(); + } else { + body = new Body(context.options.debug); + if (options.ifs && !is_reducible) body.add_comment("Flowgraph is not reducible, falling back to gotos-only mode."); + body.extend(build_naive(context, context.flow_graph.nodes)); + } + + for (const node of context.flow_graph.nodes) { + if (context.emitted_nodes.has(node) || node instanceof TerminalNode) continue; + if (node instanceof ReturnNode && !node.is_real()) continue; + body.add_comment(`bug: did not emit code for node #${node.name()}; contents below:`); + emit_node(context, node, body); + } + + let index = 0; + for (const node of context.flow_graph.nodes) { + if (context.switch_nodes.has(node)) { + context.switch_nodes.set(node, index); + index += 1; + } + } + return body; +} + +export function get_function_text(function_info, options) { + const fmt = options.formatter(); + const context = new Context({ flow_graph: function_info.flow_graph, options, fmt }); + const body = build_body(context, options); + + const function_lines = []; + if (options.debug) function_lines.push("Here's the whole function!\n"); + + for (const warning of function_info.stack_info.warnings) { + const line = fmt.with_comments("", [`Warning: ${warning}`]); + if (line) function_lines.push(line); + } + if (function_info.symbol.demangled_str !== null) { + const line = fmt.with_comments("", [function_info.symbol.demangled_str]); + if (line) function_lines.push(line); + } + + const fn_name = function_info.symbol.c_symbol_name; + const arg_strs = []; + function_info.stack_info.arguments.forEach((arg, i) => { + if (i === 0 && function_info.stack_info.replace_first_arg !== null) { + const [original_name, original_type] = function_info.stack_info.replace_first_arg; + arg_strs.push(original_type.to_decl(original_name, fmt)); + } else arg_strs.push(arg.type.to_decl(arg.format(fmt), fmt)); + }); + if (function_info.stack_info.is_variadic) arg_strs.push("..."); + const arg_str = arg_strs.join(", ") || "void"; + + let fn_header = `${fn_name}(${arg_str})`; + if (context.is_void) fn_header = `void ${fn_header}`; + else fn_header = function_info.return_type.to_decl(fn_header, fmt); + const whitespace = fmt.coding_style.newline_after_function ? "\n" : " "; + function_lines.push(`${fn_header}${whitespace}{`); + + let any_decl = false; + fmt.indented(() => { + const formatted_body = body.format(fmt); + + let local_vars = function_info.stack_info.local_vars; + if (options.target.compiler !== Target.CompilerEnum.GCC) local_vars = [...local_vars].reverse(); + for (const local_var of local_vars) { + const type_decl = local_var.toplevel_decl(fmt); + if (type_decl !== null) { + let comments = []; + if (function_info.stack_info.weak_stack_var_locations.has(local_var.value)) comments = ["compiler-managed"]; + function_lines.push(new SimpleStatement(`${type_decl};`, { comments }).format(fmt)); + any_decl = true; + } + } + + const temp_decls = []; + for (const v of function_info.stack_info.temp_vars) { + if (v.is_emitted) { + const type_decl = v.type.to_decl(v.format(fmt), fmt); + temp_decls.push(`${type_decl};`); + any_decl = true; + } + } + + const var_sort = fmt.descending_regs ? (d) => d.split("_")[1] : (d) => d; + for (const decl of sorted(temp_decls, var_sort, fmt.descending_regs)) function_lines.push(new SimpleStatement(decl).format(fmt)); + + for (const phi_var of function_info.stack_info.naive_phi_vars) { + const type_decl = phi_var.type.to_decl(phi_var.get_var_name(), fmt); + function_lines.push(new SimpleStatement(`${type_decl};`).format(fmt)); + any_decl = true; + } + + if (function_info.stack_info.replace_first_arg !== null) { + pyassert(function_info.stack_info.arguments.length >= 1); + const replaced_arg = function_info.stack_info.arguments[0]; + const [original_name] = function_info.stack_info.replace_first_arg; + const lhs = replaced_arg.type.to_decl(replaced_arg.format(fmt), fmt); + const rhs = `(${replaced_arg.type.format(fmt)}) ${original_name}`; + function_lines.push(new SimpleStatement(`${lhs} = ${rhs};`).format(fmt)); + } + + if (any_decl) function_lines.push(""); + function_lines.push(formatted_body); + function_lines.push("}"); + }); + return function_lines.join("\n"); +} diff --git a/packages/romdev-m2c/src/index.js b/packages/romdev-m2c/src/index.js new file mode 100644 index 00000000..d752b1b5 --- /dev/null +++ b/packages/romdev-m2c/src/index.js @@ -0,0 +1,42 @@ +// romdev-m2c - m2c ported to JS ESM (GPL-3.0; see NOTICE). +// +// import { decompile } from "romdev-m2c"; +// const { code, stdout, stderr } = await decompile(["--target", "mips-ido-c", "--context", ctx, "func.s"]); +// +// `decompile` takes the same flags as upstream m2c's CLI and returns what it would have +// printed. Asm inputs may also be passed inline as { name, text } objects. +export { decompile, parse_flags, run, ArgumentError } from "./main.js"; +export const UPSTREAM = { repo: "https://github.com/matt-kempster/m2c", commit: "1d1c4454a445326541305f83f2b0cb680a9ecb2d" }; + +import { Worker } from "node:worker_threads"; + +/** + * decompile() in a worker thread. Resolves to { code, stdout, stderr, timedOut }. + * On timeout the worker is terminated and code is null. + */ +export function decompileInWorker(flags, { timeoutMs = 120_000 } = {}) { + return new Promise((resolve, reject) => { + const worker = new Worker(new URL("./worker.js", import.meta.url), { workerData: { flags } }); + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + worker.terminate(); + resolve({ code: null, stdout: "", stderr: `m2c timed out after ${timeoutMs} ms\n`, timedOut: true }); + }, timeoutMs); + worker.once("message", (m) => { + if (settled) return; + settled = true; + clearTimeout(timer); + worker.terminate(); + if (m.ok) resolve({ code: m.code, stdout: m.stdout, stderr: m.stderr, timedOut: false }); + else reject(new Error(m.error)); + }); + worker.once("error", (e) => { + if (settled) return; + settled = true; + clearTimeout(timer); + reject(e); + }); + }); +} diff --git a/packages/romdev-m2c/src/instruction.js b/packages/romdev-m2c/src/instruction.js new file mode 100644 index 00000000..5c49681e --- /dev/null +++ b/packages/romdev-m2c/src/instruction.js @@ -0,0 +1,153 @@ +// Port of m2c/instruction.py +/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */ +import { DecompFailure } from "./error.js"; +import { AsmGlobalSymbol, AsmLiteral, BinOp, ArchAsmParsing, parse_asm_instruction } from "./asm_instruction.js"; +import { band, intern, shallowcopy } from "./py.js"; + +/** + * Represents a word on the stack. Currently only used for pattern matching. + * `symbolic_offset` represents a label offset that is only used in patterns. + */ +export class StackLocation { + constructor(offset, symbolic_offset) { + this.offset = offset; + this.symbolic_offset = symbolic_offset; + return intern(this, [offset, symbolic_offset]); + } + toString() { + const prefix = this.symbolic_offset === null ? "" : `${this.symbolic_offset}+`; + return `${prefix}${this.offset}($sp)`; + } + offset_as_arg() { + if (this.symbolic_offset === null) return new AsmLiteral(this.offset); + if (this.offset === 0) return new AsmGlobalSymbol(this.symbolic_offset); + return new BinOp("+", new AsmGlobalSymbol(this.symbolic_offset), new AsmLiteral(this.offset)); + } + static from_offset(offset) { + const align = (x) => band(x, ~3); + if (offset instanceof AsmLiteral) return new StackLocation(align(offset.value), null); + if (offset instanceof AsmGlobalSymbol) return new StackLocation(0, offset.symbol_name); + if (offset instanceof BinOp && (offset.op === "+" || offset.op === "-") && offset.lhs instanceof AsmGlobalSymbol && offset.rhs instanceof AsmLiteral) { + let base = offset.rhs.value; + if (offset.op === "-") base = -base; + return new StackLocation(align(base), offset.lhs.symbol_name); + } + return null; + } +} + +export class InstructionMeta { + constructor({ emit_goto, filename, lineno, synthetic }) { + // True if the original asm line was marked with a goto pattern + this.emit_goto = emit_goto; + // Asm source filename & line number + this.filename = filename; + this.lineno = lineno; + // True if the Instruction is not directly from the source asm + this.synthetic = synthetic; + return intern(this, [emit_goto, filename, lineno, synthetic]); + } + static missing() { + return new InstructionMeta({ emit_goto: false, filename: "", lineno: 0, synthetic: true }); + } + derived() { + return new InstructionMeta({ emit_goto: this.emit_goto, filename: this.filename, lineno: this.lineno, synthetic: true }); + } + loc_str() { + const adj = this.synthetic ? "near" : "at"; + return `${adj} ${this.filename} line ${this.lineno}`; + } +} + +const INSTRUCTION_DEFAULTS = { + jump_target: null, + function_target: null, + is_conditional: false, + is_return: false, + is_load: false, + is_store: false, + is_effectful: true, + has_delay_slot: false, + is_branch_likely: false, + in_pattern: false, +}; + +export class Instruction { + /** + * @param {object} f fields: mnemonic, args, meta, inputs, clobbers, outputs, eval_fn, + * and optional jump_target, function_target, is_conditional, is_return, is_load, + * is_store, is_effectful, has_delay_slot, is_branch_likely, in_pattern + */ + constructor(f) { + this.mnemonic = f.mnemonic; + this.args = f.args; + this.meta = f.meta; + this.inputs = f.inputs; + this.clobbers = f.clobbers; + this.outputs = f.outputs; + this.eval_fn = f.eval_fn; + for (const [k, v] of Object.entries(INSTRUCTION_DEFAULTS)) this[k] = f[k] === undefined ? v : f[k]; + } + is_jump() { + return this.jump_target !== null || this.is_return; + } + toString() { + if (!this.args.length) return this.mnemonic; + return `${this.mnemonic} ${this.args.map((a) => String(a)).join(", ")}`; + } + arch_mnemonic(arch) { + return `${arch.arch}:${this.mnemonic}`; + } + clone() { + return this.replace({ meta: this.meta.derived() }); + } + /** dataclasses.replace */ + replace(changes) { + const out = shallowcopy(this); + Object.assign(out, changes); + return out; + } +} + +/** Arch-specific information that relates to the asm level. Extends ArchAsmParsing. */ +export class ArchAsm extends ArchAsmParsing { + missing_return() { + throw new Error("abstract"); + } + parse(mnemonic, args, meta) { + throw new Error("abstract"); + } +} + +ArchAsm.prototype.asm_word_size = 4; + +export function parse_instruction(line, meta, arch, asm_state) { + try { + const base = parse_asm_instruction(line, arch, asm_state); + return arch.parse(base.mnemonic, base.args, meta); + } catch (e) { + let msg = `Failed to parse instruction ${meta.loc_str()}: ${line}`; + if (e instanceof DecompFailure) msg += "\n\n" + e.message; + throw new DecompFailure(msg); + } +} + +export class InstrProcessingFailure extends Error { + constructor(instr, cause) { + super(`Error while processing instruction:\n${instr}`, cause ? { cause } : undefined); + this.name = "InstrProcessingFailure"; + this.instr = instr; + } + __str__() { + return `Error while processing instruction:\n${this.instr}`; + } +} + +/** Mark an instruction as being the one currently processed, for error messages. */ +export function set_current_instr(instr, fn) { + try { + return fn(); + } catch (e) { + throw new InstrProcessingFailure(instr, e); + } +} diff --git a/packages/romdev-m2c/src/io.js b/packages/romdev-m2c/src/io.js new file mode 100644 index 00000000..3988ab0c --- /dev/null +++ b/packages/romdev-m2c/src/io.js @@ -0,0 +1,42 @@ +// io.js - stdout/stderr capture standing in for Python's print() / sys.stdout. +// m2c writes its output with print(); run() captures it into a string. + +const stack = []; + +/** Run fn with print() output captured; returns { value, stdout, stderr }. */ +export function capture(fn) { + const sink = { out: [], err: [] }; + stack.push(sink); + let value; + try { + value = fn(); + } finally { + stack.pop(); + } + return { value, stdout: sink.out.join(""), stderr: sink.err.join("") }; +} + +function current() { + return stack[stack.length - 1] ?? null; +} + +/** Python print(*args, sep=" ", end="\n", file=stdout|stderr). */ +export function print(...args) { + let opts = {}; + if (args.length && args[args.length - 1] && typeof args[args.length - 1] === "object" && args[args.length - 1].__print_opts) opts = args.pop(); + const { sep = " ", end = "\n", stderr = false } = opts; + const text = args.map((a) => (typeof a === "string" ? a : String(a))).join(sep) + end; + write(text, stderr); +} + +/** Options marker for print(): print("x", popts({ end: "" })). */ +export function popts(o) { + return { ...o, __print_opts: true }; +} + +/** sys.stdout.write / sys.stderr.write */ +export function write(text, stderr = false) { + const s = current(); + if (s) (stderr ? s.err : s.out).push(text); + else (stderr ? process.stderr : process.stdout).write(text); +} diff --git a/packages/romdev-m2c/src/ir_pattern.js b/packages/romdev-m2c/src/ir_pattern.js new file mode 100644 index 00000000..c1a66407 --- /dev/null +++ b/packages/romdev-m2c/src/ir_pattern.js @@ -0,0 +1,284 @@ +// Port of m2c/ir_pattern.py +/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */ +import { assert_never } from "./error.js"; +import { BaseNode, InstrRef, RefSet, TerminalNode, build_flowgraph } from "./flow_graph.js"; +import { AsmData, Function } from "./asm_file.js"; +import { AsmAddressMode, AsmGlobalSymbol, AsmInstruction, AsmLiteral, AsmState, BinOp, Register, RegisterList } from "./asm_instruction.js"; +import { Instruction, InstructionMeta, StackLocation, parse_instruction } from "./instruction.js"; +import { DefaultMap, pyassert, shl } from "./py.js"; +import { isupper } from "./asm_pattern.js"; +import { print } from "./io.js"; + +/** + * Template for defining "IR" patterns that can match against input asm. + * Subclasses define static-ish instance fields `parts` (string[]) and `replacement` (string), + * and can optionally implement `check()`. + */ +export class IrPattern { + check(m, arch, flow_graph) { + return true; + } + compile(arch) { + const missing_meta = InstructionMeta.missing(); + const asm_state = new AsmState({ is_pattern: true }); + const replacement_instr = parse_instruction(this.replacement, missing_meta, arch, asm_state); + + const name = `__pattern_${this.constructor.name}`; + const func = new Function({ name }); + pyassert(replacement_instr.inputs.length === new Set(replacement_instr.inputs).size, "pattern inputs must be unique"); + for (const inp of replacement_instr.inputs) { + func.new_instruction(new Instruction({ mnemonic: "in.fictive", args: [], meta: missing_meta, inputs: [], clobbers: [], outputs: [inp], eval_fn: null })); + } + for (const part of this.parts) func.new_instruction(parse_instruction(part, missing_meta, arch, asm_state)); + + const asm_data = new AsmData(); + const flow_graph = build_flowgraph(func, asm_data, arch, { fragment: true }); + return new CompiledIrPattern(this, flow_graph, replacement_instr); + } +} + +export class CompiledIrPattern { + constructor(source, flow_graph, replacement_instr) { + this.source = source; + this.flow_graph = flow_graph; + this.replacement_instr = replacement_instr; + } +} + +/** IrMatch represents the matched state of an IrPattern. */ +export class IrMatch { + constructor({ asm_data, symbolic_registers = new Map(), symbolic_args = new Map(), ref_map = new Map(), body = [] }) { + this.asm_data = asm_data; + this.symbolic_registers = symbolic_registers; + this.symbolic_args = symbolic_args; + this.ref_map = ref_map; + this.body = body; + } + static _is_symbolic_reg(arg) { + return arg.register_name.length <= 1; + } + static _is_symbolic_sym(arg) { + return isupper(arg.symbol_name); + } + static _is_label_sym(arg) { + return arg.symbol_name.startsWith("."); + } + eval_math(pat) { + if (pat instanceof AsmLiteral) return pat; + if (pat instanceof BinOp) { + const lhs = this.eval_math(pat.lhs); + const rhs = this.eval_math(pat.rhs); + if (lhs instanceof AsmLiteral && rhs instanceof AsmLiteral) { + if (pat.op === "+") return new AsmLiteral(lhs.value + rhs.value); + if (pat.op === "-") return new AsmLiteral(lhs.value - rhs.value); + if (pat.op === "<<") return new AsmLiteral(shl(lhs.value, rhs.value)); + } + return new BinOp(pat.op, lhs, rhs); + } else if (pat instanceof AsmGlobalSymbol) { + pyassert(this.symbolic_args.has(pat.symbol_name), `undefined variable in math pattern: ${pat.symbol_name}`); + return this.symbolic_args.get(pat.symbol_name); + } else { + pyassert(false, `bad pattern expr: ${pat}`); + } + } + map_reg(key) { + const ret = this.symbolic_registers.get(key.register_name); + if (ret !== undefined && ret !== null) return ret; + pyassert(!IrMatch._is_symbolic_reg(key)); + return key; + } + map_arg(key) { + if (key instanceof AsmLiteral) return key; + if (key instanceof Register) return this.map_reg(key); + if (key instanceof AsmGlobalSymbol) { + pyassert(!IrMatch._is_label_sym(key), "not supported yet"); + if (IrMatch._is_symbolic_sym(key)) { + if (!this.symbolic_args.has(key.symbol_name)) throw new Error(`KeyError: '${key.symbol_name}'`); + return this.symbolic_args.get(key.symbol_name); + } + return key; + } + if (key instanceof AsmAddressMode) return new AsmAddressMode(this.map_reg(key.base), this.map_arg(key.addend), key.writeback); + if (key instanceof BinOp) return this.eval_math(key); + pyassert(false, `bad pattern part: ${key}`); + } + map_ref(key) { + const refset = this.ref_map.get(key); + if (refset === undefined) throw new Error("KeyError: ref"); + const value = refset.get_unique(); + pyassert(value instanceof InstrRef); + return value; + } + try_map_ref(key) { + const refset = this.ref_map.get(key); + if (refset === undefined) return null; + return refset.get_unique(); + } + map_location(key) { + if (key instanceof Register) return this.map_reg(key); + if (key instanceof StackLocation) { + const loc = StackLocation.from_offset(this.map_arg(key.offset_as_arg())); + pyassert(loc !== null); + return loc; + } + assert_never(key); + } + map_asm(key) { + return new AsmInstruction( + key.mnemonic, + key.args.map((a) => this.map_arg(a)), + ); + } +} + +/** Partial (in-progress) match state of an IrPattern. */ +export class TryIrMatch extends IrMatch { + _match_var(var_map, key, value, eq = (a, b) => a === b) { + if (var_map.has(key)) { + if (!eq(var_map.get(key), value)) return false; + } else var_map.set(key, value); + return true; + } + match_arg(pat, cand) { + if (pat instanceof AsmLiteral) return pat === cand; + if (pat instanceof Register) { + if (!IrMatch._is_symbolic_reg(pat)) return pat === cand; + if (!(cand instanceof Register)) return false; + return this._match_var(this.symbolic_registers, pat.register_name, cand); + } + if (pat instanceof AsmGlobalSymbol) { + pyassert(!IrMatch._is_label_sym(pat), "not supported yet"); + if (IrMatch._is_symbolic_sym(pat)) return this._match_var(this.symbolic_args, pat.symbol_name, cand); + return pat === cand; + } + if (pat instanceof AsmAddressMode) { + return cand instanceof AsmAddressMode && this.match_arg(pat.base, cand.base) && this.match_arg(pat.addend, cand.addend) && pat.writeback === cand.writeback; + } + if (pat instanceof BinOp) return this.eval_math(pat) === cand; + if (pat instanceof RegisterList) { + return cand instanceof RegisterList && cand.regs.length === pat.regs.length && cand.regs.every((cr, i) => this.match_arg(cr, pat.regs[i])); + } + pyassert(false, `bad pattern arg: ${pat}`); + } + match_instr(pat, cand) { + if (pat.mnemonic !== cand.mnemonic || pat.args.length !== cand.args.length) return false; + return pat.args.every((a, i) => this.match_arg(a, cand.args[i])); + } + match_refset(pat, cand_set) { + return this._match_var(this.ref_map, pat, cand_set.copy(), (a, b) => a.equals(b)); + } + match_inputrefs(pat, cand) { + for (const [pat_loc, pat_refs] of pat.items()) { + const cand_loc = this.map_location(pat_loc); + const cand_refs = cand.get(cand_loc); + const pat_ref = pat_refs.get_unique(); + pyassert(pat_ref !== null, "patterns can not have phis"); + if (!this.match_refset(pat_ref, cand_refs)) return false; + } + return true; + } + rename_reg(pat, new_reg) { + this.symbolic_registers.set(pat.register_name, new_reg); + } +} + +export function simplify_ir_patterns(arch, asm_data, flow_graph, patterns, { debug_patterns }) { + const refs_by_mnemonic = new DefaultMap(() => []); + for (const node of flow_graph.nodes) for (const ref of node.block.instruction_refs) refs_by_mnemonic.get(ref.instruction.mnemonic).push(ref); + + let fictive_reg_index = 0; + + for (const pattern_base of patterns) { + const pattern = pattern_base.compile(arch); + pyassert(pattern.flow_graph.nodes.length === 2, "branching patterns not yet supported"); + pyassert(pattern.flow_graph.nodes[0] instanceof BaseNode); + pyassert(pattern.flow_graph.nodes[1] instanceof TerminalNode); + const pattern_node = pattern.flow_graph.nodes[0]; + const pattern_refs = pattern_node.block.instruction_refs; + + const n_inputs = pattern.replacement_instr.inputs.length; + const input_refs = pattern_refs.slice(0, n_inputs); + const body_refs = pattern_refs.slice(n_inputs, -1); + const tail_ref = pattern_refs[pattern_refs.length - 1]; + pyassert(input_refs.every((r) => r.instruction.mnemonic === "in.fictive")); + pyassert(body_refs.every((r) => r.instruction.mnemonic !== "in.fictive")); + pyassert(pattern.replacement_instr.inputs.every((inp) => inp instanceof Register)); + const ro = pattern.replacement_instr.outputs; + const to = tail_ref.instruction.outputs; + pyassert(ro.length === to.length && ro.every((x, i) => x === to[i]), `${ro} ${to}`); + + const cands = refs_by_mnemonic.has(tail_ref.instruction.mnemonic) ? refs_by_mnemonic.get(tail_ref.instruction.mnemonic) : []; + for (const cand_tail_ref of cands) { + const state = new TryIrMatch({ asm_data }); + if (!state.match_refset(tail_ref, new RefSet([cand_tail_ref]))) continue; + + let is_match = true; + for (const pat_ref of [tail_ref, ...[...body_refs].reverse()]) { + const cand = state.try_map_ref(pat_ref); + const pat_inputs = pattern.flow_graph.instr_inputs.get(pat_ref); + if (!(cand instanceof InstrRef && state.match_instr(pat_ref.instruction, cand.instruction) && state.match_inputrefs(pat_inputs, flow_graph.instr_inputs.get(cand)))) { + is_match = false; + break; + } + } + if (!is_match) continue; + + for (const pat_ref of [...body_refs, tail_ref]) state.body.push(state.map_ref(pat_ref)); + + if (!pattern.source.check(state, arch, flow_graph)) continue; + + const temp_reg_refs = new Map(); + for (const pat_ref of input_refs) { + pyassert(pat_ref.instruction.outputs.length === 1); + const input_reg = pat_ref.instruction.outputs[0]; + pyassert(input_reg instanceof Register); + const input_uses = pattern.flow_graph.instr_uses.get(pat_ref).get(input_reg); + const input_use_ref = state.map_ref(input_uses.refs[0]); + const original_reg = state.map_reg(input_reg); + const temp_reg = Register.fictive(original_reg.register_name, String(fictive_reg_index)); + fictive_reg_index += 1; + state.rename_reg(input_reg, temp_reg); + + const move_asm = new AsmInstruction("move.fictive", [temp_reg, original_reg]); + const move_ref = input_use_ref.add_instruction_before(move_asm, arch); + temp_reg_refs.set(temp_reg, move_ref); + + for (const src_ref of flow_graph.instr_inputs.get(input_use_ref).get(original_reg)) { + flow_graph.add_instruction_use({ use: move_ref, loc: original_reg, src: src_ref }); + } + } + + const repl_ref = state.map_ref(tail_ref); + const repl_asm = state.map_asm(pattern.replacement_instr); + repl_ref.replace_instruction(repl_asm, arch); + + flow_graph.clear_instruction_inputs(repl_ref); + for (const [temp_reg, temp_ref] of temp_reg_refs) flow_graph.add_instruction_use({ use: repl_ref, loc: temp_reg, src: temp_ref }); + + for (const pat_ref of [...body_refs].reverse()) { + const cand_ref = state.map_ref(pat_ref); + if (flow_graph.instr_uses.get(cand_ref).is_empty()) { + const nop_asm = new AsmInstruction("nop", []); + cand_ref.replace_instruction(nop_asm, arch); + flow_graph.clear_instruction_inputs(cand_ref); + } else if (!cand_ref.instruction.in_pattern) { + cand_ref.instruction = cand_ref.instruction.replace({ in_pattern: true }); + } + } + + if (debug_patterns) { + print(`Rewrote asm using ${pattern.constructor.name}:`); + print(); + for (const node of flow_graph.nodes) { + const instrs = node.block.instructions; + if (instrs.length) { + print(`${node.block.approx_label_name}:`); + for (const ins of node.block.instructions) print(String(ins)); + } + } + print(); + } + } + } + flow_graph.validate_instruction_graph(); +} diff --git a/packages/romdev-m2c/src/main.js b/packages/romdev-m2c/src/main.js new file mode 100644 index 00000000..70b83499 --- /dev/null +++ b/packages/romdev-m2c/src/main.js @@ -0,0 +1,528 @@ +// Port of m2c/main.py +import fs from "node:fs"; +import { build_typemap, dump_typemap } from "./c_types.js"; +import { DecompFailure } from "./error.js"; +import { build_flowgraph } from "./flow_graph.js"; +import { get_function_text } from "./if_statements.js"; +import { CodingStyle, Options, Target } from "./options.js"; +import { AsmData, parse_file } from "./asm_file.js"; +import { InstrProcessingFailure } from "./instruction.js"; +import { GlobalInfo, narrow_func_call_outputs, translate_to_ast, visualize_flowgraph } from "./translate.js"; +import { TypePool } from "./types.js"; +import { MipsArch, MipseeArch } from "./arch_mips.js"; +import { ValueError, int_ } from "./py.js"; +import { capture, print, write } from "./io.js"; + +let graphviz = null; +/** Graphviz compiled to WASM, loaded only when --visualize is used. */ +async function loadGraphviz() { + if (!graphviz) graphviz = (await import("@viz-js/viz")).instance(); + return graphviz; +} + +let archModules = null; +async function loadArchModules() { + if (archModules) return archModules; + const [ppc, arm, sh] = await Promise.all([import("./arch_ppc.js"), import("./arch_arm.js"), import("./arch_sh.js")]); + archModules = { ppc, arm, sh }; + return archModules; +} + +class DecompilationState { + constructor(fn, state) { + this.function = fn; + this.state = state; // {flow_graph, info} or an Error + } +} + +function isError(x) { + return x instanceof Error; +} + +/** Python traceback.format_exception_only-ish rendering for internal errors. */ +function print_exception(exc) { + let e = exc; + if (e instanceof InstrProcessingFailure && e.cause) e = e.cause; + const name = e && e.name ? e.name : "Error"; + const msg = e && e.message !== undefined ? e.message : String(e); + print("Traceback (most recent call last):"); + if (e && e.stack) { + for (const line of String(e.stack).split("\n").slice(1)) print(` ${line.trim()}`); + } + print(msg ? `${name}: ${msg}` : name); +} + +function print_exception_as_comment(exc, options, context) { + const context_phrase = context !== null ? ` in ${context}` : ""; + if (exc && (exc.code === "ENOENT" || exc.code === "EACCES" || exc.code === "EISDIR")) { + print(`/* OSError${context_phrase}: ${exc.message} */`); + return; + } else if (exc instanceof DecompFailure) { + print("/*"); + print(`Decompilation failure${context_phrase}:\n`); + print(exc.message); + if (options.stacktrace && exc.cause) { + print(); + print_exception(exc.cause); + } + print("*/"); + } else { + print("/*"); + print(`Internal error${context_phrase}:\n`); + print_exception(exc); + print("*/"); + } +} + +function make_arch(options, mods) { + const t = options.target; + if (t.arch === Target.ArchEnum.MIPS) return t.platform === Target.PlatformEnum.MIPSEE ? new MipseeArch() : new MipsArch(); + if (t.arch === Target.ArchEnum.PPC) return new mods.ppc.PpcArch(); + if (t.arch === Target.ArchEnum.ARM) return t.platform === Target.PlatformEnum.GBA ? new mods.arm.ArmGbaArch() : new mods.arm.ArmArch(); + if (t.arch === Target.ArchEnum.SH) return t.platform === Target.PlatformEnum.SH4 ? new mods.sh.Sh4Arch() : new mods.sh.Sh2Arch(); + throw new ValueError(`Invalid target arch: ${t.arch}`); +} + +/** + * Run m2c with parsed options, printing to the current io sink. Returns the exit code. + * Arch modules for non-MIPS targets are loaded by run_async / decompile. + */ +export function run(options, mods = archModules ?? {}) { + const arch = make_arch(options, mods); + + const all_functions = new Map(); + const asm_data = new AsmData(); + let typemap; + try { + for (const filename of options.filenames) { + let text; + if (typeof filename === "object" && filename !== null) text = filename.text; + else if (filename === "-") text = fs.readFileSync(0, "utf8"); + else text = fs.readFileSync(filename, "utf8"); + const name = typeof filename === "object" && filename !== null ? filename.name : filename; + const asm_file = parse_file({ name, text }, arch, options); + for (const fn of asm_file.functions) all_functions.set(fn.name, fn); + asm_file.asm_data.merge_into(asm_data); + } + if (options.heuristic_strings) asm_data.detect_heuristic_strings(); + typemap = build_typemap(options.c_contexts, arch, options.use_cache); + } catch (e) { + print_exception_as_comment(e, options, null); + return 1; + } + + if (options.dump_typemap) { + dump_typemap(typemap); + return 0; + } + + let functions; + if (!options.function_indexes_or_names.length) functions = [...all_functions.values()]; + else { + const functions_by_c_name = new Map(); + for (const [name, fn] of all_functions) functions_by_c_name.set(arch.c_symbol_name(name), fn); + functions = []; + for (const index_or_name of options.function_indexes_or_names) { + if (typeof index_or_name === "number") { + if (!(0 <= index_or_name && index_or_name < all_functions.size)) { + print(`Function index ${index_or_name} is out of bounds (must be between ` + `0 and ${all_functions.size - 1}).`, { __print_opts: true, stderr: true }); + return 1; + } + functions.push([...all_functions.values()][index_or_name]); + } else { + let fn = all_functions.get(index_or_name) ?? null; + if (fn === null) fn = functions_by_c_name.get(index_or_name) ?? null; + if (fn === null) { + print(`Function ${index_or_name} not found.`, { __print_opts: true, stderr: true }); + return 1; + } + functions.push(fn); + } + } + } + + const fmt = options.formatter(); + const function_names = new Set(all_functions.keys()); + const typepool = new TypePool({ + unknown_field_prefix: fmt.coding_style.unknown_underscore ? "unk_" : "unk", + unk_inference: options.unk_inference, + union_field_overrides: options.union_field_overrides, + }); + const global_info = new GlobalInfo(asm_data, arch, options.target, function_names, typemap, typepool, { + deterministic_vars: options.deterministic_vars, + stack_spill_detection: options.stack_spill_detection, + }); + + const decompilations = []; + for (const fn of functions) { + let state; + try { + narrow_func_call_outputs(fn, global_info); + const flow_graph = build_flowgraph(fn, global_info.asm_data, arch, { fragment: false, print_warnings: options.debug, debug_patterns: options.debug_patterns }); + state = { flow_graph, info: null }; + } catch (e) { + state = e; + } + decompilations.push(new DecompilationState(fn, state)); + } + + let global_decls_exc = null; + for (let i = 0; i < options.passes - 1; i++) { + for (const decomp of decompilations) { + if (isError(decomp.state)) continue; + const flow_graph = decomp.state.flow_graph; + try { + flow_graph.reset_block_info(); + decomp.state.info = translate_to_ast(decomp.function, flow_graph, options, global_info); + } catch (e) { + decomp.state = e; + } + } + if (global_decls_exc === null) { + try { + global_info.global_decls(fmt, options.global_decls, []); + } catch (e) { + global_decls_exc = e; + } + } + for (const decomp of decompilations) { + if (isError(decomp.state)) continue; + const info = decomp.state.info; + try { + get_function_text(info, options); + } catch (e) { + decomp.state = e; + } + } + typepool.prune_structs(); + } + + for (const decomp of decompilations) { + if (isError(decomp.state)) continue; + const flow_graph = decomp.state.flow_graph; + try { + flow_graph.reset_block_info(); + decomp.state.info = translate_to_ast(decomp.function, flow_graph, options, global_info); + } catch (e) { + decomp.state = e; + } + } + + if (options.visualize_flowgraph !== null) { + const decomp = decompilations[0]; + try { + if (isError(decomp.state)) throw decomp.state; + const dot_source = visualize_flowgraph(decomp.state.flow_graph, options.visualize_flowgraph); + if (options.visualize_format === Options.VisualizeFormatEnum.SVG) { + // Upstream pipes the dot source through graphviz; here graphviz runs as WASM (@viz-js/viz). + if (!mods.viz) throw new DecompFailure("SVG visualization: graphviz WASM not loaded (call decompile(), which loads it)"); + write(mods.viz.renderString(dot_source, { format: "svg" })); + } else write(dot_source); + return 0; + } catch (e) { + print_exception_as_comment(e, options, null); + return 1; + } + } + + let return_code = 0; + try { + const type_decls = typepool.format_type_declarations(fmt, options.print_stack_structs); + if (type_decls) print(type_decls); + if (global_decls_exc !== null) throw global_decls_exc; + const infos = decompilations.filter((d) => !isError(d.state) && d.state.info !== null).map((d) => d.state.info); + const global_decls = global_info.global_decls(fmt, options.global_decls, infos); + if (global_decls) print(global_decls); + } catch (e) { + print_exception_as_comment(e, options, null); + return_code = 1; + } + + decompilations.forEach((decomp, index) => { + if (index !== 0) print(); + const fn = decomp.function; + try { + if (options.print_assembly) { + print(String(fn)); + print(); + } + if (isError(decomp.state)) throw decomp.state; + const function_text = get_function_text(decomp.state.info, options); + print(function_text); + } catch (e) { + print_exception_as_comment(e, options, `function ${fn.name}`); + return_code = 1; + } + }); + + for (const warning of typepool.warnings) { + const line = fmt.with_comments("", [warning]); + if (line) print(line); + } + return return_code; +} + +// ---------------------------------------------------------------- flags + +const BOOL_FLAGS = { + "--no-cache": ["use_cache", false], + "--stack-structs": ["print_stack_structs", true], + "--debug": ["debug", true], + "--debug-patterns": ["debug_patterns", true], + "--stacktrace": ["stacktrace", true], + "--print-assembly": ["print_assembly", true], + "--dump-typemap": ["dump_typemap", true], + "--sanitize-tracebacks": ["sanitize_tracebacks", true], + "--valid-syntax": ["valid_syntax", true], + "--allman": ["allman", true], + "--knr": ["knr", true], + "--indent-switch-contents": ["indent_switch_contents", true], + "--unk-underscore": ["unknown_underscore", true], + "--hex-case": ["hex_case", true], + "--no-casts": ["skip_casts", true], + "--zfill-constants": ["zfill_constants", true], + "--force-decimal": ["force_decimal", true], + "--deterministic-vars": ["deterministic_vars", true], + "--descending-regs": ["descending_regs", true], + "--backwards-bss": ["backwards_bss", true], + "--stop-on-error": ["stop_on_error", true], + "--void": ["void", true], + "--gotos-only": ["ifs", false], + "--no-ifs": ["ifs", false], + "--no-switches": ["switch_detection", false], + "--no-andor": ["andor_detection", false], + "--no-unk-inference": ["unk_inference", false], + "--no-stack-spill": ["stack_spill_detection", false], + "--heuristic-strings": ["heuristic_strings", true], + "--pdb-translate": ["pdb_translate", true], + "--disable-gc": ["disable_gc", true], +}; +const VALUE_FLAGS = { + "--context": "c_contexts", + "-D": "defined", + "-U": "undefined", + "--incbin-dir": "incbin_dirs", + "-f": "functions", + "--function": "functions", + "--globals": "global_decls", + "--visualize-format": "visualize_format", + "--pointer-style": "pointer_style", + "--comment-style": "comment_style", + "--comment-column": "comment_column", + "-t": "target", + "--target": "target", + "--passes": "passes", + "-P": "passes", + "--reg-vars": "reg_vars", + "--goto": "goto_patterns", + "--union-field": "union_fields", +}; +const APPEND = new Set(["c_contexts", "defined", "undefined", "incbin_dirs", "functions", "goto_patterns", "union_fields"]); + +export class ArgumentError extends Error {} + +const ALL_LONG = [...Object.keys(BOOL_FLAGS), ...Object.keys(VALUE_FLAGS), "--visualize"].filter((o) => o.startsWith("--")); +function has_opt(flag) { + return ALL_LONG.includes(flag); +} + +/** Parse m2c command-line flags (subset-compatible with upstream argparse). Returns Options. */ +export function parse_flags(flags) { + const args = { + filenames: [], + c_contexts: [], + use_cache: true, + defined: [], + undefined: [], + incbin_dirs: [], + functions: [], + global_decls: "used", + print_stack_structs: false, + debug: false, + debug_patterns: false, + stacktrace: false, + print_assembly: false, + dump_typemap: false, + visualize_flowgraph: null, + visualize_format: "svg", + sanitize_tracebacks: false, + valid_syntax: false, + allman: false, + knr: false, + indent_switch_contents: false, + pointer_style: "right", + unknown_underscore: false, + hex_case: false, + comment_style: "multiline", + comment_column: "52", + skip_casts: false, + zfill_constants: false, + force_decimal: false, + deterministic_vars: false, + descending_regs: false, + backwards_bss: false, + target: "mips-ido-c", + passes: "2", + stop_on_error: false, + void: false, + ifs: true, + switch_detection: true, + andor_detection: true, + unk_inference: true, + stack_spill_detection: true, + heuristic_strings: false, + reg_vars: null, + goto_patterns: ["GOTO"], + pdb_translate: false, + disable_gc: false, + union_fields: [], + }; + for (let i = 0; i < flags.length; i++) { + let flag = flags[i]; + if (typeof flag !== "string") { + args.filenames.push(flag); + continue; + } + let value = null; + if (flag.startsWith("--") && flag.includes("=")) { + value = flag.slice(flag.indexOf("=") + 1); + flag = flag.slice(0, flag.indexOf("=")); + } else if (/^-[DUftP]./.test(flag) && !flag.startsWith("--")) { + value = flag.slice(2); + flag = flag.slice(0, 2); + } + if (flag.startsWith("--") && !has_opt(flag)) { + // argparse accepts unambiguous prefixes of long options + const matches = ALL_LONG.filter((o) => o.startsWith(flag)); + if (matches.length === 1) flag = matches[0]; + else if (matches.length > 1) throw new ArgumentError(`ambiguous option: ${flag} could match ${matches.join(", ")}`); + } + if (flag === "--visualize") { + if (value === null && i + 1 < flags.length && (flags[i + 1] === "asm" || flags[i + 1] === "c")) value = flags[++i]; + args.visualize_flowgraph = value ?? "c"; + continue; + } + if (Object.prototype.hasOwnProperty.call(BOOL_FLAGS, flag)) { + const [k, v] = BOOL_FLAGS[flag]; + args[k] = v; + continue; + } + if (Object.prototype.hasOwnProperty.call(VALUE_FLAGS, flag)) { + if (value === null) { + if (i + 1 >= flags.length) throw new ArgumentError(`argument ${flag}: expected one argument`); + value = flags[++i]; + } + const k = VALUE_FLAGS[flag]; + if (APPEND.has(k)) args[k] = k === "goto_patterns" ? [...args[k], value] : [...args[k], value]; + else args[k] = value; + continue; + } + if (flag.startsWith("-") && flag !== "-") throw new ArgumentError(`unrecognized arguments: ${flag}`); + args.filenames.push(flag); + } + if (!args.filenames.length) throw new ArgumentError("the following arguments are required: filename"); + + const reg_vars = args.reg_vars ? args.reg_vars.split(",") : []; + const preproc_defines = new Map(); + for (const d of args.undefined) preproc_defines.set(d, null); + for (const d of args.defined) { + const i = d.indexOf("="); + if (i >= 0) preproc_defines.set(d.slice(0, i), int_(d.slice(i + 1), 0)); + else preproc_defines.set(d, 1); + } + + const coding_style = new CodingStyle({ + newline_after_function: args.allman || args.knr, + newline_after_if: args.allman, + newline_before_else: args.allman, + switch_indent_level: args.indent_switch_contents ? 2 : 1, + pointer_style_left: args.pointer_style === "left", + unknown_underscore: args.unknown_underscore, + hex_case: args.hex_case, + comment_style: CodingStyle.CommentStyle.of(args.comment_style), + comment_column: int_(args.comment_column), + }); + + const functions = []; + for (const fn of args.functions) { + try { + functions.push(int_(fn)); + } catch (e) { + if (!(e instanceof ValueError)) throw e; + functions.push(fn); + } + } + + const union_field_overrides = new Map(); + for (const override of args.union_fields) { + const i = override.indexOf(":"); + if (i < 0) throw new ArgumentError(`Error: Invalid union field override '${override}'. Expected format: STRUCT_NAME:FIELD_NAME`); + union_field_overrides.set(override.slice(0, i), override.slice(i + 1)); + } + + let visualize_flowgraph = args.visualize_flowgraph === null ? null : Options.VisualizeTypeEnum.of(args.visualize_flowgraph); + if (visualize_flowgraph !== null) { + args.debug = false; + args.debug_patterns = false; + } + + return new Options({ + filenames: args.filenames, + function_indexes_or_names: functions, + debug: args.debug, + debug_patterns: args.debug_patterns, + stacktrace: args.stacktrace, + void: args.void, + ifs: args.ifs, + switch_detection: args.switch_detection, + andor_detection: args.andor_detection, + skip_casts: args.skip_casts, + zfill_constants: args.zfill_constants, + force_decimal: args.force_decimal, + heuristic_strings: args.heuristic_strings, + reg_vars, + goto_patterns: args.goto_patterns, + stop_on_error: args.stop_on_error, + print_assembly: args.print_assembly, + visualize_flowgraph, + visualize_format: Options.VisualizeFormatEnum.of(args.visualize_format), + c_contexts: args.c_contexts, + use_cache: args.use_cache, + dump_typemap: args.dump_typemap, + pdb_translate: args.pdb_translate, + preproc_defines, + coding_style, + sanitize_tracebacks: args.sanitize_tracebacks, + valid_syntax: args.valid_syntax, + global_decls: Options.GlobalDeclsEnum.of(args.global_decls), + target: Target.parse(args.target), + print_stack_structs: args.print_stack_structs, + unk_inference: args.unk_inference, + stack_spill_detection: args.stack_spill_detection, + passes: int_(args.passes), + incbin_dirs: args.incbin_dirs, + deterministic_vars: args.deterministic_vars, + descending_regs: args.descending_regs, + backwards_bss: args.backwards_bss, + disable_gc: args.disable_gc, + union_field_overrides, + }); +} + +/** + * In-process equivalent of running upstream m2c with : returns { code, stdout, stderr }. + * Asm inputs may be file paths, or {name, text} objects mixed into `flags`. + */ +export async function decompile(flags) { + const mods = { ...(await loadArchModules()) }; + if (flags.some((f) => typeof f === "string" && f.startsWith("--visualize"))) mods.viz = await loadGraphviz(); + let options; + try { + options = parse_flags(flags); + } catch (e) { + if (e instanceof ArgumentError || e instanceof ValueError) return { code: 2, stdout: "", stderr: `m2c: error: ${e.message}\n` }; + throw e; + } + const r = capture(() => run(options, mods)); + return { code: r.value, stdout: r.stdout, stderr: r.stderr }; +} diff --git a/packages/romdev-m2c/src/options.js b/packages/romdev-m2c/src/options.js new file mode 100644 index 00000000..7f4b00c8 --- /dev/null +++ b/packages/romdev-m2c/src/options.js @@ -0,0 +1,287 @@ +// Port of m2c/options.py +import { assert_never } from "./error.js"; +import { ValueError, format } from "./py.js"; + +let enumSeq = 0; +/** Minimal Python enum.Enum replacement: members are singletons with .name/.value. */ +export class PyEnum { + constructor(name, value) { + this.name = name; + this.value = value; + Object.defineProperty(this, "__enum_key", { value: `${new.target.name}.${name}.${++enumSeq}`, enumerable: false }); + } + __str__() { + return String(this.value); + } + toString() { + return String(this.value); + } + static define(cls, members) { + cls.members = []; + for (const [name, value] of Object.entries(members)) { + const m = new cls(name, value); + cls[name] = m; + cls.members.push(m); + } + return cls; + } + /** `EnumCls(value)` lookup; raises ValueError like Python. */ + static of(value) { + for (const m of this.members) if (m.value === value) return m; + throw new ValueError(`'${value}' is not a valid ${this.name}`); + } +} + +export class CommentStyle extends PyEnum {} +PyEnum.define(CommentStyle, { MULTILINE: "multiline", ONELINE: "oneline", NONE: "none" }); + +export class CodingStyle { + static CommentStyle = CommentStyle; + constructor({ + newline_after_function, + newline_after_if, + newline_before_else, + switch_indent_level, + pointer_style_left, + unknown_underscore, + hex_case, + comment_style, + comment_column, + }) { + this.newline_after_function = newline_after_function; + this.newline_after_if = newline_after_if; + this.newline_before_else = newline_before_else; + this.switch_indent_level = switch_indent_level; + this.pointer_style_left = pointer_style_left; + this.unknown_underscore = unknown_underscore; + this.hex_case = hex_case; + this.comment_style = comment_style; + this.comment_column = comment_column; + Object.freeze(this); + } +} + +class PlatformEnum extends PyEnum { + get arch() { + if (this === PlatformEnum.MIPS) return ArchEnum.MIPS; + else if (this === PlatformEnum.MIPSEL) return ArchEnum.MIPS; + else if (this === PlatformEnum.MIPSEE) return ArchEnum.MIPS; + else if (this === PlatformEnum.PPC) return ArchEnum.PPC; + else if (this === PlatformEnum.ARM) return ArchEnum.ARM; + else if (this === PlatformEnum.GBA) return ArchEnum.ARM; + else if (this === PlatformEnum.SH2 || this === PlatformEnum.SH4) return ArchEnum.SH; + else return assert_never(this); + } +} +PyEnum.define(PlatformEnum, { MIPS: "mips", MIPSEL: "mipsel", MIPSEE: "mipsee", PPC: "ppc", ARM: "arm", GBA: "gba", SH2: "sh2", SH4: "sh4" }); +class ArchEnum extends PyEnum {} +PyEnum.define(ArchEnum, { MIPS: "mips", PPC: "ppc", ARM: "arm", SH: "sh" }); +class EndianEnum extends PyEnum {} +PyEnum.define(EndianEnum, { LITTLE: "little", BIG: "big" }); +class CompilerEnum extends PyEnum {} +PyEnum.define(CompilerEnum, { IDO: "ido", GCC: "gcc", MWCC: "mwcc", SHC: "shc" }); +class LanguageEnum extends PyEnum {} +PyEnum.define(LanguageEnum, { C: "c", CXX: "c++" }); + +export class Target { + static PlatformEnum = PlatformEnum; + static ArchEnum = ArchEnum; + static EndianEnum = EndianEnum; + static CompilerEnum = CompilerEnum; + static LanguageEnum = LanguageEnum; + + constructor({ platform, arch, endian, compiler, language }) { + this.platform = platform; + this.arch = arch; + this.endian = endian; + this.compiler = compiler; + this.language = language; + } + + is_big_endian() { + return this.endian === EndianEnum.BIG; + } + + /** + * Parse an `platform-compiler-language` triple. + * If `-language` is missing, use the default for the compiler. + * If `-compiler` is missing, use the default for the platform. + */ + static parse(name) { + let endian = EndianEnum.BIG; + const terms = name.split("-"); + let platform, arch, compiler, language; + try { + platform = PlatformEnum.of(terms[0]); + if ([PlatformEnum.MIPSEL, PlatformEnum.MIPSEE, PlatformEnum.ARM, PlatformEnum.GBA, PlatformEnum.SH4].includes(platform)) { + endian = EndianEnum.LITTLE; + } + arch = platform.arch; + + if (terms.length >= 2) compiler = CompilerEnum.of(terms[1]); + else if (platform === PlatformEnum.SH4) compiler = CompilerEnum.SHC; + else if (arch === ArchEnum.PPC) compiler = CompilerEnum.MWCC; + else if (arch === ArchEnum.MIPS && endian === EndianEnum.BIG) compiler = CompilerEnum.IDO; + else compiler = CompilerEnum.GCC; + + if (terms.length >= 3) language = LanguageEnum.of(terms[2]); + else if (compiler === CompilerEnum.MWCC) language = LanguageEnum.CXX; + else language = LanguageEnum.C; + } catch (e) { + if (e instanceof ValueError) throw new ValueError(`Unable to parse Target '${name}' (${e.message})`); + throw e; + } + return new Target({ platform, arch, endian, compiler, language }); + } +} + +class GlobalDeclsEnum extends PyEnum {} +PyEnum.define(GlobalDeclsEnum, { ALL: "all", USED: "used", NONE: "none" }); +class VisualizeTypeEnum extends PyEnum {} +PyEnum.define(VisualizeTypeEnum, { ASM: "asm", C: "c" }); +class VisualizeFormatEnum extends PyEnum {} +PyEnum.define(VisualizeFormatEnum, { DOT: "dot", SVG: "svg" }); + +export class Options { + static GlobalDeclsEnum = GlobalDeclsEnum; + static VisualizeTypeEnum = VisualizeTypeEnum; + static VisualizeFormatEnum = VisualizeFormatEnum; + + constructor(fields) { + Object.assign(this, fields); + } + + formatter() { + return new Formatter({ + coding_style: this.coding_style, + skip_casts: this.skip_casts, + zfill_constants: this.zfill_constants, + force_decimal: this.force_decimal, + valid_syntax: this.valid_syntax, + descending_regs: this.descending_regs, + backwards_bss: this.backwards_bss, + }); + } +} + +export const DEFAULT_CODING_STYLE = new CodingStyle({ + newline_after_function: false, + newline_after_if: false, + newline_before_else: false, + switch_indent_level: 1, + pointer_style_left: false, + unknown_underscore: false, + hex_case: false, + comment_style: CommentStyle.MULTILINE, + comment_column: 52, +}); + +/** Python len() of a str (code points). */ +function pylen(s) { + let n = 0; + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i); + if (c < 0xd800 || c > 0xdbff) n++; + } + return n; +} + +export class Formatter { + constructor({ + coding_style = DEFAULT_CODING_STYLE, + indent_step = " ".repeat(4), + skip_casts = false, + extra_indent = 0, + debug = false, + valid_syntax = false, + line_length = 80, + zfill_constants = false, + force_decimal = false, + descending_regs = false, + backwards_bss = false, + } = {}) { + this.coding_style = coding_style; + this.indent_step = indent_step; + this.skip_casts = skip_casts; + this.extra_indent = extra_indent; + this.debug = debug; + this.valid_syntax = valid_syntax; + this.line_length = line_length; + this.zfill_constants = zfill_constants; + this.force_decimal = force_decimal; + this.descending_regs = descending_regs; + this.backwards_bss = backwards_bss; + } + + indent(line, indent = 0) { + return this.indent_step.repeat(Math.max(indent + this.extra_indent, 0)) + line; + } + + /** Python `with fmt.indented(amt):` - runs fn with extra indentation. */ + indented(amt, fn) { + if (typeof amt === "function") { + fn = amt; + amt = 1; + } + try { + this.extra_indent += amt; + return fn(); + } finally { + this.extra_indent -= amt; + } + } + + format_array(elements) { + if (!elements.some((el) => el.includes("\n") || pylen(el) > this.line_length)) { + const output = `{ ${elements.join(", ")} }`; + if (pylen(output) < this.line_length) return output; + } + let output = "{\n"; + for (let el of elements) { + el = el.replaceAll("\n", "\n" + this.indent_step); + output += this.indent(`${el},\n`, 1); + } + output += "}"; + return output; + } + + /** Indent `line` and append a list of `comments` joined with ';' */ + with_comments(line, comments, { indent = 0 } = {}) { + const base = this.indent(line, indent); + if (!comments.length || this.coding_style.comment_style === CommentStyle.NONE) return base; + let padding = ""; + if (line) padding = " ".repeat(Math.max(1, this.coding_style.comment_column - pylen(base))); + const comment_str = comments.join("; "); + let start, mid, end; + if (this.coding_style.comment_style === CommentStyle.ONELINE) { + start = "// "; + mid = "// "; + end = ""; + } else { + start = "/* "; + mid = " * "; + end = " */"; + } + const lines = comment_str.split("\n"); + let ret = `${base}${padding}${start}${lines[0]}`; + for (const cline of lines.slice(1)) { + const new_base = this.indent("", indent) + " ".repeat(pylen(line)); + ret += `\n${new_base}${padding}${mid}${cline}`; + } + return ret + end; + } + + format_hex(val) { + return format(val, "x").toUpperCase(); + } + + format_int(val, size_bits = null) { + if (Math.abs(val) < 10 || this.force_decimal) return String(val); + let hex_digits; + if (this.zfill_constants && size_bits !== null && size_bits !== undefined) hex_digits = format(Math.abs(val), `0${Math.floor(size_bits / 4)}X`); + else hex_digits = format(Math.abs(val), "X"); + if (hex_digits.length === 7) hex_digits = `0${hex_digits}`; + if (val < 0) return `-0x${hex_digits}`; + else return `0x${hex_digits}`; + } +} diff --git a/packages/romdev-m2c/src/py.js b/packages/romdev-m2c/src/py.js new file mode 100644 index 00000000..7346540d --- /dev/null +++ b/packages/romdev-m2c/src/py.js @@ -0,0 +1,952 @@ +// py.js - small helpers that reproduce the Python semantics m2c relies on +// (integer arithmetic, number formatting, string methods, containers), so the +// module-by-module port can stay a line-for-line translation. +// +// Porting conventions used across src/: +// - Identifiers keep m2c's Python names (snake_case functions, methods and +// attributes; CamelCase classes) so the port can be diffed against upstream. +// - Python ints are JS Numbers. Every bitwise operation that can see a value +// outside int32 goes through band/bor/bxor/shl/shr below (JS operators +// truncate to 32 bits). `//` is floordiv, `%` is pymod. +// - Frozen value dataclasses are interned (see intern()), so `===` and Map +// keys give Python's value equality and hashing. +// - `assert` becomes pyassert(), raising AssertionError. + +export class AssertionError extends Error { + constructor(message) { + super(message ?? ""); + this.name = "AssertionError"; + } +} +export class ValueError extends Error { + constructor(message) { + super(message ?? ""); + this.name = "ValueError"; + } +} +export class IndexError extends Error { + constructor(message) { + super(message ?? ""); + this.name = "IndexError"; + } +} +export class KeyError extends Error { + constructor(message) { + super(message ?? ""); + this.name = "KeyError"; + } +} + +/** Python `assert cond, msg`. */ +export function pyassert(cond, msg) { + if (!cond) throw new AssertionError(msg === undefined ? "" : String(msg)); +} + +// ---------------------------------------------------------------- integers + +const I32_MIN = -0x80000000; +const I32_MAX = 0x7fffffff; +const isI32 = (x) => x >= I32_MIN && x <= I32_MAX; + +function toBig(x) { + if (typeof x === "bigint") return x; + if (!Number.isInteger(x)) throw new TypeError(`integer expected, got ${x}`); + return BigInt(x); +} +/** + * Python ints beyond 2**53 (64-bit register/double bit patterns) are kept as + * BigInt so no bits are lost; everything in the safe range is a Number. + */ +function fromBig(b) { + const n = Number(b); + return Number.isSafeInteger(n) ? n : b; +} +export function normint(b) { + return typeof b === "bigint" ? fromBig(b) : b; +} + +/** Python `a & b` for arbitrary-size ints. */ +export function band(a, b) { + if (isI32(a) && isI32(b)) return a & b; + if (a >= 0 && b >= 0 && a <= 0xffffffff && b <= 0xffffffff) return (a & b) >>> 0; + return fromBig(toBig(a) & toBig(b)); +} +/** Python `a | b`. */ +export function bor(a, b) { + if (isI32(a) && isI32(b)) return a | b; + if (a >= 0 && b >= 0 && a <= 0xffffffff && b <= 0xffffffff) return (a | b) >>> 0; + return fromBig(toBig(a) | toBig(b)); +} +/** Python `a ^ b`. */ +export function bxor(a, b) { + if (isI32(a) && isI32(b)) return a ^ b; + if (a >= 0 && b >= 0 && a <= 0xffffffff && b <= 0xffffffff) return (a ^ b) >>> 0; + return fromBig(toBig(a) ^ toBig(b)); +} +/** Python `~a`. */ +export function bnot(a) { + if (typeof a === "bigint") return normint(-a - 1n); + return -a - 1; +} +/** Python `a << n`. */ +export function shl(a, n) { + if (n < 0) throw new ValueError("negative shift count"); + if (n < 31 && isI32(a)) { + const r = a * 2 ** n; + if (Number.isSafeInteger(r)) return r; + } + return fromBig(toBig(a) << toBig(n)); +} +/** Python `a >> n` (arithmetic, floors). */ +export function shr(a, n) { + if (n < 0) throw new ValueError("negative shift count"); + if (isI32(a)) return n >= 32 ? (a < 0 ? -1 : 0) : a >> n; + return fromBig(toBig(a) >> toBig(n)); +} +/** Python `a // b`. */ +export function floordiv(a, b) { + if (b === 0) throw new Error("ZeroDivisionError: integer division or modulo by zero"); + if (Number.isSafeInteger(a) && Number.isSafeInteger(b)) { + const q = Math.floor(a / b); + // Guard against rounding in the float division for large operands. + if (Math.abs(a) < 2 ** 52 && Math.abs(b) < 2 ** 52) return q; + const A = BigInt(a), B = BigInt(b); + let r = A / B; + if ((A % B !== 0n) && ((A < 0n) !== (B < 0n))) r -= 1n; + return Number(r); + } + return Math.floor(a / b); +} +/** Python `a % b` for ints (result has the sign of b). */ +export function pymod(a, b) { + if (b === 0) throw new Error("ZeroDivisionError: integer division or modulo by zero"); + if (Number.isSafeInteger(a) && Number.isSafeInteger(b)) { + const r = a % b; + return r !== 0 && (r < 0) !== (b < 0) ? r + b : r === 0 ? 0 : r; + } + const r = a % b; + return r !== 0 && (r < 0) !== (b < 0) ? r + b : r; +} +/** Python float `%` (math.fmod with divisor sign). */ +export function pyfmod(a, b) { + const r = a % b; + return r !== 0 && (r < 0) !== (b < 0) ? r + b : r; +} + +/** Python `hex(n)`. */ +export function hex(n) { + if (typeof n === "bigint") return n < 0n ? "-0x" + (-n).toString(16) : "0x" + n.toString(16); + return n < 0 ? "-0x" + (-n).toString(16) : "0x" + n.toString(16); +} + +/** + * Python `int(s, base)`. base 0 honours 0x/0o/0b prefixes (and rejects + * leading zeros on decimals, like Python). Underscores between digits allowed. + */ +export function int_(s, base = 10) { + if (typeof s === "number") { + if (!Number.isFinite(s)) throw new ValueError(`cannot convert float ${s} to integer`); + return Math.trunc(s); + } + if (typeof s === "boolean") return s ? 1 : 0; + const orig = s; + let t = String(s).trim(); + let neg = false; + if (t.startsWith("-")) { neg = true; t = t.slice(1); } else if (t.startsWith("+")) t = t.slice(1); + let b = base; + const low = t.toLowerCase(); + if (b === 0) { + if (low.startsWith("0x")) { b = 16; t = t.slice(2); } + else if (low.startsWith("0o")) { b = 8; t = t.slice(2); } + else if (low.startsWith("0b")) { b = 2; t = t.slice(2); } + else { + b = 10; + if (/^0+[1-9_]/.test(t) && !/^0+(_0+)*$/.test(t)) throw new ValueError(`invalid literal for int() with base 0: '${orig}'`); + } + if (t.startsWith("_")) t = t.slice(1); + } else if (b === 16 && low.startsWith("0x")) t = t.slice(2); + else if (b === 8 && low.startsWith("0o")) t = t.slice(2); + else if (b === 2 && low.startsWith("0b")) t = t.slice(2); + if (!t || t.startsWith("_") || t.endsWith("_") || t.includes("__")) throw new ValueError(`invalid literal for int() with base ${base}: '${orig}'`); + t = t.replace(/_/g, ""); + const digits = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, b); + for (const c of t.toLowerCase()) if (!digits.includes(c)) throw new ValueError(`invalid literal for int() with base ${base}: '${orig}'`); + let v; + if (t.length <= 12 || (b === 16 && t.length <= 13)) v = parseInt(t, b); + else { + let big = 0n; + const B = BigInt(b); + for (const c of t.toLowerCase()) big = big * B + BigInt(digits.indexOf(c)); + v = fromBig(neg ? -big : big); + return v; + } + return neg ? -v : v; +} + +/** Python bool(int(...)) style truthiness for common values. */ +export function truthy(x) { + if (x === null || x === undefined || x === false || x === 0 || x === "" || x === 0n) return false; + if (Array.isArray(x)) return x.length > 0; + if (x instanceof Map || x instanceof Set) return x.size > 0; + return true; +} + +// ---------------------------------------------------------------- floats + +/** Python `repr(float)` / `str(float)`. */ +export function float_repr(x) { + if (Number.isNaN(x)) return "nan"; + if (x === Infinity) return "inf"; + if (x === -Infinity) return "-inf"; + if (x === 0) return Object.is(x, -0) ? "-0.0" : "0.0"; + const e = x.toExponential(); // shortest round-trip digits + const m = /^(-?)(\d)(?:\.(\d+))?e([+-]\d+)$/.exec(e); + const sign = m[1]; + const digits = m[2] + (m[3] ?? ""); + const exp = parseInt(m[4], 10); + if (exp < -4 || exp >= 16) { + const mant = digits.length > 1 ? digits[0] + "." + digits.slice(1) : digits; + const es = Math.abs(exp) < 10 ? "0" + Math.abs(exp) : String(Math.abs(exp)); + return `${sign}${mant}e${exp < 0 ? "-" : "+"}${es}`; + } + if (exp < 0) return `${sign}0.${"0".repeat(-exp - 1)}${digits}`; + if (digits.length <= exp + 1) return `${sign}${digits}${"0".repeat(exp + 1 - digits.length)}.0`; + return `${sign}${digits.slice(0, exp + 1)}.${digits.slice(exp + 1)}`; +} + +/** Python `str()` of a value, as used in f-strings. */ +export function str(x) { + if (x === null || x === undefined) return "None"; + if (x === true) return "True"; + if (x === false) return "False"; + if (typeof x === "number") return Number.isInteger(x) && !Object.is(x, -0) && Math.abs(x) < 1e21 && !x.__float ? String(x) : String(x); + if (typeof x === "string") return x; + if (typeof x === "bigint") return x.toString(); + if (typeof x.__str__ === "function") return x.__str__(); + if (Array.isArray(x)) return "[" + x.map(repr).join(", ") + "]"; + return String(x); +} + +/** Python `repr()` for the simple cases m2c prints. */ +export function repr(x) { + if (typeof x === "string") return pyStrRepr(x); + if (x === null || x === undefined) return "None"; + if (x === true) return "True"; + if (x === false) return "False"; + if (typeof x === "number") return String(x); + if (Array.isArray(x)) return "[" + x.map(repr).join(", ") + "]"; + if (x && typeof x.__repr__ === "function") return x.__repr__(); + return str(x); +} + +/** Python repr of a str. */ +export function pyStrRepr(s) { + const q = s.includes("'") && !s.includes('"') ? '"' : "'"; + let out = q; + for (const ch of s) { + const c = ch.codePointAt(0); + if (ch === "\\") out += "\\\\"; + else if (ch === q) out += "\\" + q; + else if (ch === "\n") out += "\\n"; + else if (ch === "\r") out += "\\r"; + else if (ch === "\t") out += "\\t"; + else if (c < 0x20 || c === 0x7f) out += "\\x" + c.toString(16).padStart(2, "0"); + else if (c >= 0x80 && c < 0xa0) out += "\\x" + c.toString(16).padStart(2, "0"); + else out += ch; + } + return out + q; +} + +// Round a non-negative finite float to `prec` digits after the point, as +// Python's correctly-rounded formatting does (round-half-even on the exact +// binary value). Returns the digit string (no point) and the exponent shift. +function exactDecimal(x) { + // Exact decimal expansion of a finite double, as [digits, pointPos] where + // value = 0.digits * 10^pointPos ... we instead return integer + scale. + const buf = new DataView(new ArrayBuffer(8)); + buf.setFloat64(0, x); + const hi = buf.getUint32(0), lo = buf.getUint32(4); + const expBits = (hi >>> 20) & 0x7ff; + let mant = (BigInt(hi & 0xfffff) << 32n) | BigInt(lo); + let e2; + if (expBits === 0) e2 = -1074; + else { mant |= 1n << 52n; e2 = expBits - 1075; } + // value = mant * 2^e2 + if (e2 >= 0) return { num: mant << BigInt(e2), scale: 0 }; + // mant * 2^e2 = mant * 5^-e2 / 10^-e2 + return { num: mant * 5n ** BigInt(-e2), scale: -e2 }; +} + +function roundDigits(num, scale, keepScale) { + // num / 10^scale, rounded to keepScale decimal places, half-even. Returns BigInt of value*10^keepScale. + if (keepScale >= scale) return num * 10n ** BigInt(keepScale - scale); + const div = 10n ** BigInt(scale - keepScale); + let q = num / div; + const r = num % div; + const twice = r * 2n; + if (twice > div || (twice === div && q % 2n === 1n)) q += 1n; + return q; +} + +/** Python `format(x, ".Nf")` for floats. */ +export function format_fixed(x, prec) { + if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf"; + const neg = x < 0 || Object.is(x, -0); + const { num, scale } = exactDecimal(Math.abs(x)); + const q = roundDigits(num, scale, prec); + let s = q.toString(); + if (prec > 0) { + s = s.padStart(prec + 1, "0"); + s = s.slice(0, s.length - prec) + "." + s.slice(s.length - prec); + } + return (neg ? "-" : "") + s; +} + +/** Python `format(x, ".Ne")` for floats. */ +export function format_exp(x, prec, upper = false) { + if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf"; + const neg = x < 0 || Object.is(x, -0); + const ax = Math.abs(x); + let digits, exp; + if (ax === 0) { digits = "0".repeat(prec + 1); exp = 0; } + else { + const { num, scale } = exactDecimal(ax); + // number of integer digits + const intDigits = num.toString().length - scale; // exponent of leading digit + 1 + exp = intDigits - 1; + let q = roundDigits(num, scale, prec - exp); + if (q.toString().length > prec + 1) { exp += 1; q = roundDigits(num, scale, prec - exp); } + digits = q.toString(); + } + const mant = prec > 0 ? digits[0] + "." + digits.slice(1) : digits; + const es = Math.abs(exp) < 10 ? "0" + Math.abs(exp) : String(Math.abs(exp)); + return (neg ? "-" : "") + mant + (upper ? "E" : "e") + (exp < 0 ? "-" : "+") + es; +} + +/** Python `format(x, ".Ng")` for floats (no '#' flag). */ +export function format_general(x, prec = 6, upper = false) { + if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf"; + if (prec === 0) prec = 1; + if (x === 0) return Object.is(x, -0) ? "-0" : "0"; + const es = format_exp(x, prec - 1); + const exp = parseInt(es.slice(es.indexOf("e") + 1), 10); + let s; + if (exp >= -4 && exp < prec) { + s = format_fixed(x, prec - 1 - exp); + if (s.includes(".")) s = s.replace(/0+$/, "").replace(/\.$/, ""); + } else { + let [mant, e] = es.split("e"); + if (mant.includes(".")) mant = mant.replace(/0+$/, "").replace(/\.$/, ""); + s = mant + "e" + e; + } + return upper ? s.toUpperCase() : s; +} + +/** + * Python `format(value, spec)` for int/float/str values and the common + * format-spec features ([[fill]align][sign][#][0][width][,][.precision][type]). + */ +export function format(value, spec = "") { + if (!spec) return str(value); + const m = /^(?:(.)?([<>=^]))?([+\- ])?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/su.exec(spec); + if (!m) throw new ValueError(`Invalid format specifier '${spec}'`); + let [, fill, align, sign, alt, zero, width, grouping, precision, type] = m; + const w = width ? parseInt(width, 10) : 0; + const p = precision !== undefined ? parseInt(precision, 10) : undefined; + if (zero && !align) { fill = "0"; align = "="; } + fill = fill ?? " "; + let body, prefix = "", isNum = typeof value === "number" || typeof value === "bigint"; + if (typeof value === "string") { + body = p !== undefined ? value.slice(0, p) : value; + align = align ?? "<"; + } else { + let v = value; + let neg = false; + if (typeof v === "boolean") v = v ? 1 : 0; + const t = type ?? (Number.isInteger(v) && !(value && value.__isFloat) ? "d" : "g_repr"); + if (["d", "x", "X", "o", "b", "c", "n"].includes(t)) { + let n = typeof v === "bigint" ? v : BigInt(v); + if (n < 0n) { neg = true; n = -n; } + if (t === "x") body = n.toString(16); + else if (t === "X") body = n.toString(16).toUpperCase(); + else if (t === "o") body = n.toString(8); + else if (t === "b") body = n.toString(2); + else if (t === "c") body = String.fromCodePoint(Number(n)); + else body = n.toString(); + if (alt) prefix = t === "x" ? "0x" : t === "X" ? "0X" : t === "o" ? "0o" : t === "b" ? "0b" : ""; + if (grouping) body = body.replace(/\B(?=(\d{3})+(?!\d))/g, grouping); + } else { + let f = Number(v); + if (f < 0 || Object.is(f, -0)) { neg = true; f = -f; } + if (t === "f" || t === "F") body = format_fixed(f, p ?? 6); + else if (t === "e" || t === "E") body = format_exp(f, p ?? 6, t === "E"); + else if (t === "g" || t === "G") body = format_general(f, p ?? 6, t === "G"); + else if (t === "%") body = format_fixed(f * 100, p ?? 6) + "%"; + else body = p !== undefined ? format_general(f, p) : float_repr(f); + if (t === "F" || t === "E" || t === "G") body = body.toUpperCase(); + } + const signStr = neg ? "-" : sign === "+" ? "+" : sign === " " ? " " : ""; + prefix = signStr + prefix; + align = align ?? ">"; + } + const len = [...(prefix + body)].length; + if (w <= len) return prefix + body; + const pad = w - len; + if (align === "=" && isNum) return prefix + fill.repeat(pad) + body; + if (align === "<") return prefix + body + fill.repeat(pad); + if (align === "^") return fill.repeat(Math.floor(pad / 2)) + prefix + body + fill.repeat(pad - Math.floor(pad / 2)); + return fill.repeat(pad) + prefix + body; +} + +/** Python `"%..." % args` printf-style formatting (subset). */ +export function percent(fmt, args) { + if (!Array.isArray(args)) args = [args]; + let i = 0; + return fmt.replace(/%([-+ #0]*)(\d+|\*)?(?:\.(\d+))?([diouxXeEfFgGcrs%])/g, (_, flags, width, prec, conv) => { + if (conv === "%") return "%"; + let spec = ""; + if (flags.includes("-")) spec += "<"; + if (flags.includes("+")) spec += "+"; + else if (flags.includes(" ")) spec += " "; + if (flags.includes("#")) spec += "#"; + if (flags.includes("0") && !flags.includes("-")) spec += "0"; + if (width === "*") width = String(args[i++]); + if (width) spec += width; + if (prec !== undefined) spec += "." + prec; + const v = args[i++]; + if (conv === "s") return format(str(v), spec); + if (conv === "r") return format(repr(v), spec); + const c = conv === "i" || conv === "u" ? "d" : conv; + return format(v, spec + c); + }); +} + +// ---------------------------------------------------------------- strings + +/** Python `str.isspace()`. */ +export function isspace(s) { + return s.length > 0 && /^\s+$/u.test(s); +} +/** Python `str.isdigit()` (ASCII digits). */ +export function isdigit(s) { + return s.length > 0 && /^[0-9]+$/.test(s); +} +/** Python `str.isalnum()` (ASCII). */ +export function isalnum(s) { + return s.length > 0 && /^[A-Za-z0-9]+$/.test(s); +} +/** Python `str.isidentifier()` (ASCII subset). */ +export function isidentifier(s) { + return /^[A-Za-z_][A-Za-z0-9_]*$/.test(s); +} +/** Python `str.split()` with no separator. */ +export function split_ws(s, maxsplit = -1) { + const out = []; + let rest = s.replace(/^\s+/, ""); + while (rest) { + if (maxsplit >= 0 && out.length === maxsplit) { out.push(rest); return out; } + const m = /\s/.exec(rest); + if (!m) { out.push(rest); break; } + out.push(rest.slice(0, m.index)); + rest = rest.slice(m.index).replace(/^\s+/, ""); + } + return out; +} +/** Python `str.split(sep, maxsplit)`. */ +export function split(s, sep, maxsplit = -1) { + if (sep === undefined || sep === null) return split_ws(s, maxsplit); + const parts = s.split(sep); + if (maxsplit < 0 || parts.length <= maxsplit + 1) return parts; + return [...parts.slice(0, maxsplit), parts.slice(maxsplit).join(sep)]; +} +/** Python `str.rsplit(sep, maxsplit)`. */ +export function rsplit(s, sep, maxsplit = -1) { + const parts = s.split(sep); + if (maxsplit < 0 || parts.length <= maxsplit + 1) return parts; + const keep = parts.length - maxsplit; + return [parts.slice(0, keep).join(sep), ...parts.slice(keep)]; +} +/** Python `str.partition(sep)`. */ +export function partition(s, sep) { + const i = s.indexOf(sep); + if (i < 0) return [s, "", ""]; + return [s.slice(0, i), sep, s.slice(i + sep.length)]; +} +/** Python `str.rpartition(sep)`. */ +export function rpartition(s, sep) { + const i = s.lastIndexOf(sep); + if (i < 0) return ["", "", s]; + return [s.slice(0, i), sep, s.slice(i + sep.length)]; +} +const PY_WS = " \t\n\r\x0b\x0c\x1c\x1d\x1e\x1f\x85\xa0"; +function charsSet(chars) { + return chars === undefined || chars === null ? null : new Set(chars); +} +/** Python `str.strip(chars)`. */ +export function strip(s, chars) { + return rstrip(lstrip(s, chars), chars); +} +/** Python `str.lstrip(chars)`. */ +export function lstrip(s, chars) { + const set = charsSet(chars); + let i = 0; + while (i < s.length && (set ? set.has(s[i]) : PY_WS.includes(s[i]) || /\s/u.test(s[i]))) i++; + return s.slice(i); +} +/** Python `str.rstrip(chars)`. */ +export function rstrip(s, chars) { + const set = charsSet(chars); + let i = s.length; + while (i > 0 && (set ? set.has(s[i - 1]) : PY_WS.includes(s[i - 1]) || /\s/u.test(s[i - 1]))) i--; + return s.slice(0, i); +} +/** Python `str.splitlines()`. */ +export function splitlines(s, keepends = false) { + const out = []; + const re = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g; + let last = 0; + let m; + while ((m = re.exec(s))) { + out.push(s.slice(last, keepends ? m.index + m[0].length : m.index)); + last = m.index + m[0].length; + } + if (last < s.length) out.push(s.slice(last)); + return out; +} +/** Python `str.count(sub)`. */ +export function count(s, sub) { + if (!sub) return s.length + 1; + let n = 0; + let i = 0; + while ((i = s.indexOf(sub, i)) >= 0) { n++; i += sub.length; } + return n; +} +/** Python slice with negative indices, for strings and arrays. */ +export function slice(x, start, end) { + const n = x.length; + const norm = (v, d) => (v === undefined || v === null ? d : v < 0 ? Math.max(0, n + v) : Math.min(v, n)); + return x.slice(norm(start, 0), norm(end, n)); +} +/** Python `x[i]` with negative index support (throws IndexError). */ +export function at(x, i) { + const j = i < 0 ? x.length + i : i; + if (j < 0 || j >= x.length) throw new IndexError("index out of range"); + return x[j]; +} + +/** Python `ljust` / `rjust`. */ +export function ljust(s, w, fill = " ") { + return s.length >= w ? s : s + fill.repeat(w - s.length); +} +export function rjust(s, w, fill = " ") { + return s.length >= w ? s : fill.repeat(w - s.length) + s; +} + +// ---------------------------------------------------------------- containers + +/** Python `collections.defaultdict` over a Map. */ +export class DefaultMap extends Map { + constructor(factory, entries) { + super(entries); + this.factory = factory; + } + get(key) { + if (!super.has(key)) { + const v = this.factory(); + super.set(key, v); + return v; + } + return super.get(key); + } + /** Python dict.get(key) on a defaultdict: no insertion; undefined if missing. */ + peek(key) { + return super.get(key); + } +} + +/** Python `list.index(x)` raising ValueError. */ +export function list_index(arr, x) { + const i = arr.indexOf(x); + if (i < 0) throw new ValueError(`${str(x)} is not in list`); + return i; +} + +/** Python `max(iterable, key=...)` (first maximal element wins). */ +export function max_by(items, key) { + let best, bestK, first = true; + for (const it of items) { + const k = key(it); + if (first || compare(k, bestK) > 0) { best = it; bestK = k; first = false; } + } + if (first) throw new ValueError("max() arg is an empty sequence"); + return best; +} +/** Python `min(iterable, key=...)` (first minimal element wins). */ +export function min_by(items, key) { + let best, bestK, first = true; + for (const it of items) { + const k = key(it); + if (first || compare(k, bestK) < 0) { best = it; bestK = k; first = false; } + } + if (first) throw new ValueError("min() arg is an empty sequence"); + return best; +} + +/** Python rich comparison for numbers, strings, booleans, and tuples (arrays). */ +export function compare(a, b) { + if (Array.isArray(a) && Array.isArray(b)) { + const n = Math.min(a.length, b.length); + for (let i = 0; i < n; i++) { + const c = compare(a[i], b[i]); + if (c !== 0) return c; + } + return a.length - b.length; + } + if (typeof a === "boolean") a = a ? 1 : 0; + if (typeof b === "boolean") b = b ? 1 : 0; + if (a && typeof a.__lt__ === "function") return a.__lt__(b) ? -1 : b.__lt__(a) ? 1 : 0; + if (typeof a === "string" && typeof b === "string") { + // Python compares by code point. + if (a === b) return 0; + const n = Math.min(a.length, b.length); + for (let i = 0; i < n; i++) { + const ca = a.codePointAt(i), cb = b.codePointAt(i); + if (ca !== cb) return ca < cb ? -1 : 1; + } + return a.length - b.length; + } + if (a === null || a === undefined || b === null || b === undefined) throw new TypeError("'<' not supported with None"); + return a < b ? -1 : a > b ? 1 : 0; +} +/** Python `sorted(items, key=..., reverse=...)` (stable). */ +export function sorted(items, key = (x) => x, reverse = false) { + const arr = [...items].map((v, i) => [key(v), i, v]); + arr.sort((x, y) => { + const c = compare(x[0], y[0]); + if (c !== 0) return reverse ? -c : c; + return x[1] - y[1]; + }); + return arr.map((x) => x[2]); +} + +/** Python `range(...)` as an array. */ +export function range(a, b, step = 1) { + if (b === undefined) { b = a; a = 0; } + const out = []; + if (step > 0) for (let i = a; i < b; i += step) out.push(i); + else for (let i = a; i > b; i += step) out.push(i); + return out; +} +/** Python `zip(a, b, ...)` as an array (truncates to the shortest). */ +export function zip(...arrs) { + const n = Math.min(...arrs.map((a) => a.length)); + const out = []; + for (let i = 0; i < n; i++) out.push(arrs.map((a) => a[i])); + return out; +} +/** Python `enumerate`. */ +export function enumerate(arr, start = 0) { + return [...arr].map((v, i) => [i + start, v]); +} +/** Python `any` / `all` over an iterable of values. */ +export function any(it) { + for (const x of it) if (truthy(x)) return true; + return false; +} +export function all(it) { + for (const x of it) if (!truthy(x)) return false; + return true; +} + +// ---------------------------------------------------------------- value interning + +let internSeq = 0; +const internTables = new Map(); + +/** + * Canonicalise a frozen value object: the first instance with a given class + * and field key is returned for every later construction, so `===` and Map + * keys behave like Python's dataclass __eq__/__hash__. + * Call from a constructor as `return intern(this, [fields...])`. + */ +export function intern(obj, parts) { + const cls = obj.constructor; + let table = internTables.get(cls); + if (!table) internTables.set(cls, (table = new Map())); + const key = parts.map(internKeyPart).join("\u0001"); + const hit = table.get(key); + if (hit) return hit; + Object.defineProperty(obj, "__iid", { value: ++internSeq, enumerable: false }); + table.set(key, obj); + return obj; +} +function internKeyPart(p) { + if (p === null || p === undefined) return "N"; + switch (typeof p) { + case "number": return Object.is(p, -0) ? "n-0" : "n" + p; + case "string": return "s" + p; + case "boolean": return p ? "T" : "F"; + case "bigint": return "b" + p; + default: + if (Array.isArray(p)) return "[" + p.map(internKeyPart).join(",") + "]"; + if (p.__iid !== undefined) return "#" + p.__iid; + if (p.__enum_key !== undefined) return "E" + p.__enum_key; + throw new TypeError("intern: unhashable field " + p?.constructor?.name); + } +} + +/** Deep copy of plain data / class instances (Python copy.deepcopy). */ +export function deepcopy(x, memo = new Map()) { + if (x === null || typeof x !== "object") return x; + if (memo.has(x)) return memo.get(x); + if (x.__iid !== undefined) return x; // interned immutables + if (Array.isArray(x)) { + const out = []; + memo.set(x, out); + for (const v of x) out.push(deepcopy(v, memo)); + return out; + } + if (x instanceof Map) { + const out = new (x.constructor)(); + if (x.factory) out.factory = x.factory; + memo.set(x, out); + for (const [k, v] of x) out.set(deepcopy(k, memo), deepcopy(v, memo)); + return out; + } + if (x instanceof Set) { + const out = new Set(); + memo.set(x, out); + for (const v of x) out.add(deepcopy(v, memo)); + return out; + } + const out = Object.create(Object.getPrototypeOf(x)); + memo.set(x, out); + for (const k of Object.keys(x)) out[k] = deepcopy(x[k], memo); + return out; +} + +/** Shallow copy of a class instance (Python copy.copy / dataclasses.replace base). */ +export function shallowcopy(x) { + const out = Object.create(Object.getPrototypeOf(x)); + Object.assign(out, x); + return out; +} + +// ---------------------------------------------------------------- Python equality / hashing + +const objIds = new WeakMap(); +let nextObjId = 0; +/** Stable identity number for an object (Python id()). */ +export function objId(o) { + let id = objIds.get(o); + if (id === undefined) { + id = ++nextObjId; + objIds.set(o, id); + } + return id; +} + +/** + * A string key that is equal for two values iff Python's `==` holds (and + * therefore their hashes agree). Classes opt into structural (dataclass + * eq=True) equality with a static `__eq_fields` array naming the compared + * fields, or a custom `__pykey()` method; interned values compare by + * identity-of-canonical-instance; everything else is identity. + */ +export function pykey(x) { + if (x === null || x === undefined) return "N"; + switch (typeof x) { + case "number": + return "n" + (Object.is(x, -0) ? 0 : x); + case "boolean": + return x ? "n1" : "n0"; + case "string": + return "s" + x.length + ":" + x; + case "bigint": + return "n" + x; + case "function": + return "@" + objId(x); + } + if (Array.isArray(x)) return "(" + x.map(pykey).join(",") + ")"; + if (x.__iid !== undefined) return "#" + x.__iid; + if (typeof x.__pykey === "function") return x.__pykey(); + const ctor = x.constructor; + if (ctor && Object.prototype.hasOwnProperty.call(ctor, "__eq_fields")) { + return ctor.name + "{" + ctor.__eq_fields.map((k) => pykey(x[k])).join(",") + "}"; + } + return "@" + objId(x); +} + +/** Python `a == b`. */ +export function pyeq(a, b) { + if (a === b) return true; + if (a === null || a === undefined || b === null || b === undefined) return a == b; + if (typeof a !== "object" || typeof b !== "object") return a === b || (typeof a === typeof b ? false : pykey(a) === pykey(b)); + if (typeof a.equals === "function") return a.equals(b); + return pykey(a) === pykey(b); +} + +/** Python `x in arr` for a list, with Python equality. */ +export function pyin(x, arr) { + for (const y of arr) if (pyeq(x, y)) return true; + return false; +} + +/** dict with Python key semantics (see pykey). Map-like API; iteration yields [key, value]. */ +export class PyDict { + constructor(entries) { + this._m = new Map(); + if (entries) for (const [k, v] of entries) this.set(k, v); + } + get size() { + return this._m.size; + } + has(k) { + return this._m.has(pykey(k)); + } + get(k) { + const e = this._m.get(pykey(k)); + return e === undefined ? undefined : e[1]; + } + set(k, v) { + const key = pykey(k); + const e = this._m.get(key); + if (e) e[1] = v; + else this._m.set(key, [k, v]); + return this; + } + delete(k) { + return this._m.delete(pykey(k)); + } + clear() { + this._m.clear(); + } + *keys() { + for (const e of this._m.values()) yield e[0]; + } + *values() { + for (const e of this._m.values()) yield e[1]; + } + *entries() { + for (const e of this._m.values()) yield [e[0], e[1]]; + } + [Symbol.iterator]() { + return this.entries(); + } +} + +/** defaultdict with Python key semantics. */ +export class DefaultPyDict extends PyDict { + constructor(factory, entries) { + super(entries); + this.factory = factory; + } + get(k) { + const key = pykey(k); + const e = this._m.get(key); + if (e) return e[1]; + const v = this.factory(); + this._m.set(key, [k, v]); + return v; + } + peek(k) { + return super.get(k); + } +} + +/** set with Python element semantics (see pykey). Iteration yields elements in insertion order. */ +export class PySet { + constructor(items) { + this._m = new Map(); + if (items) for (const x of items) this.add(x); + } + get size() { + return this._m.size; + } + has(x) { + return this._m.has(pykey(x)); + } + add(x) { + const key = pykey(x); + if (!this._m.has(key)) this._m.set(key, x); + return this; + } + delete(x) { + return this._m.delete(pykey(x)); + } + clear() { + this._m.clear(); + } + values() { + return this._m.values(); + } + [Symbol.iterator]() { + return this._m.values(); + } +} + +// ---------------------------------------------------------------- dataclasses + +/** Default-value marker for a dataclass field built by a factory (field(default_factory=...)). */ +export function factory(fn) { + return { __factory: fn }; +} + +function isKw(x) { + return x !== null && typeof x === "object" && Object.getPrototypeOf(x) === Object.prototype; +} + +/** + * Python dataclass __init__: `static __fields = [[name], [name, default], [name, factory(fn)]]` + * on the class; constructors call `dcinit(this, args)` with their rest args. + * Accepts positional args in field order, optionally followed by (or replaced by) + * a plain object of keyword args. + */ +export function dcinit(self, args) { + const fields = self.constructor.__fields; + let kw = null; + if (args.length && isKw(args[args.length - 1])) { + kw = args[args.length - 1]; + args = args.slice(0, -1); + } + if (args.length > fields.length) throw new TypeError(`${self.constructor.name}: too many positional arguments`); + for (let i = 0; i < fields.length; i++) { + const f = fields[i]; + const name = f[0]; + let v; + if (i < args.length) v = args[i]; + else if (kw && Object.prototype.hasOwnProperty.call(kw, name)) v = kw[name]; + else if (f.length < 2) throw new TypeError(`${self.constructor.name}: missing required argument '${name}'`); + else v = f[1] !== null && typeof f[1] === "object" && f[1].__factory ? f[1].__factory() : f[1]; + self[name] = v === undefined ? null : v; + } + if (kw) for (const k of Object.keys(kw)) if (!fields.some((f) => f[0] === k)) throw new TypeError(`${self.constructor.name}: unexpected keyword argument '${k}'`); +} + +/** dataclasses.replace(obj, **changes) */ +export function dcreplace(obj, changes) { + const kw = {}; + for (const f of obj.constructor.__fields) kw[f[0]] = obj[f[0]]; + Object.assign(kw, changes); + return new obj.constructor(kw); +} + +/** Object.hasOwn for plain-object dicts (Python `key in dict`). */ +export function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +/** Python round() (round-half-even) for floats to int. */ +export function pyround(x) { + const r = Math.round(x); + if (Math.abs(x % 1) === 0.5) return 2 * Math.round(x / 2); + return r; +} + +/** Python int.bit_length() */ +export function bit_length(n) { + if (n < 0) n = -n; + if (n === 0) return 0; + if (n < 2 ** 31) return 32 - Math.clz32(n); + return BigInt(n).toString(2).length; +} diff --git a/packages/romdev-m2c/src/translate.js b/packages/romdev-m2c/src/translate.js new file mode 100644 index 00000000..b22e7963 --- /dev/null +++ b/packages/romdev-m2c/src/translate.js @@ -0,0 +1,3464 @@ +// Port of m2c/translate.py +/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */ +import { ArchC, is_unk_type } from "./c_types.js"; +import { parse as demangle_codewarrior_parse } from "./demangle_codewarrior.js"; +import { DecompFailure, assert_never } from "./error.js"; +import { + ArchFlowGraph, + BasicNode, + ConditionalNode, + InstrRef, + PrologueRef, + ReturnNode, + SwitchNode, + TerminalNode, + locs_clobbered_until_dominator, +} from "./flow_graph.js"; +import { simplify_ir_patterns } from "./ir_pattern.js"; +import { CodingStyle, Formatter, Options, Target } from "./options.js"; +import { AsmSymbolicData } from "./asm_file.js"; +import { AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, Macro, Register, RegisterList, Writeback } from "./asm_instruction.js"; +import { Instruction, InstrProcessingFailure, StackLocation, set_current_instr } from "./instruction.js"; +import { FunctionParam, StructDeclaration, Type } from "./types.js"; +import { + AssertionError, + DefaultMap, + DefaultPyDict, + PyDict, + PySet, + ValueError, + band, + bnot, + bor, + compare, + dcinit, + dcreplace, + factory, + floordiv, + float_repr, + format, + format_exp, + format_fixed, + format_general, + has, + hex, + int_, + objId, + pyassert, + pyeq, + pyin, + pymod, + rstrip, + shl, + sorted, + str, +} from "./py.js"; +import { py_float } from "./asm_file.js"; +import { print } from "./io.js"; + +/** Sort an array in place with a Python-style key (stable). */ +function sort_inplace(arr, key) { + const s = sorted(arr, key); + arr.splice(0, arr.length, ...s); +} + +/** + * Arch-specific information that relates to the translation level. Extends ArchFlowGraph. + */ +export class Arch extends ArchFlowGraph { + arg_name(loc) { + throw new Error("abstract"); + } + function_abi(fn_sig, likely_regs, { for_call }) { + throw new Error("abstract"); + } + function_return(expr) { + throw new Error("abstract"); + } + is_likely_partial_offset(addend) { + return 0 <= addend && addend < 0x1000000 && [0, 2 ** 15 - 1].includes(pymod(addend, 2 ** 15)); + } + c_symbol_name(asm_name) { + return asm_name; + } + simplify_ir(asm_data, flow_graph, { debug_patterns }) { + simplify_ir_patterns(this, asm_data, flow_graph, this.ir_patterns, { debug_patterns }); + } +} +Arch.prototype.ir_patterns = []; +Arch.prototype.base_struct_align = ArchC.prototype.base_struct_align; + +export const ASSOCIATIVE_OPS = new Set(["+", "&&", "||", "&", "|", "^", "*"]); +export const COMPOUND_ASSIGNMENT_OPS = new Set(["+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>"]); +export const PSEUDO_FUNCTION_OPS = new Set(["MULT_HI", "MULTU_HI", "DMULT_HI", "DMULTU_HI", "GLUE_F64", "CLZ"]); + +export function as_type(expr, type, silent, { unify = true } = {}) { + type = type.weaken_void_ptr(); + if (expr instanceof Literal) { + // For literals we (try to) avoid ever propagating information backwards, + // by creating a clone of the literal before casting it. + expr = new Literal(expr.value, expr.type.clone_literal_type()); + unify = true; + } + const ptr_target_type = type.get_pointer_target(); + if (unify && expr.type.unify(type)) { + if (silent || expr instanceof Literal) return expr; + } else if (ptr_target_type !== null) { + const ptr_target_type_size = ptr_target_type.get_size_bytes(); + const [field_path, field_type] = expr.type.get_deref_field(0, { target_size: ptr_target_type_size }); + if (field_path !== null && field_type.unify(ptr_target_type)) { + expr = new AddressOf( + new StructAccess({ struct_var: expr, offset: 0, target_size: ptr_target_type_size, field_path, stack_info: null, type: field_type }), + { type }, + ); + if (silent) return expr; + } + } + return new Cast({ expr, reinterpret: true, silent: false, type }); +} + +export function as_f32(expr) { + return as_type(expr, Type.f32(), true); +} +export function as_f64(expr) { + return as_type(expr, Type.f64(), true); +} +export function as_sintish(expr, { silent = false } = {}) { + return as_type(expr, Type.sintish(), silent); +} +export function as_uintish(expr) { + return as_type(expr, Type.uintish(), false); +} +export function as_s16(expr) { + return as_type(expr, Type.s16(), false); +} +export function as_u16(expr) { + return as_type(expr, Type.u16(), false); +} +export function as_u32(expr) { + return as_type(expr, Type.u32(), false); +} +export function as_s64(expr, { silent = false } = {}) { + return as_type(expr, Type.s64(), silent); +} +export function as_u64(expr, { silent = false } = {}) { + return as_type(expr, Type.u64(), silent); +} +export function as_intish(expr) { + return as_type(expr, Type.intish(), true); +} +export function as_int64(expr) { + return as_type(expr, Type.int64(), true); +} +export function as_intptr(expr) { + return as_type(expr, Type.intptr(), true); +} +export function as_ptr(expr) { + return as_type(expr, Type.ptr(), true); +} +export function as_function_ptr(expr) { + return as_type(expr, Type.ptr(Type.function()), true); +} + +/** A persistent Var, that can be merged with other ones using a union-find-based setup. */ +export class PlannedVar { + constructor(_parent = null) { + this._parent = _parent; + } + get_representative() { + let root = this; + const seen = []; + while (root._parent !== null) { + seen.push(root); + root = root._parent; + } + for (const v of seen) v._parent = root; + return root; + } + join(other) { + const a = this.get_representative(); + const b = other.get_representative(); + if (a !== b) a._parent = b; + } +} + +export const PhiInheritSource = Object.freeze({ DOMINATOR: "DOMINATOR", ANY_PARENT: "ANY_PARENT" }); + +/** Function state that's persistent between multiple translation passes. */ +export class PersistentFunctionState { + constructor() { + // (Register, Reference) -> PlannedVar + this.planned_vars = new PyDict(); + // (Register, Node) -> PhiInheritSource + this.planned_inherited_phis = new PyDict(); + } +} + +export class StackInfo { + constructor(fn, persistent_state, global_info, flow_graph) { + this.function = fn; + this.persistent_state = persistent_state; + this.global_info = global_info; + this.flow_graph = flow_graph; + this.warnings = []; + this.allocated_stack_size = 0; + this.is_leaf = true; + this.is_variadic = false; + this.frame_pointer_reg = null; + this.subroutine_arg_top = 0; + this.callee_save_regs = new Set(); + this.callee_save_reg_region = [0, 0]; + this.unique_type_map = new PyDict(); + this.local_vars = []; + this.temp_vars = []; + this.naive_phi_vars = []; + this.reg_vars = new Map(); + this.planned_vars = new PyDict(); + this.used_reg_vars = new Set(); + this.arguments = []; + this.temp_name_counter = new Map(); + this.nonzero_accesses = new PySet(); + this.param_names = new PyDict(); + this.stack_pointer_type = null; + this.replace_first_arg = null; + this.weak_stack_var_types = new Map(); + this.weak_stack_var_locations = new Set(); + } + + temp_var(prefix) { + const counter = (this.temp_name_counter.get(prefix) ?? 0) + 1; + this.temp_name_counter.set(prefix, counter); + return prefix + (counter > 1 ? `_${counter}` : ""); + } + + in_subroutine_arg_region(location) { + if (this.global_info.arch.arch === Target.ArchEnum.PPC) return false; + if (this.is_leaf) return false; + return location < this.subroutine_arg_top; + } + + in_callee_save_reg_region(location) { + const [lower_bound, upper_bound] = this.callee_save_reg_region; + if (lower_bound <= location && location < upper_bound) return true; + // PPC saves LR in the header of the previous stack frame + if (this.global_info.arch.arch === Target.ArchEnum.PPC && location === this.allocated_stack_size + 4) return true; + return false; + } + + location_above_stack(location) { + return location >= this.allocated_stack_size; + } + + add_known_param(loc, name, type) { + if (loc.sort_index === 0 && type.is_pointer() && this.replace_first_arg === null) { + const namespace = this.function.name.split("_")[0]; + const base_struct_type = type.get_pointer_target(); + const self_struct = this.global_info.typepool.get_struct_by_tag_name(namespace, this.global_info.typemap); + if (self_struct !== null && base_struct_type !== null && base_struct_type.is_struct()) { + const self_struct_type = Type.struct(self_struct); + const [field_path, field_type] = self_struct_type.get_field(0, { target_size: base_struct_type.get_size_bytes() }); + if (field_path !== null && field_type.unify(base_struct_type) && !self_struct_type.unify(base_struct_type)) { + this.replace_first_arg = [name || "_self", type]; + name = name === "thisx" ? "this" : "self"; + type = Type.ptr(Type.struct(self_struct)); + } + } + } + if (name) this.param_names.set(loc, name); + const arg = this.get_argument(loc); + this.arguments.push(arg); + sort_inplace(this.arguments, (a) => a.loc); + arg.type.unify(type); + return type; + } + + get_param_name(loc) { + return this.param_names.get(loc) ?? null; + } + + add_local_var(v) { + if (this.local_vars.some((x) => x.value === v.value)) return; + this.local_vars.push(v); + sort_inplace(this.local_vars, (x) => x.value); + } + + add_argument(arg) { + for (const a of this.arguments) { + if (a.loc.equals(arg.loc)) { + if (a.loc.reg === null && arg.loc.reg !== null) { + this.arguments.splice(this.arguments.indexOf(a), 1); + break; + } + return; + } + } + this.arguments.push(arg); + sort_inplace(this.arguments, (a) => a.loc); + } + + get_argument(loc) { + return new PassedInArg(loc, { stack_info: this, type: this.unique_type_for("arg", loc, Type.any_reg()) }); + } + + get_argument_above_stack(offset) { + const aligned_offset = band(offset, -4); + const loc = new ArgLoc(aligned_offset, null, null); + const arg = this.get_argument(loc); + if (aligned_offset === offset - 3) return [as_type(arg, Type.int_of_size(8), true), arg]; + if (aligned_offset === offset - 2) return [as_type(arg, Type.int_of_size(16), true), arg]; + return [arg, arg]; + } + + record_struct_access(ptr, location) { + if (location) this.nonzero_accesses.add(unwrap_deep(ptr)); + } + + has_nonzero_access(ptr) { + return this.nonzero_accesses.has(unwrap_deep(ptr)); + } + + unique_type_for(category, key, def) { + const k = [category, key]; + if (!this.unique_type_map.has(k)) this.unique_type_map.set(k, def); + return this.unique_type_map.get(k); + } + + saved_reg_symbol(reg_name) { + const sym_name = "saved_reg_" + reg_name; + const type = this.unique_type_for("saved_reg", sym_name, Type.any_reg()); + return new GlobalSymbol({ c_symbol_name: sym_name, type }); + } + + should_save(expr, offset) { + expr = early_unwrap(expr); + if (expr instanceof GlobalSymbol && (expr.c_symbol_name.startsWith("saved_reg_") || expr.c_symbol_name === "sp")) return true; + if (expr instanceof PassedInArg && expr.loc.offset !== null && (offset === null || offset === this.allocated_stack_size + expr.loc.offset)) return true; + return false; + } + + get_stack_var(location, { store }) { + if (this.in_callee_save_reg_region(location)) { + return new LocalVar(location, { type: Type.any_reg(), path: null }); + } else if (this.location_above_stack(location)) { + const offset = location - this.allocated_stack_size; + const [ret, arg] = this.get_argument_above_stack(offset); + if (!store) this.add_argument(arg); + return ret; + } else if (this.in_subroutine_arg_region(location)) { + return new SubroutineArg(location, { type: Type.any_reg() }); + } else { + pyassert(this.stack_pointer_type !== null); + let [field_path, field_type] = this.stack_pointer_type.get_deref_field(location, { target_size: null }); + + const previous_stored_type = this.weak_stack_var_types.get(location) ?? null; + if (previous_stored_type !== null) { + if (!previous_stored_type.unify(field_type)) this.weak_stack_var_locations.add(location); + if (store) field_type = Type.any_field(); + else field_type = previous_stored_type; + } + if (store) this.weak_stack_var_types.set(location, field_type); + return new LocalVar(location, { type: field_type, path: field_path }); + } + } + + maybe_get_register_var(reg) { + return this.reg_vars.get(reg) ?? null; + } + + add_register_var(reg, name) { + const type = reg.is_float() ? Type.floatish() : Type.intptr(); + const v = new Var(this, { prefix: `var_${name}`, is_planned: true, type }); + this.reg_vars.set(reg, v); + this.temp_vars.push(v); + } + + get_planned_var(reg, source) { + const v = this.reg_vars.get(reg) ?? null; + if (v && source instanceof InstrRef && source.instruction.function_target === null) return v; + return this.planned_vars.get([reg, source]) ?? null; + } + + get_persistent_planned_var(reg, source) { + let ret = this.persistent_state.planned_vars.get([reg, source]) ?? null; + if (!ret) { + ret = new PlannedVar(); + this.persistent_state.planned_vars.set([reg, source], ret); + } + return ret; + } + + add_planned_inherited_phi(node, reg, source) { + this.persistent_state.planned_inherited_phis.set([reg, node], source); + } + + get_planned_inherited_phi(node, reg) { + return this.persistent_state.planned_inherited_phis.get([reg, node]) ?? null; + } + + is_stack_reg(reg) { + if (reg === this.global_info.arch.stack_pointer_reg) return true; + if (reg === this.frame_pointer_reg) return true; + return false; + } + + /** Reorganize struct information in unique_type_map by var & offset */ + get_struct_type_map() { + const struct_type_map = new PyDict(); + for (const [[category, key], type] of this.unique_type_map) { + if (category !== "struct") continue; + const [v, offset] = key; + if (!struct_type_map.has(v)) struct_type_map.set(v, new Map()); + struct_type_map.get(v).set(offset, type); + } + return struct_type_map; + } + + toString() { + return [ + `Stack info for function ${this.function.name}:`, + `Allocated stack size: ${this.allocated_stack_size}`, + `Leaf? ${this.is_leaf ? "True" : "False"}`, + `Bounds of callee-saved vars region: (${this.callee_save_reg_region[0]}, ${this.callee_save_reg_region[1]})`, + `Subroutine arg top: ${this.subroutine_arg_top}`, + `Callee save registers: {${[...this.callee_save_regs].map((r) => `Register(register_name='${r.register_name}')`).join(", ")}}`, + ].join("\n"); + } +} + +export function get_stack_info(fn, persistent_state, global_info, flow_graph) { + const arch = global_info.arch; + const info = new StackInfo(fn, persistent_state, global_info, flow_graph); + + const callee_saved_offsets = []; + const allowed_callee_save_gaps = new Set(); + const temp_reg_values = new Map(); + for (const inst of flow_graph.entry_node().block.instructions) { + const arch_mnemonic = inst.arch_mnemonic(arch); + if (inst.function_target) { + break; + } else if (arch_mnemonic === "mips:addiu" && inst.args[0] === arch.stack_pointer_reg) { + pyassert(inst.args[2] instanceof AsmLiteral); + info.allocated_stack_size = Math.abs(inst.args[2].as_s16()); + } else if (arch_mnemonic === "mips:subu" && inst.args[0] === arch.stack_pointer_reg && inst.args[1] === arch.stack_pointer_reg && temp_reg_values.has(inst.args[2])) { + pyassert(inst.args[2] instanceof Register); + info.allocated_stack_size = temp_reg_values.get(inst.args[2]); + } else if (arch_mnemonic === "ppc:stwu" && inst.args[0] === arch.stack_pointer_reg) { + pyassert(inst.args[1] instanceof AsmAddressMode); + pyassert(inst.args[1].addend instanceof AsmLiteral); + info.allocated_stack_size = Math.abs(inst.args[1].addend.value); + } else if (arch_mnemonic === "arm:push" || arch_mnemonic === "arm:vpush") { + pyassert(inst.args[0] instanceof RegisterList); + for (const reg of [...inst.args[0].regs].reverse()) { + const [tp] = reg.arm_regtype_index(); + const num_words = { r: 1, s: 1, d: 2, q: 4 }[tp]; + for (let i = 0; i < num_words; i++) { + info.allocated_stack_size += 4; + if (arch.saved_regs.includes(reg)) callee_saved_offsets.push(-info.allocated_stack_size); + } + if (arch.saved_regs.includes(reg)) info.callee_save_regs.add(reg); + if (reg === new Register("lr")) info.is_leaf = false; + } + } else if ((arch_mnemonic === "arm:sub" || arch_mnemonic === "arm:add") && inst.args[0] === arch.stack_pointer_reg && inst.args[1] === arch.stack_pointer_reg && inst.args[2] instanceof AsmLiteral) { + const imm = inst.args[2].value * (arch_mnemonic === "arm:add" ? -1 : 1); + info.allocated_stack_size += Math.max(imm, 0); + } else if ( + ["mips:move", "arm:mov", "ppc:mr"].includes(arch_mnemonic) && + inst.args[0] instanceof Register && + arch.frame_pointer_regs.includes(inst.args[0]) && + inst.args[1] === arch.stack_pointer_reg + ) { + info.frame_pointer_reg = inst.args[0]; + } else if (arch_mnemonic === "sh:mov" && inst.args[0] === arch.stack_pointer_reg && inst.args[1] instanceof Register && arch.frame_pointer_regs.includes(inst.args[1])) { + info.frame_pointer_reg = inst.args[1]; + } else if (arch_mnemonic === "sh:add" && inst.args[0] instanceof AsmLiteral && inst.args[0].as_s8() < 0 && inst.args[1] === arch.stack_pointer_reg) { + info.allocated_stack_size += -inst.args[0].as_s8(); + } else if ( + (arch_mnemonic === "sh:mov.l" || arch_mnemonic === "sh:sts.l") && + inst.args[0] instanceof Register && + arch.saved_regs.includes(inst.args[0]) && + inst.args[1] instanceof AsmAddressMode && + inst.args[1].base === arch.stack_pointer_reg && + inst.args[1].writeback === Writeback.PRE + ) { + info.allocated_stack_size += 4; + info.callee_save_regs.add(inst.args[0]); + callee_saved_offsets.push(-info.allocated_stack_size); + if (inst.args[0] === arch.return_address_reg) info.is_leaf = false; + } else if ( + ["mips:sw", "mips:sd", "mips:sq", "mips:swc1", "mips:sdc1", "ppc:stw", "ppc:stmw", "ppc:stfd", "ppc:psq_st"].includes(arch_mnemonic) && + inst.args[0] instanceof Register && + arch.saved_regs.includes(inst.args[0]) && + inst.args[1] instanceof AsmAddressMode && + inst.args[1].base === arch.stack_pointer_reg && + (!info.callee_save_regs.has(inst.args[0]) || arch_mnemonic === "ppc:psq_st") + ) { + if (inst.args[0] === arch.return_address_reg || inst.args[0] === new Register("r0")) info.is_leaf = false; + const n = Math.min(inst.inputs.length, inst.outputs.length); + for (let k = 0; k < n; k++) { + const inp = inst.inputs[k]; + const mem = inst.outputs[k]; + if (inp instanceof Register && mem instanceof StackLocation) { + pyassert(mem.symbolic_offset === null); + const stack_offset = mem.offset; + if (arch_mnemonic !== "ppc:psq_st") info.callee_save_regs.add(inp); + callee_saved_offsets.push(stack_offset); + if (arch_mnemonic === "mips:sd") allowed_callee_save_gaps.add(stack_offset + 8); + if (arch_mnemonic === "mips:swc1") allowed_callee_save_gaps.add(stack_offset + 4); + } + } + } else if (arch_mnemonic === "ppc:mflr" && inst.args[0] === new Register("r0")) { + info.is_leaf = false; + } else if (arch_mnemonic === "mips:li" && arch.temp_regs.includes(inst.args[0])) { + pyassert(inst.args[0] instanceof Register); + pyassert(inst.args[1] instanceof AsmLiteral); + temp_reg_values.set(inst.args[0], inst.args[1].value); + } else if (arch_mnemonic === "mips:ori" && inst.args[0] === inst.args[1] && temp_reg_values.has(inst.args[0])) { + pyassert(inst.args[0] instanceof Register); + pyassert(inst.args[2] instanceof AsmLiteral); + temp_reg_values.set(inst.args[0], bor(temp_reg_values.get(inst.args[0]), inst.args[2].value)); + } + } + + if (arch.arch === Target.ArchEnum.ARM || arch.arch === Target.ArchEnum.SH) { + for (let i = 0; i < callee_saved_offsets.length; i++) callee_saved_offsets[i] += info.allocated_stack_size; + } + + if (!info.is_leaf) { + info.subroutine_arg_top = info.allocated_stack_size; + for (const node of flow_graph.nodes) { + for (const inst of node.block.instructions) { + const arch_mnemonic = inst.arch_mnemonic(arch); + if (inst.is_load) { + for (const arg of inst.args) { + if (arg instanceof AsmAddressMode && info.is_stack_reg(arg.base) && arg.addend instanceof AsmLiteral) { + const offset = band(arg.addend.value, -4); + if (offset >= arch.home_space_size) info.subroutine_arg_top = Math.min(info.subroutine_arg_top, offset); + } + } + } + if ( + ["mips:addiu", "ppc:addi", "arm:add"].includes(arch_mnemonic) && + inst.args[1] instanceof Register && + info.is_stack_reg(inst.args[1]) && + inst.args[0] instanceof Register && + !info.is_stack_reg(inst.args[0]) && + inst.args[2] instanceof AsmLiteral && + inst.args[2].value < info.allocated_stack_size + ) { + info.subroutine_arg_top = Math.min(info.subroutine_arg_top, inst.args[2].value); + } + if (arch_mnemonic === "arm:mov" && inst.args[1] instanceof Register && info.is_stack_reg(inst.args[1]) && inst.args[0] instanceof Register && !info.is_stack_reg(inst.args[0])) { + info.subroutine_arg_top = 0; + } + } + } + } + + if (callee_saved_offsets.length) { + callee_saved_offsets.sort((a, b) => a - b); + const bottom = callee_saved_offsets[0]; + let top = bottom; + let internal_padding_added = false; + let has_warned = false; + for (const offset of callee_saved_offsets) { + while (top < offset && allowed_callee_save_gaps.has(top)) top += 4; + if (offset !== top) { + if (!internal_padding_added && offset === top + 4) internal_padding_added = true; + else if (!has_warned) { + has_warned = true; + info.warnings.push(`Gap in callee-saved word stack region.\n` + `Saved: [${callee_saved_offsets.map((o) => hex(o)).join(", ")}], ` + `gap at: ${hex(top)}.`); + } + } + top = offset + 4; + } + info.callee_save_reg_region = [bottom, top]; + info.subroutine_arg_top = Math.min(info.subroutine_arg_top, bottom); + } + + const stack_struct_name = `_m2c_stack_${fn.name}`; + let stack_struct = global_info.typepool.get_struct_by_tag_name(stack_struct_name, global_info.typemap); + if (stack_struct !== null) { + if (stack_struct.size !== info.allocated_stack_size) { + throw new DecompFailure( + `Function ${fn.name} has a provided stack type ${stack_struct_name} ` + `with size ${stack_struct.size}, but the detected stack size was ` + `${info.allocated_stack_size}.`, + ); + } + } else { + stack_struct = StructDeclaration.unknown(global_info.typepool, info.allocated_stack_size, stack_struct_name); + } + stack_struct.is_stack = true; + stack_struct.new_field_prefix = "sp"; + info.stack_pointer_type = Type.ptr(Type.struct(stack_struct)); + return info; +} + +export function format_hex(val) { + return format(val, "x").toUpperCase(); +} + +const ESCAPE_TABLE = new Map([ + [0, "\\0"], + [8, "\\b"], + [12, "\\f"], + [10, "\\n"], + [13, "\\r"], + [9, "\\t"], + [11, "\\v"], + [0x5c, "\\\\"], + [0x22, '\\"'], +]); + +/** Returns the escaped byte as an array of byte values. */ +export function escape_byte(b) { + if (ESCAPE_TABLE.has(b)) return [...ESCAPE_TABLE.get(b)].map((c) => c.charCodeAt(0)); + if (b < 0x20 || b === 0xff || b === 0x7f) return [..."\\x" + b.toString(16).padStart(2, "0")].map((c) => c.charCodeAt(0)); + return [b]; +} + +export class Var { + static __fields = [["stack_info"], ["prefix"], ["is_planned"], ["type"], ["is_emitted", false], ["name", null], ["debug_exprs", factory(() => [])]]; + constructor(...args) { + dcinit(this, args); + } + format(fmt) { + pyassert(this.is_emitted); + if (this.name === null) this.name = this.stack_info.temp_var(this.prefix); + return this.name; + } + toString() { + return ``; + } +} + +export class Expression { + dependencies() { + throw new Error("abstract"); + } + /** Mark an expression as "will occur in the output". */ + use() { + for (const expr of this.dependencies()) expr.use(); + } + format(fmt) { + throw new Error("abstract"); + } + toString() { + const fmt = new Formatter({ debug: true }); + return '"' + this.format(fmt) + '"'; + } +} + +export class Condition extends Expression { + negated() { + throw new Error("abstract"); + } +} + +export class Statement { + should_write() { + throw new Error("abstract"); + } + format(fmt) { + throw new Error("abstract"); + } + toString() { + const fmt = new Formatter({ debug: true }); + return '"' + this.format(fmt) + '"'; + } +} + +export class ErrorExpr extends Condition { + static __fields = [["desc", null], ["type", factory(() => Type.any_reg())]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + negated() { + return this; + } + format(fmt) { + if (this.desc !== null) return `M2C_ERROR(/* ${this.desc} */)`; + return "M2C_ERROR()"; + } +} + +export class CommentExpr extends Expression { + static __fields = [["expr"], ["type"], ["prefix", null], ["suffix", null]]; + static __eq_fields = ["expr", "prefix", "suffix"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.expr]; + } + format(fmt) { + const expr_str = this.expr.format(fmt); + if (fmt.coding_style.comment_style === CodingStyle.CommentStyle.NONE) return expr_str; + const prefix_str = this.prefix !== null ? `/* ${this.prefix} */ ` : ""; + const suffix_str = this.suffix !== null ? ` /* ${this.suffix} */` : ""; + return `${prefix_str}${expr_str}${suffix_str}`; + } + static wrap(expr, prefix = null, suffix = null) { + if (prefix === null && suffix === null) return expr; + return new CommentExpr({ expr, type: expr.type, prefix, suffix }); + } +} + +export class SecondF64Half extends Expression { + static __fields = [["type", factory(() => Type.any_reg())]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + format(fmt) { + return "(second half of f64)"; + } +} + +export class CarryBit extends Expression { + static __fields = [["expr", null], ["type", factory(() => Type.intish())]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return this.expr !== null ? [this.expr] : []; + } + format(fmt) { + if (this.expr !== null) return `M2C_CARRY(${this.expr.format(fmt)})`; + return "M2C_CARRY"; + } +} + +function swap_lt_gt(op) { + return [...op].map((c) => (c === "<" ? ">" : c === ">" ? "<" : c)).join(""); +} + +export class BinaryOp extends Condition { + static __fields = [["left"], ["op"], ["right"], ["type"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + static int(left, op, right) { + return new BinaryOp({ left: as_intish(left), op, right: as_intish(right), type: Type.intish() }); + } + static int64(left, op, right) { + return new BinaryOp({ left: as_int64(left), op, right: as_int64(right), type: Type.int64() }); + } + static intptr(left, op, right) { + return new BinaryOp({ left: as_intptr(left), op, right: as_intptr(right), type: Type.intptr() }); + } + static icmp(left, op, right) { + return new BinaryOp({ left: as_intptr(left), op, right: as_intptr(right), type: Type.boolean() }); + } + static scmp(left, op, right) { + return new BinaryOp({ left: as_sintish(left, { silent: true }), op, right: as_sintish(right, { silent: true }), type: Type.boolean() }); + } + static sintptr_cmp(left, op, right) { + return new BinaryOp({ left: as_type(left, Type.sintptr(), false), op, right: as_type(right, Type.sintptr(), false), type: Type.boolean() }); + } + static ucmp(left, op, right) { + return new BinaryOp({ left: as_uintish(left), op, right: as_uintish(right), type: Type.boolean() }); + } + static uintptr_cmp(left, op, right) { + return new BinaryOp({ left: as_type(left, Type.uintptr(), false), op, right: as_type(right, Type.uintptr(), false), type: Type.boolean() }); + } + static fcmp(left, op, right) { + return new BinaryOp({ left: as_f32(left), op, right: as_f32(right), type: Type.boolean() }); + } + static dcmp(left, op, right) { + return new BinaryOp({ left: as_f64(left), op, right: as_f64(right), type: Type.boolean() }); + } + static sint(left, op, right, { silent = false } = {}) { + return new BinaryOp({ left: as_sintish(left, { silent }), op, right: as_sintish(right, { silent }), type: Type.s32() }); + } + static uint(left, op, right) { + return new BinaryOp({ left: as_uintish(left), op, right: as_uintish(right), type: Type.u32() }); + } + static sshift(left, op, right) { + return new BinaryOp({ left: as_sintish(left), op, right: as_intish(right), type: Type.s32() }); + } + static ushift(left, op, right) { + return new BinaryOp({ left: as_uintish(left), op, right: as_intish(right), type: Type.u32() }); + } + static s64(left, op, right) { + return new BinaryOp({ left: as_s64(left), op, right: as_s64(right), type: Type.s64() }); + } + static u64(left, op, right) { + return new BinaryOp({ left: as_u64(left), op, right: as_u64(right), type: Type.u64() }); + } + static f32(left, op, right) { + return new BinaryOp({ left: as_f32(left), op, right: as_f32(right), type: Type.f32() }); + } + static f64(left, op, right) { + return new BinaryOp({ left: as_f64(left), op, right: as_f64(right), type: Type.f64() }); + } + + is_comparison() { + return ["==", "!=", ">", "<", ">=", "<="].includes(this.op); + } + is_floating() { + return this.left.type.is_float() && this.right.type.is_float(); + } + negated() { + if ((this.op === "&&" || this.op === "||") && this.left instanceof Condition && this.right instanceof Condition) { + return new BinaryOp({ left: this.left.negated(), op: { "&&": "||", "||": "&&" }[this.op], right: this.right.negated(), type: Type.boolean() }); + } + if (!this.is_comparison() || (this.is_floating() && ["<", ">", "<=", ">="].includes(this.op))) { + return new UnaryOp("!", this, { type: Type.boolean() }); + } + return new BinaryOp({ left: this.left, op: { "==": "!=", "!=": "==", ">": "<=", "<": ">=", ">=": "<", "<=": ">" }[this.op], right: this.right, type: Type.boolean() }); + } + dependencies() { + return [this.left, this.right]; + } + normalize_for_formatting() { + const right_expr = late_unwrap(this.right); + if (!this.is_floating() && right_expr instanceof Literal && right_expr.value < 0) { + if (this.op === "+") { + const neg = new Literal({ value: -right_expr.value, type: right_expr.type }); + return new BinaryOp({ op: "-", left: this.left, right: neg, type: this.type }); + } + if (this.op === "&" || this.op === "|") { + const neg = new Literal({ value: bnot(right_expr.value), type: right_expr.type }); + const right = new UnaryOp("~", neg, { type: Type.any_reg() }); + return new BinaryOp({ op: this.op, left: this.left, right, type: this.type }); + } + } + return this; + } + format(fmt) { + const left_expr = late_unwrap(this.left); + let right_expr = late_unwrap(this.right); + + const adj = this.normalize_for_formatting(); + if (adj !== this) return adj.format(fmt); + + if (this.is_comparison() && left_expr instanceof Literal && !(right_expr instanceof Literal)) { + return new BinaryOp({ left: right_expr, op: swap_lt_gt(this.op), right: left_expr, type: this.type }).format(fmt); + } + + if ((this.op === "==" || this.op === "!=") && right_expr instanceof Literal) { + right_expr = elide_literal_casts(as_type(right_expr, left_expr.type, true)); + } + + let lhs = left_expr.format(fmt); + if (left_expr instanceof BinaryOp && left_expr.op === this.op && ASSOCIATIVE_OPS.has(this.op)) lhs = lhs.slice(1, -1); + + let rhs; + if ((this.op === "/" || this.op === "%") && right_expr instanceof Literal) rhs = right_expr.format(fmt, true); + else rhs = right_expr.format(fmt); + + if (PSEUDO_FUNCTION_OPS.has(this.op)) return `${this.op}(${lhs}, ${rhs})`; + return `(${lhs} ${this.op} ${rhs})`; + } +} + +export class TernaryOp extends Expression { + static __fields = [["cond"], ["left"], ["right"], ["type"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.cond, this.left, this.right]; + } + format(fmt) { + const cond_str = simplify_condition(this.cond).format(fmt); + const left_str = this.left.format(fmt); + const right_str = this.right.format(fmt); + return `(${cond_str} ? ${left_str} : ${right_str})`; + } +} + +export class UnaryOp extends Condition { + static __fields = [["op"], ["expr"], ["type"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.expr]; + } + static int(op, expr) { + return new UnaryOp({ op, expr: as_intish(expr), type: expr.type }); + } + static sint(op, expr) { + expr = as_sintish(expr, { silent: true }); + return new UnaryOp({ op, expr, type: expr.type }); + } + negated() { + if (this.op === "!" && (this.expr instanceof UnaryOp || this.expr instanceof BinaryOp)) return this.expr; + return new UnaryOp("!", this, { type: Type.boolean() }); + } + format(fmt) { + if (PSEUDO_FUNCTION_OPS.has(this.op)) return `${this.op}(${format_expr(this.expr, fmt)})`; + return `${this.op}${this.expr.format(fmt)}`; + } +} + +export class ExprCondition extends Condition { + static __fields = [["expr"], ["type"], ["is_negated", false]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.expr]; + } + negated() { + return new ExprCondition(this.expr, this.type, !this.is_negated); + } + format(fmt) { + const neg = this.is_negated ? "!" : ""; + return `${neg}${this.expr.format(fmt)}`; + } +} + +const COMMA_CONDITION_DEFAULT_TYPE = Type.boolean(); + +export class CommaConditionExpr extends Condition { + static __fields = [["statements"], ["condition"], ["type", COMMA_CONDITION_DEFAULT_TYPE]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + pyassert(false, "CommaConditionExpr should not be used within translate.py"); + return []; + } + negated() { + return new CommaConditionExpr(this.statements, this.condition.negated()); + } + format(fmt) { + const comma_joined = this.statements.map((stmt) => rstrip(stmt.format(fmt), ";")).join(", "); + return `(${comma_joined}, ${this.condition.format(fmt)})`; + } +} + +export class Cast extends Expression { + static __fields = [["expr"], ["type"], ["reinterpret", false], ["silent", true]]; + static __eq_fields = ["expr", "reinterpret", "silent"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.expr]; + } + use() { + this.expr.type.unify(this.type); + super.use(); + } + needed_for_store() { + if (!this.reinterpret) return true; + if (!this.expr.type.unify(this.type)) return true; + return false; + } + should_wrap_transparently() { + return this.reinterpret && this.expr.type.is_float() === this.type.is_float() && should_wrap_transparently(this.expr); + } + format(fmt) { + if (this.reinterpret && this.expr.type.is_float() !== this.type.is_float()) { + if (fmt.valid_syntax) return `M2C_BITWISE(${this.type.format(fmt)}, ${this.expr.format(fmt)})`; + return `(bitwise ${this.type.format(fmt)}) ${this.expr.format(fmt)}`; + } + if (this.reinterpret && (this.silent || (is_type_obvious(this.expr) && this.expr.type.unify(this.type)))) return this.expr.format(fmt); + if (fmt.skip_casts) return this.expr.format(fmt); + const fn_sig = this.type.get_function_pointer_signature(); + if (fn_sig) return `((${this.type.format(fmt)}) ${this.expr.format(fmt)})`; + return `(${this.type.format(fmt)}) ${this.expr.format(fmt)}`; + } +} + +export class FuncCall extends Expression { + static __fields = [["function"], ["args"], ["type"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [...this.args, this.function]; + } + format(fmt) { + const target = late_unwrap(this.function); + const fn_sig = target.type.get_function_pointer_signature(); + if (fn_sig && target instanceof Cast && target.reinterpret) { + const prototype_sig = target.expr.type.get_function_pointer_signature(); + if (prototype_sig && prototype_sig.unify_with_args(fn_sig)) { + return new Cast(new FuncCall(target.expr, this.args, prototype_sig.return_type), this.type, { reinterpret: true, silent: true }).format(fmt); + } + } + const args = this.args.map((arg) => format_expr(arg, fmt)).join(", "); + return `${target.format(fmt)}(${args})`; + } +} + +export class LocalVar extends Expression { + static __fields = [["value"], ["type"], ["path"]]; + static __eq_fields = ["value"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + format(fmt) { + const fallback_name = `unksp${format_hex(this.value)}`; + if (this.path === null) return fallback_name; + const name = StructAccess.access_path_to_field_name(this.path, fmt); + if (name.startsWith("->")) return name.slice(2); + return fallback_name; + } + /** Return a declaration for this LocalVar, if required. */ + toplevel_decl(fmt) { + if (this.path === null || this.path.length !== 2 || typeof this.path[1] !== "string") return null; + return this.type.to_decl(this.path[1], fmt); + } +} + +export class PlannedPhiExpr extends Expression { + static __fields = [["var"], ["type"], ["sources"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + format(fmt) { + return this.var.format(fmt); + } +} + +export class PassedInArg extends Expression { + static __fields = [["loc"], ["stack_info"], ["type"]]; + static __eq_fields = ["loc"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + format(fmt) { + const name = this.stack_info.get_param_name(this.loc); + if (name) return name; + return this.stack_info.global_info.arch.arg_name(this.loc); + } +} + +export class SubroutineArg extends Expression { + static __fields = [["value"], ["type"]]; + static __eq_fields = ["value"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + format(fmt) { + return `subroutine_arg${format_hex(floordiv(this.value, 4))}`; + } +} + +/** + * Represents struct_var->offset. eq=True since it represents a live expression. + */ +export class StructAccess extends Expression { + static __fields = [["struct_var"], ["offset"], ["target_size"], ["field_path"], ["stack_info"], ["type"], ["checked_late_field_path", false]]; + static __eq_fields = ["struct_var", "offset", "target_size"]; + constructor(...args) { + super(); + dcinit(this, args); + pyassert(this.stack_info !== null || this.field_path !== null, "Must provide at least one of (stack_info, field_path)"); + StructAccess.assert_valid_field_path(this.field_path); + } + static assert_valid_field_path(path) { + pyassert(path === null || (path.length && typeof path[0] === "number"), "The first element of the field path, if present, must be an int"); + } + /** Convert an access path into a dereferencing field name. */ + static access_path_to_field_name(path, fmt) { + StructAccess.assert_valid_field_path(path); + let output = ""; + if (path.length >= 2 && path[0] === 0 && typeof path[1] === "string") { + output += `->${path[1]}`; + path = path.slice(2); + } + for (const p of path) { + if (typeof p === "string") output += `.${p}`; + else if (typeof p === "number") output += `[${fmt.format_int(p)}]`; + else assert_never(p); + } + return output; + } + dependencies() { + return [this.struct_var]; + } + make_reference() { + const field_path = this.late_field_path(); + if (field_path && field_path.length >= 2 && field_path[field_path.length - 1] === 0) return dcreplace(this, { field_path: field_path.slice(0, -1) }); + return null; + } + late_field_path() { + if (this.field_path === null && !this.checked_late_field_path) { + const v = late_unwrap(this.struct_var); + v.format(new Formatter()); + const [field_path, field_type] = v.type.get_deref_field(this.offset, { target_size: this.target_size }); + if (field_path !== null) { + StructAccess.assert_valid_field_path(field_path); + this.field_path = field_path; + this.type.unify(field_type); + } + this.checked_late_field_path = true; + } + return this.field_path; + } + late_has_known_type() { + if (this.late_field_path() !== null) return true; + pyassert(this.stack_info !== null, "StructAccess must have stack_info if field_path isn't set"); + if (this.offset === 0) { + const v = late_unwrap(this.struct_var); + if (!this.stack_info.has_nonzero_access(v) && v instanceof AddressOf && v.expr instanceof GlobalSymbol && v.expr.type_provided) return true; + } + return false; + } + format(fmt) { + let v = late_unwrap(this.struct_var); + let has_nonzero_access = false; + if (this.stack_info !== null) has_nonzero_access = this.stack_info.has_nonzero_access(v); + + let field_path = this.late_field_path(); + + if (field_path !== null && !(field_path.length === 1 && field_path[0] === 0)) { + has_nonzero_access = true; + } else if (fmt.valid_syntax && (this.offset !== 0 || has_nonzero_access)) { + const offset_str = fmt.format_int(this.offset); + return `M2C_FIELD(${v.format(fmt)}, ${Type.ptr(this.type).format(fmt)}, ${offset_str})`; + } else { + const prefix = "unk" + (fmt.coding_style.unknown_underscore ? "_" : ""); + field_path = [0, prefix + format_hex(this.offset)]; + } + let field_name = StructAccess.access_path_to_field_name(field_path, fmt); + + let deref = true; + if (v instanceof AddressOf && !v.expr.type.is_array() && !(v.expr instanceof GlobalSymbol && v.expr.is_string_constant()) && field_name.startsWith("->")) { + v = v.expr; + field_name = field_name.replace("->", "."); + deref = false; + } + + if (this.offset === 0 && !has_nonzero_access) return `${deref ? "*" : ""}${v.format(fmt)}`; + return `${parenthesize_for_struct_access(v, fmt)}${field_name}`; + } +} + +export class ArrayAccess extends Expression { + static __fields = [["ptr"], ["index"], ["type"]]; + static __eq_fields = ["ptr", "index"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.ptr, this.index]; + } + format(fmt) { + const base = parenthesize_for_struct_access(this.ptr, fmt); + const index = format_expr(this.index, fmt); + return `${base}[${index}]`; + } +} + +export class GlobalSymbol extends Expression { + static __fields = [ + ["c_symbol_name"], + ["type"], + ["asm_data_entry", null], + ["symbol_in_context", false], + ["type_provided", false], + ["initializer_in_typemap", false], + ["demangled_str", null], + ["is_referenced", false], + ]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + use() { + this.is_referenced = true; + } + is_string_constant() { + const ent = this.asm_data_entry; + if (!ent || ent.data.length !== 1 || !(ent.data[0] instanceof Uint8Array)) return false; + return ent.is_string; + } + format_string_constant(fmt) { + pyassert(this.is_string_constant(), "checked by caller"); + let has_trailing_null = false; + let data = this.asm_data_entry.data[0]; + let end = data.length; + while (end > 0 && data[end - 1] === 0) { + end -= 1; + has_trailing_null = true; + } + const escaped = []; + for (let i = 0; i < end; i++) escaped.push(...escape_byte(data[i])); + const strdata = decode_utf8_backslashreplace(Uint8Array.from(escaped)); + let ret = `"${strdata}"`; + if (!has_trailing_null) ret += " /* not null-terminated */"; + return ret; + } + format(fmt) { + return this.c_symbol_name; + } + /** Returns [array_dim, extra_bytes]. */ + potential_array_dim(element_size) { + pyassert(element_size !== 0, "potential_array_dim cannot be called on zero size"); + if (this.asm_data_entry === null || this.asm_data_entry.is_jtbl) return [0, element_size]; + const [min_data_size, max_data_size] = this.asm_data_entry.size_range_bytes(); + if (element_size > max_data_size) return [0, max_data_size]; + if (min_data_size <= element_size && element_size <= max_data_size && !this.type.is_array()) return [1, 0]; + const array_dim = floordiv(min_data_size, element_size); + const extra_bytes = pymod(min_data_size, element_size); + if (extra_bytes !== 0) { + const padding_bytes = element_size - extra_bytes; + if (min_data_size + padding_bytes > max_data_size) return [array_dim, extra_bytes]; + } + return [floordiv(max_data_size, element_size), 0]; + } +} + +/** bytes.decode("utf-8", "backslashreplace") */ +export function decode_utf8_backslashreplace(bytes) { + let out = ""; + let i = 0; + while (i < bytes.length) { + const b = bytes[i]; + let n = 0; + let cp = 0; + if (b < 0x80) { + out += String.fromCharCode(b); + i++; + continue; + } else if (b >= 0xc2 && b <= 0xdf) { + n = 1; + cp = b & 0x1f; + } else if (b >= 0xe0 && b <= 0xef) { + n = 2; + cp = b & 0x0f; + } else if (b >= 0xf0 && b <= 0xf4) { + n = 3; + cp = b & 0x07; + } else { + out += "\\x" + b.toString(16).padStart(2, "0"); + i++; + continue; + } + let ok = i + n < bytes.length + 0 && i + n <= bytes.length - 1 + 1; + let j = 1; + for (; j <= n; j++) { + const c = bytes[i + j]; + if (c === undefined || (c & 0xc0) !== 0x80) { + ok = false; + break; + } + // Reject overlongs / surrogates / out of range like CPython's decoder + if (j === 1) { + if (b === 0xe0 && c < 0xa0) ok = false; + if (b === 0xed && c > 0x9f) ok = false; + if (b === 0xf0 && c < 0x90) ok = false; + if (b === 0xf4 && c > 0x8f) ok = false; + if (!ok) break; + } + cp = (cp << 6) | (c & 0x3f); + } + if (!ok || j <= n) { + out += "\\x" + b.toString(16).padStart(2, "0"); + i++; + continue; + } + out += String.fromCodePoint(cp); + i += n + 1; + } + return out; +} + +export class Literal extends Expression { + static __fields = [["value"], ["type", factory(() => Type.any())], ["elide_cast", false]]; + static __eq_fields = ["value"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + format(fmt, force_dec = false) { + const enum_name = this.type.get_enum_name(this.value); + if (enum_name !== null) return enum_name; + + if (this.type.is_likely_float()) { + if (this.type.get_size_bits() === 64) return format_f64_imm(this.value); + return format_f32_imm(this.value) + "f"; + } + if (this.type.is_pointer() && this.value === 0) return "NULL"; + + let prefix = ""; + let suffix = ""; + if (!fmt.skip_casts && !this.elide_cast) { + if (this.type.is_pointer()) prefix = `(${this.type.format(fmt)})`; + if (this.type.is_unsigned()) suffix = "U"; + } + + let value; + if (force_dec) value = str(this.value); + else { + const size_bits = this.type.get_size_bits(); + let v = this.value; + if (this.type.is_signed() && size_bits && band(v, shl(1, size_bits - 1)) && v > shl(3, size_bits - 2) && v < 2 ** size_bits) { + v -= shl(1, size_bits); + } + value = fmt.format_int(v, size_bits); + } + return prefix + value + suffix; + } +} + +export class AddressOf extends Expression { + static __fields = [["expr"], ["type", factory(() => Type.ptr())]]; + static __eq_fields = ["expr"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.expr]; + } + format(fmt) { + if (this.expr instanceof GlobalSymbol) { + if (this.expr.is_string_constant()) return this.expr.format_string_constant(fmt); + } + if (this.expr.type.is_array()) return `${this.expr.format(fmt)}`; + if (this.expr.type.is_function()) return `${this.expr.format(fmt)}`; + if (this.expr instanceof StructAccess) { + const ref = this.expr.make_reference(); + if (ref) return `${ref.format(fmt)}`; + } + return `&${this.expr.format(fmt)}`; + } +} + +export class Lwl extends Expression { + static __fields = [["load_expr"], ["key"], ["type", factory(() => Type.any_reg())]]; + static __eq_fields = ["load_expr", "key"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.load_expr]; + } + format(fmt) { + return `M2C_LWL(${this.load_expr.format(fmt)})`; + } +} + +export class Load3Bytes extends Expression { + static __fields = [["load_expr"], ["type", factory(() => Type.any_reg())]]; + static __eq_fields = ["load_expr"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.load_expr]; + } + format(fmt) { + if (fmt.valid_syntax) return `M2C_FIRST3BYTES(${this.load_expr.format(fmt)})`; + return `(first 3 bytes) ${this.load_expr.format(fmt)}`; + } +} + +export class UnalignedLoad extends Expression { + static __fields = [["load_expr"], ["type", factory(() => Type.any_reg())]]; + static __eq_fields = ["load_expr"]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return [this.load_expr]; + } + format(fmt) { + if (fmt.valid_syntax) return `M2C_UNALIGNED32(${this.load_expr.format(fmt)})`; + return `(unaligned s32) ${this.load_expr.format(fmt)}`; + } +} + +export class EvalOnceExpr extends Expression { + static __fields = [ + ["wrapped_expr"], + ["var"], + ["type"], + ["sources"], + ["emit_exactly_once"], + ["trivial"], + ["transparent"], + ["is_fictive_temp"], + ["forced_emit", false], + ["is_used", false], + ]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependency(may_move_forward) { + if (this.trivial) return this.wrapped_expr; + if (this.var.is_emitted) return null; + if (!this.transparent && this.is_used && !may_move_forward) return null; + return this.wrapped_expr; + } + dependencies() { + pyassert(false, "never called, and it's unclear what to pass for may_move_forward"); + } + use() { + if (this.trivial || (this.transparent && !this.var.is_emitted)) { + this.wrapped_expr.use(); + } else if (!this.is_used) { + if (!this.emit_exactly_once) this.wrapped_expr.use(); + } else { + this.var.is_emitted = true; + } + this.is_used = true; + } + force() { + if (!this.forced_emit && !this.trivial) { + this.forced_emit = true; + this.var.is_emitted = true; + this.use(); + this.use(); + } + } + uses_var() { + return this.var.is_emitted && !this.trivial; + } + format(fmt) { + if (!this.uses_var()) return this.wrapped_expr.format(fmt); + return this.var.format(fmt); + } +} + +/** A NaivePhiExpr acts as a phi node (see upstream docs). */ +export class NaivePhiExpr extends Expression { + static __fields = [["reg"], ["node"], ["type"], ["sources"], ["uses_dominator"], ["used_naive_phis"], ["name", null], ["num_usages", 0], ["replacement_expr", null]]; + constructor(...args) { + super(); + dcinit(this, args); + } + dependencies() { + return []; + } + get_var_name() { + return this.name || `unnamed-phi(${this.reg.register_name})`; + } + use() { + if (this.num_usages === 0) this.used_naive_phis.push(this); + this.num_usages += 1; + if (this.replacement_expr !== null) this.replacement_expr.use(); + } + format(fmt) { + if (this.replacement_expr !== null) return this.replacement_expr.format(fmt); + return this.get_var_name(); + } +} + +export class SwitchControl { + static __fields = [["control_expr"], ["num_cases", null], ["jump_table", null], ["offset", 0], ["is_irregular", false]]; + constructor(...args) { + dcinit(this, args); + } + /** Return true if `cond` is the bounds check before using `jump_table`. */ + matches_guard_condition(cond) { + const cmp_expr = simplify_condition(cond); + if (!(cmp_expr instanceof BinaryOp) || !(cmp_expr.op === ">=" || cmp_expr.op === ">")) return false; + const cmp_exclusive = cmp_expr.op === ">"; + const left_expr = late_unwrap_ints(cmp_expr.left); + if (this.offset !== 0) { + if ( + !(left_expr instanceof BinaryOp) || + !pyeq(late_unwrap(left_expr.left), late_unwrap(this.control_expr)) || + left_expr.op !== "+" || + !pyeq(late_unwrap(left_expr.right), new Literal(-this.offset)) + ) { + return false; + } + } else if (!pyeq(left_expr, late_unwrap_ints(this.control_expr))) return false; + const right_expr = late_unwrap(cmp_expr.right); + if (!(right_expr instanceof Literal)) return false; + return right_expr.value + (cmp_exclusive ? 1 : 0) === this.num_cases; + } + static irregular_from_expr(control_expr) { + return new SwitchControl({ control_expr, offset: 0, is_irregular: true }); + } + static from_expr(expr, num_cases) { + const error_expr = new SwitchControl(expr); + const struct_expr = early_unwrap(expr); + if (!(struct_expr instanceof StructAccess) || struct_expr.offset !== 0) return error_expr; + const add_expr = early_unwrap(struct_expr.struct_var); + if (!(add_expr instanceof BinaryOp) || add_expr.op !== "+") return error_expr; + const left_expr = early_unwrap(add_expr.left); + const right_expr = early_unwrap(add_expr.right); + let jtbl_addr_expr, mul_expr; + if (left_expr instanceof AddressOf && left_expr.expr instanceof GlobalSymbol) { + jtbl_addr_expr = left_expr; + mul_expr = right_expr; + } else if (right_expr instanceof AddressOf && right_expr.expr instanceof GlobalSymbol) { + mul_expr = left_expr; + jtbl_addr_expr = right_expr; + } else return error_expr; + const jump_table = jtbl_addr_expr.expr; + pyassert(jump_table instanceof GlobalSymbol); + if (!(mul_expr instanceof BinaryOp) || mul_expr.op !== "*" || !pyeq(early_unwrap(mul_expr.right), new Literal(4))) return error_expr; + let control_expr = mul_expr.left; + let offset = 0; + const uw_control_expr = early_unwrap(control_expr); + if (uw_control_expr instanceof BinaryOp && uw_control_expr.op === "+") { + const offset_lit = early_unwrap(uw_control_expr.right); + if (offset_lit instanceof Literal) { + control_expr = uw_control_expr.left; + offset = -offset_lit.value; + } + } + if (jump_table.asm_data_entry === null || !jump_table.asm_data_entry.is_jtbl) return error_expr; + return new SwitchControl(control_expr, num_cases, jump_table, offset); + } +} + +export class EvalOnceStmt extends Statement { + static __fields = [["expr"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + should_write() { + if (this.expr.emit_exactly_once && !this.expr.is_used) return true; + if (!this.expr.var.is_emitted) return false; + if (var_for_expr(late_unwrap(this.expr.wrapped_expr)) === this.expr.var) return false; + return true; + } + format(fmt) { + const val = elide_literal_casts(this.expr.wrapped_expr); + if (this.expr.emit_exactly_once && !this.expr.is_used) { + const val_str = format_expr(val, fmt); + return `${val_str};`; + } + return format_assignment(this.expr.var, val, fmt); + } +} + +export class SetNaivePhiStmt extends Statement { + static __fields = [["phi"], ["expr"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + should_write() { + return !pyeq(late_unwrap(this.expr), this.phi); + } + format(fmt) { + return format_assignment(this.phi, this.expr, fmt); + } +} + +export class ExprStmt extends Statement { + static __fields = [["expr"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + should_write() { + return true; + } + format(fmt) { + return `${format_expr(this.expr, fmt)};`; + } +} + +export class StoreStmt extends Statement { + static __fields = [["source"], ["dest"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + should_write() { + return true; + } + format(fmt) { + const dest = this.dest; + let source = this.source; + if ((dest instanceof StructAccess && dest.late_has_known_type()) || dest instanceof ArrayAccess || dest instanceof LocalVar || dest instanceof SubroutineArg) { + source = elide_literal_casts(source); + } + return format_assignment(dest, source, fmt); + } +} + +export class CommentStmt extends Statement { + static __fields = [["contents"]]; + constructor(...args) { + super(); + dcinit(this, args); + } + should_write() { + return true; + } + format(fmt) { + return `// ${this.contents}`; + } +} + +export class AddressMode { + static __fields = [["offset"], ["base"]]; + static __eq_fields = ["offset", "base"]; + constructor(...args) { + dcinit(this, args); + } + toString() { + if (this.offset) return `${this.offset}(${this.base})`; + return `(${this.base})`; + } +} + +export class RawSymbolRef { + static __fields = [["offset"], ["sym"]]; + static __eq_fields = ["offset", "sym"]; + constructor(...args) { + dcinit(this, args); + } + toString() { + if (this.offset) return `${this.sym.symbol_name} + ${this.offset}`; + return this.sym.symbol_name; + } +} + +/** Metadata associated with a register value assignment. */ +export class RegMeta { + static __fields = [ + ["inherited", false], + ["initial", false], + ["is_read", false], + ["function_return", false], + ["uninteresting", false], + ["force", false], + ["in_pattern", false], + ]; + constructor(...args) { + dcinit(this, args); + } +} + +export class RegData { + constructor(value, meta) { + this.value = value; + this.meta = meta; + } +} + +export class RegInfo { + constructor({ stack_info, contents = new Map(), read_inherited = new Set(), _current_instr_ref = null }) { + this.stack_info = stack_info; + this.contents = contents; + this.read_inherited = read_inherited; + this._current_instr_ref = _current_instr_ref; + } + current_instr_ref() { + pyassert(this._current_instr_ref !== null); + return this._current_instr_ref; + } + current_instr() { + return this.current_instr_ref().instruction; + } + has_current_instr() { + return this._current_instr_ref !== null; + } + /** Python `with regs.set_current_instr(ref): fn()` */ + set_current_instr(instr_ref, fn) { + pyassert(this._current_instr_ref === null); + this._current_instr_ref = instr_ref; + try { + return set_current_instr(instr_ref.instruction, fn); + } finally { + this._current_instr_ref = null; + } + } + /** Python __getitem__ */ + get(key) { + if (this.has_current_instr() && !this.current_instr().inputs.includes(key)) { + const lineno = this.get_instruction_lineno(); + return new ErrorExpr(`Read from unset register ${key} on line ${lineno}`); + } + if (key === new Register("zero")) return new Literal(0); + const data = this.contents.get(key) ?? null; + if (data === null) return new ErrorExpr(`Read from unset register ${key}`); + const ret = data.value; + const meta = data.meta; + meta.is_read = true; + if (meta.inherited) this.read_inherited.add(key); + if (ret instanceof EvalOnceExpr && ret.trivial) return ret.wrapped_expr; + if (meta.initial) { + const uw_ret = unwrap_deep(ret); + if (uw_ret instanceof PassedInArg) { + const arg = this.stack_info.get_argument(uw_ret.loc); + this.stack_info.add_argument(arg); + arg.type.unify(ret.type); + } + } + if (meta.force) { + pyassert(ret instanceof EvalOnceExpr); + ret.force(); + } + return ret; + } + /** Python __contains__ */ + has(key) { + return this.contents.has(key); + } + /** Assign a value to a register from inside an instruction context. */ + set_with_meta(key, value, meta) { + const instr = this.current_instr(); + if (!instr.outputs.includes(key)) throw new DecompFailure(`Undeclared write to ${key} in ${instr}`); + pyassert(key !== new Register("zero")); + this.contents.set(key, new RegData(value, meta)); + } + /** Assign a value to a register from outside an instruction context. */ + global_set_with_meta(key, value, meta) { + pyassert(!this.has_current_instr()); + pyassert(key !== new Register("zero")); + this.contents.set(key, new RegData(value, meta)); + } + update_meta(key, meta) { + pyassert(key !== new Register("zero")); + if (!this.contents.has(key)) throw new Error(`KeyError: ${key}`); + this.contents.set(key, new RegData(this.contents.get(key).value, meta)); + } + /** Python __delitem__ */ + delete(key) { + pyassert(key !== new Register("zero")); + if (!this.contents.has(key)) throw new Error(`KeyError: ${key}`); + this.contents.delete(key); + } + get_raw(key) { + const data = this.contents.get(key) ?? null; + return data !== null ? data.value : null; + } + get_meta(key) { + const data = this.contents.get(key) ?? null; + return data !== null ? data.meta : null; + } + get_instruction_lineno() { + if (!this.has_current_instr()) return 0; + return this.current_instr().meta.lineno; + } + toString() { + return sorted(this.contents.entries(), (x) => x[0].register_name) + .filter(([, v]) => !this.stack_info.should_save(v.value, null)) + .map(([k, v]) => `${k}: ${v.value}`) + .join(", "); + } +} + +/** Contains translated assembly code, the block's branch condition, and block's final register states. */ +export class BlockInfo { + static __fields = [["to_write"], ["return_value"], ["switch_control"], ["branch_condition"], ["final_register_states"], ["has_function_call"]]; + constructor(...args) { + dcinit(this, args); + } + toString() { + const newline = "\n\t"; + return [ + `Statements: ${this.statements_to_write().map((w) => String(w)).join(newline)}`, + `Branch condition: ${this.branch_condition === null ? "None" : this.branch_condition}`, + `Final register states: ${this.final_register_states}`, + ].join("\n"); + } + statements_to_write() { + return this.to_write.filter((st) => st.should_write()); + } +} + +export function visualize_flowgraph(flow_graph, viz_type) { + const fmt = new Formatter({ debug: true }); + const nodes = []; + const edges = []; + const emit_node = (name, lines) => nodes.push([name, lines]); + const emit_edge = (source, target, attrs = {}) => edges.push([source, target, attrs]); + + for (const node of flow_graph.nodes) { + const block_info = _get_optional_block_info(node); + let asm_lines = []; + let c_lines = []; + if (block_info) { + asm_lines = node.block.instructions.map((i) => `${i.meta.synthetic ? "*" : " "} ${i}`); + c_lines = block_info.to_write.filter((w) => w.should_write()).map((w) => w.format(fmt)); + } + if (node instanceof BasicNode) { + emit_edge(node.name(), node.successor.name(), { color: "black" }); + } else if (node instanceof ConditionalNode) { + if (block_info) { + pyassert(block_info.branch_condition !== null); + c_lines.push(`if (${block_info.branch_condition.format(fmt)})`); + } + emit_edge(node.name(), node.fallthrough_edge.name(), { label: "F", color: "blue" }); + emit_edge(node.name(), node.conditional_edge.name(), { label: "T", color: "red" }); + } else if (node instanceof ReturnNode) { + if (block_info !== null && block_info.return_value) c_lines.push(`return (${block_info.return_value.format(fmt)});`); + else c_lines.push("return;"); + emit_edge(node.name(), node.terminal.name()); + } else if (node instanceof SwitchNode) { + pyassert(block_info !== null); + const switch_control = block_info.switch_control; + pyassert(switch_control !== null); + c_lines.push(`switch (${switch_control.control_expr.format(fmt)})`); + node.cases.forEach((c, i) => emit_edge(node.name(), c.name(), { label: String(i + switch_control.offset), color: "green" })); + } else { + pyassert(node instanceof TerminalNode); + asm_lines.push("// exit"); + c_lines.push("// exit"); + } + let line_label = ""; + const first_instr = node.block.instructions[0] ?? null; + if (first_instr !== null && first_instr.meta.lineno > 0) line_label = ` (line ${first_instr.meta.lineno})`; + let lines = [`// Node ${node.name()}${line_label}`]; + if (viz_type === Options.VisualizeTypeEnum.ASM) lines = lines.concat(asm_lines); + else if (viz_type === Options.VisualizeTypeEnum.C) lines = lines.concat(c_lines); + else throw new ValueError("Invalid viz_type: {viz_type!r}"); + emit_node(node.name(), lines); + } + const escape = (value) => value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n"); + const quote = (value) => '"' + escape(value) + '"'; + const lines = ["digraph {", ' node [shape="rect", fontname="Monospace"];', ' edge [fontname="Monospace"];']; + for (const [name, source] of nodes) { + const label = source.map((line) => escape(line) + "\\l").join(""); + lines.push(` ${quote(name)} [label="${label}"];`); + } + for (const [source, target, attrs] of edges) { + const attr_strs = Object.entries(attrs).map(([name, value]) => `${name}=${quote(value)}`); + const attr_text = attr_strs.length ? ` [${attr_strs.join(", ")}]` : ""; + lines.push(` ${quote(source)} -> ${quote(target)}${attr_text};`); + } + lines.push("}"); + return lines.join("\n") + "\n"; +} + +export function get_block_info_for_block(block) { + const ret = block.block_info; + pyassert(ret instanceof BlockInfo); + return ret; +} +export function get_block_info(node) { + return get_block_info_for_block(node.block); +} +function _get_optional_block_info(node) { + if (node.block.block_info === null) return null; + return get_block_info(node); +} + +export class InstrArgs { + static __fields = [["instruction_ref"], ["raw_args"], ["regs"], ["stack_info"]]; + constructor(...args) { + dcinit(this, args); + } + raw_arg(index) { + pyassert(index >= 0); + if (index >= this.raw_args.length) throw new DecompFailure(`Too few arguments for instruction, expected at least ${index + 1}`); + return this.raw_args[index]; + } + reg_ref(index) { + const ret = this.raw_arg(index); + if (!(ret instanceof Register)) throw new DecompFailure(`Expected instruction argument to be a register, but found ${ret}`); + return ret; + } + imm_value(index) { + const arg = this.full_imm(index); + pyassert(arg instanceof Literal); + return arg.value; + } + reg(index) { + return this.regs.get(this.reg_ref(index)); + } + /** Extract a double from a register (may read the paired register). */ + dreg(index) { + const reg = this.reg_ref(index); + if (this.stack_info.global_info.arch.arch !== Target.ArchEnum.ARM && !reg.is_float()) throw new DecompFailure(`Expected instruction argument ${reg} to be a float register`); + const ret = this.regs.get(reg); + if (this.stack_info.global_info.arch.arch === Target.ArchEnum.PPC) return ret; + if (!(ret instanceof Literal) || ret.type.get_size_bits() === 64) return ret; + const reg_num = int_(reg.register_name.slice(1)); + if (reg_num % 2 !== 0) throw new DecompFailure("Tried to use a double-precision instruction with odd-numbered float " + `register ${reg}`); + const other = this.regs.get(new Register(`${reg.register_name[0]}${reg_num + 1}`)); + if (other instanceof Literal && other.type.get_size_bits() !== 64) { + const value = bor(ret.value, shl(other.value, 32)); + return new Literal(value, { type: Type.f64() }); + } + ret.type.unify(Type.uintish()); + other.type.unify(Type.uintish()); + return new BinaryOp({ op: "GLUE_F64", left: other, right: ret, type: Type.f64() }); + } + cmp_reg(key) { + let cond = this.regs.get(new Register(key)); + if (!(cond instanceof Condition)) cond = BinaryOp.icmp(cond, "!=", new Literal(0)); + return cond; + } + full_imm(index) { + const arg = strip_macros(this.raw_arg(index)); + return literal_expr(arg, this.stack_info); + } + s8_imm(index) { + const ret = this.full_imm(index); + if (ret instanceof Literal) return new Literal(band(ret.value + 0x80, 0xff) - 0x80); + return ret; + } + s16_imm(index) { + const ret = this.full_imm(index); + if (ret instanceof Literal) return new Literal(band(ret.value + 0x8000, 0xffff) - 0x8000); + return ret; + } + u16_imm(index) { + const ret = this.full_imm(index); + if (ret instanceof Literal) return new Literal(band(ret.value, 0xffff)); + return ret; + } + reg_or_imm(index) { + const arg = this.raw_arg(index); + if (arg instanceof Register) return this.regs.get(arg); + return this.full_imm(index); + } + reg_or_s8_imm(index) { + const arg = this.raw_arg(index); + if (arg instanceof Register) return this.regs.get(arg); + return this.s8_imm(index); + } + hi_imm(index) { + const arg = this.raw_arg(index); + if (!(arg instanceof Macro) || !["hi", "ha", "h"].includes(arg.macro_name)) throw new DecompFailure(`lui/lis argument must be a literal or %hi/@ha/@h macro, found ${arg}`); + const ref = parse_symbol_ref(arg.argument); + if (ref === null) throw new DecompFailure(`Invalid macro argument ${arg.argument}`); + return ref; + } + maybe_gprel_imm(index) { + const val = this.raw_arg(index); + if (!(val instanceof Macro) || val.macro_name !== "gp_rel") return null; + const ref = parse_symbol_ref(val.argument); + if (ref === null) throw new DecompFailure(`Invalid macro argument ${val.argument}`); + return ref; + } + maybe_got_imm(index) { + const arg = this.raw_arg(index); + if (!(arg instanceof AsmAddressMode) || arg.base !== new Register("gp")) return null; + const val = arg.addend; + if (!(val instanceof Macro) || !["got", "call16"].includes(val.macro_name)) return null; + const ref = parse_symbol_ref(val.argument); + if (ref === null) throw new DecompFailure(`Invalid macro argument ${val.argument}`); + return ref; + } + shifted_u16_imm(index) { + const raw_imm = this.u16_imm(index); + pyassert(raw_imm instanceof Literal); + return new Literal(shl(raw_imm.value, 16)); + } + sym_imm(index) { + const arg = this.raw_arg(index); + if (arg instanceof AsmGlobalSymbol) return this.stack_info.global_info.address_of_gsym(arg.symbol_name); + if (arg instanceof AsmLiteral) return this.full_imm(index); + throw new DecompFailure(`Bad function call operand ${arg}`); + } + memory_ref(index) { + const ret = strip_macros(this.raw_arg(index)); + const ref = parse_symbol_ref(ret); + if (ref !== null) return ref; + if (!(ret instanceof AsmAddressMode)) throw new DecompFailure("Expected instruction argument to be of the form offset($register), " + `but found ${ret}`); + if (!(ret.addend instanceof AsmLiteral)) throw new DecompFailure(`Unable to parse offset for instruction argument ${ret}. ` + "Expected a constant or a %lo macro."); + return new AddressMode({ offset: ret.addend.value, base: ret.base }); + } + count() { + return this.raw_args.length; + } +} + +/** Compute whether an EvalOnceExpr should be marked as `trivial = True`. */ +export function is_trivial_expression(expr) { + if (expr instanceof Literal || expr instanceof GlobalSymbol || expr instanceof SecondF64Half) return true; + if (expr instanceof AddressOf) return expr.dependencies().every((e) => is_trivial_expression(e)); + return false; +} + +/** Compute whether an EvalOnceExpr should be marked as `transparent = True`. */ +export function should_wrap_transparently(expr) { + if ( + expr instanceof Literal || + expr instanceof LocalVar || + expr instanceof PassedInArg || + expr instanceof NaivePhiExpr || + expr instanceof PlannedPhiExpr || + expr instanceof SecondF64Half || + expr instanceof SubroutineArg + ) { + return true; + } + if (expr instanceof EvalOnceExpr) return !expr.is_fictive_temp; + if (expr instanceof GlobalSymbol) return !expr.is_string_constant(); + if (expr instanceof AddressOf) return should_wrap_transparently(expr.expr); + if (expr instanceof Cast) return expr.should_wrap_transparently(); + if (expr instanceof StructAccess && expr.struct_var instanceof AddressOf && expr.struct_var.expr instanceof GlobalSymbol && should_wrap_transparently(expr.struct_var.expr)) return true; + return false; +} + +/** Determine whether an expression's type is "obvious". */ +export function is_type_obvious(expr) { + if ( + expr instanceof Cast || + expr instanceof Literal || + expr instanceof AddressOf || + expr instanceof LocalVar || + expr instanceof NaivePhiExpr || + expr instanceof PassedInArg || + expr instanceof PlannedPhiExpr || + expr instanceof FuncCall + ) { + return true; + } + if (expr instanceof EvalOnceExpr) { + if (expr.uses_var()) return true; + return is_type_obvious(expr.wrapped_expr); + } + return false; +} + +/** Simplify a boolean expression. */ +export function simplify_condition(expr) { + if (expr instanceof EvalOnceExpr && !expr.uses_var()) return simplify_condition(expr.wrapped_expr); + if (expr instanceof UnaryOp) { + const inner = simplify_condition(expr.expr); + if (expr.op === "!" && inner instanceof Condition) return inner.negated(); + return new UnaryOp({ expr: inner, op: expr.op, type: expr.type }); + } + if (expr instanceof BinaryOp) { + const left = simplify_condition(expr.left); + const right = simplify_condition(expr.right); + if (left instanceof UnaryOp && left.op === "!" && pyeq(right, new Literal(0))) { + if (expr.op === "==") return left.expr; + if (expr.op === "!=") return left; + } + if (left instanceof BinaryOp && (left.is_comparison() || left.op === "&") && pyeq(right, new Literal(0))) { + if (expr.op === "==") return simplify_condition(left.negated()); + if (expr.op === "!=") return left; + } + if (expr.is_comparison() && left instanceof Literal && !(right instanceof Literal)) { + return new BinaryOp({ left: right, op: swap_lt_gt(expr.op), right: left, type: expr.type }); + } + return new BinaryOp({ left, op: expr.op, right, type: expr.type }); + } + return expr; +} + +/** Check if parentheses in a string are balanced. */ +export function balanced_parentheses(string) { + let bal = 0; + for (const c of string) { + if (c === "(") bal += 1; + else if (c === ")") { + if (bal === 0) return false; + bal -= 1; + } + } + return bal === 0; +} + +/** Stringify an expression, stripping unnecessary parentheses around it. */ +export function format_expr(expr, fmt) { + const ret = expr.format(fmt); + if (ret.startsWith("(") && balanced_parentheses(ret.slice(1, -1))) return ret.slice(1, -1); + return ret; +} + +/** Stringify `dest = source;`. */ +export function format_assignment(dest, source, fmt) { + let is_dest; + if (dest instanceof Expression) { + dest = late_unwrap(dest); + const d = dest; + is_dest = (e) => pyeq(e, d); + } else { + const d = dest; + is_dest = (e) => var_for_expr(e) === d; + } + source = late_unwrap(source); + if (source instanceof BinaryOp && COMPOUND_ASSIGNMENT_OPS.has(source.op)) { + source = source.normalize_for_formatting(); + let rhs = null; + if (is_dest(late_unwrap(source.left))) rhs = source.right; + else if (is_dest(late_unwrap(source.right)) && ASSOCIATIVE_OPS.has(source.op)) rhs = source.left; + if (rhs !== null) return `${dest.format(fmt)} ${source.op}= ${format_expr(rhs, fmt)};`; + } + return `${dest.format(fmt)} = ${format_expr(source, fmt)};`; +} + +/** If an expression *may* expand to the read of a Var, return that var. */ +export function var_for_expr(expr) { + if (expr instanceof PlannedPhiExpr) return expr.var; + if (expr instanceof EvalOnceExpr && !expr.trivial) return expr.var; + return null; +} + +export function parenthesize_for_struct_access(expr, fmt) { + const s = expr.format(fmt); + if (s.startsWith("*") || s.startsWith("&") || (expr instanceof Cast && expr.needed_for_store())) return `(${s})`; + return s; +} + +export function elide_literal_casts(expr) { + const uw_expr = late_unwrap(expr); + if (uw_expr instanceof Cast && !uw_expr.needed_for_store()) return elide_literal_casts(uw_expr.expr); + if (uw_expr instanceof Literal && uw_expr.type.is_int() && uw_expr.value >= 0) return dcreplace(uw_expr, { elide_cast: true }); + return uw_expr; +} + +export function uses_expr_sub(expr, expr_filter, is_parent_addressof, may_move_forward, seen) { + const cache_key = `${objId(expr)},${may_move_forward ? 1 : 0},${is_parent_addressof ? 1 : 0}`; + if (seen.has(cache_key)) return false; + seen.add(cache_key); + if (expr_filter(expr) && !is_parent_addressof) return true; + if (expr instanceof EvalOnceExpr) { + const e = expr.dependency(may_move_forward); + return e !== null && uses_expr_sub(e, expr_filter, false, may_move_forward || expr.emit_exactly_once, seen); + } else if (expr instanceof AddressOf) { + return uses_expr_sub(expr.expr, expr_filter, true, may_move_forward, seen); + } else { + for (const e of expr.dependencies()) if (uses_expr_sub(e, expr_filter, false, may_move_forward, seen)) return true; + return false; + } +} + +export function uses_expr(expr, expr_filter) { + return uses_expr_sub(expr, expr_filter, false, false, new Set()); +} + +/** Unwrap EvalOnceExpr's, stopping at variable boundaries. */ +export function late_unwrap(expr) { + if (expr instanceof EvalOnceExpr && !expr.uses_var()) return late_unwrap(expr.wrapped_expr); + if (expr instanceof NaivePhiExpr && expr.replacement_expr !== null) return late_unwrap(expr.replacement_expr); + return expr; +} + +/** Unwrap transparent EvalOnceExpr's. */ +export function transparent_unwrap(expr) { + if (expr instanceof EvalOnceExpr && expr.transparent && !expr.uses_var()) return transparent_unwrap(expr.wrapped_expr); + return expr; +} + +/** Unwrap EvalOnceExpr's, even past variable boundaries. */ +export function early_unwrap(expr) { + if (expr instanceof EvalOnceExpr && !expr.forced_emit && !expr.emit_exactly_once) return early_unwrap(expr.wrapped_expr); + return expr; +} + +export function early_unwrap_ints(expr) { + const uw_expr = early_unwrap(expr); + if (uw_expr instanceof Cast && uw_expr.reinterpret && uw_expr.type.is_int()) return early_unwrap_ints(uw_expr.expr); + return uw_expr; +} + +export function late_unwrap_ints(expr) { + const uw_expr = late_unwrap(expr); + if (uw_expr instanceof Cast && uw_expr.reinterpret && uw_expr.type.is_int()) return late_unwrap_ints(uw_expr.expr); + return uw_expr; +} + +export function unwrap_deep(expr) { + if (expr instanceof EvalOnceExpr) return unwrap_deep(expr.wrapped_expr); + return expr; +} + +export function literal_expr(arg, stack_info) { + if (arg instanceof AsmGlobalSymbol) return stack_info.global_info.address_of_gsym(arg.symbol_name); + if (arg instanceof AsmLiteral) return new Literal(arg.value); + if (arg instanceof BinOp) { + const lhs = literal_expr(arg.lhs, stack_info); + const rhs = literal_expr(arg.rhs, stack_info); + return BinaryOp.int(lhs, arg.op, rhs); + } + throw new DecompFailure(`Instruction argument ${arg} must be a literal`); +} + +export function parse_symbol_ref(arg) { + if (arg instanceof AsmGlobalSymbol) return new RawSymbolRef({ offset: 0, sym: arg }); + if (arg instanceof BinOp && "+-".includes(arg.op) && arg.lhs instanceof AsmGlobalSymbol && arg.rhs instanceof AsmLiteral) { + return new RawSymbolRef({ offset: arg.rhs.value * (arg.op === "-" ? -1 : 1), sym: arg.lhs }); + } + return null; +} + +function pack_f32_bits(value) { + if (Number.isFinite(value) && !Number.isFinite(Math.fround(value))) throw new Error("OverflowError: float too large to pack with f format"); + const dv = new DataView(new ArrayBuffer(4)); + dv.setFloat32(0, value); + return dv.getUint32(0); +} + +export function format_f32_imm(num) { + const bits = Number(BigInt.asUintN(32, BigInt(num))); + const dv = new DataView(new ArrayBuffer(4)); + dv.setUint32(0, bits); + const value = dv.getFloat32(0); + const packed = bits; + + if (!value || value === 4294967296.0) return float_repr(value); + + let fmt_char; + if (Math.abs(Math.log10(Math.abs(value))) > 6.9) fmt_char = "e"; + else if (Math.abs(value) < 1) fmt_char = "f"; + else fmt_char = "g"; + + const fmt = (prec) => { + let ret; + if (fmt_char === "e") ret = format_exp(value, prec); + else if (fmt_char === "f") ret = format_fixed(value, prec); + else ret = format_general(value, prec); + if (fmt_char === "e") return ret.replaceAll("e+", "e").replaceAll("e0", "e").replaceAll("e-0", "e-"); + if (ret.includes("e")) return "0"; + return ret; + }; + + let prec = 20; + while (prec > 0) { + prec -= 1; + const value2 = py_float(fmt(prec)); + if (pack_f32_bits(value2) !== packed) { + prec += 1; + break; + } + } + if (prec === 20) return float_repr(value); + let ret = fmt(prec); + if (!ret.includes(".") && !ret.includes("e")) ret += ".0"; + return ret; +} + +export function format_f64_imm(num) { + const dv = new DataView(new ArrayBuffer(8)); + dv.setBigUint64(0, BigInt.asUintN(64, BigInt(num))); + return float_repr(dv.getFloat64(0)); +} + +/** Replace %lo(...) by 0, and assert that there are no %hi(...). */ +export function strip_macros(arg) { + if (arg instanceof Macro) { + if (arg.macro_name === "sda2" || arg.macro_name === "sda21") return arg.argument; + if (arg.macro_name === "hi") throw new DecompFailure("%hi macro outside of lui"); + if (arg.macro_name !== "lo" && arg.macro_name !== "l") throw new DecompFailure(`Unrecognized linker macro %${arg.macro_name}`); + if (arg.argument instanceof AsmLiteral) return new AsmLiteral(arg.argument.value); + return new AsmLiteral(0); + } else if (arg instanceof AsmAddressMode && arg.addend instanceof Macro) { + if (["sda2", "sda21", "gp_rel"].includes(arg.addend.macro_name)) return arg.addend.argument; + if (arg.addend.macro_name !== "lo" && arg.addend.macro_name !== "l") throw new DecompFailure(`Bad linker macro in instruction argument ${arg}, expected %lo`); + return new AsmAddressMode(arg.base, new AsmLiteral(0), arg.writeback); + } + return arg; +} + +export class ArgLoc { + static __fields = [["offset"], ["sort_index"], ["reg"]]; + constructor(...args) { + dcinit(this, args); + } + __lt__(other) { + if (this.sort_index !== null) { + if (other.sort_index === null) return true; + return this.sort_index < other.sort_index; + } + if (other.sort_index !== null) return false; + pyassert(this.offset !== null); + pyassert(other.offset !== null); + return this.offset < other.offset; + } + equals(other) { + if (!(other instanceof ArgLoc)) return false; + if (this.offset !== null) return other.offset === this.offset; + return other.offset === null && this.reg === other.reg; + } + __pykey() { + if (this.offset !== null) return `AL:o${this.offset}`; + return `AL:r${this.reg === null ? "N" : "#" + this.reg.__iid}`; + } +} + +export class AbiArgSlot { + static __fields = [["loc"], ["type"], ["name", null], ["comment", null]]; + constructor(...args) { + dcinit(this, args); + } +} + +export class Abi { + static __fields = [["arg_slots"], ["possible_slots"]]; + constructor(...args) { + dcinit(this, args); + } +} + +export function find_clobbers_until_dominator(stack_info, node) { + pyassert(node.immediate_dominator !== null); + const seen = new Set([node.immediate_dominator]); + const stack = [...node.parents]; + const clobbered_vars = new Set(); + let has_fn_call = false; + while (stack.length) { + const n = stack.pop(); + if (seen.has(n)) continue; + seen.add(n); + for (const instr_ref of n.block.instruction_refs) { + const instr = instr_ref.instruction; + for (const loc of instr.outputs) { + if (loc instanceof Register) { + const v = stack_info.get_planned_var(loc, instr_ref); + if (v !== null) clobbered_vars.add(v); + } + } + if (instr.function_target !== null) has_fn_call = true; + } + stack.push(...n.parents); + } + return [clobbered_vars, has_fn_call]; +} + +export function reg_sources(node, reg) { + pyassert(node.immediate_dominator !== null); + const seen = new Set([node.immediate_dominator]); + const stack = [...node.parents]; + const sources = []; + let uses_dominator = false; + while (stack.length) { + const n = stack.pop(); + if (n === node.immediate_dominator) uses_dominator = true; + if (seen.has(n)) continue; + seen.add(n); + let broke = false; + const refs = n.block.instruction_refs; + for (let i = refs.length - 1; i >= 0; i--) { + const instr_ref = refs[i]; + const instr = instr_ref.instruction; + if (instr.outputs.includes(reg)) { + sources.push(instr_ref); + broke = true; + break; + } else if (instr.clobbers.includes(reg)) { + return [[], false]; + } + } + if (!broke) stack.push(...n.parents); + } + return [sources, uses_dominator]; +} + +export function assign_naive_phis(used_naive_phis, stack_info) { + let i = 0; + while (i < used_naive_phis.length) { + const phi = used_naive_phis[i]; + pyassert(phi.num_usages > 0); + pyassert(phi.sources.length >= 2); + pyassert(phi.node.parents.length >= 2); + + const equivalent_blocks = new DefaultPyDict(() => []); + for (const source of phi.sources) { + let block; + if (source instanceof InstrRef) block = source.block; + else block = stack_info.flow_graph.entry_node().block; + const expr = get_block_info_for_block(block).final_register_states.get(phi.reg); + expr.type.unify(phi.type); + equivalent_blocks.get(transparent_unwrap(expr)).push(block); + } + + const exprs = [...equivalent_blocks.keys()]; + const first_uw = early_unwrap(exprs[0]); + if (exprs.slice(1).every((e) => pyeq(early_unwrap(e), first_uw))) { + const phi_expr = exprs.length === 1 ? exprs[0] : first_uw; + phi.replacement_expr = as_type(phi_expr, phi.type, true); + for (let k = 0; k < phi.num_usages; k++) phi_expr.use(); + if (exprs.length === 1) { + if (phi.uses_dominator) stack_info.add_planned_inherited_phi(phi.node, phi.reg, PhiInheritSource.DOMINATOR); + else if (is_trivial_expression(exprs[0])) stack_info.add_planned_inherited_phi(phi.node, phi.reg, PhiInheritSource.ANY_PARENT); + } + } else { + for (const [, blocks] of equivalent_blocks) { + for (const block of blocks) { + const block_info = get_block_info_for_block(block); + const expr = block_info.final_register_states.get(phi.reg); + expr.use(); + const typed_expr = as_type(expr, phi.type, true); + block_info.to_write.push(new SetNaivePhiStmt(phi, typed_expr)); + } + } + } + i += 1; + } + + for (const phi of used_naive_phis) { + if (!phi.replacement_expr) { + const output_reg_name = stack_info.function.reg_formatter.format(phi.reg); + let prefix = `phi_${output_reg_name}`; + if (stack_info.global_info.deterministic_vars) prefix = `${prefix}_${phi.node.block.index}`; + phi.name = stack_info.temp_var(prefix); + stack_info.naive_phi_vars.push(phi); + const v = stack_info.get_persistent_planned_var(phi.reg, phi.sources[0]); + for (const source of phi.sources.slice(1)) stack_info.get_persistent_planned_var(phi.reg, source).join(v); + } + } +} + +/** Propagate RegMeta bits forwards/backwards. */ +export function propagate_register_meta(nodes, reg) { + const non_terminal = nodes.filter((n) => !(n instanceof TerminalNode)); + + for (const n of non_terminal) { + if (get_block_info(n).final_register_states.read_inherited.has(reg)) { + for (const p of n.parents) { + const par_meta = get_block_info(p).final_register_states.get_meta(reg); + if (par_meta) par_meta.is_read = true; + } + } + } + + let todo = [...non_terminal]; + while (todo.length) { + const n = todo.pop(); + const meta = get_block_info(n).final_register_states.get_meta(reg); + for (const p of n.parents) { + const par_meta = get_block_info(p).final_register_states.get_meta(reg); + if (par_meta && !par_meta.is_read && meta && meta.inherited && meta.is_read) { + par_meta.is_read = true; + todo.push(p); + } + } + } + + for (const n of non_terminal) { + const meta = get_block_info(n).final_register_states.get_meta(reg); + if (meta) { + if (meta.inherited) { + meta.uninteresting = true; + meta.function_return = true; + meta.in_pattern = true; + } else { + meta.uninteresting = meta.uninteresting || meta.is_read || meta.function_return || meta.in_pattern; + } + } + } + + todo = [...non_terminal]; + while (todo.length) { + const n = todo.pop(); + if (n instanceof TerminalNode) continue; + const meta = get_block_info(n).final_register_states.get_meta(reg); + if (!meta || !meta.inherited) continue; + let all_uninteresting = true; + let all_function_return = true; + let all_in_pattern = true; + for (const p of n.parents) { + const par_meta = get_block_info(p).final_register_states.get_meta(reg); + if (par_meta) { + all_uninteresting = all_uninteresting && par_meta.uninteresting; + all_function_return = all_function_return && par_meta.function_return; + all_in_pattern = all_in_pattern && par_meta.in_pattern; + } + } + if (meta.uninteresting && !all_uninteresting && !meta.is_read) { + meta.uninteresting = false; + todo.push(...n.children()); + } + if (meta.function_return && !all_function_return) { + meta.function_return = false; + todo.push(...n.children()); + } + if (meta.in_pattern && !all_in_pattern) { + meta.in_pattern = false; + todo.push(...n.children()); + } + } +} + +/** Determine which of the arch's base_return_regs is most likely to contain the return value. */ +export function determine_return_register(return_blocks, fn_decl_provided, arch) { + const priority = (block_info, reg) => { + const meta = block_info.final_register_states.get_meta(reg); + if (!meta) return 4; + if (meta.uninteresting) return 2; + if (meta.in_pattern) return 1; + if (meta.function_return) return 0; + return 3; + }; + if (!return_blocks.length) return null; + let best_reg = null; + let best_prio = -1; + for (const [reg, floating] of arch.base_return_regs) { + const prios = return_blocks.map((b) => priority(b, reg)); + const max_prio = Math.max(...prios); + if (max_prio === 4) continue; + if (max_prio <= 2 && !fn_decl_provided) continue; + if (max_prio > best_prio) { + best_prio = max_prio; + best_reg = [reg, floating]; + } + } + return best_reg; +} + +export class NodeState { + constructor({ node, stack_info, regs }) { + this.node = node; + this.stack_info = stack_info; + this.regs = regs; + // LocalVar -> [Register, Expression, bool] + this.local_var_writes = new PyDict(); + this.subroutine_args = new Map(); + this.in_pattern = false; + this.to_write = []; + this.branch_condition = null; + this.switch_control = null; + this.has_function_call = false; + } + + _eval_once(expr, { emit_exactly_once, transparent, reg, source }) { + const planned_var = this.stack_info.get_planned_var(reg, source); + let is_fictive_temp = false; + + if (reg.register_name.includes("_fictive_")) { + if (expr instanceof EvalOnceExpr && !expr.var.is_planned) { + pyassert(!emit_exactly_once); + pyassert(!planned_var); + return expr; + } + reg = new Register(reg.register_name.split("_fictive_")[0]); + is_fictive_temp = true; + } + + const trivial = transparent && is_trivial_expression(expr); + if (emit_exactly_once) expr.use(); + + let force = false; + let v; + if (planned_var !== null) { + v = planned_var; + expr = as_type(expr, v.type, true); + this.prevent_later_var_uses(new Set([v])); + if (uses_expr(expr, (e) => var_for_expr(e) === v)) force = true; + } else { + let prefix = this.stack_info.function.reg_formatter.format(reg); + if (prefix === "condition_bit") prefix = "cond"; + let temp_name = `temp_${prefix}`; + if (this.stack_info.global_info.deterministic_vars) temp_name = `${temp_name}_${this.regs.get_instruction_lineno()}`; + v = new Var(this.stack_info, temp_name, { is_planned: false, type: expr.type }); + this.stack_info.temp_vars.push(v); + } + + const ret = new EvalOnceExpr({ + wrapped_expr: expr, + var: v, + type: expr.type, + sources: [source], + emit_exactly_once, + trivial, + transparent, + is_fictive_temp, + }); + const stmt = new EvalOnceStmt(ret); + this.write_statement(stmt); + v.debug_exprs.push(ret); + + if (planned_var !== null) { + v.is_emitted = true; + ret.use(); + if (force) ret.force(); + } + return ret; + } + + /** Prevent later uses of registers that recursively contain something that matches a filter. */ + _prevent_later_uses(expr_filter) { + for (const [r, data] of [...this.regs.contents.entries()]) { + const expr = data.value; + if (expr instanceof PlannedPhiExpr || expr instanceof NaivePhiExpr) continue; + if (!data.meta.force && uses_expr(expr, expr_filter)) { + if (!(expr instanceof EvalOnceExpr)) assert_never(expr); + this.regs.update_meta(r, dcreplace(data.meta, { force: true })); + } + } + for (const [loc, [reg, write, force]] of [...this.local_var_writes.entries()]) { + if (!force && uses_expr(write, expr_filter)) this.local_var_writes.set(loc, [reg, write, true]); + } + } + + prevent_later_value_uses(sub_expr) { + this._prevent_later_uses((e) => pyeq(e, sub_expr)); + } + + prevent_later_var_uses(vars) { + if (vars.size) this._prevent_later_uses((e) => vars.has(var_for_expr(e))); + } + + prevent_later_function_calls() { + this._prevent_later_uses((e) => e instanceof FuncCall); + } + + prevent_later_reads() { + this._prevent_later_uses((e) => e instanceof StructAccess || e instanceof ArrayAccess); + } + + set_initial_reg(reg, expr, meta) { + pyassert(meta.initial); + expr = this._eval_once(expr, { emit_exactly_once: false, transparent: true, reg, source: new PrologueRef(reg) }); + this.regs.global_set_with_meta(reg, expr, meta); + if (expr.var.is_emitted) this.regs.get(reg); + } + + set_reg(reg, expr) { + if (expr instanceof LocalVar) { + if ( + this.node instanceof ReturnNode && + this.stack_info.maybe_get_register_var(reg) && + this.stack_info.in_callee_save_reg_region(expr.value) && + this.stack_info.callee_save_regs.has(reg) + ) { + return expr; + } + if (this.stack_info.global_info.stack_spill_detection && this.local_var_writes.has(expr)) { + const [orig_reg, orig_expr, force] = this.local_var_writes.get(expr); + if (orig_reg === reg) { + expr = orig_expr; + if (force) { + let base_expr = expr; + while (base_expr instanceof Cast) base_expr = base_expr.expr; + if (base_expr instanceof EvalOnceExpr) base_expr.force(); + } + } + } + } + return this.set_reg_real(reg, expr); + } + + set_reg_real(reg, uw_expr, { transparent = null, emit_exactly_once = false, function_return = false } = {}) { + const source = this.regs.current_instr_ref(); + if (transparent === null) transparent = should_wrap_transparently(uw_expr); + const expr = this._eval_once(uw_expr, { emit_exactly_once, transparent, reg, source }); + if (reg === new Register("zero")) { + expr.use(); + this.write_statement(new ExprStmt(expr)); + } else { + const in_pattern = source.instruction.in_pattern; + this.regs.set_with_meta(reg, expr, new RegMeta({ in_pattern, function_return })); + } + return expr; + } + + clear_caller_save_regs() { + for (const reg of this.stack_info.global_info.arch.temp_regs) if (this.regs.has(reg)) this.regs.delete(reg); + } + + maybe_clear_local_var_writes(func_args) { + for (const arg of func_args) { + if (uses_expr(arg, (expr) => expr instanceof AddressOf && expr.expr instanceof LocalVar)) { + this.local_var_writes.clear(); + return; + } + } + } + + set_branch_condition(cond) { + pyassert(this.node instanceof ConditionalNode); + pyassert(this.branch_condition === null); + this.branch_condition = cond; + } + + set_switch_expr(expr, just_index = false) { + pyassert(this.node instanceof SwitchNode); + pyassert(this.switch_control === null); + if (just_index) this.switch_control = new SwitchControl(expr, { num_cases: this.node.cases.length }); + else this.switch_control = SwitchControl.from_expr(expr, this.node.cases.length); + } + + write_statement(stmt) { + this.to_write.push(stmt); + } + + store_memory(store, reg) { + const source = store.source; + const dest = store.dest; + if (dest instanceof SubroutineArg) { + if (dest.value >= this.stack_info.global_info.arch.home_space_size) this.subroutine_args.set(dest.value, source); + return; + } + let raw_value = source; + while (raw_value instanceof Cast && raw_value.reinterpret) raw_value = raw_value.expr; + if (dest instanceof LocalVar) { + this.stack_info.add_local_var(dest); + this.local_var_writes.set(dest, [reg, raw_value, false]); + } + if ((dest instanceof LocalVar || dest instanceof PassedInArg) && pyeq(early_unwrap(raw_value), dest)) return; + source.use(); + dest.use(); + this.prevent_later_value_uses(dest); + this.prevent_later_function_calls(); + this.write_statement(store); + } + + push_subroutine_arg(source) { + const m = new Map(); + for (const [offset, arg] of this.subroutine_args) m.set(offset + 4, arg); + this.subroutine_args = m; + this.subroutine_args.set(0, source); + } + + _reg_probably_meant_as_function_argument(reg, call_instr) { + for (const source of this.stack_info.flow_graph.instr_inputs.get(call_instr).get(reg)) { + const uses = this.stack_info.flow_graph.instr_uses.get(source).get(reg); + pyassert(uses.has(call_instr)); + if (uses.length === 1 && source instanceof InstrRef && source.instruction.function_target === null && call_instr.instruction.function_target !== reg) return true; + } + return false; + } + + make_function_call(fn_target, outputs) { + const call_instr = this.regs.current_instr_ref(); + const arch = this.stack_info.global_info.arch; + fn_target = as_function_ptr(fn_target); + const fn_sig = fn_target.type.get_function_pointer_signature(); + pyassert(fn_sig !== null, "known function pointers must have a signature"); + + const instr_inputs = this.stack_info.flow_graph.instr_inputs.get(call_instr); + const likely_regs = new Map(); + for (const [reg, data] of this.regs.contents) { + if (!arch.argument_regs.includes(reg)) likely_regs.set(reg, false); + else if ( + (arch.arch === Target.ArchEnum.PPC || arch.arch === Target.ArchEnum.ARM) && + !fn_sig.is_variadic && + (data.meta.inherited || data.meta.function_return || arch.arch === Target.ArchEnum.ARM) && + !this._reg_probably_meant_as_function_argument(reg, call_instr) + ) { + likely_regs.set(reg, false); + } else if ([...instr_inputs.get(reg)].every((source) => !(source instanceof InstrRef) || source.instruction.in_pattern)) { + likely_regs.set(reg, false); + } else likely_regs.set(reg, true); + } + + const abi = arch.function_abi(fn_sig, likely_regs, { for_call: true }); + + const func_args = []; + for (const slot of abi.arg_slots) { + let expr; + if (slot.loc.reg) expr = this.regs.get(slot.loc.reg); + else { + const offset = slot.loc.offset; + pyassert(offset !== null); + if (this.subroutine_args.has(offset)) { + expr = this.subroutine_args.get(offset); + this.subroutine_args.delete(offset); + } else expr = new ErrorExpr(`Unable to find stack arg ${format(offset, "#x")} in block`); + } + func_args.push(CommentExpr.wrap(as_type(expr, slot.type, true), slot.comment)); + } + + for (const slot of abi.possible_slots) { + pyassert(slot.loc.reg !== null); + func_args.push(this.regs.get(slot.loc.reg)); + } + + for (const [, arg] of sorted(this.subroutine_args.entries(), (e) => e[0])) { + if (fn_sig.params_known && !fn_sig.is_variadic) func_args.push(CommentExpr.wrap(arg, "extra?")); + else func_args.push(arg); + } + + if (!fn_sig.params_known) { + while (func_args.length > fn_sig.params.length) fn_sig.params.push(new FunctionParam()); + const n = Math.min(func_args.length, fn_sig.params.length); + for (let i = 0; i < n; i++) func_args[i] = as_type(func_args[i], fn_sig.params[i].type.decay(), true); + } + + this.subroutine_args.clear(); + + const source = this.regs.current_instr_ref(); + let call = new FuncCall(fn_target, func_args, fn_sig.return_type.weaken_void_ptr()); + call = this._eval_once(call, { emit_exactly_once: true, transparent: false, reg: new Register("ret"), source }); + + this.clear_caller_save_regs(); + this.maybe_clear_local_var_writes(func_args); + this.prevent_later_function_calls(); + this.prevent_later_reads(); + + const return_reg_vals = arch.function_return(call); + for (const out of outputs) { + if (!(out instanceof Register)) continue; + if (!return_reg_vals.has(out)) throw new Error(`KeyError: ${out}`); + const val = return_reg_vals.get(out); + this.set_reg_real(out, val, { transparent: false, function_return: true }); + } + this.has_function_call = true; + } +} + +export function evaluate_instruction(instr_ref, state) { + const instr = instr_ref.instruction; + if (instr.is_return) pyassert(state.node instanceof ReturnNode); + if (instr.is_conditional) pyassert(state.branch_condition === null && state.switch_control === null); + if (instr.eval_fn !== null) { + const args = new InstrArgs(instr_ref, instr.args, state.regs, state.stack_info); + instr.eval_fn(state, args); + } + if (instr.is_conditional) pyassert(state.branch_condition !== null || state.switch_control !== null); +} + +/** Given a node and current register contents, return a BlockInfo containing the translated AST. */ +export function translate_node_body(state) { + for (const instr_ref of state.node.block.instruction_refs) { + state.regs.set_current_instr(instr_ref, () => evaluate_instruction(instr_ref, state)); + } + if (state.branch_condition !== null) state.branch_condition.use(); + if (state.switch_control !== null) state.switch_control.control_expr.use(); + return new BlockInfo({ + to_write: state.to_write, + return_value: null, + switch_control: state.switch_control, + branch_condition: state.branch_condition, + final_register_states: state.regs, + has_function_call: state.has_function_call, + }); +} + +function py_exc_str(e) { + if (e instanceof DecompFailure) return e.message; + if (e && typeof e.message === "string") return e.message; + return String(e); +} + +export function translate_block(state, options) { + const node = state.node; + if (options.debug) print(`\nNode in question: ${node}`); + let block_info; + try { + block_info = translate_node_body(state); + if (options.debug) print(String(block_info)); + } catch (e0) { + let e = e0; + if (options.stop_on_error) throw e; + let instr = null; + if (e instanceof InstrProcessingFailure && e.cause instanceof Error) { + instr = e.instr; + e = e.cause; + } + let emsg; + if (e instanceof DecompFailure) { + emsg = py_exc_str(e); + print(emsg); + } else { + print(`Traceback (most recent call last):\n${e && e.stack ? e.stack : e}`, { __print_opts: true, stderr: true }); + emsg = py_exc_str(e) || `${e && e.name ? e.name : "Error"}`; + const parts = emsg.trim().split("\n"); + emsg = parts[parts.length - 1].trim(); + } + const error_stmts = [new CommentStmt(`Error: ${emsg}`)]; + if (instr !== null) { + print(`Error occurred while processing instruction: ${instr}`, { __print_opts: true, stderr: true }); + error_stmts.push(new CommentStmt(`At instruction: ${instr}`)); + } + print({ __print_opts: true, stderr: true }); + block_info = new BlockInfo({ + to_write: error_stmts, + return_value: null, + switch_control: null, + branch_condition: new ErrorExpr(), + final_register_states: state.regs, + has_function_call: false, + }); + } + return block_info; +} + +/** Create a NodeState for translating a child of a node in the dominator tree. */ +export function create_dominated_node_state(parent_state, child, used_naive_phis) { + const stack_info = parent_state.stack_info; + const new_regs = new RegInfo({ stack_info }); + const child_state = new NodeState({ node: child, regs: new_regs, stack_info }); + for (const [reg, data] of parent_state.regs.contents) { + new_regs.global_set_with_meta(reg, data.value, new RegMeta({ inherited: true, force: data.meta.force, initial: data.meta.initial })); + } + + const phi_regs = [...locs_clobbered_until_dominator(child)].filter((r) => r instanceof Register); + for (const reg of phi_regs) { + let [sources, uses_dominator] = reg_sources(child, reg); + + const inherited_phi = stack_info.get_planned_inherited_phi(child, reg); + if (inherited_phi !== null) { + if (inherited_phi === PhiInheritSource.DOMINATOR) { + const meta = new_regs.get_meta(reg); + if (meta !== null) { + new_regs.update_meta(reg, dcreplace(meta, { initial: false })); + continue; + } + } else { + let found_par_value = null; + for (const parent of child.parents) { + if (parent.block.block_info) { + const par_regs = get_block_info(parent).final_register_states; + if (!par_regs.contents.has(reg)) throw new Error(`KeyError: ${reg}`); + const par_value = par_regs.contents.get(reg).value; + if (par_value instanceof EvalOnceExpr && par_value.trivial) { + found_par_value = par_value; + break; + } + } + } + if (found_par_value !== null) { + const new_val = new EvalOnceExpr({ + wrapped_expr: found_par_value.wrapped_expr, + var: new Var(stack_info, "_m2c_inherited_phi", { is_planned: false, type: found_par_value.type }), + type: found_par_value.type, + sources, + emit_exactly_once: false, + trivial: true, + transparent: true, + is_fictive_temp: false, + }); + new_regs.global_set_with_meta(reg, new_val, new RegMeta({ inherited: true })); + continue; + } + } + } + + if (uses_dominator) { + const dom_expr = parent_state.regs.get_raw(reg); + if (dom_expr === null) sources = []; + else if (dom_expr instanceof EvalOnceExpr || dom_expr instanceof PlannedPhiExpr || dom_expr instanceof NaivePhiExpr) sources.push(...dom_expr.sources); + else assert_never(dom_expr); + } + + if (sources.length) { + let expr; + const v = stack_info.get_planned_var(reg, sources[0]); + if (v !== null && sources.slice(1).every((s) => stack_info.get_planned_var(reg, s) === v)) { + expr = new PlannedPhiExpr(v, v.type, sources); + } else { + expr = new NaivePhiExpr({ reg, node: child, type: Type.any_reg(), sources, uses_dominator, used_naive_phis }); + } + new_regs.global_set_with_meta(reg, expr, new RegMeta({ inherited: true })); + } else if (new_regs.has(reg)) { + new_regs.delete(reg); + } + } + + const [clobbered_vars, has_fn_call] = find_clobbers_until_dominator(stack_info, child); + child_state.prevent_later_var_uses(clobbered_vars); + + if (child.parents.length !== 1 || parent_state.node.children().length !== 1) child_state.prevent_later_function_calls(); + if (has_fn_call) child_state.prevent_later_reads(); + return child_state; +} + +/** Do translation for all non-terminal nodes, attaching block info to them. */ +export function translate_all_blocks(initial_state, used_naive_phis, return_blocks, options) { + const translate_stack = [[null, initial_state.node]]; + while (translate_stack.length) { + const [parent_state, node0] = translate_stack.pop(); + let state; + if (parent_state === null) state = initial_state; + else state = create_dominated_node_state(parent_state, node0, used_naive_phis); + const block_info = translate_block(state, options); + const node = state.node; + node.block.add_block_info(block_info); + if (node instanceof ReturnNode) return_blocks.push(block_info); + for (const child of [...state.node.immediately_dominates].reverse()) { + if (!(child instanceof TerminalNode)) translate_stack.push([state, child]); + } + } +} + +/** After translating a function, perform a final type-resolution pass. */ +export function resolve_types_late(stack_info) { + for (const location of [...stack_info.weak_stack_var_types.keys()]) stack_info.get_stack_var(location, { store: false }); + const struct_type_map = stack_info.get_struct_type_map(); + for (const [v, offset_type_map] of struct_type_map) { + if (offset_type_map.size === 1 && offset_type_map.has(0)) { + const type = offset_type_map.get(0); + v.type.unify(Type.ptr(type)); + } + } +} + +export class FunctionInfo { + constructor(stack_info, flow_graph, return_type, symbol) { + this.stack_info = stack_info; + this.flow_graph = flow_graph; + this.return_type = return_type; + this.symbol = symbol; + } +} + +export class FailedToGenerateInitializer extends Error { + constructor(reason) { + super(reason); + this.reason = reason; + } +} + +export class GlobalInfo { + constructor(asm_data, arch, target, local_functions, typemap, typepool, { deterministic_vars, stack_spill_detection }) { + this.asm_data = asm_data; + this.arch = arch; + this.target = target; + this.local_functions = local_functions; // Set + this.typemap = typemap; + this.typepool = typepool; + this.deterministic_vars = deterministic_vars; + this.stack_spill_detection = stack_spill_detection; + this.global_symbol_map = new Map(); + this.persistent_function_state = new DefaultMap(() => new PersistentFunctionState()); + } + + get_persistent_function_state(func_name) { + return this.persistent_function_state.get(func_name); + } + + asm_data_value(sym_name) { + return this.asm_data.values.get(sym_name) ?? null; + } + + address_of_gsym(sym_name) { + let sym; + if (this.global_symbol_map.has(sym_name)) sym = this.global_symbol_map.get(sym_name); + else { + const c_sym_name = this.arch.c_symbol_name(sym_name); + let demangled_symbol = null; + let demangled_str = null; + if (this.target.language === Target.LanguageEnum.CXX && this.target.compiler === Target.CompilerEnum.MWCC) { + try { + demangled_symbol = demangle_codewarrior_parse(sym_name); + demangled_str = String(demangled_symbol); + } catch (e) { + if (!(e instanceof ValueError)) throw e; + demangled_symbol = null; + } + } + sym = new GlobalSymbol({ c_symbol_name: c_sym_name, type: Type.any(), asm_data_entry: this.asm_data_value(sym_name), demangled_str }); + this.global_symbol_map.set(sym_name, sym); + + if (this.target.language === Target.LanguageEnum.CXX && this.target.compiler === Target.CompilerEnum.MWCC && sym_name.startsWith("__vt__") && sym.asm_data_entry !== null) { + sym.type.unify(this.vtable_type(sym_name, sym.asm_data_entry)); + } + + const fn = this.typemap.functions.get(c_sym_name) ?? null; + let ctype; + if (fn !== null) ctype = fn.type; + else ctype = this.typemap.var_types.get(c_sym_name) ?? null; + + if (ctype !== null) { + sym.symbol_in_context = true; + sym.initializer_in_typemap = this.typemap.vars_with_initializers.has(c_sym_name); + let type; + if (this.typepool.unk_inference && is_unk_type(ctype, this.typemap)) type = Type.gsym_unk_ctype(ctype, this.typemap, this.typepool); + else type = Type.ctype(ctype, this.typemap, this.typepool); + sym.type.unify(type); + if (!this.typepool.unknown_decls.has(c_sym_name)) sym.type_provided = true; + } else if (this.local_functions.has(sym_name)) { + sym.type.unify(Type.function()); + } + + if (demangled_symbol !== null) sym.type.unify(Type.demangled_symbol(this.typemap, this.typepool, demangled_symbol)); + } + return new AddressOf(sym, { type: sym.type.reference() }); + } + + /** Parse MWCC vtable data to create a custom struct to represent it. */ + vtable_type(sym_name, asm_data_entry) { + const size = asm_data_entry.size_range_bytes()[1]; + const struct = StructDeclaration.unknown(this.typepool, size, sym_name, 4); + let offset = 0; + for (const entry of asm_data_entry.data) { + if (entry instanceof Uint8Array) { + if (entry.length % 4 !== 0) throw new DecompFailure(`Unable to parse misaligned vtable data in ${sym_name}`); + for (let i = 0; i < floordiv(entry.length, 4); i++) { + const field_name = `${struct.new_field_prefix}${format(offset, "X")}`; + struct.try_add_field(Type.reg32({ likely_float: false }), offset, field_name, 4); + offset += 4; + } + } else { + const sym = entry.as_symbol_without_addend(); + if (sym === null) throw new DecompFailure(`Unable to parse vtable data in ${sym_name}`); + let entry_name = sym; + try { + const demangled_field_sym = demangle_codewarrior_parse(sym); + if (demangled_field_sym.name.qualified_name !== null && demangled_field_sym.name.qualified_name !== undefined) { + const q = demangled_field_sym.name.qualified_name; + entry_name = String(q[q.length - 1]); + } + } catch (e) { + if (!(e instanceof ValueError)) throw e; + } + const field = struct.try_add_field(this.address_of_gsym(sym).type, offset, entry_name, 4); + pyassert(field !== null); + field.known = true; + offset += 4; + } + } + return Type.struct(struct); + } + + /** Return true if the function exists in the context, and has no return value */ + is_function_known_void(sym_name) { + const fn = this.typemap.functions.get(sym_name) ?? null; + if (fn === null) return false; + return fn.ret_type === null; + } + + initializer_for_symbol(sym, fmt) { + pyassert(sym.asm_data_entry !== null); + const data = [...sym.asm_data_entry.data]; + + const read_uint = (n) => { + pyassert(0 < n && n <= 16); + if (!data.length) throw new FailedToGenerateInitializer("not enough data"); + if (!(data[0] instanceof Uint8Array)) { + const arg = data[0].data; + throw new FailedToGenerateInitializer(`cannot parse ${arg} as integer`); + } + if (data[0].length < n) { + if (data.length > 1) { + const s = data[1]; + pyassert(s instanceof AsmSymbolicData); + throw new FailedToGenerateInitializer(`partial read of ${s.data}`); + } else throw new FailedToGenerateInitializer("not enough data"); + } + let bs = data[0].slice(0, n); + data[0] = data[0].slice(n); + if (!data[0].length) data.shift(); + if (!this.target.is_big_endian()) bs = bs.reverse(); + let value = 0n; + for (const b of bs) value = (value << 8n) | BigInt(b); + return Number(value); + }; + + const try_read_pointer = () => { + if (!data.length || data[0] instanceof Uint8Array) return null; + const label = data[0].as_symbol_without_addend(); + if (label === null) return null; + data.shift(); + const expr = this.address_of_gsym(label); + expr.use(); + return expr; + }; + + const for_type = (type) => { + if (type.is_struct() || type.is_array()) { + const struct_fields = type.get_initializer_fields(); + if (!struct_fields || !struct_fields.length) { + if (type.is_array()) throw new FailedToGenerateInitializer("unsized array"); + throw new FailedToGenerateInitializer("confusing struct layout"); + } + const members = []; + for (const field of struct_fields) { + if (typeof field === "number") { + for (let i = 0; i < field; i++) { + const padding = read_uint(1); + if (padding !== 0) throw new FailedToGenerateInitializer("non-zero padding"); + } + } else members.push(for_type(field)); + } + return fmt.format_array(members); + } + if (type.is_reg()) { + const size = type.get_size_bytes(); + if (!size) throw new FailedToGenerateInitializer("unknown size"); + if (size === 4) { + const ptr = try_read_pointer(); + if (ptr !== null) return as_type(ptr, type, true).format(fmt); + } + const value = read_uint(size); + const enum_name = type.get_enum_name(value); + if (enum_name !== null) return enum_name; + const expr = as_type(new Literal(value), type, true); + return elide_literal_casts(expr).format(fmt); + } + if (type.get_size_bits() === null) throw new FailedToGenerateInitializer("unknown type"); + throw new FailedToGenerateInitializer("bad type"); + }; + + const type = sym.type.get_array()[0]; + if (sym.is_string_constant() && type !== null && type.get_size_bytes() === 1) return sym.format_string_constant(fmt); + return for_type(sym.type); + } + + find_forward_declares_needed(functions) { + const funcs_seen = new Set(); + const forward_declares_needed = this.asm_data.mentioned_labels; + for (const func of functions) { + funcs_seen.add(func.stack_info.function.name); + for (const instr of func.stack_info.function.body) { + if (!(instr instanceof Instruction)) continue; + for (const arg of instr.args) { + let func_name; + if (arg instanceof AsmGlobalSymbol) func_name = arg.symbol_name; + else if (arg instanceof Macro && arg.argument instanceof AsmGlobalSymbol) func_name = arg.argument.symbol_name; + else continue; + if (this.local_functions.has(func_name)) { + if (!funcs_seen.has(func_name)) forward_declares_needed.add(func_name); + } + } + } + } + return forward_declares_needed; + } + + global_decls(fmt, decls, functions) { + const forward_declares_needed = this.find_forward_declares_needed(functions); + const lines = []; + const processed_names = new Set(); + for (;;) { + const names = new Set(); + for (const [n, s] of this.global_symbol_map) if (s.is_referenced) names.add(n); + if (decls === Options.GlobalDeclsEnum.ALL) { + for (const [name, ent] of this.asm_data.values) if (!ent.is_text) names.add(name); + } + for (const p of processed_names) names.delete(p); + if (!names.size) break; + for (const name of sorted(names)) { + processed_names.add(name); + const sym = this.address_of_gsym(name).expr; + pyassert(sym instanceof GlobalSymbol); + let data_entry = sym.asm_data_entry; + + if (data_entry !== null && data_entry.is_text) { + if (!sym.type.is_function()) continue; + data_entry = null; + } + + const is_in_file = data_entry !== null || this.local_functions.has(name); + const is_global = sym.symbol_in_context; + const is_const = data_entry !== null && data_entry.is_readonly; + + if (data_entry && data_entry.is_jtbl) continue; + if (is_in_file && is_global && sym.type.is_function()) continue; + if (this.local_functions.size === 1 && this.local_functions.has(name)) continue; + if (!is_in_file && sym.type_provided) continue; + + let data_entry_order; + if (data_entry) { + const [file, index] = data_entry.sort_order; + data_entry_order = data_entry.is_bss && fmt.backwards_bss ? [file, index * -1] : [file, index]; + } else data_entry_order = ["", 0]; + + const sort_order = [!sym.type.is_function(), is_in_file, !is_in_file ? is_global : false, is_const, data_entry_order, name]; + let qualifier = ""; + let value = null; + const comments = []; + + if (is_in_file && is_global) qualifier = ""; + else if (is_in_file) qualifier = "static"; + else qualifier = "extern"; + + if (sym.type.is_function()) { + comments.push(qualifier); + qualifier = ""; + } + + let [element_type, array_dim] = sym.type.get_array(); + const is_vla = element_type !== null && (array_dim === null || array_dim <= 0); + if (data_entry && (!sym.type_provided || is_vla)) { + if (element_type === null) element_type = sym.type; + const type_size = element_type.get_size_bytes(); + if (type_size) { + const [potential_dim, extra_bytes] = sym.potential_array_dim(type_size); + if (potential_dim === 0 && extra_bytes > 0) comments.push(`type too large by ${fmt.format_int(type_size - extra_bytes)}`); + else if (potential_dim > 1 || is_vla) { + array_dim = potential_dim; + sym.type = Type.array(element_type, array_dim); + } + if (potential_dim !== 0 && extra_bytes > 0) comments.push(`extra bytes: ${fmt.format_int(extra_bytes)}`); + } + } + + if (data_entry && !data_entry.is_bss && !data_entry.is_text) { + try { + value = this.initializer_for_symbol(sym, fmt); + } catch (e) { + if (!(e instanceof FailedToGenerateInitializer)) throw e; + comments.push(`unable to generate initializer: ${e.reason}`); + } + } + + if (is_const) { + comments.push("const"); + if (sym.is_string_constant()) continue; + if (array_dim === null && data_entry !== null && data_entry.used_as_literal) continue; + } + + if (decls === Options.GlobalDeclsEnum.NONE) continue; + if (decls !== Options.GlobalDeclsEnum.ALL && sym.initializer_in_typemap) continue; + if (decls !== Options.GlobalDeclsEnum.ALL && this.target.language === Target.LanguageEnum.CXX && this.target.compiler === Target.CompilerEnum.MWCC && name.startsWith("__vt__")) continue; + if (sym.type.is_function() && decls !== Options.GlobalDeclsEnum.ALL && this.local_functions.has(name) && !forward_declares_needed.has(name)) continue; + + qualifier = qualifier ? `${qualifier} ` : ""; + const value_str = value ? ` = ${value}` : ""; + lines.push([sort_order, fmt.with_comments(`${qualifier}${sym.type.to_decl(name, fmt)}${value_str};`, comments) + "\n"]); + } + } + const sorted_lines = sorted(lines, (l) => l); + return sorted_lines.map(([, line]) => line).join(""); + } +} + +/** Modify the `outputs` list of function call Instructions using the context file. */ +export function narrow_func_call_outputs(fn, global_info) { + for (const instr of fn.body) { + if (instr instanceof Instruction && instr.function_target instanceof AsmGlobalSymbol && global_info.is_function_known_void(instr.function_target.symbol_name)) { + instr.outputs.length = 0; + } + } +} + +/** Set up stack_info planned vars from state from earlier translation passes. */ +export function setup_planned_vars(stack_info, persistent_state) { + const planned_vars = new DefaultMap(() => []); + for (const [key, persistent_var] of persistent_state.planned_vars) planned_vars.get(persistent_var.get_representative()).push(key); + for (const keys of planned_vars.values()) { + const reg = keys[0][0]; + const reg_name = stack_info.function.reg_formatter.format(reg); + let prefix = `var_${reg_name}`; + if (stack_info.global_info.deterministic_vars) { + const lineno = Math.min(...keys.map(([, source]) => (!(source instanceof InstrRef) ? 0 : source.instruction.meta.lineno))); + prefix = `${prefix}_${lineno}`; + } + const v = new Var(stack_info, { prefix, is_planned: true, type: Type.any_reg() }); + stack_info.temp_vars.push(v); + for (const key of keys) stack_info.planned_vars.set(key, v); + } +} + +/** Set up per-register planned vars based on command line flags. */ +export function setup_reg_vars(stack_info, options) { + const arch = stack_info.global_info.arch; + let reg_vars; + const rv = options.reg_vars; + if (rv.length === 1 && rv[0] === "saved") reg_vars = arch.saved_regs; + else if (rv.length === 1 && rv[0] === "most") reg_vars = [...arch.saved_regs, ...arch.simple_temp_regs]; + else if (rv.length === 1 && rv[0] === "all") reg_vars = [...arch.saved_regs, ...arch.simple_temp_regs, ...arch.argument_regs]; + else reg_vars = rv.map((x) => stack_info.function.reg_formatter.parse(x, arch)); + for (const reg of reg_vars) { + const reg_name = stack_info.function.reg_formatter.format(reg); + stack_info.add_register_var(reg, reg_name); + } +} + +/** Set up initial register contents for translation. */ +export function setup_initial_registers(state, fn_sig) { + const stack_info = state.stack_info; + const arch = stack_info.global_info.arch; + state.set_initial_reg(arch.stack_pointer_reg, new GlobalSymbol("sp", { type: Type.ptr() }), new RegMeta({ initial: true })); + for (const reg of arch.saved_regs) state.set_initial_reg(reg, stack_info.saved_reg_symbol(reg.register_name), new RegMeta({ initial: true })); + + const make_arg = (loc, type) => { + if (loc.offset !== null) pyassert(pymod(loc.offset, 4) === 0); + return new PassedInArg(loc, { stack_info, type }); + }; + + const likely_regs = new Map(); + for (const reg of arch.argument_regs) likely_regs.set(reg, true); + const abi = arch.function_abi(fn_sig, likely_regs, { for_call: false }); + for (const slot of abi.arg_slots) { + const type = stack_info.add_known_param(slot.loc, slot.name, slot.type); + if (slot.loc.reg !== null) state.set_initial_reg(slot.loc.reg, make_arg(slot.loc, type), new RegMeta({ uninteresting: true, initial: true })); + } + for (const slot of abi.possible_slots) { + if (slot.loc.reg !== null) state.set_initial_reg(slot.loc.reg, make_arg(slot.loc, slot.type), new RegMeta({ uninteresting: true, initial: true })); + } +} + +/** Given a function, produce a FlowGraph with AST transformations for each block. */ +export function translate_to_ast(fn, flow_graph, options, global_info) { + const persistent_state = global_info.get_persistent_function_state(fn.name); + const stack_info = get_stack_info(fn, persistent_state, global_info, flow_graph); + const state = new NodeState({ node: flow_graph.entry_node(), regs: new RegInfo({ stack_info }), stack_info }); + + setup_planned_vars(stack_info, persistent_state); + setup_reg_vars(stack_info, options); + + const fn_sym = global_info.address_of_gsym(fn.name).expr; + pyassert(fn_sym instanceof GlobalSymbol); + + const fn_type = fn_sym.type; + fn_type.unify(Type.function()); + const fn_sig = Type.ptr(fn_type).get_function_pointer_signature(); + pyassert(fn_sig !== null, "fn_type is known to be a function"); + stack_info.is_variadic = fn_sig.is_variadic; + + setup_initial_registers(state, fn_sig); + + if (options.debug) { + print(String(stack_info)); + print("\nNow, we attempt to translate:"); + } + + const used_naive_phis = []; + const return_blocks = []; + translate_all_blocks(state, used_naive_phis, return_blocks, options); + + const arch = global_info.arch; + for (const [reg] of arch.base_return_regs) propagate_register_meta(flow_graph.nodes, reg); + + const return_type = fn_sig.return_type; + let return_reg = null; + if (!options.void && !return_type.is_void()) return_reg = determine_return_register(return_blocks, fn_sym.type_provided, arch); + + if (return_reg !== null) { + const [reg, is_floating] = return_reg; + if (is_floating) return_type.unify(Type.floatish()); + else return_type.unify(Type.intptr()); + for (const b of return_blocks) { + if (b.final_register_states.has(reg)) { + let ret_val = b.final_register_states.get(reg); + ret_val = as_type(ret_val, return_type, true); + ret_val.use(); + b.return_value = ret_val; + } + } + } else { + return_type.unify(Type.void()); + } + + assign_naive_phis(used_naive_phis, stack_info); + + if (!fn_sig.params_known) { + while (fn_sig.params.length < stack_info.arguments.length) fn_sig.params.push(new FunctionParam()); + const n = Math.min(fn_sig.params.length, stack_info.arguments.length); + for (let i = 0; i < n; i++) { + const param = fn_sig.params[i]; + const arg = stack_info.arguments[i]; + param.type.unify(arg.type); + if (!param.name) param.name = arg.format(new Formatter()); + } + } + + resolve_types_late(stack_info); + return new FunctionInfo(stack_info, flow_graph, return_type, fn_sym); +} + +// Re-exports used by arch modules +export { compare, pyin, has, AssertionError, ArchC }; diff --git a/packages/romdev-m2c/src/types.js b/packages/romdev-m2c/src/types.js new file mode 100644 index 00000000..c50876af --- /dev/null +++ b/packages/romdev-m2c/src/types.js @@ -0,0 +1,1164 @@ +// Port of m2c/types.py +import { c_ast as ca } from "romdev-pycparser"; +import { UndefinedStructError, is_unk_type, parse_constant_int, parse_function, parse_struct, primitive_size, resolve_typedefs, set_decl_name, to_c } from "./c_types.js"; +import { CxxSymbol, CxxTerm } from "./demangle_codewarrior.js"; +import { DecompFailure, assert_never } from "./error.js"; +import { Formatter } from "./options.js"; +import { bnot, compare, floordiv, format, pymod, pyassert, sorted } from "./py.js"; + +/** Mutable shared state for Types, maintaining the set of available struct types. */ +export class TypePool { + constructor({ unknown_field_prefix, unk_inference, union_field_overrides = new Map() }) { + this.unknown_field_prefix = unknown_field_prefix; + this.unk_inference = unk_inference; + this.structs = new Set(); + this.structs_by_tag_name = new Map(); + this.structs_by_ctype = new Map(); + this.unknown_decls = new Map(); + this.warnings = []; + this.union_field_overrides = union_field_overrides; + } + + /** Return the StructDeclaration for a given ctype struct, if known */ + get_struct_for_ctype(ctype) { + const struct = this.structs_by_ctype.get(ctype); + if (struct !== undefined) return struct; + if (ctype.name !== null && ctype.name !== undefined) return this.structs_by_tag_name.get(ctype.name) ?? null; + return null; + } + + get_or_create_struct_by_tag_name(tag_name, typemap, { size = null, with_typedef = false } = {}) { + let struct = this.get_struct_by_tag_name(tag_name, typemap); + if (struct !== null) return struct; + struct = StructDeclaration.unknown(this, size, tag_name, 4); + if (with_typedef) struct.typedef_name = tag_name; + return struct; + } + + get_struct_by_tag_name(tag_name, typemap) { + const struct = this.structs_by_tag_name.get(tag_name); + if (struct !== undefined) return struct; + if (typemap !== null && typemap !== undefined) { + const cstruct = typemap.structs.get(tag_name); + if (cstruct !== undefined) { + const type = Type.ctype(cstruct.type, typemap, this); + return type.get_struct_declaration(); + } + } + return null; + } + + /** Add the struct declaration to the set of known structs for later access */ + add_struct(struct, ctype_or_tag_name) { + this.structs.add(struct); + let tag_name; + if (typeof ctype_or_tag_name === "string") tag_name = ctype_or_tag_name; + else { + const ctype = ctype_or_tag_name; + tag_name = ctype.name ?? null; + this.structs_by_ctype.set(ctype, struct); + } + if (tag_name !== null) { + pyassert(!this.structs_by_tag_name.has(tag_name), `Duplicate tag: ${tag_name}`); + this.structs_by_tag_name.set(tag_name, struct); + } + } + + format_type_declarations(fmt, stack_structs) { + const decls = []; + for (const struct of sorted(this.structs, (s) => s.tag_name || s.typedef_name || "")) { + if (!stack_structs && struct.is_stack) continue; + if (struct.fields.some((f) => !f.known) || struct.is_stack) decls.push(struct.format(fmt) + "\n"); + } + return decls.join("\n"); + } + + /** Remove overlapping fields from all known structs */ + prune_structs() { + for (const struct of this.structs) { + struct.prune_overlapping_fields(); + struct.rename_inferred_vtables(); + } + } +} + +export class TypeData { + static K_INT = 1 << 0; + static K_PTR = 1 << 1; + static K_FLOAT = 1 << 2; + static K_FN = 1 << 3; + static K_VOID = 1 << 4; + static K_ARRAY = 1 << 5; + static K_STRUCT = 1 << 6; + static K_INTPTR = TypeData.K_INT | TypeData.K_PTR; + static K_ANYREG = TypeData.K_INT | TypeData.K_PTR | TypeData.K_FLOAT; + static K_ANY = TypeData.K_INT | TypeData.K_PTR | TypeData.K_FLOAT | TypeData.K_FN | TypeData.K_VOID | TypeData.K_ARRAY | TypeData.K_STRUCT; + static SIGNED = 1; + static UNSIGNED = 2; + static ANY_SIGN = 3; + + constructor({ + kind = TypeData.K_ANY, + likely_kind = TypeData.K_ANY, + size_bits = null, + uf_parent = null, + sign = TypeData.ANY_SIGN, + ptr_to = null, + fn_sig = null, + array_dim = null, + struct = null, + enum: enum_ = null, + new_field_within = new Set(), + } = {}) { + this.kind = kind; + this.likely_kind = likely_kind; + this.size_bits = size_bits; + this.uf_parent = uf_parent; + this.sign = sign; + this.ptr_to = ptr_to; + this.fn_sig = fn_sig; + this.array_dim = array_dim; + this.struct = struct; + this.enum = enum_; + this.new_field_within = new_field_within; + pyassert(this.kind); + this.likely_kind &= this.kind; + } + + get_representative() { + const equivalent_typedatas = new Set(); + let root = this; + while (root.uf_parent !== null) { + pyassert(!equivalent_typedatas.has(root), "TypeData cycle detected"); + equivalent_typedatas.add(root); + root = root.uf_parent; + } + for (const td of equivalent_typedatas) td.uf_parent = root; + return root; + } +} + +const DEBUG_REPR_IDS = new Map(); + +/** + * Type information for an expression, which may improve over time. + */ +export class Type { + constructor(_data) { + this._data = _data; + } + + /** Try to set this type equal to another. Returns true on success. */ + unify(other, { seen = null } = {}) { + const x = this.data(); + const y = other.data(); + if (x === y) return true; + + if (seen === null) seen = new Set([x, y]); + else if (seen.has(x) || seen.has(y)) return false; + else seen = new Set([...seen, x, y]); + + if (x.size_bits !== null && y.size_bits !== null && x.size_bits !== y.size_bits) return false; + + let kind = x.kind & y.kind; + let likely_kind = x.likely_kind & y.likely_kind; + let size_bits = x.size_bits !== null ? x.size_bits : y.size_bits; + const ptr_to = x.ptr_to !== null ? x.ptr_to : y.ptr_to; + const fn_sig = x.fn_sig !== null ? x.fn_sig : y.fn_sig; + let array_dim = x.array_dim !== null ? x.array_dim : y.array_dim; + const struct = x.struct !== null ? x.struct : y.struct; + const enum_ = x.enum !== null ? x.enum : y.enum; + const sign = x.sign & y.sign; + if (![null, 32, 64].includes(size_bits)) kind &= ~TypeData.K_FLOAT; + if (![null, 32].includes(size_bits)) kind &= ~TypeData.K_PTR; + if (![null].includes(size_bits)) kind &= ~TypeData.K_FN; + if (![null, 0].includes(size_bits)) kind &= ~TypeData.K_VOID; + likely_kind &= kind; + if (kind === 0 || sign === 0) return false; + if (kind === TypeData.K_PTR) size_bits = 32; + if (sign !== TypeData.ANY_SIGN) pyassert(kind & TypeData.K_INTPTR); + if (enum_ !== null) pyassert(kind === TypeData.K_INT); + if (x.ptr_to !== null && y.ptr_to !== null) { + if (!x.ptr_to.unify(y.ptr_to, { seen })) return false; + } + if (x.fn_sig !== null && y.fn_sig !== null) { + if (!x.fn_sig.unify(y.fn_sig, { seen })) return false; + } + if (x.array_dim !== null && y.array_dim !== null) { + if (kind === TypeData.K_ARRAY) { + if (x.array_dim !== y.array_dim) return false; + } else { + pyassert(kind === TypeData.K_PTR); + if (x.array_dim !== y.array_dim) array_dim = 0; + } + } + if (x.struct !== null && y.struct !== null) { + if (!x.struct.unify(y.struct, { seen })) return false; + } + if (x.enum !== null && y.enum !== null) { + if (x.enum !== y.enum) return false; + } + if (x.new_field_within.has(y.struct) || y.new_field_within.has(x.struct)) return false; + x.kind = kind; + x.likely_kind = likely_kind; + x.size_bits = size_bits; + x.sign = sign; + x.ptr_to = ptr_to; + x.fn_sig = fn_sig; + x.array_dim = array_dim; + x.struct = struct; + x.enum = enum_; + for (const s of y.new_field_within) x.new_field_within.add(s); + y.uf_parent = x; + return true; + } + + data() { + if (this._data.uf_parent === null) return this._data; + this._data = this._data.get_representative(); + return this._data; + } + + is_float() { + return this.data().kind === TypeData.K_FLOAT; + } + is_likely_float() { + const data = this.data(); + return data.kind === TypeData.K_FLOAT || data.likely_kind === TypeData.K_FLOAT; + } + is_pointer() { + return this.data().kind === TypeData.K_PTR; + } + is_pointer_or_array() { + const k = this.data().kind; + return k === TypeData.K_PTR || k === TypeData.K_ARRAY; + } + is_int() { + return this.data().kind === TypeData.K_INT; + } + is_reg() { + return (this.data().kind & ~TypeData.K_ANYREG) === 0; + } + is_function() { + return this.data().kind === TypeData.K_FN; + } + is_void() { + return this.data().kind === TypeData.K_VOID; + } + is_array() { + return this.data().kind === TypeData.K_ARRAY; + } + is_struct() { + return this.data().kind === TypeData.K_STRUCT; + } + is_signed() { + return this.data().sign === TypeData.SIGNED; + } + is_unsigned() { + return this.data().sign === TypeData.UNSIGNED; + } + get_enum_name(value) { + const data = this.data(); + if (data.enum === null) return null; + return data.enum.names.get(value) ?? null; + } + get_size_bits() { + return this.data().size_bits; + } + get_size_bytes() { + const size_bits = this.get_size_bits(); + return size_bits === null ? null : floordiv(size_bits, 8); + } + + /** Return the size & alignment of self when used as a function argument */ + get_parameter_size_align_bytes() { + const data = this.data(); + if (this.is_struct()) { + pyassert(data.struct !== null); + if (data.struct.size === null) throw new DecompFailure(`Cannot use incomplete type ${this} as parameter`); + return [data.struct.size, data.struct.align]; + } + const size = floordiv(this.get_size_bits() || 32, 8); + return [size, size]; + } + + /** If self is a pointer-to-a-Type, return the Type */ + get_pointer_target() { + const data = this.data(); + if (this.is_pointer() && data.ptr_to !== null) return data.ptr_to; + return null; + } + + /** Return a pointer to self. If self is an array, decay the type to a pointer */ + reference() { + if (this.is_array()) { + const data = this.data(); + pyassert(data.ptr_to !== null); + return Type.ptr(data.ptr_to, { array_dim: data.array_dim }); + } + return Type.ptr(this); + } + + /** If self is an array, return a pointer to the element type. Otherwise, return self. */ + decay() { + if (this.is_array()) { + const data = this.data(); + pyassert(data.ptr_to !== null); + return Type.ptr(data.ptr_to, { array_dim: data.array_dim }); + } + return this; + } + + /** If self is an explicit `void *`, return `Type.ptr()` without an target type. */ + weaken_void_ptr() { + const target = this.get_pointer_target(); + if (target !== null && target.is_void()) return Type.ptr(); + return this; + } + + /** If self is an array, return [inner Type, array dimension] */ + get_array() { + if (!this.is_array()) return [null, null]; + const data = this.data(); + pyassert(data.ptr_to !== null); + return [data.ptr_to, data.array_dim]; + } + + /** If self is a function pointer, return the FunctionSignature */ + get_function_pointer_signature() { + const data = this.data(); + if (this.is_pointer() && data.ptr_to !== null) { + const ptr_to = data.ptr_to.data(); + if (ptr_to.kind === TypeData.K_FN) return ptr_to.fn_sig; + } + return null; + } + + /** If self is a struct, return the StructDeclaration */ + get_struct_declaration() { + if (this.is_struct()) { + const data = this.data(); + pyassert(data.struct !== null); + return data.struct; + } + return null; + } + + clone_literal_type() { + const data = this.data(); + const size_bits = data.size_bits === 64 ? 64 : null; + return new Type(new TypeData({ kind: TypeData.K_ANYREG, likely_kind: data.likely_kind, size_bits })); + } + + static _no_matching_field() { + return [null, Type.any(), 0]; + } + + /** + * Locate the field in self at the appropriate offset, and optionally with an exact + * target size (both values in bytes). Returns [field_path, field_type, remaining_offset]. + */ + get_field(offset, { target_size, exact = true }) { + if (offset < 0) return Type._no_matching_field(); + + if (this.is_array()) { + const data = this.data(); + pyassert(data.ptr_to !== null); + const size = data.ptr_to.get_size_bytes(); + pyassert(size !== null); + const index = floordiv(offset, size); + const remaining_offset = pymod(offset, size); + if (data.array_dim !== null && index >= data.array_dim) return Type._no_matching_field(); + pyassert(index >= 0 && remaining_offset >= 0); + const [subpath, subtype, sub_remaining_offset] = data.ptr_to.get_field(remaining_offset, { target_size, exact }); + if (subpath !== null) { + subpath.unshift(index); + return [subpath, subtype, sub_remaining_offset]; + } + return Type._no_matching_field(); + } + + if (this.is_struct()) { + const data = this.data(); + pyassert(data.struct !== null); + if (data.struct.size !== null && offset >= data.struct.size) return Type._no_matching_field(); + + let possible_fields = data.struct.fields_containing_offset(offset); + if (!possible_fields.length && data.struct.has_bitfields) return Type._no_matching_field(); + + const possible_results = []; + if (!data.struct.is_stack && (target_size === null || target_size === this.get_size_bytes())) possible_results.push([[], this, offset]); + + if (data.struct.is_union && data.struct.preferred_union_field) { + possible_fields = possible_fields.filter((field) => field.name === data.struct.preferred_union_field); + } + + for (const field of possible_fields) { + const inner_offset_bits = offset - field.offset; + const [subpath, subtype, sub_remaining_offset] = field.type.get_field(inner_offset_bits, { target_size, exact }); + if (subpath === null) continue; + subpath.unshift(field.name); + possible_results.push([subpath, subtype, sub_remaining_offset]); + if (target_size !== null && target_size === subtype.get_size_bytes() && sub_remaining_offset === 0) return possible_results[possible_results.length - 1]; + } + + const zero_offset_results = possible_results.filter((r) => r[2] === 0); + if (zero_offset_results.length) return zero_offset_results[0]; + else if (exact) { + const field_type = Type.any_field({ new_within: data.struct }); + const field_name = `${data.struct.new_field_prefix}${format(offset, "X")}`; + const new_field = data.struct.try_add_field(field_type, offset, field_name, target_size); + if (new_field !== null) return [[field_name], field_type, 0]; + } else if (possible_results.length) return possible_results[0]; + } + + if ((target_size === null || target_size === this.get_size_bytes()) && offset === 0) return [[], this, offset]; + + return Type._no_matching_field(); + } + + /** Similar to `.get_field()`, but treat self as a pointer and find the field in the pointer's target. */ + get_deref_field(offset, { target_size, exact = true }) { + const target = this.get_pointer_target(); + if (target === null) return Type._no_matching_field(); + + const size = target.get_size_bytes(); + let array_index; + if (size !== null && size !== 0) { + array_index = floordiv(offset, size); + offset = pymod(offset, size); + } else array_index = 0; + + if (array_index !== 0) { + const known_array_size = this.data().array_dim; + if (known_array_size === null || array_index < 0 || array_index >= known_array_size) return Type._no_matching_field(); + } + + const [field_path, field_type, remaining_offset] = target.get_field(offset, { target_size, exact }); + if (field_path !== null) field_path.unshift(array_index); + return [field_path, field_type, remaining_offset]; + } + + /** + * If self is a struct or array, return a list of fields suitable for creating an + * initializer; padding is represented by an int. + */ + get_initializer_fields() { + const data = this.data(); + if (this.is_array()) { + pyassert(data.ptr_to !== null); + if (data.array_dim === null) return null; + return new Array(Math.max(0, data.array_dim)).fill(data.ptr_to); + } + if (this.is_struct()) { + pyassert(data.struct !== null); + if (data.struct.has_bitfields) return null; + const output = []; + let position = 0; + const add_padding = (upto) => { + pyassert(upto >= position); + if (upto > position) output.push(upto - position); + }; + for (const field of data.struct.fields) { + if (field.offset < position) return null; + add_padding(field.offset); + const field_size = field.type.get_size_bytes(); + if (field_size === null) return null; + output.push(field.type); + position = field.offset + field_size; + if (data.struct.is_union) break; + } + if (data.struct.size !== null && position > data.struct.size) return null; + add_padding(data.struct.min_size()); + return output; + } + return null; + } + + to_decl(name, fmt) { + const decl = new ca.Decl(name, [], [], [], [], [], this._to_ctype(new Set(), fmt), null, null, null); + set_decl_name(decl); + let ret = to_c(decl); + if (fmt.coding_style.pointer_style_left) { + for (;;) { + const replaced = ret.replaceAll(" *", "* ").replaceAll("* )", "*)").replaceAll("* ,", "*,"); + if (replaced === ret) break; + ret = replaced; + } + } + return ret; + } + + _to_ctype(seen, fmt) { + const simple_ctype = (typename) => new ca.TypeDecl(null, [], [], new ca.IdentifierType([typename])); + const unk_symbol = fmt.valid_syntax ? "M2C_UNK" : "?"; + + const data = this.data(); + if (seen.has(data)) return simple_ctype(unk_symbol); + seen.add(data); + const size_bits = data.size_bits || 32; + const sign = data.sign & TypeData.SIGNED ? "s" : "u"; + + if (data.enum !== null && data.enum.tag !== null && data.enum.tag !== undefined) { + pyassert(data.kind === TypeData.K_INT); + return new ca.TypeDecl(null, [], [], new ca.Enum(data.enum.tag, [], null)); + } + + const lk = data.likely_kind & (TypeData.K_INT | TypeData.K_FLOAT); + if ((data.kind & TypeData.K_ANYREG) === TypeData.K_ANYREG && lk !== TypeData.K_INT && lk !== TypeData.K_FLOAT) { + if (data.size_bits !== null) return simple_ctype(`${unk_symbol}${size_bits}`); + return simple_ctype(unk_symbol); + } + + if (data.kind === TypeData.K_FLOAT || (data.likely_kind & (TypeData.K_FLOAT | TypeData.K_INT)) === TypeData.K_FLOAT) return simple_ctype(`f${size_bits}`); + + if (data.kind === TypeData.K_PTR) { + let target_ctype; + if (data.ptr_to === null) target_ctype = simple_ctype("void"); + else target_ctype = data.ptr_to._to_ctype(new Set(seen), fmt); + if (target_ctype instanceof ca.FuncDecl && target_ctype.args) { + for (const arg of target_ctype.args.params) { + if (arg instanceof ca.Decl) { + arg.name = null; + set_decl_name(arg); + } + } + } + return new ca.PtrDecl([], target_ctype); + } + + if (data.kind === TypeData.K_FN) { + pyassert(data.fn_sig !== null); + const return_ctype = data.fn_sig.return_type._to_ctype(new Set(seen), fmt); + const params = []; + for (const param of data.fn_sig.params) { + const decl = new ca.Decl(param.name, [], [], [], [], [], param.type._to_ctype(new Set(seen), fmt), null, null, null); + set_decl_name(decl); + params.push(decl); + } + if (data.fn_sig.is_variadic) params.push(new ca.EllipsisParam()); + return new ca.FuncDecl(new ca.ParamList(params), return_ctype); + } + + if (data.kind === TypeData.K_VOID) return simple_ctype("void"); + + if (data.kind === TypeData.K_ARRAY) { + pyassert(data.ptr_to !== null); + let dim = null; + if (data.array_dim !== null) dim = new ca.Constant("", fmt.format_int(data.array_dim)); + return new ca.ArrayDecl(data.ptr_to._to_ctype(new Set(seen), fmt), dim, []); + } + + if (data.kind === TypeData.K_STRUCT) { + pyassert(data.struct !== null); + if (data.struct.typedef_name) return simple_ctype(data.struct.typedef_name); + const name = data.struct.tag_name || "_anonymous"; + const type = data.struct.is_union ? new ca.Union(name, [], null) : new ca.Struct(name, [], null); + return new ca.TypeDecl(name, [], [], type); + } + + return simple_ctype(`${sign}${size_bits}`); + } + + format(fmt) { + return this.to_decl("", fmt); + } + toString() { + return this.format(new Formatter({ debug: true })); + } + __repr__() { + const data = this.data(); + const signstr = (data.sign & TypeData.SIGNED ? "+" : "") + (data.sign & TypeData.UNSIGNED ? "-" : ""); + const kindstr = + (data.kind & TypeData.K_INT ? "I" : "") + + (data.kind & TypeData.K_PTR ? "P" : "") + + (data.kind & TypeData.K_FLOAT ? "F" : "") + + (data.kind & TypeData.K_FN ? "N" : "") + + (data.kind & TypeData.K_VOID ? "V" : "") + + (data.kind & TypeData.K_ARRAY ? "A" : "") + + (data.kind & TypeData.K_STRUCT ? "S" : ""); + const sizestr = data.size_bits !== null ? String(data.size_bits) : "?"; + if (!DEBUG_REPR_IDS.has(data)) DEBUG_REPR_IDS.set(data, DEBUG_REPR_IDS.size); + return `Type(${signstr + kindstr + sizestr})@${DEBUG_REPR_IDS.get(data)}`; + } + + static any() { + return new Type(new TypeData()); + } + static any_reg() { + return new Type(new TypeData({ kind: TypeData.K_ANYREG })); + } + static any_field({ new_within = null } = {}) { + return new Type(new TypeData({ kind: TypeData.K_ANY & ~TypeData.K_VOID, new_field_within: new_within ? new Set([new_within]) : new Set() })); + } + static intish() { + return new Type(new TypeData({ kind: TypeData.K_INT })); + } + static uintish() { + return new Type(new TypeData({ kind: TypeData.K_INT, sign: TypeData.UNSIGNED })); + } + static sintish() { + return new Type(new TypeData({ kind: TypeData.K_INT, sign: TypeData.SIGNED })); + } + static intptr() { + return new Type(new TypeData({ kind: TypeData.K_INTPTR })); + } + static uintptr() { + return new Type(new TypeData({ kind: TypeData.K_INTPTR, sign: TypeData.UNSIGNED })); + } + static sintptr() { + return new Type(new TypeData({ kind: TypeData.K_INTPTR, sign: TypeData.SIGNED })); + } + static ptr(type = null, { array_dim = null } = {}) { + return new Type(new TypeData({ kind: TypeData.K_PTR, size_bits: 32, array_dim, ptr_to: type })); + } + static function(fn_sig = null) { + if (fn_sig === null) fn_sig = new FunctionSignature(); + return new Type(new TypeData({ kind: TypeData.K_FN, fn_sig })); + } + static f32() { + return new Type(new TypeData({ kind: TypeData.K_FLOAT, size_bits: 32 })); + } + static floatish() { + return new Type(new TypeData({ kind: TypeData.K_FLOAT })); + } + static f64() { + return new Type(new TypeData({ kind: TypeData.K_FLOAT, size_bits: 64 })); + } + static f128() { + return new Type(new TypeData({ kind: TypeData.K_FLOAT, size_bits: 128 })); + } + static s8() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 8, sign: TypeData.SIGNED })); + } + static u8() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 8, sign: TypeData.UNSIGNED })); + } + static s16() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 16, sign: TypeData.SIGNED })); + } + static u16() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 16, sign: TypeData.UNSIGNED })); + } + static s32() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 32, sign: TypeData.SIGNED })); + } + static u32() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 32, sign: TypeData.UNSIGNED })); + } + static s64() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 64, sign: TypeData.SIGNED })); + } + static u64() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 64, sign: TypeData.UNSIGNED })); + } + static int64() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 64 })); + } + static int_of_size(size_bits) { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits })); + } + static reg32({ likely_float }) { + const likely = likely_float ? TypeData.K_FLOAT : TypeData.K_INTPTR; + return new Type(new TypeData({ kind: TypeData.K_ANYREG, likely_kind: likely, size_bits: 32 })); + } + static reg64({ likely_float }) { + const kind = TypeData.K_FLOAT | TypeData.K_INT; + const likely = likely_float ? TypeData.K_FLOAT : TypeData.K_INT; + return new Type(new TypeData({ kind, likely_kind: likely, size_bits: 64 })); + } + static reg128() { + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 128 })); + } + static boolean() { + return Type.intish(); + } + static void() { + return new Type(new TypeData({ kind: TypeData.K_VOID, size_bits: 0 })); + } + static array(type, dim) { + const el_size = type.get_size_bits(); + pyassert(el_size !== null); + const size_bits = dim === null ? null : el_size * dim; + return new Type(new TypeData({ kind: TypeData.K_ARRAY, size_bits, ptr_to: type, array_dim: dim })); + } + static struct(st) { + const size_bits = st.size !== null ? st.size * 8 : null; + return new Type(new TypeData({ kind: TypeData.K_STRUCT, size_bits, struct: st })); + } + + static gsym_unk_ctype(ctype, typemap, typepool) { + const [real_ctype] = resolve_typedefs(ctype, typemap); + let type = Type.any(); + if (real_ctype instanceof ca.TypeDecl && real_ctype.type instanceof ca.IdentifierType) { + const size_bits = primitive_size(real_ctype.type) * 8; + if (size_bits < 32) type = Type.int_of_size(size_bits); + } + if (ctype instanceof ca.TypeDecl && ctype.declname) { + if (typepool.unknown_decls.has(ctype.declname)) return typepool.unknown_decls.get(ctype.declname); + typepool.unknown_decls.set(ctype.declname, type); + } + return type; + } + + static ctype(ctype, typemap, typepool, { in_struct = false } = {}) { + const [real_ctype] = resolve_typedefs(ctype, typemap); + + if (real_ctype instanceof ca.ArrayDecl) { + let dim = null; + try { + if (real_ctype.dim !== null && real_ctype.dim !== undefined) dim = parse_constant_int(real_ctype.dim, typemap); + else if (in_struct) dim = 1; + } catch (e) { + if (!(e instanceof DecompFailure)) throw e; + } + const elem_type = Type.ctype(real_ctype.type, typemap, typepool); + return Type.array(elem_type, dim); + } + if (real_ctype instanceof ca.PtrDecl) return Type.ptr(Type.ctype(real_ctype.type, typemap, typepool)); + if (real_ctype instanceof ca.FuncDecl) { + const fn = parse_function(real_ctype); + pyassert(fn !== null); + const fn_sig = new FunctionSignature({ return_type: Type.void(), is_variadic: fn.is_variadic }); + if (fn.ret_type !== null) fn_sig.return_type = Type.ctype(fn.ret_type, typemap, typepool); + if (fn.params !== null) { + fn_sig.params = fn.params.map((param) => new FunctionParam({ name: param.name || "", type: Type.ctype(param.type, typemap, typepool) })); + fn_sig.params_known = true; + } + return Type.function(fn_sig); + } + if (real_ctype instanceof ca.TypeDecl) { + const inner_type = real_ctype.type; + if (inner_type instanceof ca.Struct || inner_type instanceof ca.Union) return Type.struct(StructDeclaration.from_ctype(inner_type, typemap, typepool)); + if (inner_type instanceof ca.Enum) { + let enum_ = null; + if (inner_type.name !== null && inner_type.name !== undefined) enum_ = typemap.enums.get(inner_type.name) ?? null; + if (enum_ === null) enum_ = typemap.enums.get(inner_type) ?? null; + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 32, sign: TypeData.SIGNED, enum: enum_ })); + } + pyassert(!(inner_type instanceof ca.Typeof), "handled by resolve_typedefs"); + const names = inner_type.names; + if (names.includes("double")) return Type.f64(); + if (names.includes("float")) return Type.f32(); + if (names.includes("void")) return Type.void(); + const size_bits = 8 * primitive_size(inner_type); + pyassert(size_bits > 0); + const sign = names.includes("unsigned") ? TypeData.UNSIGNED : TypeData.SIGNED; + return new Type(new TypeData({ kind: TypeData.K_INT, size_bits, sign })); + } + assert_never(real_ctype); + } + + static demangled_symbol(typemap, typepool, sym) { + return Type.demangled_type(typemap, typepool, sym.type, sym.name); + } + + static demangled_type(typemap, typepool, sym_type, sym_name = null) { + const type_for_class = (qualified_name) => { + const class_name = qualified_name.map((n) => String(n)).join("::"); + const class_struct = typepool.get_or_create_struct_by_tag_name(class_name, typemap, { size: null, with_typedef: true }); + return Type.struct(class_struct); + }; + + let final_name = null; + if (sym_name !== null && sym_name !== undefined) { + pyassert(sym_name.kind === CxxTerm.Kind.QUALIFIED); + pyassert(sym_name.qualified_name !== null && sym_name.qualified_name !== undefined); + pyassert(sym_name.qualified_name.length >= 1); + const parts = String(sym_name.qualified_name[sym_name.qualified_name.length - 1]).split("@"); + final_name = parts[parts.length - 1]; + } + + if (final_name === "__vt") return Type.any(); + if (final_name === "__RTTI") return Type.struct(typepool.get_or_create_struct_by_tag_name("RTTI", typemap, { size: 8 })); + + let type = Type.any(); + const K = CxxTerm.Kind; + for (const term of [...sym_type.terms].reverse()) { + if (term.kind === K.CONST) { + // pass + } else if (term.kind === K.POINTER || term.kind === K.REFERENCE) type = Type.ptr(type); + else if (term.kind === K.BOOL) type = Type.boolean(); + else if (term.kind === K.CHAR) type = Type.int_of_size(8); + else if (term.kind === K.SHORT || term.kind === K.WIDE_CHAR) type = Type.int_of_size(16); + else if (term.kind === K.INT || term.kind === K.LONG) type = Type.int_of_size(32); + else if (term.kind === K.LONG_LONG) type = Type.int_of_size(64); + else if (term.kind === K.FLOAT) type = Type.f32(); + else if (term.kind === K.DOUBLE) type = Type.f64(); + else if (term.kind === K.LONG_DOUBLE) type = Type.f128(); + else if (term.kind === K.SIGNED) type.unify(new Type(new TypeData({ kind: TypeData.K_INT, sign: TypeData.SIGNED }))); + else if (term.kind === K.UNSIGNED) type.unify(new Type(new TypeData({ kind: TypeData.K_INT, sign: TypeData.UNSIGNED }))); + else if (term.kind === K.ARRAY) { + pyassert(term.array_dim !== null && term.array_dim !== undefined, "array CxxTerms must have array_dim"); + type = Type.array(type, term.array_dim); + } else if (term.kind === K.FUNCTION) { + pyassert(term.function_params !== null && term.function_params !== undefined); + const params = []; + if (sym_name !== null && sym_name !== undefined && sym_name.qualified_name !== null && sym_name.qualified_name !== undefined && sym_name.qualified_name.length > 1 && !CxxSymbol.STATIC_FUNCTIONS.has(final_name)) { + const class_type = type_for_class(sym_name.qualified_name.slice(0, -1)); + params.push(new FunctionParam({ type: Type.ptr(class_type), name: "this" })); + } + if (final_name === "__dt") params.push(new FunctionParam({ type: Type.s16(), name: "destroyFlag" })); + let is_variadic = false; + term.function_params.forEach((param_type, i) => { + const name = `arg${i}`; + if (param_type.terms[0].kind === K.VOID) pyassert(term.function_params.length === 1); + else if (param_type.terms[0].kind === K.ELLIPSIS) { + pyassert(i === term.function_params.length - 1); + is_variadic = true; + } else params.push(new FunctionParam({ type: Type.demangled_type(typemap, typepool, param_type), name })); + }); + let return_type = Type.any(); + if (term.function_return !== null && term.function_return !== undefined) return_type = Type.demangled_type(typemap, typepool, term.function_return); + else if (final_name === "__ct" || final_name === "__dt") return_type = Type.ptr(); + type = Type.function(new FunctionSignature({ params, params_known: true, is_variadic, return_type })); + } else if (term.kind === K.QUALIFIED) { + pyassert(term.qualified_name !== null && term.qualified_name !== undefined); + type = type_for_class(term.qualified_name); + } else if (term.kind === K.VOID) type = Type.void(); + else if (term.kind === K.ELLIPSIS) pyassert(false, String(term.kind)); + else pyassert(false, String(term.kind)); + } + return type; + } +} + +export class FunctionParam { + constructor({ type = Type.any(), name = "" } = {}) { + this.type = type; + this.name = name; + } +} + +export class FunctionSignature { + constructor({ return_type = Type.any(), params = [], params_known = false, is_variadic = false } = {}) { + this.return_type = return_type; + this.params = params; + this.params_known = params_known; + this.is_variadic = is_variadic; + } + + unify(other, { seen }) { + if (this.params_known && other.params_known) { + if (this.is_variadic !== other.is_variadic) return false; + if (this.params.length !== other.params.length) return false; + } + let can_unify = this.return_type.unify(other.return_type, { seen }); + const n = Math.min(this.params.length, other.params.length); + for (let i = 0; i < n; i++) can_unify = this.params[i].type.unify(other.params[i].type, { seen }) && can_unify; + if (!can_unify) return false; + + if (!this.params_known) { + this.is_variadic = this.is_variadic || other.is_variadic; + this.params_known = this.params_known || other.params_known; + while (other.params.length > this.params.length) this.params.push(other.params[this.params.length]); + } + if (!other.params_known) { + other.is_variadic = other.is_variadic || this.is_variadic; + other.params_known = other.params_known || this.params_known; + while (this.params.length > other.params.length) other.params.push(this.params[other.params.length]); + } + + const m = Math.min(this.params.length, other.params.length); + for (let i = 0; i < m; i++) { + const x = this.params[i]; + const y = other.params[i]; + if (!x.name && y.name) x.name = y.name; + else if (!y.name && x.name) y.name = x.name; + } + return true; + } + + /** Unify a function's signature with a list of argument types (at a callsite). */ + unify_with_args(concrete) { + if (this.params.length > concrete.params.length) return false; + if (!this.is_variadic && this.params.length !== concrete.params.length) return false; + let can_unify = true; + const n = Math.min(this.params.length, concrete.params.length); + for (let i = 0; i < n; i++) can_unify = this.params[i].type.unify(concrete.params[i].type) && can_unify; + return can_unify; + } +} + +class StructField { + constructor({ type, offset, name, known }) { + this.type = type; + this.offset = offset; + this.name = name; + this.known = known; + } +} + +class BitField { + constructor({ bit_offset, bit_width, name }) { + this.bit_offset = bit_offset; + this.bit_width = bit_width; + this.name = name; + } +} + +/** Representation of a C struct or union */ +export class StructDeclaration { + static StructField = StructField; + static BitField = BitField; + + constructor({ + size, + align, + new_field_prefix, + tag_name = null, + typedef_name = null, + fields = [], + bitfields = [], + has_bitfields = false, + is_union = false, + is_stack = false, + preferred_union_field = null, + }) { + this.size = size; + this.align = align; + this.new_field_prefix = new_field_prefix; + this.tag_name = tag_name; + this.typedef_name = typedef_name; + this.fields = fields; // sorted by `.offset` + this.bitfields = bitfields; // sorted by `.bit_offset` + this.has_bitfields = has_bitfields; + this.is_union = is_union; + this.is_stack = is_stack; + this.preferred_union_field = preferred_union_field; + } + + StructField(f) { + return new StructField(f); + } + + min_size() { + if (this.size !== null) return this.size; + let m = 0; + for (const field of this.fields) m = Math.max(m, field.offset + (field.type.get_size_bytes() || 1)); + return m; + } + + unify(other, { seen = null } = {}) { + void seen; + return this === other; + } + + /** Return the list of StructFields which contain the given offset (in bytes) */ + fields_containing_offset(offset) { + const fields = []; + for (const field of this.fields) { + if (field.offset > offset) break; + const field_size = field.type.get_size_bytes() || 1; + if (field.offset + field_size <= offset) continue; + fields.push(field); + } + return fields; + } + + /** Try to add a field into the struct, and return it if successful. */ + try_add_field(type, offset, name, size) { + if (this.is_union) return null; + if (this.size !== null && !(0 <= offset && offset < this.size)) return null; + size = size || 1; + for (const field of this.fields) { + const field_size = field.type.get_size_bytes() || 1; + if (offset <= field.offset && field.offset < offset + size) return null; + if (field.offset <= offset && offset < field.offset + field_size) return null; + } + const field = new StructField({ type, offset, name, known: false }); + this.fields.push(field); + this.fields = sorted(this.fields, (f) => f.offset); + return field; + } + + /** Remove overlapping fields with `known=False` from the struct */ + prune_overlapping_fields() { + if (this.is_union) return null; + this.fields = sorted(this.fields, (f) => [f.offset, -(f.type.get_size_bytes() || 0)]); + + let end_pseudofield; + if (this.size !== null) end_pseudofield = [new StructField({ offset: this.size, type: Type.void(), known: true, name: "" })]; + else end_pseudofield = []; + + const fields_to_remove = new Set(); + this.fields.forEach((field, i) => { + if (field.known || fields_to_remove.has(field)) return; + const field_size = field.type.get_size_bytes() || 1; + let conflicting_fields = []; + for (const f2 of [...this.fields.slice(i + 1), ...end_pseudofield]) { + pyassert(f2.offset >= field.offset); + if (f2.offset >= field.offset + field_size) break; + if (fields_to_remove.has(f2)) continue; + let offset = f2.offset - field.offset; + const [sub_path, sub_type] = field.type.get_field(offset, { target_size: f2.type.get_size_bytes() }); + if (sub_path !== null && sub_type.unify(f2.type)) { + conflicting_fields.push(f2); + } else if (!f2.known && f2.type.is_int() && field.type.is_int()) { + // pass + } else { + if (conflicting_fields.length) { + offset = conflicting_fields[0].offset - field.offset; + conflicting_fields = []; + } + if (offset === 0) conflicting_fields = [field]; + if (offset >= 4) field.type = Type.any_reg(); + else field.type = Type.int_of_size(offset * 8); + break; + } + } + for (const f of conflicting_fields) fields_to_remove.add(f); + }); + this.fields = this.fields.filter((f) => !fields_to_remove.has(f)); + } + + /** Rename inferred fields that are pointers to vtables */ + rename_inferred_vtables() { + const sep = this.new_field_prefix.endsWith("_") ? "_" : ""; + for (const field of this.fields) { + if (field.known || !field.name.startsWith(this.new_field_prefix)) continue; + const type_ptr = field.type.get_pointer_target(); + if (type_ptr === null) continue; + const struct = type_ptr.get_struct_declaration(); + if (struct === null || struct.tag_name === null) continue; + if (struct.tag_name.startsWith("__vt__")) { + const name = field.name.replace(this.new_field_prefix, `vtable${sep}`); + if (!this.fields.some((f) => f.name === name)) field.name = name; + } + } + } + + /** Return the C representation of the struct/union. */ + format(fmt) { + const keyword = this.is_union ? "union" : "struct"; + const decl = this.tag_name ? `${keyword} ${this.tag_name}` : `${keyword}`; + const head = this.typedef_name ? `typedef ${decl} {` : `${decl} {`; + const tail = this.typedef_name ? `} ${this.typedef_name};` : "};"; + + if (this.size === 0 && !this.fields.length) return fmt.with_comments(head + tail, ["size 0x0"]); + + const lines = []; + lines.push(fmt.indent(head)); + let position = 0; + fmt.indented(() => { + const offset_str_digits = fmt.format_hex(this.min_size()).length; + const offset_comment = (offset) => `/* 0x${fmt.format_hex(offset).padStart(offset_str_digits, "0")} */`; + let prev_field = null; + + const pad_to = (offset, is_final) => { + if (position < offset) { + const underscore = fmt.coding_style.unknown_underscore ? "_" : ""; + const name = `pad${underscore}${fmt.format_hex(position)}`; + const padding_size = offset - position; + const comments = []; + if (prev_field !== null && !(is_final && this.is_stack)) { + const last_size = prev_field.type.get_size_bytes(); + if (last_size && padding_size > last_size) { + const array_dim_str = fmt.format_int(floordiv(padding_size, last_size) + 1); + comments.push(`maybe part of ${prev_field.name}[${array_dim_str}]?`); + } + } + lines.push(fmt.with_comments(`${offset_comment(position)} char ${name}[${fmt.format_int(padding_size)}];`, comments)); + position = offset; + } + }; + + for (const field of this.fields) { + pad_to(field.offset, false); + const field_decl = `${offset_comment(field.offset)} ${field.type.to_decl(field.name, fmt)};`; + const comments = []; + if (!this.is_union && position > field.offset) comments.push("overlap"); + if (this.is_union && field.offset !== 0) comments.push("offset"); + if (!field.known) comments.push("inferred"); + lines.push(fmt.with_comments(field_decl, comments)); + const s = field.type.get_struct_declaration(); + if (s !== null) field.type.unify(Type.struct(s)); + position = Math.max(position, field.offset + (field.type.get_size_bytes() || 0)); + prev_field = field; + } + pad_to(this.min_size(), true); + }); + const cmp = this.size === null ? ">=" : "="; + lines.push(fmt.with_comments(tail, [`size ${cmp} 0x${fmt.format_hex(position)}`])); + return lines.join("\n"); + } + + /** Return an StructDeclaration without any known fields */ + static unknown(typepool, size, tag_name, align = 1) { + const preferred_field = typepool.union_field_overrides.get(tag_name) ?? null; + const decl = new StructDeclaration({ size, align, tag_name, new_field_prefix: typepool.unknown_field_prefix, preferred_union_field: preferred_field }); + typepool.add_struct(decl, tag_name); + return decl; + } + + /** Return StructDeclaration for a given ctype struct or union, registering it if needed. */ + static from_ctype(ctype, typemap, typepool) { + const existing_struct = typepool.get_struct_for_ctype(ctype); + if (existing_struct) return existing_struct; + + let typedef_name = null; + if (typemap.struct_typedefs.has(ctype)) { + const typedef = typemap.struct_typedefs.get(ctype); + pyassert(typedef.type instanceof ca.IdentifierType); + typedef_name = typedef.type.names[0]; + } else if (ctype.name && typemap.struct_typedefs.has(ctype.name)) { + const typedef = typemap.struct_typedefs.get(ctype.name); + pyassert(typedef.type instanceof ca.IdentifierType); + typedef_name = typedef.type.names[0]; + } + + let struct_fields, struct_bitfields, struct_has_bitfields, struct_size, struct_align; + try { + const struct = parse_struct(ctype, typemap); + struct_fields = struct.fields; + struct_bitfields = struct.bitfields; + struct_has_bitfields = struct.has_bitfields; + struct_size = struct.size; + struct_align = struct.align; + } catch (e) { + if (!(e instanceof UndefinedStructError)) throw e; + struct_fields = new Map(); + struct_bitfields = new Map(); + struct_has_bitfields = false; + struct_size = 0; + struct_align = 1; + typepool.warnings.push(`Warning: struct ${typedef_name || ctype.name || "None"} is not defined (only forward-declared)`); + } + + pyassert(pymod(struct_size, struct_align) === 0, "struct size must be a multiple of its alignment"); + + const struct_name = typedef_name || ctype.name; + const preferred_field = struct_name ? (typepool.union_field_overrides.get(struct_name) ?? null) : null; + + const decl = new StructDeclaration({ + size: struct_size, + align: struct_align, + tag_name: ctype.name ?? null, + typedef_name, + fields: [], + bitfields: [], + has_bitfields: struct_has_bitfields, + is_union: ctype instanceof ca.Union, + new_field_prefix: typepool.unknown_field_prefix, + preferred_union_field: preferred_field, + }); + typepool.add_struct(decl, ctype); + + for (const [bit_offset, bit_fields] of sorted(struct_bitfields.entries(), (e) => e[0])) { + for (const bit_field of bit_fields) decl.bitfields.push(new BitField({ bit_offset, bit_width: bit_field.width, name: bit_field.name })); + } + + for (const [offset, fields] of sorted(struct_fields.entries(), (e) => e[0])) { + for (const field of fields) { + if (typepool.unk_inference && is_unk_type(field.type, typemap)) continue; + const field_type = Type.ctype(field.type, typemap, typepool, { in_struct: true }); + pyassert(field.size === field_type.get_size_bytes(), `(${field.size}, ${field_type.get_size_bytes()}, '${field.name}', ${field_type})`); + decl.fields.push(new StructField({ type: field_type, offset, name: field.name, known: true })); + } + } + for (let i = 1; i < decl.fields.length; i++) pyassert(decl.fields[i - 1].offset <= decl.fields[i].offset); + return decl; + } +} + +export { compare, bnot, to_c }; diff --git a/packages/romdev-m2c/src/worker.js b/packages/romdev-m2c/src/worker.js new file mode 100644 index 00000000..5b8c93a4 --- /dev/null +++ b/packages/romdev-m2c/src/worker.js @@ -0,0 +1,11 @@ +// Worker-thread entry: runs one decompile() so a slow function cannot block the +// caller's event loop, and so callers can enforce a timeout. +import { parentPort, workerData } from "node:worker_threads"; +import { decompile } from "./main.js"; + +try { + const r = await decompile(workerData.flags); + parentPort.postMessage({ ok: true, ...r }); +} catch (e) { + parentPort.postMessage({ ok: false, error: String(e && e.stack ? e.stack : e) }); +} diff --git a/packages/romdev-m2c/test/demangle_codewarrior.test.mjs b/packages/romdev-m2c/test/demangle_codewarrior.test.mjs new file mode 100644 index 00000000..15e65f4a --- /dev/null +++ b/packages/romdev-m2c/test/demangle_codewarrior.test.mjs @@ -0,0 +1,15 @@ +// The self-test table from m2c/demangle_codewarrior.py (its `--test` mode), +// run against the JS port. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { demangle, TEST_CASES, test as selfTest } from "../src/demangle_codewarrior.js"; + +for (const [mangled, demangled] of TEST_CASES) { + test(`demangle ${mangled}`, () => { + assert.equal(demangle(mangled), demangled); + }); +} + +test("self-test reports all cases passing", () => { + assert.equal(selfTest(), true); +}); diff --git a/packages/romdev-m2c/test/e2e.test.mjs b/packages/romdev-m2c/test/e2e.test.mjs new file mode 100644 index 00000000..54dd4bba --- /dev/null +++ b/packages/romdev-m2c/test/e2e.test.mjs @@ -0,0 +1,132 @@ +// Port of m2c's run_tests.py end-to-end runner (tests/end_to_end/**). +// Each case's asm input is decompiled in-process with the JS port and compared +// byte-for-byte against upstream's committed expected output. +// +// The corpus is read from the pinned upstream checkout: $M2C_SRC, else +// ~/.romdev/tools/m2c. Filter cases with M2C_FILTER= over names like +// "e2e:loop/irix-o2.s". Set M2C_E2E_SUMMARY=1 to print a pass/fail summary. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { decompile } from "../src/main.js"; + +const SRC = process.env.M2C_SRC || path.join(os.homedir(), ".romdev", "tools", "m2c"); +const E2E = path.join(SRC, "tests", "end_to_end"); +const PATH_FLAGS = new Set(["--context", "--incbin-dir"]); +const CRASH_STRING = "CRASHED\n"; + +/** Python shlex.split (POSIX mode) for the simple flag files used by the corpus. */ +export function shlex_split(s) { + const out = []; + let cur = null; + let i = 0; + while (i < s.length) { + const c = s[i]; + if (/\s/.test(c)) { + if (cur !== null) out.push(cur); + cur = null; + i++; + } else if (c === "'") { + const j = s.indexOf("'", i + 1); + if (j < 0) throw new Error("No closing quotation"); + cur = (cur ?? "") + s.slice(i + 1, j); + i = j + 1; + } else if (c === '"') { + let j = i + 1; + let buf = ""; + while (j < s.length && s[j] !== '"') { + if (s[j] === "\\" && j + 1 < s.length && '\\"$`\n'.includes(s[j + 1])) { + buf += s[j + 1]; + j += 2; + } else buf += s[j++]; + } + if (j >= s.length) throw new Error("No closing quotation"); + cur = (cur ?? "") + buf; + i = j + 1; + } else if (c === "\\" && i + 1 < s.length) { + cur = (cur ?? "") + s[i + 1]; + i += 2; + } else if (c === "#" && cur === null) { + while (i < s.length && s[i] !== "\n") i++; + } else { + cur = (cur ?? "") + c; + i++; + } + } + if (cur !== null) out.push(cur); + return out; +} + +function get_test_flags(flags_path) { + if (!fs.existsSync(flags_path)) return []; + const flags_list = shlex_split(fs.readFileSync(flags_path, "utf8")); + for (let i = 0; i < flags_list.length; i++) { + if (!PATH_FLAGS.has(flags_list[i])) continue; + if (i + 1 >= flags_list.length) throw new Error(`${flags_path} contains ${flags_list[i]} without argument`); + flags_list[i + 1] = path.join(path.dirname(flags_path), flags_list[i + 1]); + } + return flags_list; +} + +export function collect_cases() { + const cases = []; + if (!fs.existsSync(E2E)) return cases; + for (const dir of fs.readdirSync(E2E).sort()) { + const d = path.join(E2E, dir); + if (!fs.statSync(d).isDirectory()) continue; + for (const f of fs.readdirSync(d)) { + if (!f.endsWith(".s")) continue; + const stem = f.slice(0, -2); + cases.push({ + name: `e2e:${dir}/${f}`, + asm_file: path.join(d, f), + output_file: path.join(d, `${stem}-out.c`), + flags_path: path.join(d, `${stem}-flags.txt`), + }); + } + } + cases.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + return cases; +} + +export async function run_case(c) { + const flags = ["--sanitize-tracebacks", "--stop-on-error", "--function", "test", ...get_test_flags(c.flags_path), c.asm_file]; + const r = await decompile(flags); + const out = r.stdout.replaceAll(SRC, "."); + return r.code === 0 ? out : `${CRASH_STRING}\n${out}`; +} + +const filter = process.env.M2C_FILTER ? new RegExp(process.env.M2C_FILTER) : null; +const cases = collect_cases().filter((c) => !filter || filter.test(c.name)); +const results = { pass: 0, fail: 0, failed: [] }; + +if (!cases.length) { + test("m2c e2e corpus", { skip: `no upstream checkout at ${SRC}` }, () => {}); +} +for (const c of cases) { + test(c.name, async () => { + const expected = fs.readFileSync(c.output_file, "utf8"); + let actual; + try { + actual = await run_case(c); + } catch (e) { + results.fail++; + results.failed.push(c.name); + throw e; + } + if (actual === expected) results.pass++; + else { + results.fail++; + results.failed.push(c.name); + } + assert.equal(actual, expected); + }); +} +if (process.env.M2C_E2E_SUMMARY) { + test("summary", () => { + process.stdout.write(`\nm2c e2e: ${results.pass} passed, ${results.fail} failed of ${cases.length}\n`); + for (const n of results.failed) process.stdout.write(` FAIL ${n}\n`); + }); +} diff --git a/packages/romdev-m2c/test/unit/test_arm.test.mjs b/packages/romdev-m2c/test/unit/test_arm.test.mjs new file mode 100644 index 00000000..92eff6b8 --- /dev/null +++ b/packages/romdev-m2c/test/unit/test_arm.test.mjs @@ -0,0 +1,55 @@ +// Port of m2c tests/unit/test_arm.py +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { Cc, parse_suffix } from "../../src/arch_arm.js"; + +function parse_cc(cc) { + if (!cc) return null; + if (cc === "hs") return Cc.CS; + if (cc === "lo") return Cc.CC; + return Cc.of(cc); +} + +test("parse_suffix handles all known instructions", () => { + const dirs = ",ia,ib,da,db,fa,fd,ea,ed".split(","); + const cc_strs = ",hs,lo,eq,ne,cs,cc,mi,pl,vs,vc,hi,ls,ge,lt,gt,le,al".split(","); + const ccs = cc_strs.map((s) => [s, parse_cc(s)]); + + for (const mn of [ + "b", "bl", "blx", "bx", "clz", "cmn", "cmp", "cpy", "ldr", "ldrb", "ldrh", "ldrsb", "ldrsh", "mla", "nop", + "pop", "push", "rbit", "rev", "rev16", "sdiv", "sdiv", "smlabb", "smulbb", "str", "strb", "strh", + "tablejmp.fictive", "teq", "tst", "udiv", + ]) { + for (const [cc_str, cc] of ccs) assert.deepEqual(parse_suffix(mn + cc_str), [mn, cc, "", ""], mn + cc_str); + } + + for (const [cc_str, cc] of ccs) { + for (const sz of ["sb", "b", "sh", "h"]) assert.deepEqual(parse_suffix(`ldr${cc_str}${sz}`), [`ldr${sz}`, cc, "", ""]); + for (const sz of ["b", "h"]) assert.deepEqual(parse_suffix(`str${cc_str}${sz}`), [`str${sz}`, cc, "", ""]); + } + + for (const mn of [ + "adc", "add", "and", "asr", "bic", "eor", "lsl", "lsr", "mov", "mul", "mvn", "neg", "orn", "orr", "ror", + "rrx", "rsb", "rsc", "sbc", "smlal", "smull", "sub", "umlal", "umull", + ]) { + for (const [cc_str, cc] of ccs) { + for (const s of ["", "s"]) { + assert.deepEqual(parse_suffix(mn + cc_str + s), [mn, cc, s, ""]); + assert.deepEqual(parse_suffix(mn + s + cc_str), [mn, cc, s, ""]); + } + } + } + + for (const mn of ["stm", "ldm"]) { + for (const [cc_str, cc] of ccs) { + const tr = { fa: ["da", "ib"], ea: ["db", "ia"], fd: ["ia", "db"], ed: ["ib", "da"] }; + for (const d of dirs) { + let exp = d; + if (Object.hasOwn(tr, d)) exp = tr[d][mn === "ldm" ? 0 : 1]; + assert.deepEqual(parse_suffix(`${mn}${cc_str}${d}`), [mn, cc, "", exp]); + } + } + } + + for (const mn of ["it", "cbz", "cbnz"]) assert.deepEqual(parse_suffix(mn), [mn, null, "", ""]); +}); diff --git a/packages/romdev-m2c/test/visualize.test.mjs b/packages/romdev-m2c/test/visualize.test.mjs new file mode 100644 index 00000000..d357904f --- /dev/null +++ b/packages/romdev-m2c/test/visualize.test.mjs @@ -0,0 +1,51 @@ +// --visualize: upstream m2c emits the flow graph as graphviz dot and, by +// default, pipes it through graphviz to SVG. There is no upstream fixture for +// it, so these expectations come from reading translate.py visualize_flowgraph +// and main.py. SVG rendering uses graphviz compiled to WASM (@viz-js/viz). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { decompile } from "../src/index.js"; + +const SRC = process.env.M2C_SRC || path.join(os.homedir(), ".romdev", "tools", "m2c"); +const ASM = path.join(SRC, "tests", "end_to_end", "loop", "irix-o2.s"); +const skip = fs.existsSync(ASM) ? false : `no upstream checkout at ${SRC}`; + +test("dot output follows visualize_flowgraph", { skip }, async () => { + const r = await decompile(["--visualize", "c", "--visualize-format", "dot", "--function", "test", ASM]); + assert.equal(r.code, 0); + const lines = r.stdout.split("\n"); + assert.deepEqual(lines.slice(0, 3), ["digraph {", ' node [shape="rect", fontname="Monospace"];', ' edge [fontname="Monospace"];']); + assert.equal(lines.at(-2), "}"); + assert.equal(lines.at(-1), ""); + // One node statement per flow graph node, C lines joined with \l, exit node last. + const nodes = lines.filter((l) => /^ {2}"\d+" \[label=/.test(l)); + assert.equal(nodes.length, 9); + assert.equal(nodes[0], ' "0" [label="// Node 0 (line 6)\\lvar_v0 = 0;\\lif ((arg1 <= 0))\\l"];'); + assert.equal(nodes.at(-1), ' "8" [label="// Node 8\\l// exit\\l"];'); + // Conditional edges: fallthrough F/blue then taken T/red; basic edges black; return edge bare. + assert.ok(lines.includes(' "0" -> "1" [label="F", color="blue"];')); + assert.ok(lines.includes(' "0" -> "7" [label="T", color="red"];')); + assert.ok(lines.includes(' "2" -> "3" [color="black"];')); + assert.ok(lines.includes(' "7" -> "8";')); +}); + +test("asm view lists instructions, marking synthetic ones with *", { skip }, async () => { + const r = await decompile(["--visualize", "asm", "--visualize-format", "dot", "--function", "test", ASM]); + assert.equal(r.code, 0); + assert.match(r.stdout, /"7" \[label="\/\/ Node 7 \(line 29\)\\l  jr \$ra\\l  nop\\l"\]/); +}); + +test("default --visualize renders SVG through graphviz WASM", { skip }, async () => { + const r = await decompile(["--visualize", "--function", "test", ASM]); + assert.equal(r.code, 0); + assert.match(r.stdout, /^<\?xml version="1.0" encoding="UTF-8" standalone="no"\?>/); + assert.match(r.stdout, /]*>/); + assert.match(r.stdout, /<\/svg>\n?$/); + assert.equal((r.stdout.match(//g) ?? []).length, 9); + assert.equal((r.stdout.match(//g) ?? []).length, 13); + assert.ok(r.stdout.includes("0->7")); + assert.ok(r.stdout.includes("// Node 0 (line 6)")); +}); diff --git a/packages/romdev-permuter/.gitignore b/packages/romdev-permuter/.gitignore new file mode 100644 index 00000000..79e5f440 --- /dev/null +++ b/packages/romdev-permuter/.gitignore @@ -0,0 +1,2 @@ +test/.work/ +.permuter-tmp/ diff --git a/packages/romdev-permuter/LICENSE b/packages/romdev-permuter/LICENSE new file mode 100644 index 00000000..ce6aab3a --- /dev/null +++ b/packages/romdev-permuter/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Simon Lindholm and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/romdev-permuter/NOTICE b/packages/romdev-permuter/NOTICE new file mode 100644 index 00000000..8cf28b71 --- /dev/null +++ b/packages/romdev-permuter/NOTICE @@ -0,0 +1,37 @@ +romdev-permuter + +A plain JavaScript port of decomp-permuter +(https://github.com/simonlindholm/decomp-permuter), pinned at commit +41bd0bfc32aa5ea78de4cf28be603163256c2a4c. decomp-permuter is +Copyright (c) 2019 Simon Lindholm and contributors, MIT licensed; the license +text is in LICENSE. default_weights.toml is copied unchanged from upstream. + +The C parser/printer it uses is romdev-pycparser (the port of the pycparser +fork decomp-permuter vendors as perm_pycparser; BSD, see that package). + +src/pyrandom.js reimplements the documented algorithms of CPython's random +module (MT19937 and the random.py sampling methods) and src/difflib.js those of +difflib's SequenceMatcher and unified_diff, so seeds and scores replay +upstream's; no CPython code is included. + +src/pow.js ports the pow() of the ARM optimized-routines (Copyright (c) 2018, +Arm Limited, MIT), as shipped in glibc and musl, so the permuter's weights +equal the doubles CPython's `**` obtains from the C library; src/pow-data.js +holds its tables, generated from musl's pow_data.c / exp_data.c by +scripts/gen-pow-data.mjs. + +src/levenshtein.js ports rapidfuzz's reference Levenshtein implementation +(Levenshtein_py.py, Editops.as_opcodes; Copyright (c) 2020 Max Bachmann, MIT), +which the `Levenshtein` package upstream's --algorithm levenshtein uses. + +permuter@home (src/net/, bin/pah.mjs, bin/pah-controller.mjs) ports upstream's +src/net/*.py and its Rust controller (src/net/controller). Its crypto is +libsodium through libsodium.js (libsodium-wrappers, ISC; libsodium is +Copyright (c) 2013-2025 Frank Denis, ISC), a dependency, not bundled. +src/net/icons/*.ico are upstream's systray icons, copied unchanged. The systray +helper itself (upstream src/net/cmd/systray, Go, MIT, Copyright (c) 2017 Zack +Young) is not included; see src/net/systray.js. + +The evaluator runs jobs with romdev's WASM toolchain instead of upstream's +Docker image: the controller's docker_image names a toolchain profile +("romdev:ido5.3", "romdev:ido7.1" or "romdev:=,..."). diff --git a/packages/romdev-permuter/README.md b/packages/romdev-permuter/README.md new file mode 100644 index 00000000..15f72676 --- /dev/null +++ b/packages/romdev-permuter/README.md @@ -0,0 +1,81 @@ +# romdev-permuter + +A plain JavaScript (ESM) port of +[decomp-permuter](https://github.com/simonlindholm/decomp-permuter), the tool +matching-decompilation projects use to search for a C variant that compiles to +the original bytes. It keeps upstream's PERM macros, randomization passes, +objdump-diff scorer and `compile.sh` contract, evaluates candidates in Node +worker threads, and disassembles through WebAssembly binutils. No Python is +needed. + +It is part of [romdev](https://github.com/monteslu/romdev). + +## Upstream and license + +- Upstream: decomp-permuter, https://github.com/simonlindholm/decomp-permuter +- Ported from commit `41bd0bfc32aa5ea78de4cf28be603163256c2a4c` +- License: MIT (matches upstream). See `LICENSE` and `NOTICE`. +- `default_weights.toml` and the permuter@home systray icons are copied + unchanged from upstream. +- `src/pyrandom.js` and `src/difflib.js` reimplement the documented algorithms + of CPython's `random` and `difflib` so seeds and scores replay upstream's (no + CPython code is included). `src/pow.js` ports ARM optimized-routines' `pow()` + (MIT); `src/levenshtein.js` ports rapidfuzz's reference Levenshtein (MIT). +- permuter@home crypto uses the + [`libsodium-wrappers`](https://www.npmjs.com/package/libsodium-wrappers) + dependency (ISC). The Go systray helper is not included. + +## How romdev uses it + +romdevtools' `decomp` tool runs it for `decomp({op:'search', ...})`: a bounded +permuter job on one function, which can be cancelled, resumed and queried for +its best candidate. romdev supplies an in-process compile function that runs +the project's original compiler as WebAssembly, so no host compiler, shell or +Docker image is involved. Where upstream's permuter@home controller names a +Docker image, this port names a romdev toolchain profile (`romdev:ido5.3`, +`romdev:ido7.1` or `romdev:=,...`). + +Disassembly uses `mips-linux-gnu-objdump` from the +[`romdev-toolchain-mips-gcc`](https://www.npmjs.com/package/romdev-toolchain-mips-gcc) +dependency. Other architectures need a WASM objdump registered with +`setObjdumpGlue(arch, gluePath)`. + +## Command line + +| bin | upstream equivalent | +|---|---| +| `romdev-permuter` | `permuter.py`: run the permuter on one or more directories | +| `romdev-permuter-import` | `import.py`: create `nonmatchings//` from a C file and a function's assembly | +| `romdev-permuter-remote` | `pah.py`: the permuter@home client (`ping`, `setup`, `vouch`, `run-server`) | +| `romdev-permuter-remote-controller` | the permuter@home control server (`run`, `setup`) | + +```sh +npx romdev-permuter nonmatchings/func_80001234 -j 4 --stop-on-zero +``` + +Run from the command line, a permuter directory's `compile.sh` is run with +`bash`, as upstream does. `romdev-permuter-import` needs a toolchain adapter for +the project's build, `cpp` and assembler steps: romdevtools' own when it is +installed beside this package, or a module named by `ROMDEV_PERMUTER_TOOLCHAIN`. + +## API + +```js +import { run, makeOptions, UPSTREAM } from "romdev-permuter"; +``` + +The index exports the CLI entry (`run`, `makeOptions`), the building blocks +(`Permuter`, `Candidate`, `Compiler`, `Scorer`, `Randomizer`, +`RANDOMIZATION_PASSES`, `perm_parse`, `perm_evaluate_one`), the objdump layer +(`objdump`, `simplify_objdump`, `get_arch`, `setObjdumpGlue`), the import entry +(`importMain`, `resolveToolchain`), and `UPSTREAM` (`{ repo, commit }`). +Exports: `.` only. + +## Requirements + +Node >= 24, ESM only. No Python, no native code. Depends on +`romdev-pycparser`, `romdev-toolchain-mips-gcc` and `libsodium-wrappers`. + +## Versions + +romdev-permuter 0.1.0 ports decomp-permuter at commit `41bd0bfc`. diff --git a/packages/romdev-permuter/bin/import.mjs b/packages/romdev-permuter/bin/import.mjs new file mode 100755 index 00000000..ceeaf6a9 --- /dev/null +++ b/packages/romdev-permuter/bin/import.mjs @@ -0,0 +1,18 @@ +#!/usr/bin/env node +// romdev-permuter import: decomp-permuter's import.py, run in node. +// import.mjs [make flags] [--keep] +// [--preserve-macros REGEX] [--no-prune] [--decompme] [--settings FILE] +// Creates nonmatchings// in the current directory. The build, cpp and +// assembler steps run through romdev's toolchain adapter (see src/import.js). +import { importMain, ImportExit } from "../src/import.js"; + +try { + await importMain(process.argv.slice(2)); + process.exit(0); +} catch (e) { + if (e instanceof ImportExit) { + if (e.message) process.stderr.write(e.message + "\n"); + process.exit(e.code); + } + throw e; +} diff --git a/packages/romdev-permuter/bin/permuter.mjs b/packages/romdev-permuter/bin/permuter.mjs new file mode 100755 index 00000000..64176d66 --- /dev/null +++ b/packages/romdev-permuter/bin/permuter.mjs @@ -0,0 +1,93 @@ +#!/usr/bin/env node +// romdev-permuter CLI: decomp-permuter's permuter.py flags, run in node. +// romdev-permuter ... [-j N] [--stop-on-zero] [--seed [i,]N] ... +// -J runs through permuter@home (src/net/), with no local threads unless -j is given. +import { run, PermuterUsageError, DEFAULT_RAND_KEEP_PROB } from "../src/main.js"; +import { RANDOMIZATION_PASSES, PASS_DOCS } from "../src/randomizer.js"; + +const usage = `usage: romdev-permuter [-h] [--help=randomization-passes] [--show-errors] [--show-timings] + [--print-diffs] [--abort-exceptions] [--better-only] [--best-only] [--stop-on-zero] [--quiet] + [--stack-diffs] [--algorithm {difflib,levenshtein}] [--keep-prob PROB] [-j THREADS] [-J] [--pah-debug] + [--priority PRIORITY] [--no-context-output] + [--only-if-below N] [--debug] [--speed [1-100]] [--no-ignore-branch-targets] [--seed SEED] + directory [directory ...]`; + +function fail(msg) { + process.stderr.write(`${usage}\nromdev-permuter: error: ${msg}\n`); + process.exit(2); +} + +const opts = { directories: [], threads: 0 }; +const argv = process.argv.slice(2); +const floatIn = (v, lo, hi, flag) => { + const x = Number(v); + if (!Number.isFinite(x)) fail(`argument ${flag}: invalid float value: '${v}'`); + if (x < lo || x > hi) fail(`argument ${flag}: value ${v} is out of range (must be between ${lo} and ${hi})`); + return x; +}; +for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const [flag, inline] = a.startsWith("--") && a.includes("=") && a !== "--help=randomization-passes" ? [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)] : [a, null]; + const val = () => { + if (inline != null) return inline; + if (i + 1 >= argv.length) fail(`argument ${flag}: expected one argument`); + return argv[++i]; + }; + switch (flag) { + case "-h": case "--help": process.stdout.write(usage + "\n"); process.exit(0); break; + case "--help=randomization-passes": + for (const m of RANDOMIZATION_PASSES) process.stdout.write(`${m.name}:\n ${PASS_DOCS[m.name]}\n\n`); + process.exit(0); break; + case "--show-errors": opts.show_errors = true; break; + case "--show-timings": opts.show_timings = true; break; + case "--print-diffs": opts.print_diffs = true; break; + case "--abort-exceptions": opts.abort_exceptions = true; break; + case "--better-only": opts.better_only = true; break; + case "--best-only": opts.best_only = true; break; + case "--stop-on-zero": opts.stop_on_zero = true; break; + case "--quiet": opts.quiet = true; break; + case "--stack-diffs": opts.stack_differences = true; break; + case "--algorithm": { const v = val(); if (v !== "difflib" && v !== "levenshtein") fail(`argument --algorithm: invalid choice: '${v}' (choose from 'difflib', 'levenshtein')`); opts.algorithm = v; break; } + case "--keep-prob": opts.keep_prob = floatIn(val(), 0, 1, "--keep-prob"); break; + case "--seed": opts.force_seed = val(); break; + case "-j": { const v = val(); opts.threads = parseInt(v, 10); if (!Number.isInteger(opts.threads)) fail(`argument -j: invalid int value: '${v}'`); break; } + case "-J": opts.use_network = true; break; + case "--pah-debug": opts.network_debug = true; break; + case "--priority": opts.network_priority = floatIn(val(), 0.01, 2.0, "--priority"); break; + case "--no-context-output": opts.no_context_output = true; break; + case "--only-if-below": opts.score_threshold = parseInt(val(), 10); break; + case "--debug": opts.debug_mode = true; break; + case "--speed": { const s = parseInt(val(), 10); if (!(s >= 1 && s <= 100)) fail("argument --speed: invalid choice"); opts.speed = s; break; } + case "--no-ignore-branch-targets": opts.ign_branch_targets = false; break; + default: + if (a.startsWith("-") && a.length > 1) { + if (/^-j\d+$/.test(a)) { opts.threads = parseInt(a.slice(2), 10); break; } + fail(`unrecognized arguments: ${a}`); + } + opts.directories.push(a); + } +} +if (!opts.directories.length) fail("the following arguments are required: directory"); +if (!opts.threads && !opts.use_network) opts.threads = 1; +opts.keep_prob ??= DEFAULT_RAND_KEEP_PROB; + +// Each directory's compile.sh runs through romdev's toolchain adapter when one +// is available (no bash, no host compiler); otherwise upstream's +// `bash compile.sh`. +const { resolveToolchainUrl } = await import("../src/import.js"); +const toolchainUrl = resolveToolchainUrl(); +if (toolchainUrl && !process.env.ROMDEV_PERMUTER_BASH_COMPILE) opts.compileModule = { url: toolchainUrl, name: "compileWithScript" }; + +const ac = new AbortController(); +process.on("SIGINT", () => ac.abort()); +process.on("SIGTERM", () => ac.abort()); +try { + await run({ ...opts, signal: ac.signal }); + process.exit(0); +} catch (e) { + if (e instanceof PermuterUsageError) { + process.stderr.write(e.message + "\n"); + process.exit(1); + } + throw e; +} diff --git a/packages/romdev-permuter/bin/remote-controller.mjs b/packages/romdev-permuter/bin/remote-controller.mjs new file mode 100755 index 00000000..32a01c87 --- /dev/null +++ b/packages/romdev-permuter/bin/remote-controller.mjs @@ -0,0 +1,47 @@ +#!/usr/bin/env node +// The permuter@home control server (upstream's Rust `pahserver`): +// romdev-permuter-remote-controller run --listen-on IP:PORT --config config.toml --db db.json [--debug] +// romdev-permuter-remote-controller setup --db db.json +import { run_controller, run_setup } from "../src/net/controller.js"; +import { enable_debug_mode } from "../src/net/core.js"; + +const usage = `Usage: romdev-permuter-remote-controller [] + +The permuter@home control server. + +Commands: + run Run the permuter@home control server. + setup Setup initial database and config for permuter@home.`; + +function die(msg) { process.stderr.write(msg + "\n"); process.exit(1); } + +const [cmd, ...args] = process.argv.slice(2); +const opts = {}; +for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a === "--debug") opts.debug = true; + else if (["--listen-on", "--config", "--db"].includes(a)) { + if (i + 1 >= args.length) die(`Missing value for option '${a}'.`); + opts[a.slice(2).replace("-", "_")] = args[++i]; + } else die(`Unrecognized argument: ${a}`); +} + +if (cmd === "run") { + for (const k of ["listen_on", "config", "db"]) if (!opts[k]) die(`Required options not provided:\n --${k.replace("_", "-")}`); + if (opts.debug) enable_debug_mode(); + const c = await run_controller({ listen_on: opts.listen_on, config: opts.config, db: opts.db, debug: opts.debug }); + process.stderr.write(`listening on ${c.address}\n`); + const stop = async () => { await c.close(); process.exit(0); }; + process.on("SIGINT", stop); + process.on("SIGTERM", stop); +} else if (cmd === "setup") { + if (!opts.db) die("Required options not provided:\n --db"); + try { + process.stdout.write((await run_setup(opts.db)) + "\n"); + } catch (e) { + die(e.message); + } +} else { + process.stdout.write(usage + "\n"); + process.exit(cmd === "--help" || cmd === "-h" ? 0 : 1); +} diff --git a/packages/romdev-permuter/bin/remote.mjs b/packages/romdev-permuter/bin/remote.mjs new file mode 100755 index 00000000..142ea649 --- /dev/null +++ b/packages/romdev-permuter/bin/remote.mjs @@ -0,0 +1,225 @@ +#!/usr/bin/env node +// permuter@home CLI, a port of decomp-permuter's pah.py (src/net/cmd/): +// romdev-permuter-remote [--debug] ping | setup | vouch MAGIC | run-server --cores N --memory GB [--systray] [--min-priority P] +// To use p@h as a client, pass -J to romdev-permuter; this is only needed for +// configuration or to run a worker server. +import { createInterface } from "node:readline/promises"; +import { connect, read_config, write_config, enable_debug_mode, sign_with_magic, verify_with_magic, SigningKey, VerifyKey, + sealedBoxEncrypt, sealedBoxDecrypt, EOFError, nacl, json_prop } from "../src/net/core.js"; +import { Server, SystrayState, AsyncQueue, server_main_loop } from "../src/net/server.js"; +import { ServerError } from "../src/error.js"; +import { plural } from "../src/helpers.js"; + +const usage = `usage: romdev-permuter-remote [-h] [--debug] ... + +permuter@home - run the permuter across the Internet! + +To use p@h as a client, just pass -J when running the permuter. This script is +only necessary for configuration or when running a worker server. + +positional arguments: + + ping Check server connectivity. + run-server + Run a permuter worker server, allowing anyone with access to the + central controller server to run permuter jobs on your machine. + setup Set up permuter@home. This will require someone else to grant you + access to the central server. + vouch Give someone access to the central server. + +options: + -h, --help show this help message and exit + --debug Enable debug logging.`; + +const out = (s = "") => process.stdout.write(s + "\n"); +let rl = null; +async function input(prompt) { + rl ??= createInterface({ input: process.stdin, output: process.stdout, terminal: false }); + process.stdout.write(prompt); + const line = await rl.question(""); + return line; +} +async function ask(msg, { dflt }) { + msg += dflt ? " (Y/n)? " : " (y/N)? "; + const res = (await input(msg)).trim().toLowerCase(); + if (!res) return dflt; + if (["y", "yes", "n", "no"].includes(res)) return res[0] === "y"; + out("Bad response!"); + process.exit(1); +} + +async function run_ping() { + const port = await connect(); + const t0 = performance.now(); + await port.send_json({ method: "ping" }); + const msg = await port.receive_json(); + const rtt = performance.now() - t0; + out(`Connected successfully! Round-trip time: ${rtt.toFixed(1)} ms`); + out(`${plural(json_prop(msg, "servers", "int"), "server")} online (${plural(Math.trunc(json_prop(msg, "cores", "float")), "core")}, ${plural(json_prop(msg, "clients", "int"), "client")})`); + port.close(); +} + +function random_name() { + let s = ""; + for (let i = 0; i < 5; i++) s += String.fromCharCode(97 + Math.floor(Math.random() * 26)); + return s; +} + +async function run_setup() { + const config = await read_config(); + let signing_key = config.signing_key; + if (!signing_key || !(await ask("Keep previous secret key", { dflt: true }))) { + signing_key = SigningKey.generate(); + config.signing_key = signing_key; + write_config(config); + } + let nickname = config.initial_setup_nickname; + if (!nickname || !(await ask(`Keep previous nickname [${nickname}]`, { dflt: true }))) { + const default_nickname = process.env.USER || random_name(); + nickname = (await input(`Nickname [default: ${default_nickname}]: `)) || default_nickname; + config.initial_setup_nickname = nickname; + write_config(config); + } + const signed_nickname = sign_with_magic("NAME", signing_key, Buffer.from(nickname, "utf8")); + const vouch_text = Buffer.concat([Buffer.from(signing_key.verify_key.encode()), signed_nickname]).toString("base64"); + out("Ask someone to run the following command:"); + out(`romdev-permuter-remote vouch ${vouch_text}`); + out(); + out("They should give you a token back in return. Paste that here:"); + const inp = (await input("")).trim(); + try { + const data = Buffer.from(sealedBoxDecrypt(Buffer.from(inp, "base64"), signing_key.to_curve25519_private_key())); + config.server_address = new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(32)); + config.server_verify_key = new VerifyKey(data.subarray(0, 32)); + config.initial_setup_nickname = null; + } catch { + out("Invalid token!"); + process.exit(1); + } + out(`Server: ${config.server_address}`); + out("Testing connection..."); + const port = await connect(config); + await port.send_json({ method: "ping" }); + await port.receive_json(); + port.close(); + try { + write_config(config); + } catch (e) { + out(`Failed to write config: ${e.message}`); + process.exit(1); + } + out("permuter@home successfully set up!"); +} + +async function run_vouch(magic) { + let verify_key, signed_nickname, nickname; + try { + const vouch_data = Buffer.from(magic, "base64"); + verify_key = new VerifyKey(vouch_data.subarray(0, 32)); + signed_nickname = vouch_data.subarray(32); + nickname = new TextDecoder("utf-8", { fatal: true }).decode(verify_with_magic("NAME", verify_key, signed_nickname)); + } catch { + out("Could not parse data!"); + process.exit(1); + } + let config, port; + try { + config = await read_config(); + port = await connect(config); + await port.send_json({ method: "vouch", who: verify_key.hex(), signed_name: Buffer.from(signed_nickname).toString("hex") }); + await port.receive_json(); + } catch (e) { + out(`Error: ${e.message}`); + process.exit(1); + } + if (!(await ask(`Grant permuter server access to ${nickname}`, { dflt: true }))) { port.close(); return; } + try { + await port.send_json({}); + await port.receive_json(); + } catch (e) { + out(`Failed to grant access: ${e.message}`); + process.exit(1); + } + port.close(); + const data = Buffer.concat([Buffer.from(config.server_verify_key.encode()), Buffer.from(config.server_address, "utf8")]); + const token = sealedBoxEncrypt(data, verify_key.to_curve25519_public_key()); + out("Granted!"); + out(); + out("Send them the following token:"); + out(Buffer.from(token).toString("base64")); +} + +async function run_server(args) { + const opts = { num_cores: null, max_memory_gb: null, systray: false, min_priority: 0.1 }; + const num = (v, flag) => { + const x = Number(v); + if (v == null || !Number.isFinite(x)) { process.stderr.write(`romdev-permuter-remote run-server: error: argument ${flag}: invalid float value: '${v}'\n`); process.exit(2); } + return x; + }; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a === "--cores") opts.num_cores = num(args[++i], "--cores"); + else if (a === "--memory") opts.max_memory_gb = num(args[++i], "--memory"); + else if (a === "--systray") opts.systray = true; + else if (a === "--min-priority") opts.min_priority = num(args[++i], "--min-priority"); + else { process.stderr.write(`romdev-permuter-remote run-server: error: unrecognized arguments: ${a}\n`); process.exit(2); } + } + const missing = [["--cores", opts.num_cores], ["--memory", opts.max_memory_gb]].filter(([, v]) => v == null).map(([k]) => k); + if (missing.length) { process.stderr.write(`romdev-permuter-remote run-server: error: the following arguments are required: ${missing.join(", ")}\n`); process.exit(2); } + + const io_queue = new AsyncQueue(); + const config = await read_config(); + let systray = new SystrayState(); + if (opts.systray) { + const { RealSystrayState } = await import("../src/net/systray.js"); + try { + systray = await RealSystrayState.create(io_queue); + } catch (e) { + out("Failed to initialize systray!"); + out(); + out(e.message); + process.exit(1); + } + } + const stop = () => io_queue.put([null, { kind: "shutdown" }]); + process.on("SIGINT", stop); + process.on("SIGTERM", stop); + try { + const server = new Server({ num_cores: opts.num_cores, max_memory_gb: opts.max_memory_gb, min_priority: opts.min_priority }, config, io_queue); + await server.start(); + try { + systray.server_connected(); + await server_main_loop(io_queue, server, systray); + } finally { + await server.stop(); + } + } finally { + await systray.stop(); + } +} + +async function main() { + await nacl(); + const argv = process.argv.slice(2); + if (argv[0] === "--debug") { enable_debug_mode(); argv.shift(); } + const [cmd, ...rest] = argv; + try { + if (cmd === "ping") await run_ping(); + else if (cmd === "setup") await run_setup(); + else if (cmd === "vouch") { + if (rest.length !== 1) { process.stderr.write("romdev-permuter-remote vouch: error: the following arguments are required: magic\n"); process.exit(2); } + await run_vouch(rest[0]); + } else if (cmd === "run-server") await run_server(rest); + else if (cmd === undefined || cmd === "-h" || cmd === "--help") out(usage); + else { process.stderr.write(`${usage}\nromdev-permuter-remote: error: argument : invalid choice: '${cmd}'\n`); process.exit(2); } + } catch (e) { + if (e instanceof EOFError) { out(`Network error: ${e.message}`); process.exit(1); } + if (e instanceof ServerError) { out(`Error: ${e.message}`); process.exit(1); } + throw e; + } finally { + rl?.close(); + } + process.exit(0); +} + +main(); diff --git a/packages/romdev-permuter/default_weights.toml b/packages/romdev-permuter/default_weights.toml new file mode 100644 index 00000000..4e13e124 --- /dev/null +++ b/packages/romdev-permuter/default_weights.toml @@ -0,0 +1,71 @@ +# These are the default weights for each randomization pass for each compiler type. +# They can be overridden by settings.toml in the non-matching directory. + +[base] +perm_temp_for_expr = 100 +perm_expand_expr = 20 +perm_reorder_stmts = 10 +perm_reorder_decls = 10 +perm_add_mask = 15 +perm_xor_zero = 10 +perm_cast_simple = 10 +perm_refer_to_var = 10 +perm_float_literal = 3 +perm_randomize_internal_type = 10 +perm_randomize_external_type = 5 +perm_randomize_function_type = 5 +perm_split_assignment = 10 +perm_sameline = 3 +perm_ins_block = 10 +perm_struct_ref = 10 +perm_empty_stmt = 10 +perm_condition = 10 +perm_mult_zero = 5 +perm_factor_mult = 5 +perm_factor_shift = 5 +perm_dummy_comma_expr = 5 +perm_add_self_assignment = 5 +perm_commutative = 5 +perm_add_sub = 5 +perm_inequalities = 5 +perm_compound_assignment = 5 +perm_remove_ast = 5 +perm_duplicate_assignment = 5 +perm_chain_assignment = 5 +perm_long_chain_assignment = 3 +perm_pad_var_decl = 1 +perm_inline = 10 +perm_var_cond_block = 5 +perm_alias_array = 1 + +[ido] +perm_float_literal = 10 +perm_sameline = 10 +perm_inline = 0 +perm_var_cond_block = 0 +perm_alias_array = 0.5 + +[mwcc] +perm_chain_assignment = 10 +perm_compound_assignment = 0.5 +perm_empty_stmt = 0.5 +perm_struct_ref = 0.5 +perm_sameline = 0.5 +perm_xor_zero = 0.5 +perm_var_cond_block = 1 + +[gcc] +perm_alias_array = 3 +# The following passes were originally written with IDO in mind and are not beneficial for GCC +perm_add_mask = 0.5 +perm_xor_zero = 0.5 +perm_refer_to_var = 0.5 +perm_float_literal = 0.5 +perm_sameline = 0.5 +perm_empty_stmt = 0.5 +perm_condition = 0.5 +perm_mult_zero = 0.5 +perm_dummy_comma_expr = 0.5 +perm_add_self_assignment = 0.5 +perm_duplicate_assignment = 0.5 +perm_pad_var_decl = 0.5 diff --git a/packages/romdev-permuter/package.json b/packages/romdev-permuter/package.json new file mode 100644 index 00000000..f549b882 --- /dev/null +++ b/packages/romdev-permuter/package.json @@ -0,0 +1,47 @@ +{ + "name": "romdev-permuter", + "version": "0.1.0", + "description": "Plain-JS port of decomp-permuter: PERM macros, randomization passes, the objdump-diff scorer and the compile.sh contract, with candidate evaluation in node worker threads and disassembly through WASM binutils.", + "type": "module", + "main": "src/index.js", + "exports": { + ".": "./src/index.js", + "./package.json": "./package.json" + }, + "bin": { + "romdev-permuter": "bin/permuter.mjs", + "romdev-permuter-import": "bin/import.mjs", + "romdev-permuter-remote": "bin/remote.mjs", + "romdev-permuter-remote-controller": "bin/remote-controller.mjs" + }, + "files": [ + "src", + "bin", + "default_weights.toml", + "prelude.inc", + "LICENSE", + "NOTICE" + ], + "engines": { + "node": ">=24" + }, + "license": "MIT", + "dependencies": { + "libsodium-wrappers": "0.8.4", + "romdev-pycparser": "0.1.0", + "romdev-toolchain-mips-gcc": "0.1.3" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/monteslu/romdev.git", + "directory": "packages/romdev-permuter" + }, + "homepage": "https://github.com/monteslu/romdev#readme", + "bugs": { + "url": "https://github.com/monteslu/romdev/issues" + }, + "author": "Luis Montes", + "scripts": { + "test": "node --test" + } +} diff --git a/packages/romdev-permuter/prelude.inc b/packages/romdev-permuter/prelude.inc new file mode 100644 index 00000000..9198db56 --- /dev/null +++ b/packages/romdev-permuter/prelude.inc @@ -0,0 +1,83 @@ +.set noat +.set noreorder +.set gp=64 + +.macro glabel label, visibility=global + .\visibility \label + .type \label, @function + \label: +.endm + +.macro endlabel label + .size \label, . - \label +.endm + +.macro alabel label, visibility=global + .\visibility \label + .type \label, @function + \label: +.endm + +.macro ehlabel label, visibility=global + .\visibility \label + \label: +.endm + + +.macro jlabel label, visibility=local + \label: +.endm + + +.macro dlabel label, visibility=global + .\visibility \label + .type \label, @object + \label: +.endm + +.macro enddlabel label + .size \label, . - \label +.endm + + +.macro nonmatching label, size=1 + .global \label\().NON_MATCHING + .type \label\().NON_MATCHING, @object + .size \label\().NON_MATCHING, \size + \label\().NON_MATCHING: +.endm + +# Float register aliases (o32 ABI) + +.set $fv0, $f0 +.set $fv0f, $f1 +.set $fv1, $f2 +.set $fv1f, $f3 +.set $ft0, $f4 +.set $ft0f, $f5 +.set $ft1, $f6 +.set $ft1f, $f7 +.set $ft2, $f8 +.set $ft2f, $f9 +.set $ft3, $f10 +.set $ft3f, $f11 +.set $fa0, $f12 +.set $fa0f, $f13 +.set $fa1, $f14 +.set $fa1f, $f15 +.set $ft4, $f16 +.set $ft4f, $f17 +.set $ft5, $f18 +.set $ft5f, $f19 +.set $fs0, $f20 +.set $fs0f, $f21 +.set $fs1, $f22 +.set $fs1f, $f23 +.set $fs2, $f24 +.set $fs2f, $f25 +.set $fs3, $f26 +.set $fs3f, $f27 +.set $fs4, $f28 +.set $fs4f, $f29 +.set $fs5, $f30 +.set $fs5f, $f31 diff --git a/packages/romdev-permuter/scripts/gen-pow-data.mjs b/packages/romdev-permuter/scripts/gen-pow-data.mjs new file mode 100644 index 00000000..17768b4f --- /dev/null +++ b/packages/romdev-permuter/scripts/gen-pow-data.mjs @@ -0,0 +1,88 @@ +#!/usr/bin/env node +// Regenerate src/pow-data.js from the ARM optimized-routines pow tables as +// shipped in musl (src/math/pow_data.c, src/math/exp_data.c); glibc carries +// the same tables. Values are kept as IEEE-754 bit patterns so nothing is +// re-rounded on the way. +// node scripts/gen-pow-data.mjs +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const [powFile, expFile] = process.argv.slice(2); +if (!expFile) { console.error("usage: node scripts/gen-pow-data.mjs "); process.exit(2); } + +/** A C hex-float literal (0x1.8p52, -0x1p-1) as exact bits. */ +function hexFloatBits(lit) { + const m = /^(-?)0x([0-9a-f]+)(?:\.([0-9a-f]*))?p([+-]?\d+)$/i.exec(lit.trim()); + if (!m) throw new Error(`not a hex float: ${lit}`); + const frac = m[3] ?? ""; + let mant = BigInt("0x" + m[2] + frac); + let exp = Number(m[4]) - 4 * frac.length; + if (mant === 0n) return m[1] ? 0x8000000000000000n : 0n; + // Normalise to 53 bits (these literals are exact doubles, so no rounding). + let bitsLen = mant.toString(2).length; + while (bitsLen > 53) { if (mant & 1n) throw new Error(`inexact literal ${lit}`); mant >>= 1n; exp++; bitsLen--; } + while (bitsLen < 53) { mant <<= 1n; exp--; bitsLen++; } + const e = BigInt(exp + 52 + 1023); + if (e <= 0n || e >= 0x7ffn) throw new Error(`out of normal range: ${lit}`); + return (m[1] ? 1n << 63n : 0n) | (e << 52n) | (mant & ((1n << 52n) - 1n)); +} +const f64 = (bits) => { const b = new DataView(new ArrayBuffer(8)); b.setBigUint64(0, bits); return b.getFloat64(0); }; +const bitsOf = (d) => { const b = new DataView(new ArrayBuffer(8)); b.setFloat64(0, d); return b.getBigUint64(0); }; +/** `lit` or `lit * k` with k a small integer (the scaled poly coefficients); exact. */ +function value(expr) { + const [a, b] = expr.split("*").map((s) => s.trim()); + const v = f64(hexFloatBits(a)); + return b ? v * Number(b) : v; +} +const hex = (d) => "0x" + bitsOf(d).toString(16).padStart(16, "0"); + +const pow = readFileSync(powFile, "utf8"); +const ln2hi = value(/\.ln2hi = ([^,]+),/.exec(pow)[1]); +const ln2lo = value(/\.ln2lo = ([^,]+),/.exec(pow)[1]); +const poly = /\.poly = \{([\s\S]*?)\},/.exec(pow)[1].split("\n").map((l) => l.replace(/\/\/.*/, "").trim()).filter(Boolean) + .map((l) => value(l.replace(/,$/, ""))); +const tab = [...pow.matchAll(/^A\(([^,]+), ([^,]+), ([^)]+)\)/gm)].map((m) => [value(m[1]), value(m[2]), value(m[3])]); +if (tab.length !== 128 || poly.length !== 7) throw new Error("unexpected pow_data shape"); + +const exp = readFileSync(expFile, "utf8"); +const N = 128; +const invln2N = value(/\.invln2N = ([^,]+) \* N,/.exec(exp)[1]) * N; +const negln2hiN = value(/\.negln2hiN = ([^,]+),/.exec(exp)[1]); +const negln2loN = value(/\.negln2loN = ([^,]+),/.exec(exp)[1]); +const shift = value(/#else\n\.shift = ([^,]+),/.exec(exp)[1]); +const epoly = /\.poly = \{([\s\S]*?)\},/.exec(exp)[1].split("\n").map((l) => l.replace(/\/\/.*/, "").trim()).filter(Boolean) + .map((l) => value(l.replace(/,$/, ""))); +const etab = /\.tab = \{([\s\S]*?)\},\s*\};/.exec(exp)[1].split(/[\s,]+/).filter((t) => /^0x/.test(t)).map((t) => BigInt(t)); +if (etab.length !== 2 * N || epoly.length !== 4) throw new Error("unexpected exp_data shape"); + +const here = path.dirname(fileURLToPath(import.meta.url)); +const out = `// Generated by scripts/gen-pow-data.mjs from the ARM optimized-routines pow +// tables (Copyright (c) 2018, Arm Limited, MIT; as shipped in musl and glibc). +// IEEE-754 bit patterns; do not edit. +const b = new DataView(new ArrayBuffer(8)); +const d = (h) => { b.setBigUint64(0, BigInt(h)); return b.getFloat64(0); }; + +export const POW_LOG = { + ln2hi: d("${hex(ln2hi)}"), + ln2lo: d("${hex(ln2lo)}"), + poly: [${poly.map((v) => `d("${hex(v)}")`).join(", ")}], + // [invc, logc, logctail] per subinterval + tab: [ +${tab.map((r) => ` [${r.map((v) => `d("${hex(v)}")`).join(", ")}],`).join("\n")} + ], +}; + +export const EXP = { + invln2N: d("${hex(invln2N)}"), + negln2hiN: d("${hex(negln2hiN)}"), + negln2loN: d("${hex(negln2loN)}"), + shift: d("${hex(shift)}"), + poly: [${epoly.map((v) => `d("${hex(v)}")`).join(", ")}], + tab: [ +${etab.map((v, k) => (k % 2 === 0 ? " " : "") + `0x${v.toString(16)}n,` + (k % 2 === 1 ? "\n" : " ")).join("").trimEnd()} + ], +}; +`; +writeFileSync(path.join(here, "..", "src", "pow-data.js"), out); +console.log("wrote src/pow-data.js"); diff --git a/packages/romdev-permuter/src/ast_types.js b/packages/romdev-permuter/src/ast_types.js new file mode 100644 index 00000000..a5a161bd --- /dev/null +++ b/packages/romdev-permuter/src/ast_types.js @@ -0,0 +1,263 @@ +// ast_types.js - a port of decomp-permuter's src/ast_types.py: expression +// typing over the C AST, with the upstream simplifications (const/volatile +// ignored, int-like arithmetic promotes to int, one namespace for variables). +import { c_ast as ca, Node } from "romdev-pycparser"; + +const isa = (x, ...classes) => x != null && classes.some((c) => x instanceof c); + +export class AssertionError extends Error { + constructor(message = "") { super(message); this.name = "AssertionError"; } +} +function assert(cond, msg) { if (!cond) throw new AssertionError(msg); } + +export class KeyError extends Error { + constructor(key) { super(String(key)); this.name = "KeyError"; } +} + +/** @typedef {{typedefs: Map, var_types: Map, local_vars: Set, struct_defs: Map}} TypeMap */ + +/** @returns {TypeMap} */ +export function newTypeMap() { + return { typedefs: new Map(), var_types: new Map(), local_vars: new Set(), struct_defs: new Map() }; +} + +export function is_local_var(name, typemap) { return typemap.local_vars.has(name); } + +export function basic_type(name) { + const names = typeof name === "string" ? [name] : name; + const idtype = new ca.IdentifierType({ names }); + return new ca.TypeDecl({ declname: null, quals: [], align: [], type: idtype }); +} + +export function pointer(type) { return new ca.PtrDecl({ quals: [], type }); } + +export function resolve_typedefs(type, typemap) { + while (type instanceof ca.TypeDecl && type.type instanceof ca.IdentifierType && type.type.names.length === 1 + && typemap.typedefs.has(type.type.names[0])) { + type = typemap.typedefs.get(type.type.names[0]); + } + return type; +} + +export function pointer_decay(type, typemap) { + const real_type = resolve_typedefs(type, typemap); + if (real_type instanceof ca.ArrayDecl) return pointer(real_type.type); + if (real_type instanceof ca.FuncDecl) return pointer(type); + if (real_type instanceof ca.TypeDecl && real_type.type instanceof ca.Enum) return basic_type("int"); + assert(!isa(type, ca.ArrayDecl, ca.FuncDecl), "resolve_typedefs can't hide arrays/functions"); + return type; +} + +export function get_decl_type(decl) { + assert(decl.name != null); + assert(isa(decl.type, ca.PtrDecl, ca.ArrayDecl, ca.FuncDecl, ca.TypeDecl)); + return decl.type; +} + +export function deref_type(type, typemap) { + type = resolve_typedefs(type, typemap); + assert(isa(type, ca.ArrayDecl, ca.PtrDecl), "dereferencing non-pointer"); + return type.type; +} + +export function struct_member_type(struct, field_name, typemap) { + if (!truthy(struct.decls)) { + assert(typemap.struct_defs.has(struct.name), `Accessing field ${field_name} of undefined struct ${struct.name}`); + struct = typemap.struct_defs.get(struct.name); + } + assert(truthy(struct.decls), "struct_defs never points to an incomplete type"); + for (const decl of struct.decls) { + if (decl instanceof ca.Decl) { + if (decl.name === field_name) return get_decl_type(decl); + if (decl.name == null && isa(decl.type, ca.Struct, ca.Union)) { + try { + return struct_member_type(decl.type, field_name, typemap); + } catch (e) { + if (!(e instanceof AssertionError)) throw e; + } + } + } + } + assert(false, `No field ${field_name} in struct ${struct.name}`); +} + +const truthy = (v) => !(v == null || v === false || v === "" || (Array.isArray(v) && v.length === 0)); + +function varType(typemap, name) { + if (!typemap.var_types.has(name)) throw new KeyError(name); + return typemap.var_types.get(name); +} + +export function expr_type(node, typemap) { + const rec = (sub) => expr_type(sub, typemap); + if (node instanceof ca.Assignment) return rec(node.lvalue); + if (node instanceof ca.StructRef) { + let lhs_type = rec(node.name); + if (node.type === "->") lhs_type = deref_type(lhs_type, typemap); + const struct_type = resolve_typedefs(lhs_type, typemap); + assert(struct_type instanceof ca.TypeDecl); + assert(isa(struct_type.type, ca.Struct, ca.Union), `struct deref of non-struct ${struct_type.declname}`); + return struct_member_type(struct_type.type, node.field.name, typemap); + } + if (node instanceof ca.Cast) return node.to_type.type; + if (node instanceof ca.Constant) { + if (node.type === "string") return pointer(basic_type("char")); + if (node.type === "char") return basic_type("int"); + return basic_type(node.type.split(" ")); + } + if (node instanceof ca.ID) return varType(typemap, node.name); + if (node instanceof ca.UnaryOp) { + if (["p++", "p--", "++", "--"].includes(node.op)) return rec(node.expr); + if (node.op === "&") return pointer(rec(node.expr)); + if (node.op === "*") return deref_type(rec(node.expr), typemap); + if (node.op === "-" || node.op === "+") { + const subtype = pointer_decay(rec(node.expr), typemap); + if (allowed_basic_type(subtype, typemap, ["double"])) return basic_type("double"); + if (allowed_basic_type(subtype, typemap, ["float"])) return basic_type("float"); + } + if (["sizeof", "-", "+", "~", "!"].includes(node.op)) return basic_type("int"); + assert(false, `unknown unary op ${node.op}`); + } + if (node instanceof ca.BinaryOp) { + const lhs_type = pointer_decay(rec(node.left), typemap); + const rhs_type = pointer_decay(rec(node.right), typemap); + if (node.op === ">>" || node.op === "<<") return lhs_type; + if (["<", "<=", ">", ">=", "==", "!=", "&&", "||"].includes(node.op)) return basic_type("int"); + if ("&|^%".includes(node.op)) return basic_type("int"); + const real_lhs = resolve_typedefs(lhs_type, typemap); + const real_rhs = resolve_typedefs(rhs_type, typemap); + if ("+-".includes(node.op)) { + const lptr = real_lhs instanceof ca.PtrDecl; + const rptr = real_rhs instanceof ca.PtrDecl; + if (lptr || rptr) { + if (lptr && rptr) { + assert(node.op !== "+", "pointer + pointer"); + return basic_type("int"); + } + if (lptr) return lhs_type; + assert(node.op === "+", "int - pointer"); + return rhs_type; + } + } + if ("*/+-".includes(node.op)) { + assert(real_lhs instanceof ca.TypeDecl); + assert(real_rhs instanceof ca.TypeDecl); + assert(real_lhs.type instanceof ca.IdentifierType); + assert(real_rhs.type instanceof ca.IdentifierType); + const names = real_lhs.type.names.concat(real_rhs.type.names); + if (names.includes("double")) return basic_type("double"); + if (names.includes("float")) return basic_type("float"); + return basic_type("int"); + } + } + if (node instanceof ca.FuncCall) { + let fptr_type = resolve_typedefs(rec(node.name), typemap); + if (fptr_type instanceof ca.PtrDecl) fptr_type = fptr_type.type; + fptr_type = resolve_typedefs(fptr_type, typemap); + assert(fptr_type instanceof ca.FuncDecl, "call to non-function"); + return fptr_type.type; + } + if (node instanceof ca.ExprList) return rec(node.exprs[node.exprs.length - 1]); + if (node instanceof ca.ArrayRef) return deref_type(rec(node.name), typemap); + if (node instanceof ca.TernaryOp) return rec(node.iftrue); + assert(false, `Unknown expression node type: ${node?.constructor?.name}`); +} + +export function decayed_expr_type(expr, typemap) { return pointer_decay(expr_type(expr, typemap), typemap); } + +function _same_param_type(p1, p2, typemap) { + if (p1 instanceof ca.EllipsisParam && p2 instanceof ca.EllipsisParam) return true; + if (p1 instanceof ca.ID && p2 instanceof ca.ID) return p1.name === p2.name; + if (isa(p1, ca.Typename, ca.Decl) && isa(p2, ca.Typename, ca.Decl) + && isa(p1.type, ca.PtrDecl, ca.ArrayDecl, ca.TypeDecl, ca.FuncDecl) + && isa(p2.type, ca.PtrDecl, ca.ArrayDecl, ca.TypeDecl, ca.FuncDecl) + && same_type(p1.type, p2.type, typemap)) return true; + return false; +} + +export function same_type(type1, type2, typemap, allow_similar = false) { + for (;;) { + type1 = resolve_typedefs(type1, typemap); + type2 = resolve_typedefs(type2, typemap); + if (type1 instanceof ca.ArrayDecl && type2 instanceof ca.ArrayDecl) { type1 = type1.type; type2 = type2.type; continue; } + if (type1 instanceof ca.PtrDecl && type2 instanceof ca.PtrDecl) { type1 = type1.type; type2 = type2.type; continue; } + if (type1 instanceof ca.TypeDecl && type2 instanceof ca.TypeDecl) { + const sub1 = type1.type, sub2 = type2.type; + if (sub1 instanceof ca.Struct && sub2 instanceof ca.Struct) return sub1.name === sub2.name; + if (sub1 instanceof ca.Union && sub2 instanceof ca.Union) return sub1.name === sub2.name; + if (allow_similar && isa(sub1, ca.IdentifierType, ca.Enum) && isa(sub2, ca.IdentifierType, ca.Enum)) return true; + if (sub1 instanceof ca.Enum && sub2 instanceof ca.Enum) return sub1.name === sub2.name; + if (sub1 instanceof ca.IdentifierType && sub2 instanceof ca.IdentifierType) { + const a = sub1.names.slice().sort(), b = sub2.names.slice().sort(); + return a.length === b.length && a.every((x, i) => x === b[i]); + } + } + if (type1 instanceof ca.FuncDecl && type2 instanceof ca.FuncDecl) { + const params1 = type1.args ? type1.args.params : []; + const params2 = type2.args ? type2.args.params : []; + if (params1.length !== params2.length) return false; + for (let i = 0; i < params1.length; i++) if (!_same_param_type(params1[i], params2[i], typemap)) return false; + type1 = type1.type; + type2 = type2.type; + allow_similar = false; + continue; + } + return false; + } +} + +/** Does a type resolve to a basic type with one of the allowed keywords in it? */ +export function allowed_basic_type(type, typemap, allowed_types) { + const base_type = resolve_typedefs(type, typemap); + if (!(base_type instanceof ca.TypeDecl)) return false; + if (!(base_type.type instanceof ca.IdentifierType)) return false; + if (allowed_types.every((x) => !base_type.type.names.includes(x))) return false; + return true; +} + +export function build_typemap(ast, target_fn) { + const ret = newTypeMap(); + for (const item of ast.ext) if (item instanceof ca.Typedef) ret.typedefs.set(item.name, item.type); + let within_fn = false; + const visit = (node) => { + if (node instanceof ca.Struct || node instanceof ca.Union) { + if (truthy(node.decls) && node.name != null) ret.struct_defs.set(node.name, node); + return; + } + if (node instanceof ca.FuncDecl) { visit(node.type); return; } + if (node instanceof ca.Decl) { + if (node.name != null) { + ret.var_types.set(node.name, get_decl_type(node)); + if (within_fn) ret.local_vars.add(node.name); + } + visit(node.type); + return; + } + if (node instanceof ca.Enumerator) { ret.var_types.set(node.name, basic_type("int")); return; } + if (node instanceof ca.FuncDef) { + assert(node.decl.type instanceof ca.FuncDecl); + if (node.decl.name == null) return; + ret.var_types.set(node.decl.name, get_decl_type(node.decl)); + if (node === target_fn) { + within_fn = true; + if (node.decl.type.args) visit(node.decl.type.args); + visit(node.body); + within_fn = false; + } + return; + } + for (const c of node) visit(c); + }; + visit(ast); + return ret; +} + +export function set_decl_name(decl) { + const name = decl.name; + assert(name != null); + let type = get_decl_type(decl); + while (!(type instanceof ca.TypeDecl)) type = type.type; + type.declname = name; +} + +export { Node }; diff --git a/packages/romdev-permuter/src/ast_util.js b/packages/romdev-permuter/src/ast_util.js new file mode 100644 index 00000000..ff35f806 --- /dev/null +++ b/packages/romdev-permuter/src/ast_util.js @@ -0,0 +1,506 @@ +// ast_util.js - a port of decomp-permuter's src/ast_util.py. +import { c_ast as ca, CParser, CGenerator, ParseError, Node } from "romdev-pycparser"; +import { CandidateConstructionFailure } from "./error.js"; +import { set_decl_name } from "./ast_types.js"; + +/** isinstance(x, (A, B, ...)) */ +export const isa = (x, ...classes) => x != null && classes.some((c) => x instanceof c); + +export class AssertionError extends Error { + constructor(message = "") { super(message); this.name = "AssertionError"; } +} +export function assert(cond, msg) { if (!cond) throw new AssertionError(msg); } + +/** Python truthiness for AST field values (None, '', [], nodes). */ +export const truthy = (v) => !(v == null || v === false || v === 0 || v === "" || (Array.isArray(v) && v.length === 0)); + +/** copy.copy of a node: same class, same field values (lists shared). */ +export function shallowCopy(node) { + const out = Object.create(Object.getPrototypeOf(node)); + for (const k of Object.keys(node)) out[k] = node[k]; + return out; +} + +/** copy.deepcopy of nodes/lists/dicts, preserving sharing within the copied graph. Coords stay shared. */ +export function deepcopy(x, memo = new Map()) { + if (x == null || typeof x !== "object") return x; + if (memo.has(x)) return memo.get(x); + if (Array.isArray(x)) { + const out = []; + memo.set(x, out); + for (const e of x) out.push(deepcopy(e, memo)); + return out; + } + if (x instanceof Node) { + const out = Object.create(Object.getPrototypeOf(x)); + memo.set(x, out); + for (const k of Object.keys(x)) out[k] = k === "coord" ? x[k] : deepcopy(x[k], memo); + return out; + } + if (x instanceof Map) { + const out = new Map(); + memo.set(x, out); + for (const [k, v] of x) out.set(deepcopy(k, memo), deepcopy(v, memo)); + return out; + } + if (Object.getPrototypeOf(x) === Object.prototype) { + const out = {}; + memo.set(x, out); + for (const k of Object.keys(x)) out[k] = deepcopy(x[k], memo); + return out; + } + return x; +} + +export function to_c_raw(node) { return new CGenerator().visit(node); } + +export function to_c(node, { from_import = false } = {}) { + const source = from_import ? to_c_raw(node) : new PatchedCGenerator().visit(node); + return process_pragmas(source); +} + +export function process_pragmas(source) { + // Support MWCC-specific "u32 var : 0x1234;" syntax encoded as standard C + // "u32 var = FIXEDADDR(0x1234)". + source = source.replaceAll(" = FIXEDADDR(", " : ("); + if (!source.includes("#pragma")) return source; + const lines = source.split("\n"); + const out = []; + let same_line = 0; + let ignore = 0; + for (let line of lines) { + let stripped = line.trim(); + if (stripped.startsWith("#pragma _permuter ")) { + line = ""; + stripped = stripped.slice("#pragma _permuter ".length); + if (stripped === "sameline start") same_line += 1; + else if (stripped === "sameline end") same_line -= 1; + else if (stripped === "latedefine start") ignore += 1; + else if (stripped === "latedefine end") { + assert(ignore > 0, "mismatched ignore pragmas"); + ignore -= 1; + } else if (stripped.startsWith("define ")) { + assert(ignore > 0, "define pragma must be within latedefine block"); + line = "#" + stripped; + } else if (stripped.startsWith("b64literal ")) { + line = Buffer.from(stripped.split(" ").slice(1).join(" "), "base64").toString("utf8"); + } + } else if (ignore > 0) { + line = ""; + } + if (!same_line) line += "\n"; + else if (line && out.length && !out[out.length - 1].endsWith("\n")) line = " " + line.replace(/^\s+/, ""); + out.push(line); + } + assert(same_line === 0); + assert(ignore === 0, "unbalanced ignore pragmas"); + return out.join("").replace(/\s+$/, "") + "\n"; +} + +/** Like a CGenerator, except it keeps else-ifs prettier despite normalize_ast. */ +export class PatchedCGenerator extends CGenerator { + visit_If(n) { + let n2 = n; + if (n.iffalse && n.iffalse instanceof ca.Compound && truthy(n.iffalse.block_items) + && n.iffalse.block_items.length === 1 && n.iffalse.block_items[0] instanceof ca.If) { + n2 = new ca.If(n.cond, n.iftrue, n.iffalse.block_items[0]); + } + return super.visit_If(n2); + } +} + +export function extract_fn(ast, fn_name) { + const ret = []; + for (let i = 0; i < ast.ext.length; i++) { + let node = ast.ext[i]; + if (node instanceof ca.FuncDef) { + if (node.decl.name === fn_name) ret.push([node, i]); + else if (!node.decl.funcspec.includes("inline")) { + node = node.decl; + ast.ext[i] = node; + } + } + if (node instanceof ca.Decl && node.type instanceof ca.FuncDecl) { + node.storage = node.storage.filter((st) => st !== "static"); + } + } + if (ret.length === 0) throw new CandidateConstructionFailure(`Function ${fn_name} not found in base.c.`); + if (ret.length > 1) throw new CandidateConstructionFailure(`Found multiple copies of function ${fn_name} in base.c.`); + return ret[0]; +} + +export function parse_c(source, { from_import = false } = {}) { + source = source.replace(/^#ident[^\n]*/gm, ""); + try { + const parser = new CParser(); + const ast = parser.parse(source, ""); + deduplicate_typedefs(ast); + return ast; + } catch (e) { + if (!(e instanceof ParseError)) throw e; + const full = String(e.message); + const k = full.indexOf(": "); + const position = full.slice(0, k); + const msg = full.slice(k + 2); + const parts = position.split(":"); + let posstr; + if (parts.length >= 2) { + const lineno = pyIntStrict(parts[1]); + posstr = ` at approximately line ${lineno}`; + if (parts.length >= 3) posstr += `, column ${parts[2]}`; + if (!from_import) posstr += " (after PERM expansion)"; + const lines = source.split("\n"); + const idx = lineno - 1; + const line = idx < 0 ? lines[lines.length + idx] : lines[idx]; + if (line === undefined) posstr += "(out of bounds?)"; + else posstr += "\n\n" + line.replace(/\s+$/, ""); + } else { + posstr = ""; + } + throw new CandidateConstructionFailure(`Syntax error in base.c.\n${msg}${posstr}`); + } +} + +function pyIntStrict(s) { + if (!/^\s*[+-]?\d+\s*$/.test(s)) throw new Error(`invalid literal for int() with base 10: '${s}'`); + return parseInt(s, 10); +} + +/** Node indices for "region" tests: starts/ends keyed by node identity. */ +export function compute_node_indices(top_node) { + const starts = new Map(); + const ends = new Map(); + let cur_index = 1; + const visit = (node) => { + assert(!starts.has(node), "nodes should only appear once in AST"); + starts.set(node, cur_index); + cur_index += 2; + for (const c of node) visit(c); + ends.set(node, cur_index); + cur_index += 2; + }; + visit(top_node); + return { starts, ends }; +} + +/** + * Structural AST equality over constructor fields (equal_ast). `cmp` may + * decide a pair first by returning true/false (null = undecided). + */ +export function equal_ast(a, b, cmp = null) { + const equal = (x, y) => { + if (cmp != null) { + const res = cmp(x, y); + if (res != null) return res; + } + if (typeOfPy(x) !== typeOfPy(y)) return false; + if (x == null) return y == null; + if (Array.isArray(x)) { + if (x.length !== y.length) return false; + for (let i = 0; i < x.length; i++) if (!equal(x[i], y[i])) return false; + return true; + } + if (typeof x === "number" || typeof x === "string" || typeof x === "bigint") return x === y; + assert(x instanceof Node); + assert(y instanceof Node); + for (const name of x.constructor.fields) if (!equal(x[name], y[name])) return false; + return true; + }; + return equal(a, b); +} + +/** type(x) for equal_ast: node class, or a primitive tag. */ +function typeOfPy(x) { + if (x == null) return "None"; + if (Array.isArray(x)) return "list"; + if (x instanceof Node) return x.constructor; + if (typeof x === "boolean") return "bool"; + if (typeof x === "number" || typeof x === "bigint") return "int"; + if (typeof x === "string") return "str"; + if (typeof x === "object" && x.constructor) return x.constructor; + return typeof x; +} + +const EXPR_CLASSES = [ca.ArrayRef, ca.Assignment, ca.BinaryOp, ca.Cast, ca.CompoundLiteral, ca.Constant, + ca.ExprList, ca.FuncCall, ca.ID, ca.StructRef, ca.TernaryOp, ca.UnaryOp]; + +export function as_expr(value) { return isa(value, ...EXPR_CLASSES) ? value : null; } + +export function is_lvalue(expr) { + if (isa(expr, ca.ID, ca.StructRef, ca.ArrayRef)) return true; + if (expr instanceof ca.UnaryOp) return expr.op === "*"; + return false; +} + +export function is_effectful(expr) { + let found = false; + const visit = (node) => { + if (node instanceof ca.UnaryOp) { + if (["p++", "p--", "++", "--"].includes(node.op)) found = true; + else generic(node.expr); + return; + } + if (node instanceof ca.FuncCall || node instanceof ca.Assignment) { found = true; return; } + generic(node); + }; + // NodeVisitor.generic_visit(node): visit each child (the visitor above is + // called on the UnaryOp's operand through generic_visit, as upstream does). + const generic = (node) => { for (const c of node) visit(c); }; + visit(expr); + return found; +} + +export function get_block_stmts(block, force) { + if (block instanceof ca.Compound) { + const ret = block.block_items || []; + if (force && !truthy(block.block_items)) block.block_items = ret; + return ret; + } + const ret = block.stmts || []; + if (force && !truthy(block.stmts)) block.stmts = ret; + return ret; +} + +export function make_decl(name, type, { quals = null, align = null, storage = null, funcspec = null, + gcc_attributes = null, init = null, bitsize = null, asmlabel = null } = {}) { + type = deepcopy(type); + const decl = new ca.Decl({ + name, + quals: quals || [], + align: align || [], + storage: storage || [], + funcspec: funcspec || [], + gcc_attributes: gcc_attributes || [], + type, + init, + bitsize, + asmlabel, + }); + set_decl_name(decl); + return decl; +} + +export function insert_decl(fn, varName, type, random = null) { + const decl = make_decl(varName, type); + if (!truthy(fn.body.block_items)) fn.body.block_items = []; + const items = fn.body.block_items; + let index = items.length; + for (let i = 0; i < items.length; i++) { + if (!(items[i] instanceof ca.Decl)) { index = i; break; } + } + if (random) index = random.randint(0, index); + items.splice(index, 0, decl); +} + +export function insert_statements(block, index, stmts) { + get_block_stmts(block, true).splice(index, 0, ...stmts); +} + +export function insert_statement(block, index, stmt) { insert_statements(block, index, [stmt]); } + +export function brace_nested_blocks(stmt) { + const brace = (s) => (isa(s, ca.Compound, ca.Case, ca.Default) ? s : new ca.Compound([s])); + if (isa(stmt, ca.For, ca.While, ca.DoWhile)) stmt.stmt = brace(stmt.stmt); + else if (stmt instanceof ca.If) { + stmt.iftrue = brace(stmt.iftrue); + if (stmt.iffalse) stmt.iffalse = brace(stmt.iffalse); + } else if (stmt instanceof ca.Switch) stmt.stmt = brace(stmt.stmt); + else if (stmt instanceof ca.Label) brace_nested_blocks(stmt.stmt); +} + +export function has_nested_block(node) { + return isa(node, ca.Compound, ca.For, ca.While, ca.DoWhile, ca.If, ca.Switch, ca.Case, ca.Default); +} + +export function for_nested_blocks(stmt, callback) { + const invoke = (s) => { + assert(isa(s, ca.Compound, ca.Case, ca.Default), "brace_nested_blocks should have turned nested statements into blocks"); + callback(s); + }; + if (stmt instanceof ca.Compound) invoke(stmt); + else if (isa(stmt, ca.For, ca.While, ca.DoWhile)) invoke(stmt.stmt); + else if (stmt instanceof ca.If) { + if (stmt.iftrue) invoke(stmt.iftrue); + if (stmt.iffalse) invoke(stmt.iffalse); + } else if (stmt instanceof ca.Switch) invoke(stmt.stmt); + else if (isa(stmt, ca.Case, ca.Default)) invoke(stmt); + else if (stmt instanceof ca.Label) for_nested_blocks(stmt.stmt, callback); +} + +/** Add braces to all ifs/fors/etc., to make it easier to insert statements. */ +export function normalize_ast(fn, ast) { + void ast; + const rec = (block) => { + for (const stmt of get_block_stmts(block, false)) { + brace_nested_blocks(stmt); + for_nested_blocks(stmt, rec); + } + }; + rec(fn.body); +} + +/** + * Multi-name typedefs sharing an anonymous struct/union/enum emit a single + * named definition instead of duplicating the body per typedef. + */ +export function deduplicate_typedefs(ast) { + let temp_shared_id = 0; + const seen_structs = new Set(); + const process_decl = (item) => { + if (isa(item.type, ca.Struct, ca.Union, ca.Enum)) return; + let tp = item.type; + while (!(tp instanceof ca.TypeDecl)) tp = pyGetType(tp); + const inner = tp.type; + if (!isa(inner, ca.Struct, ca.Union, ca.Enum)) return; + const has_body = inner instanceof ca.Enum ? inner.values != null : inner.decls != null; + if (!has_body) return; + if (seen_structs.has(inner)) { + if (!truthy(inner.name)) { + temp_shared_id += 1; + inner.name = `_PermuterAnon${temp_shared_id}`; + } + const fwd = deepcopy(inner); + if (fwd instanceof ca.Enum) fwd.values = null; + else fwd.decls = null; + tp.type = fwd; + } else { + seen_structs.add(inner); + } + }; + const visit = (node) => { + if (node instanceof ca.Decl || node instanceof ca.Typedef) process_decl(node); + for (const c of node) visit(c); + }; + visit(ast); +} + +/** `x.type` with Python attribute semantics. */ +function pyGetType(x) { + if (!(x instanceof Node) || !x.constructor.fields.includes("type")) { + throw new Error(`AttributeError: '${x == null ? "NoneType" : x.constructor.name}' object has no attribute 'type'`); + } + return x.type; +} + +/** + * Prune unnecessary parts of the AST (prune_ast). Used by import tooling; the + * permuter itself does not call it. + */ +export function prune_ast(fn, ast) { + const edges = new Map(); + const addEdge = (name, i) => { if (!edges.has(name)) edges.set(name, []); edges.get(name).push(i); }; + const gc_roots = []; + const can_fwd_declare_typedef = new Set(); + const can_fwd_declare_tagged = new Set(); + const add_type_edges = (tp, i) => { + while (isa(tp, ca.PtrDecl, ca.ArrayDecl)) tp = tp.type; + if (tp instanceof ca.FuncDecl) return; + const inner_type = tp instanceof ca.TypeDecl ? tp.type : tp; + if (isa(inner_type, ca.IdentifierType, ca.Typeof)) return; + if (truthy(inner_type.name)) addEdge(inner_type.name, i); + if (inner_type instanceof ca.Enum && inner_type.values) { + for (const value of inner_type.values.enumerators) addEdge(value.name, i); + } + if (isa(inner_type, ca.Struct, ca.Union) && truthy(inner_type.decls)) { + for (const decl of inner_type.decls) if (decl instanceof ca.Decl) add_type_edges(decl.type, i); + } + }; + for (let i = 0; i < ast.ext.length; i++) { + const item = ast.ext[i]; + if (item instanceof ca.Decl && !item.init) { + if (truthy(item.name)) addEdge(item.name, i); + if (isa(item.type, ca.Struct, ca.Union, ca.Enum) && truthy(item.type.name)) can_fwd_declare_tagged.add(item.type.name); + add_type_edges(item.type, i); + } else if (item instanceof ca.Typedef) { + addEdge(item.name, i); + if (item.type instanceof ca.TypeDecl && isa(item.type.type, ca.Struct, ca.Union, ca.Enum)) can_fwd_declare_typedef.add(item.name); + add_type_edges(item.type, i); + } else if (item instanceof ca.Pragma && item.string.includes("GLOBAL_ASM")) { + // pass + } else if (item !== fn && item instanceof ca.FuncDef) { + assert(item.decl.name != null); + addEdge(item.decl.name, i); + } else { + gc_roots.push(i); + } + } + const mentioned_ids = new Set(); + const idVisit = (node) => { + if (node instanceof ca.Pragma) { for (const t of node.string.match(/[a-zA-Z0-9_$]+/g) ?? []) mentioned_ids.add(t); return; } + if (node instanceof ca.ID) { mentioned_ids.add(node.name); return; } + for (const c of node) idVisit(c); + }; + idVisit(ast); + const gc_todo = gc_roots; + const need_fwd_decl_typedef = []; + const need_fwd_decl_tagged = []; + const add_name = (name) => { + if (edges.has(name)) { + gc_todo.push(...edges.get(name)); + edges.delete(name); + } + }; + const visit = (node) => { + if (node instanceof ca.Pragma) { for (const t of node.string.match(/[a-zA-Z0-9_$]+/g) ?? []) add_name(t); return; } + if (node instanceof ca.ID) { add_name(node.name); return; } + if (node instanceof ca.IdentifierType) { for (const name of node.names) add_name(name); return; } + if (isa(node, ca.Enum)) { if (truthy(node.name) && !node.values) add_name(node.name); } + else if (isa(node, ca.Struct, ca.Union)) { if (truthy(node.name) && !truthy(node.decls)) add_name(node.name); } + else if (node instanceof ca.PtrDecl) { + if (node.type instanceof ca.TypeDecl && truthy(node.type.declname) && !mentioned_ids.has(node.type.declname)) { + const tp = node.type.type; + if (tp instanceof ca.IdentifierType) { + if (tp.names.every((name) => can_fwd_declare_typedef.has(name))) { + need_fwd_decl_typedef.push(...tp.names); + return; + } + } else if (tp instanceof ca.Typeof) { + // pass + } else if (truthy(tp.name) && can_fwd_declare_tagged.has(tp.name)) { + if (!truthy(tp instanceof ca.Enum ? tp.values : tp.decls)) { + need_fwd_decl_tagged.push(tp.name); + return; + } + } + } + } else if (node instanceof ca.TypeDecl) { + if (truthy(node.declname)) add_name(node.declname); + } + for (const c of node) visit(c); + }; + const keep_exts = new Set(); + while (gc_todo.length) { + const i = gc_todo.pop(); + if (!keep_exts.has(i)) { + keep_exts.add(i); + visit(ast.ext[i]); + } + } + let temp_id = 0; + const fwd_declare = (tp) => { + if (isa(tp, ca.Struct, ca.Union)) tp.decls = null; + else if (tp instanceof ca.Enum) tp.values = null; + else assert(false); + }; + const new_ext = []; + ast.ext.forEach((item, i) => { + if (keep_exts.has(i)) { + // keep + } else if (item instanceof ca.Typedef && need_fwd_decl_typedef.includes(item.name)) { + if (!truthy(item.type.type.name)) { + temp_id += 1; + item.type.type.name = `_PermuterTemp${temp_id}`; + } + item.type.type = deepcopy(item.type.type); + fwd_declare(item.type.type); + } else if (item instanceof ca.Decl && isa(item.type, ca.Struct, ca.Union, ca.Enum) && truthy(item.type.name) + && need_fwd_decl_tagged.includes(item.type.name)) { + fwd_declare(item.type); + } else { + return; + } + new_ext.push(item); + }); + ast.ext = new_ext; + return ast.ext.indexOf(fn); +} diff --git a/packages/romdev-permuter/src/candidate.js b/packages/romdev-permuter/src/candidate.js new file mode 100644 index 00000000..94674aa4 --- /dev/null +++ b/packages/romdev-permuter/src/candidate.js @@ -0,0 +1,77 @@ +// candidate.js - decomp-permuter's src/candidate.py: an AST candidate that can +// be randomized, printed, compiled and scored. +import * as ast_util from "./ast_util.js"; +import { Randomizer } from "./randomizer.js"; +import { apply_ast_perms } from "./perm/ast.js"; +import { tryRemove } from "./compiler.js"; + +/** @typedef {{score: number, hash: string|null, source: string|null, profiler?: any}} CandidateResult */ + +// functools.lru_cache(maxsize=16) over (source, fn_name). +const SHARED_AST_CACHE = new Map(); +const CACHE_SIZE = 16; + +function cachedSharedAst(source, fn_name) { + const key = fn_name + "\u0000" + source; + if (SHARED_AST_CACHE.has(key)) { + const v = SHARED_AST_CACHE.get(key); + SHARED_AST_CACHE.delete(key); + SHARED_AST_CACHE.set(key, v); + return v; + } + const ast = ast_util.parse_c(source); + const [orig_fn, fn_index] = ast_util.extract_fn(ast, fn_name); + ast_util.normalize_ast(orig_fn, ast); + const v = [orig_fn, fn_index, ast]; + SHARED_AST_CACHE.set(key, v); + if (SHARED_AST_CACHE.size > CACHE_SIZE) SHARED_AST_CACHE.delete(SHARED_AST_CACHE.keys().next().value); + return v; +} + +export class Candidate { + constructor({ ast, fn_name, rng_seed, randomizer }) { + this.ast = ast; + this.fn_name = fn_name; + this.rng_seed = rng_seed; + this.randomizer = randomizer; + this.score_value = null; + this.score_hash = null; + this._cache_source = null; + } + + static from_source(source, eval_state, fn_name, randomization_weights, rng_seed) { + // Share the AST between candidates of the same source, deep-copying only + // the target function (the rest is never mutated in place). + const [orig_fn, fn_index, shared] = cachedSharedAst(source, fn_name); + const ast = ast_util.shallowCopy(shared); + ast.ext = shared.ext.slice(); + const fn_copy = ast_util.deepcopy(orig_fn); + ast.ext[fn_index] = fn_copy; + apply_ast_perms(fn_copy, eval_state); + return new Candidate({ ast, fn_name, rng_seed, randomizer: new Randomizer(randomization_weights, rng_seed) }); + } + + randomize_ast() { + this.randomizer.randomize(this.ast, this.fn_name); + this._cache_source = null; + } + + get_source() { + if (this._cache_source == null) this._cache_source = ast_util.to_c(this.ast); + return this._cache_source; + } + + compile(compiler, show_errors = false) { return compiler.compile(this.get_source(), { show_errors }); } + + /** @returns {Promise} */ + async score(scorer, o_file) { + this.score_value = null; + this.score_hash = null; + try { + [this.score_value, this.score_hash] = await scorer.score(o_file); + } finally { + if (o_file) tryRemove(o_file); + } + return { score: this.score_value, hash: this.score_hash, source: this.get_source() }; + } +} diff --git a/packages/romdev-permuter/src/compiler.js b/packages/romdev-permuter/src/compiler.js new file mode 100644 index 00000000..a28d40bd --- /dev/null +++ b/packages/romdev-permuter/src/compiler.js @@ -0,0 +1,102 @@ +// compiler.js - decomp-permuter's src/compiler.py: compile a candidate with +// the directory's compile.sh, keeping upstream's contract exactly: +// +// bash compile.sh -o +// +// exit status 0 = the object exists and should be scored; anything else is a +// failed compile (score = PENALTY_INF). A caller may instead supply an +// in-process compile function with the same contract. +import { spawn } from "node:child_process"; +import { writeFileSync, mkdirSync, rmSync, copyFileSync, existsSync } from "node:fs"; +import path from "node:path"; +import { randomBytes } from "node:crypto"; + +let bashPath = null; +/** shutil.which("bash") */ +function findBash() { + if (bashPath) return bashPath; + for (const dir of (process.env.PATH ?? "").split(path.delimiter)) { + const p = path.join(dir, "bash"); + if (dir && existsSync(p)) { bashPath = p; return p; } + } + throw new Error("No `bash` executable was found on PATH. Install bash and make sure it's on PATH."); +} + +export function tryRemove(p) { + try { rmSync(p, { force: true }); } catch { /* ignore */ } +} + +export class Compiler { + /** + * @param {string|null} compile_cmd path to compile.sh (passed to `compileFn` as its third argument when given) + * @param {{show_errors?: boolean, debug_mode?: boolean, tmpDir: string, compileFn?: ((cPath: string, oPath: string) => Promise)|null, timeoutMs?: number, log?: (s: string) => void}} opts + */ + constructor(compile_cmd, { show_errors = false, debug_mode = false, tmpDir, compileFn = null, timeoutMs = 0, log = (s) => process.stderr.write(s) }) { + this.compile_cmd = compile_cmd; + this.show_errors = show_errors; + this.debug_mode = debug_mode; + this.tmpDir = tmpDir; + this.compileFn = compileFn; + this.timeoutMs = timeoutMs; + this.log = log; + if (!compileFn) this._bash = findBash(); + mkdirSync(tmpDir, { recursive: true }); + } + + /** + * Try to compile a piece of C code. Returns the path of the resulting .o + * (the caller removes it), or null on failure. + * @param {string} source + * @returns {Promise} + */ + async compile(source, { show_errors = false } = {}) { + show_errors = show_errors || this.show_errors || this.debug_mode; + const tag = randomBytes(6).toString("hex"); + const c_name = path.join(this.tmpDir, `permuter${tag}.c`); + const o_name = path.join(this.tmpDir, `permuter${tag}.o`); + writeFileSync(c_name, source); + if (this.debug_mode) { + this.log("DEBUG MODE: Saving a full copy of base candidate source to ./debug_source.c\n"); + writeFileSync("./debug_source.c", source); + } + let ok; + let output = ""; + try { + if (this.compileFn) { + ok = await this.compileFn(c_name, o_name, this.compile_cmd); + } else { + const r = await runProcess(this._bash, [this.compile_cmd, c_name, "-o", o_name], this.timeoutMs); + ok = r.code === 0; + output = r.output; + } + } catch (e) { + ok = false; + output = String(e?.message ?? e); + } + if (!ok) { + if (show_errors && output) this.log(output); + if (!show_errors) tryRemove(c_name); + tryRemove(o_name); + return null; + } + if (this.debug_mode) { + this.log("DEBUG MODE: Saving the base candidate o file to ./debug_compiled_object.o\n\n"); + copyFileSync(o_name, "./debug_compiled_object.o"); + } + tryRemove(c_name); + return o_name; + } +} + +function runProcess(cmd, args, timeoutMs) { + return new Promise((resolve) => { + const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); + let output = ""; + child.stdout.on("data", (d) => { output += d; }); + child.stderr.on("data", (d) => { output += d; }); + let timer = null; + if (timeoutMs > 0) timer = setTimeout(() => { try { child.kill("SIGKILL"); } catch { /* gone */ } }, timeoutMs); + child.on("error", (e) => { if (timer) clearTimeout(timer); resolve({ code: -1, output: output + String(e.message) }); }); + child.on("close", (code) => { if (timer) clearTimeout(timer); resolve({ code: code ?? -1, output }); }); + }); +} diff --git a/packages/romdev-permuter/src/difflib.js b/packages/romdev-permuter/src/difflib.js new file mode 100644 index 00000000..2ec87d28 --- /dev/null +++ b/packages/romdev-permuter/src/difflib.js @@ -0,0 +1,201 @@ +// difflib.js - the parts of Python's difflib the permuter uses: SequenceMatcher +// (isjunk=None; autojunk as given) with get_opcodes / get_grouped_opcodes, and +// unified_diff. A line-for-line port of CPython Lib/difflib.py, because the +// scorer's penalties are computed from these exact opcodes. +// +// Elements are compared through a key function (identity by default); the +// permuter's diff compares source lines by their stripped text. + +export class SequenceMatcher { + /** + * @param {{autojunk?: boolean, key?: (x:any) => any}} [opts] + */ + constructor({ autojunk = true, key = (x) => x } = {}) { + this.autojunk = autojunk; + this.key = key; + this.a = this.b = null; + this.ka = this.kb = null; + } + + set_seqs(a, b) { this.set_seq1(a); this.set_seq2(b); } + + set_seq1(a) { + if (a === this.a) return; + this.a = a; + this.ka = a.map(this.key); + this.matching_blocks = this.opcodes = null; + } + + set_seq2(b) { + if (b === this.b) return; + this.b = b; + this.kb = b.map(this.key); + this.matching_blocks = this.opcodes = null; + this.fullbcount = null; + this.__chain_b(); + } + + __chain_b() { + const b = this.kb; + /** @type {Map} */ + const b2j = new Map(); + b.forEach((elt, i) => { + let indices = b2j.get(elt); + if (!indices) { indices = []; b2j.set(elt, indices); } + indices.push(i); + }); + this.b2j = b2j; + this.bjunk = new Set(); // isjunk is always None here + this.bpopular = new Set(); + const n = b.length; + if (this.autojunk && n >= 200) { + const ntest = Math.floor(n / 100) + 1; + for (const [elt, idxs] of b2j) if (idxs.length > ntest) this.bpopular.add(elt); + for (const elt of this.bpopular) b2j.delete(elt); + } + } + + find_longest_match(alo, ahi, blo, bhi) { + const a = this.ka, b = this.kb, b2j = this.b2j; + const isbjunk = (x) => this.bjunk.has(x); + let besti = alo, bestj = blo, bestsize = 0; + let j2len = new Map(); + const nothing = []; + for (let i = alo; i < ahi; i++) { + const newj2len = new Map(); + for (const j of b2j.get(a[i]) ?? nothing) { + if (j < blo) continue; + if (j >= bhi) break; + const k = (j2len.get(j - 1) ?? 0) + 1; + newj2len.set(j, k); + if (k > bestsize) { besti = i - k + 1; bestj = j - k + 1; bestsize = k; } + } + j2len = newj2len; + } + while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) { + besti--; bestj--; bestsize++; + } + while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) { + bestsize++; + } + while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) { + besti--; bestj--; bestsize++; + } + while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) { + bestsize++; + } + return [besti, bestj, bestsize]; + } + + get_matching_blocks() { + if (this.matching_blocks != null) return this.matching_blocks; + const la = this.a.length, lb = this.b.length; + const queue = [[0, la, 0, lb]]; + const matching_blocks = []; + while (queue.length) { + const [alo, ahi, blo, bhi] = queue.pop(); + const x = this.find_longest_match(alo, ahi, blo, bhi); + const [i, j, k] = x; + if (k) { + matching_blocks.push(x); + if (alo < i && blo < j) queue.push([alo, i, blo, j]); + if (i + k < ahi && j + k < bhi) queue.push([i + k, ahi, j + k, bhi]); + } + } + matching_blocks.sort((p, q) => p[0] - q[0] || p[1] - q[1] || p[2] - q[2]); + let i1 = 0, j1 = 0, k1 = 0; + const non_adjacent = []; + for (const [i2, j2, k2] of matching_blocks) { + if (i1 + k1 === i2 && j1 + k1 === j2) k1 += k2; + else { + if (k1) non_adjacent.push([i1, j1, k1]); + i1 = i2; j1 = j2; k1 = k2; + } + } + if (k1) non_adjacent.push([i1, j1, k1]); + non_adjacent.push([la, lb, 0]); + this.matching_blocks = non_adjacent; + return this.matching_blocks; + } + + get_opcodes() { + if (this.opcodes != null) return this.opcodes; + let i = 0, j = 0; + const answer = []; + this.opcodes = answer; + for (const [ai, bj, size] of this.get_matching_blocks()) { + let tag = ""; + if (i < ai && j < bj) tag = "replace"; + else if (i < ai) tag = "delete"; + else if (j < bj) tag = "insert"; + if (tag) answer.push([tag, i, ai, j, bj]); + i = ai + size; j = bj + size; + if (size) answer.push(["equal", ai, i, bj, j]); + } + return answer; + } + + *get_grouped_opcodes(n = 3) { + let codes = this.get_opcodes().map((c) => c.slice()); + if (!codes.length) codes = [["equal", 0, 1, 0, 1]]; + if (codes[0][0] === "equal") { + const [tag, i1, i2, j1, j2] = codes[0]; + codes[0] = [tag, Math.max(i1, i2 - n), i2, Math.max(j1, j2 - n), j2]; + } + if (codes[codes.length - 1][0] === "equal") { + const [tag, i1, i2, j1, j2] = codes[codes.length - 1]; + codes[codes.length - 1] = [tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]; + } + const nn = n + n; + let group = []; + for (let [tag, i1, i2, j1, j2] of codes) { + if (tag === "equal" && i2 - i1 > nn) { + group.push([tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]); + yield group; + group = []; + i1 = Math.max(i1, i2 - n); + j1 = Math.max(j1, j2 - n); + } + group.push([tag, i1, i2, j1, j2]); + } + if (group.length && !(group.length === 1 && group[0][0] === "equal")) yield group; + } +} + +function formatRangeUnified(start, stop) { + let beginning = start + 1; + const length = stop - start; + if (length === 1) return `${beginning}`; + if (!length) beginning -= 1; + return `${beginning},${length}`; +} + +/** + * difflib.unified_diff(a, b, fromfile, tofile, lineterm="") with an optional + * element key (the permuter's diff compares lines by their stripped text). + * @returns {string[]} + */ +export function unified_diff(a, b, { fromfile = "", tofile = "", n = 3, lineterm = "\n", key } = {}) { + const out = []; + let started = false; + const sm = new SequenceMatcher({ autojunk: true, key }); + sm.set_seqs(a, b); + for (const group of sm.get_grouped_opcodes(n)) { + if (!started) { + started = true; + out.push(`--- ${fromfile}${lineterm}`); + out.push(`+++ ${tofile}${lineterm}`); + } + const first = group[0], last = group[group.length - 1]; + out.push(`@@ -${formatRangeUnified(first[1], last[2])} +${formatRangeUnified(first[3], last[4])} @@${lineterm}`); + for (const [tag, i1, i2, j1, j2] of group) { + if (tag === "equal") { + for (const line of a.slice(i1, i2)) out.push(" " + line); + continue; + } + if (tag === "replace" || tag === "delete") for (const line of a.slice(i1, i2)) out.push("-" + line); + if (tag === "replace" || tag === "insert") for (const line of b.slice(j1, j2)) out.push("+" + line); + } + } + return out; +} diff --git a/packages/romdev-permuter/src/error.js b/packages/romdev-permuter/src/error.js new file mode 100644 index 00000000..b5ced106 --- /dev/null +++ b/packages/romdev-permuter/src/error.js @@ -0,0 +1,10 @@ +// error.js - decomp-permuter's src/error.py. + +export class ServerError extends Error { + constructor(message) { super(message); this.name = "ServerError"; } +} + +/** The base source cannot be turned into a candidate (syntax error, missing function, no compile). */ +export class CandidateConstructionFailure extends Error { + constructor(message) { super(message); this.name = "CandidateConstructionFailure"; } +} diff --git a/packages/romdev-permuter/src/helpers.js b/packages/romdev-permuter/src/helpers.js new file mode 100644 index 00000000..054a32dc --- /dev/null +++ b/packages/romdev-permuter/src/helpers.js @@ -0,0 +1,168 @@ +// helpers.js - decomp-permuter's src/helpers.py (settings + weights), plus the +// small TOML reader those files need. +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { CandidateConstructionFailure } from "./error.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +export const DEFAULT_WEIGHTS_FILE = path.join(here, "..", "default_weights.toml"); + +export function plural(n, noun) { return `${n} ${noun}${n !== 1 ? "s" : ""}`; } + +/** Cut the source down to the target function and what follows (trim_source). */ +export function trim_source(source, fn_name) { + const fn_index = source.indexOf(fn_name); + if (fn_index !== -1) { + const new_index = fn_index === 0 ? -1 : source.lastIndexOf("\n", fn_index - 1); + if (new_index !== -1) return source.slice(new_index); + } + return source; +} + +/** + * Parse the TOML subset settings.toml / default_weights.toml use: tables, + * `key = value` with strings (multi-line ones included), integers, floats, + * booleans and flat arrays, and + * comments. Anything else is rejected rather than guessed. + * @returns {Record} + */ +export function parseToml(text) { + const root = {}; + let cur = root; + const lines = text.split(/\r?\n/); + for (let ln = 0; ln < lines.length; ln++) { + const line = stripComment(lines[ln]).trim(); + if (!line) continue; + let m = /^\[\s*([A-Za-z0-9_.-]+)\s*\]$/.exec(line); + if (m) { + cur = root; + for (const part of m[1].split(".")) { + cur[part] ??= {}; + cur = cur[part]; + } + continue; + } + m = /^([A-Za-z0-9_-]+|"[^"]*")\s*=\s*(.+)$/.exec(line); + if (!m) throw new Error(`TOML: cannot parse line ${ln + 1}: ${lines[ln]}`); + const key = m[1].startsWith("\"") ? m[1].slice(1, -1) : m[1]; + const rest = m[2].trim(); + const delim = rest.startsWith('"""') ? '"""' : rest.startsWith("'''") ? "'''" : null; + if (delim) { + // Multi-line string (settings.toml's compiler_command): a newline right + // after the opening delimiter is trimmed; basic strings take escapes. + let body = rest.slice(3); + let end = body.indexOf(delim); + const startLine = ln; + while (end < 0) { + if (++ln >= lines.length) throw new Error(`TOML: unterminated multi-line string on line ${startLine + 1}`); + body += "\n" + lines[ln]; + end = body.indexOf(delim); + } + if (body.slice(end + 3).trim() && !body.slice(end + 3).trim().startsWith("#")) throw new Error(`TOML: text after a multi-line string on line ${ln + 1}`); + body = body.slice(0, end); + if (body.startsWith("\n")) body = body.slice(1); + cur[key] = delim === "'''" ? body : JSON.parse(`"${body.replace(/\\\s*\n\s*/g, "").replace(/\n/g, "\\n").replace(/"/g, (q, i, s) => (s[i - 1] === "\\" ? q : '\\"'))}"`); + continue; + } + cur[key] = parseTomlValue(rest, ln + 1); + } + return root; +} + +function stripComment(line) { + let inStr = null; + for (let i = 0; i < line.length; i++) { + const c = line[i]; + if (inStr) { + if (c === "\\" && inStr === "\"") { i++; continue; } + if (c === inStr) inStr = null; + } else if (c === "\"" || c === "'") inStr = c; + else if (c === "#") return line.slice(0, i); + } + return line; +} + +function parseTomlValue(v, ln) { + if (v.startsWith("\"")) { + if (!v.endsWith("\"") || v.length < 2) throw new Error(`TOML: bad string on line ${ln}`); + return JSON.parse(v); + } + if (v.startsWith("'")) { + if (!v.endsWith("'") || v.length < 2) throw new Error(`TOML: bad string on line ${ln}`); + return v.slice(1, -1); + } + if (v === "true") return true; + if (v === "false") return false; + if (v.startsWith("[")) { + const inner = v.slice(1, -1).trim(); + if (!inner) return []; + return inner.split(",").map((s) => s.trim()).filter(Boolean).map((s) => parseTomlValue(s, ln)); + } + const clean = v.replaceAll("_", ""); + if (/^[+-]?\d+$/.test(clean)) return { int: Number(clean) }; + if (/^[+-]?(\d+\.\d*|\.\d+|\d+)([eE][+-]?\d+)?$/.test(clean)) return Number(clean); + if (/^0x[0-9a-fA-F]+$/.test(clean)) return { int: Number(clean) }; + throw new Error(`TOML: unsupported value on line ${ln}: ${v}`); +} + +// TOML distinguishes int from float; json_prop's float coercion depends on it. +const isInt = (v) => v != null && typeof v === "object" && "int" in v && Object.keys(v).length === 1; +const unwrap = (v) => (isInt(v) ? v.int : v); + +function typeName(v) { + if (isInt(v)) return "int"; + if (typeof v === "number") return "float"; + if (typeof v === "string") return "str"; + if (typeof v === "boolean") return "bool"; + if (Array.isArray(v)) return "list"; + if (v && typeof v === "object") return "dict"; + return "NoneType"; +} + +/** _json_as_type: str / float (ints coerce) / dict / int. */ +function asType(what, value, t) { + const tn = typeName(value); + if (tn === t) return unwrap(value); + if (t === "float" && tn === "int") return value.int; + throw new Error(`${what} must have type ${t}; got ${tn}`); +} + +export function json_prop(obj, prop, t, dflt = undefined) { + const value = obj[prop]; + if (value === undefined) { + if (dflt !== undefined && dflt !== null) return dflt; + throw new Error(`Member ${prop} does not exist`); + } + return asType("Member " + prop, value, t); +} + +export function json_dict(obj, t) { + const ret = {}; + for (const [key, value] of Object.entries(obj)) ret[key] = asType("Dict entries", value, t); + return ret; +} + +export function merge_randomization_weights(base, overrides) { + const out = {}; + for (const [key, weight] of Object.entries(base)) out[key] = Object.hasOwn(overrides, key) ? overrides[key] : weight; + return out; +} + +export function get_default_randomization_weights(compiler_type, weightsFile = DEFAULT_WEIGHTS_FILE) { + const obj = parseToml(readFileSync(weightsFile, "utf8")); + const base_weights = json_dict(json_prop(obj, "base", "dict", {}), "float"); + if (!(compiler_type in obj)) throw new CandidateConstructionFailure(`Unable to find compiler type ${compiler_type} in default_weights.toml`); + const compiler_weights = json_dict(json_prop(obj, compiler_type, "dict"), "float"); + return merge_randomization_weights(base_weights, compiler_weights); +} + +/** settings.toml of a permuter directory, or {} when absent. */ +export function get_settings(dir) { + let text; + try { text = readFileSync(path.join(dir, "settings.toml"), "utf8"); } catch (e) { + if (e.code === "ENOENT") return {}; + throw e; + } + return parseToml(text); +} diff --git a/packages/romdev-permuter/src/import.js b/packages/romdev-permuter/src/import.js new file mode 100644 index 00000000..9d5116bf --- /dev/null +++ b/packages/romdev-permuter/src/import.js @@ -0,0 +1,728 @@ +// import.js - decomp-permuter's import.py: turn a C file + a function's asm + +// the project's compile command into a permuter directory +// (nonmatchings//{base.c,compile.sh,target.s,target.o,base.o,settings.toml}), +// or upload it to decomp.me. +// +// Every external program upstream runs (make --dry-run / ninja -t commands, +// cpp, the assembler, compile.sh) goes through a toolchain adapter so romdev +// can run them as WASM/JS; see resolveToolchain(). The adapter contract: +// buildCommandLines({root, cFile, makeFlags, buildSystem}) -> {lines, invocation} +// what `make --always-make --dry-run --debug=j PERMUTER=1 ` (or +// `ninja -t commands `) would print, as text lines +// preprocess({cwd, argv, stdin}) -> string argv[0] is "cpp" +// run({cwd, argv}) -> {code, log} the assembler +// compileScript({script, input, output}) -> boolean run a compile.sh +import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync, chmodSync, rmSync, renameSync, copyFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import * as ast_util from "./ast_util.js"; +import { CandidateConstructionFailure } from "./error.js"; +import { get_default_randomization_weights, parseToml } from "./helpers.js"; +import { shlexSplit } from "./scorer.js"; +import { Compiler } from "./compiler.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +export const DEFAULT_ASM_PRELUDE_FILE = path.join(here, "..", "prelude.inc"); +export const DEFAULT_AS_CMDLINE = ["mips-linux-gnu-as", "-march=vr4300", "-mabi=32"]; +const RE_FUNC_NAME = /^[a-zA-Z0-9_$]+$/; +export const CPP = ["cpp", "-P", "-undef"]; +export const STUB_FN_MACROS = [ + "-D_Static_assert(x, y)=", + "-D__attribute__(x)=", + "-DGLOBAL_ASM(...)=", + "-D__asm__(...)=_permuter_ignore_line __asm__(__VA_ARGS__)", +]; +export const SETTINGS_FILES = ["permuter_settings.toml", "tools/permuter_settings.toml", "config/permuter_settings.toml"]; + +/** sys.exit(1) with a message on stderr (the CLI turns it into an exit code). */ +export class ImportExit extends Error { + constructor(message, code = 1) { super(message); this.name = "ImportExit"; this.code = code; } +} + +/** shlex.quote */ +export function shq(s) { + if (!s) return "''"; + if (/^[\w@%+=:,./-]+$/.test(s)) return s; + return "'" + s.replaceAll("'", "'\"'\"'") + "'"; +} +export const formatcmd = (cmdline) => cmdline.map(shq).join(" "); + +function json_dict(data, prop, allow_missing = true) { + if (!(prop in data)) { + if (allow_missing) return {}; + throw new Error(`missing "${prop}" property`); + } + const ret = data[prop]; + if (ret == null || typeof ret !== "object" || Array.isArray(ret)) throw new Error(`"${prop}" property must be a dict`); + return ret; +} + +/** str.splitlines(keepends=True) */ +function splitlinesKeep(s) { + const out = []; + let start = 0; + for (let i = 0; i < s.length; i++) { + if (s[i] === "\n" || s[i] === "\r") { + const end = s[i] === "\r" && s[i + 1] === "\n" ? i + 2 : i + 1; + out.push(s.slice(start, end)); + start = end; + i = end - 1; + } + } + if (start < s.length) out.push(s.slice(start)); + return out; +} +const pySplit = (s) => s.split(/\s+/).filter(Boolean); + +export function prune_asm(asm_cont, log) { + let func_name = null; + const asm_lines = []; + const late_rodata = []; + let cur_section = ".text"; + for (const line of splitlinesKeep(asm_cont)) { + let changed_section = false; + const line_parts = pySplit(line); + if (line_parts.length >= 2 && line_parts[0] === ".section") { + cur_section = line_parts[1]; + changed_section = true; + } else if ([".text", ".rdata", ".rodata", ".late_rodata", ".bss", ".data"].includes(line.trim())) { + cur_section = line.trim(); + changed_section = true; + } + if (cur_section === ".late_rodata") { + if (!changed_section) late_rodata.push(line); + continue; + } + if (func_name == null && cur_section === ".text" && line_parts.length >= 2 && (line_parts[0] === "glabel" || line_parts[0] === ".globl")) { + func_name = line_parts[1]; + } + asm_lines.push(line); + } + if (late_rodata.length) asm_lines.push("\n.section .rodata\n", ...late_rodata); + if (func_name == null) throw new ImportExit("Missing function name in assembly file! The file should start with 'glabel function_name'."); + if (!RE_FUNC_NAME.test(func_name)) throw new ImportExit(`Bad function name: ${func_name}`); + void log; + return [func_name, asm_lines.join("")]; +} + +function find_global_asm_func(root_dir, c_file, func_name) { + let source; + try { source = readFileSync(c_file, "utf8"); } catch (e) { throw new ImportExit(`Could not open C file: ${e.message}`); } + let global_asm = null; + for (const line of splitlinesKeep(source)) { + let stop_global_asm = false; + if (global_asm != null) { + if (line.startsWith(")")) stop_global_asm = true; + else global_asm.push(line); + } else { + if (!line.startsWith("GLOBAL_ASM(") && !line.startsWith("#pragma GLOBAL_ASM(")) continue; + global_asm = []; + if (line.includes(")")) { + const ind = line.indexOf("("); + const ind2 = line.indexOf(")", ind); + const fname = path.join(root_dir, line.slice(ind + 2, ind2 - 1)); + try { + global_asm.push(...splitlinesKeep(readFileSync(fname, "utf8"))); + } catch (e) { + throw new ImportExit(`Failed to open GLOBAL_ASM file ${fname}: ${e.message}`); + } + stop_global_asm = true; + } + } + if (stop_global_asm) { + for (const line2 of global_asm) if (line2.includes("glabel " + func_name)) return global_asm.join(""); + global_asm = null; + } + } + throw new ImportExit(`Failed to find GLOBAL_ASM for function ${func_name}.`); +} + +export function parse_asm(root_dir, c_file, asm_file_or_func_name) { + let require_matching_func_name = false; + let asm_cont; + try { + asm_cont = readFileSync(asm_file_or_func_name, "utf8"); + } catch (e) { + if (RE_FUNC_NAME.test(asm_file_or_func_name)) { + asm_cont = find_global_asm_func(root_dir, c_file, asm_file_or_func_name); + require_matching_func_name = true; + } else { + throw new ImportExit(`Could not open assembly file: ${e.message}`); + } + } + const ret = prune_asm(asm_cont); + if (require_matching_func_name && ret[0] !== asm_file_or_func_name) throw new ImportExit("GLOBAL_ASM file contains multiple functions."); + return ret; +} + +export function create_directory(func_name, cwd = process.cwd()) { + mkdirSync(path.join(cwd, "nonmatchings"), { recursive: true }); + for (let ctr = 1; ; ctr++) { + const dirname = `nonmatchings/${ctr > 1 ? `${func_name}-${ctr}` : func_name}`; + try { + mkdirSync(path.join(cwd, dirname)); + return dirname; + } catch (e) { + if (e.code !== "EEXIST") throw e; + } + } +} + +export function find_root_dir(filename, pattern) { + let old_dirname = null; + let dirname = path.dirname(path.resolve(filename)); + while (dirname && (!old_dirname || dirname.length < old_dirname.length)) { + for (const fname of pattern) { + try { if (statSync(path.join(dirname, fname)).isFile()) return dirname; } catch { /* absent */ } + } + old_dirname = dirname; + dirname = path.dirname(dirname); + } + return null; +} + +export function fixup_build_command(parts, ignore_part) { + let res = []; + let skip_count = 0; + let assembler = null; + const last_o = parts.length - 1 - [...parts].reverse().indexOf("-o"); + parts.forEach((part, i) => { + if (skip_count > 0) { skip_count--; return; } + if (["-MF", "-MT", "-MQ"].includes(part) || i === last_o) { skip_count = 1; return; } + if (["-M", "-MM", "-MG", "-MP", "-MD", "-MMD", "-Mno-modules"].includes(part)) return; + if (part === ignore_part) return; + res.push(part); + }); + // An asm-processor wrapper in the recorded command (upstream matches these + // four substrings); only its argv is read, nothing is run. + const idx = res.findIndex((arg) => /asm_processor|asm-processor|build\.py|preprocess\.py/.test(arg)); + if (idx >= 0) { + const ind1 = res.indexOf("--", idx + 1); + const ind2 = ind1 >= 0 ? res.indexOf("--", ind1 + 1) : -1; + if (ind1 >= 0 && ind2 >= 0) { + const compiler = res.slice(idx + 1, ind1); + assembler = res.slice(ind1 + 1, ind2); + const compiler_args = res.slice(ind2 + 1); + while (compiler.length && compiler[0].startsWith("-")) { + const flag = compiler.shift(); + if (["--input-enc", "--output-enc", "--asm-prelude", "--convert-statics", "--keep-preprocessed"].includes(flag)) compiler.shift(); + } + res = [...compiler, ...compiler_args]; + } + } + return [res, assembler]; +} + +export async function find_build_command_line(toolchain, root_dir, c_file, make_flags, build_system) { + if (build_system !== "make" && build_system !== "ninja") throw new ImportExit(`Unknown build system '${build_system}'.`, 1); + const rel_c_file = path.relative(root_dir, path.resolve(c_file)); + const { lines: debug_output, invocation } = await toolchain.buildCommandLines({ root: root_dir, cFile: rel_c_file, makeFlags: make_flags, buildSystem: build_system }); + const output = []; + let close_match = ""; + let assembler = DEFAULT_AS_CMDLINE; + for (let line of debug_output) { + while (line.includes("//")) line = line.replaceAll("//", "/"); + while (line.includes("/./")) line = line.replaceAll("/./", "/"); + if (!line.includes(rel_c_file)) continue; + close_match = line; + let parts = shlexSplit(line); + if (parts[0] === "bash" && parts.includes("-c")) { + for (const part of parts) { + if (part.includes(rel_c_file)) { parts = shlexSplit(part); break; } + } + } + if (!parts.includes(rel_c_file)) continue; + if (!parts.includes("-o")) continue; + if (parts.includes("-fsyntax-only")) continue; + const [cmdline, asmproc_assembler] = fixup_build_command(parts, rel_c_file); + if (asmproc_assembler) assembler = asmproc_assembler; + output.push(cmdline); + } + if (!output.length) { + const close_extra = close_match ? "\nFound one possible candidate, but didn't match due to " + + "either spaces in paths, having -fsyntax-only, or missing an -o flag:\n" + close_match : ""; + throw new ImportExit("Failed to find compile command from build script output. " + + `Please ensure running '${invocation.join(" ")}' contains a line with the string '${rel_c_file}'.${close_extra}`); + } + if (output.length > 1) { + throw new ImportExit(`Error: found multiple compile commands for ${rel_c_file}:\n${output.map(formatcmd).join("\n")}\n` + + `Please modify the build script such that '${invocation.join(" ")}' produces a single compile command.`); + } + return [output[0], assembler]; +} + +export function build_preserve_macros(preserve_regex, settings) { + const subdata = json_dict(settings, "preserve_macros"); + const regexes = []; + for (const [regex, value] of Object.entries(subdata)) { + if (typeof value !== "string") throw new Error("AssertionError: preserve_macros values must be strings"); + regexes.push([new RegExp(`^(?:${regex})$`), value]); + } + if (preserve_regex === "" || (preserve_regex == null && !regexes.length)) return null; + const global_regex_text = preserve_regex == null ? "(?:" + Object.keys(subdata).join(")|(?:") + ")" : preserve_regex; + const global_regex = new RegExp(`^(?:${global_regex_text})$`); + const type_fn = (macro) => { + for (const [regex, value] of regexes) if (regex.test(macro)) return value; + return "int"; + }; + return [global_regex, type_fn]; +} + +async function preprocess_c_with_macros(toolchain, cpp_command, cwd, preserve_macros) { + const [preserve_regex, preserve_type_fn] = preserve_macros; + let source = await toolchain.preprocess({ cwd, argv: [...cpp_command, "-dD", "-fdirectives-only"] }); + source = source.replace(/^\s*#\s*define\s+([a-zA-Z0-9_]+)([ \t(]|$)/gm, (_m, name, g2) => { + const after = g2 === "(" ? "(" : " "; + return preserve_regex.test(name) ? `_permuter define ${name}${after}` : `#define ${name}${after}`; + }); + source = source.replace(/^#define __STDC_[^\n]*\n/gm, ""); + source = await toolchain.preprocess({ cwd, argv: [...CPP, ...STUB_FN_MACROS], stdin: source }); + const late_defines = []; + const lines = []; + const graph = new Map(); + const g = (k) => { if (!graph.has(k)) graph.set(k, new Set()); return graph.get(k); }; + for (let line of source.split(/\r\n|\r|\n/).filter((_, i, a) => !(i === a.length - 1 && a[i] === ""))) { + const is_macro = line.startsWith("_permuter define "); + let params = []; + let ignore = false; + if (line.includes("_permuter_ignore_line ")) { + line = line.replaceAll("_permuter_ignore_line ", ""); + ignore = true; + } + let name; + if (is_macro) { + const ind1 = line.indexOf("("); + const ind2 = line.indexOf(" ", "_permuter define ".length); + let ind = Math.min(ind1, ind2); + if (ind === -1) ind = ind1 === -1 && ind2 === -1 ? line.length : Math.max(ind1, ind2); + const before = line.slice(0, ind); + const after = line.slice(ind); + name = pySplit(before)[2]; + late_defines.push([name, after]); + if (after.startsWith("(")) params = after.slice(1, after.indexOf(")")).split(",").map((w) => w.trim()); + } else { + if (ignore) lines.push(`#pragma _permuter b64literal ${Buffer.from(line, "utf8").toString("base64")}`); + else lines.push(line); + name = ""; + } + for (const m of line.matchAll(/[a-zA-Z0-9_]+/g)) { + const name2 = m[0]; + let has_wildcard = false; + if (is_macro && !params.includes(name2)) { + const wcbefore = line.slice(0, m.index).replace(/\s+$/, "").endsWith("##"); + const wcafter = line.slice(m.index + name2.length).replace(/^\s+/, "").startsWith("##"); + if (wcbefore || wcafter) { + g(name).add(name2 + "*"); + has_wildcard = true; + } + } + if (!has_wildcard) g(name).add(name2); + } + } + const used_anywhere = new Set(); + const used_by_nonmacro = g(""); + const queue = [""]; + while (queue.length) { + const name = queue.pop(); + if (!used_anywhere.has(name)) { + used_anywhere.add(name); + if (name.endsWith("*")) { + const wildcard = name.slice(0, -1); + for (const [name2, set] of graph) if (name2.includes(wildcard)) queue.push(...set); + } else { + queue.push(...g(name)); + } + } + } + const get_decl = (name, after) => { + const typ = preserve_type_fn(name); + return after.startsWith("(") ? `${typ} ${name}();` : `extern ${typ} ${name};`; + }; + const used_macros = late_defines.filter(([name]) => used_by_nonmacro.has(name)).map(([name]) => name); + return [[ + "#pragma _permuter latedefine start", + ...late_defines.filter(([name]) => used_anywhere.has(name)).map(([name, after]) => `#pragma _permuter define ${name}${after}`), + ...late_defines.filter(([name]) => used_by_nonmacro.has(name)).map(([name, after]) => get_decl(name, after)), + "#pragma _permuter latedefine end", + ...lines, + "", + ].join("\n"), used_macros]; +} + +export async function import_c_file(toolchain, compiler, cwd, in_file, preserve_macros, log) { + in_file = path.relative(cwd, path.resolve(in_file)); + let include_next = 0; + const cpp_command = [...CPP, in_file, "-D__sgi", "-D_LANGUAGE_C", "-DNON_MATCHING", "-DNONMATCHING", "-DPERMUTER", + "-D_MIPS_SZINT=32", "-D_MIPS_SZLONG=32"]; + for (const arg of compiler) { + if (include_next > 0) { include_next--; cpp_command.push(arg); continue; } + if (["-D", "-U", "-I"].includes(arg)) { cpp_command.push(arg); include_next = 1; continue; } + if (arg.startsWith("-D") || arg.startsWith("-U") || arg.startsWith("-I") || arg === "-nostdinc") cpp_command.push(arg); + } + let source, macros; + try { + if (preserve_macros == null) { + source = await toolchain.preprocess({ cwd, argv: [...cpp_command, ...STUB_FN_MACROS] }); + macros = []; + } else { + [source, macros] = await preprocess_c_with_macros(toolchain, cpp_command, cwd, preserve_macros); + } + } catch (e) { + throw new ImportExit("Failed to preprocess input file, when running command:\n" + formatcmd(e.argv ?? cpp_command) + (e.message ? `\n${e.message}` : "")); + } + log(`Preserving ${macros.length ? "macros: " + macros.join(", ") : "no macros"}. Use --preserve-macros='' to override.`); + return source; +} + +export function prune_source(source, should_prune, func_name, log) { + try { + const ast = ast_util.parse_c(source, { from_import: true }); + const [orig_fn] = ast_util.extract_fn(ast, func_name); + if (should_prune) { + try { + ast_util.prune_ast(orig_fn, ast); + source = ast_util.to_c_raw(ast); + } catch (e) { + log("Source minimization failed! You could try --no-prune as a workaround."); + throw e; + } + } + return [source, ast_util.to_c(ast, { from_import: true })]; + } catch (e) { + if (!(e instanceof CandidateConstructionFailure)) throw e; + log(e.message); + if (should_prune && source.includes("PERM_")) log("Please put in PERM macros after import, otherwise source minimization does not work."); + else log("Proceeding anyway, but expect errors when permuting!"); + return [source, null]; + } +} + +export function prune_and_separate_context(source, should_prune, func_name, log) { + let ast; + try { + ast = ast_util.parse_c(source, { from_import: true }); + } catch (e) { + if (!(e instanceof CandidateConstructionFailure)) throw e; + log(e.message); + log("Unable to split context from source."); + log("Using the entire source as context."); + return ["", ast_util.process_pragmas(source)]; + } + let orig_fn, ind; + try { + [orig_fn, ind] = ast_util.extract_fn(ast, func_name); + } catch (e) { + if (!(e instanceof CandidateConstructionFailure)) throw e; + log(e.message); + log("Falling back to just removing function bodies."); + return ["", ast_util.to_c(ast, { from_import: true })]; + } + if (should_prune) { + try { + ind = ast_util.prune_ast(orig_fn, ast); + } catch (e) { + log("Source minimization failed! You could try --no-prune as a workaround."); + throw e; + } + } + ast.ext.splice(ind, 1); + return [ast_util.to_c(orig_fn, { from_import: true }), ast_util.to_c(ast, { from_import: true })]; +} + +/** fnmatch.fnmatch (POSIX: case-sensitive). */ +export function fnmatch(name, pat) { + let re = ""; + for (let i = 0; i < pat.length; i++) { + const c = pat[i]; + if (c === "*") re += "[\\s\\S]*"; + else if (c === "?") re += "[\\s\\S]"; + else if (c === "[") { + let j = i + 1; + if (pat[j] === "!") j++; + if (pat[j] === "]") j++; + while (j < pat.length && pat[j] !== "]") j++; + if (j >= pat.length) re += "\\["; + else { + let stuff = pat.slice(i + 1, j).replaceAll("\\", "\\\\"); + if (stuff.startsWith("!")) stuff = "^" + stuff.slice(1); + else if (stuff.startsWith("^")) stuff = "\\" + stuff; + re += `[${stuff}]`; + i = j; + } + } else re += c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); + } + return new RegExp(`^(?:${re})$`).test(name); +} + +async function get_decompme_compiler_name(compiler, settings, api_base, log) { + const compiler_mappings = json_dict(json_dict(settings, "decompme"), "compilers"); + const compiler_path = compiler[0]; + for (const [p, compiler_name] of Object.entries(compiler_mappings)) { + if (typeof compiler_name !== "string") throw new Error("AssertionError"); + if (fnmatch(compiler_path, p)) return compiler_name; + } + let available_ids = []; + try { + const r = await fetch(`${api_base}/api/compiler`, { headers: { "User-Agent": "decomp-permuter" } }); + const json_data = await r.json(); + available_ids = Object.keys(json_dict(json_data, "compilers", false)); + } catch (e) { + log(`Failed to request available compilers from decomp.me:\n${e.message}`); + } + log(""); + log(`Unable to map compiler path "${compiler_path}" to something decomp.me understands.`); + const trail = "permuter_settings.toml, where ... is one of: " + available_ids.join(", "); + if (Object.keys(compiler_mappings).length) { + log(`Please add an entry: (wildcards allowed!)\n\n"${compiler_path}" = "..."\n\nto the [decompme.compilers] section of ${trail}`); + } else { + log(`Please add a section: (wildcards allowed!)\n\n[decompme.compilers]\n"${compiler_path}" = "..."\n\nto ${trail}`); + } + throw new ImportExit("", 1); +} + +export function finalize_compile_command(cmdline) { + const quoted = cmdline.map((arg) => (arg === "|" ? arg : shq(arg))); + const ind = [...quoted, "|"].indexOf("|"); + return [...quoted.slice(0, ind), '"$INPUT"', ...quoted.slice(ind), "-o", '"$OUTPUT"'].join(" "); +} + +export function get_compiler_flags(settings, cmdline) { + const flags = json_dict(settings, "decompme").flags; + if (flags) { + if (typeof flags !== "string") throw new Error("AssertionError"); + return flags; + } + const out = []; + for (let k = 0; k + 1 < cmdline.length; k++) if (cmdline[k] !== "|" && cmdline[k + 1] !== "|") out.push(cmdline[k + 1]); + return out.map(shq).join(" "); +} + +export function write_compile_command(compiler, cwd, out_file) { + writeFileSync(out_file, "#!/usr/bin/env bash\nset -euo pipefail\nINPUT=\"$(realpath \"$1\")\"\nOUTPUT=\"$(realpath \"$3\")\"\n" + + `cd ${shq(cwd)}\n` + finalize_compile_command(compiler)); + chmodSync(out_file, 0o755); +} + +export function write_asm(asm_prelude_file, asm_cont, out_file) { + const asm_prelude = readFileSync(asm_prelude_file || DEFAULT_ASM_PRELUDE_FILE, "utf8"); + writeFileSync(out_file, asm_prelude + asm_cont); +} + +async function compile_asm(toolchain, assembler, cwd, in_file, out_file) { + const cmdline = [...assembler, path.resolve(in_file), "-o", path.resolve(out_file)]; + const r = await toolchain.run({ cwd, argv: cmdline }); + if (r.code !== 0) throw new ImportExit(`Failed to assemble .s file, command line:\n${formatcmd(cmdline)}${r.log ? "\n" + r.log : ""}`); +} + +/** json.dumps(str) with ensure_ascii. */ +function pyJsonStr(s) { + return JSON.stringify(s).replace(/[\u007f-￿]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")); +} + +async function compile_base(toolchain, compile_script, source, c_file, out_file, tmpDir, log) { + if (source.includes("PERM_")) { + log("Cannot test-compile imported code because it contains PERM macros. It is recommended to put in PERM macros after import."); + return; + } + source = "#line 1 " + pyJsonStr(c_file) + "\n" + source; + const compiler = new Compiler(null, { show_errors: true, tmpDir, log: (s) => process.stderr.write(s), + compileFn: (c, o) => toolchain.compileScript({ script: compile_script, input: c, output: o }) }); + const o_file = await compiler.compile(source); + if (o_file) { + try { renameSync(o_file, out_file); } catch { copyFileSync(o_file, out_file); rmSync(o_file, { force: true }); } + } else { + log("Warning: failed to compile .c file."); + } +} + +/** Python repr of a float weight (100.0, 0.5, 1e-05). */ +function pyFloat(x) { + if (Number.isInteger(x) && Math.abs(x) < 1e16) return x.toFixed(1); + const s = String(x); + if (/e/.test(s)) return s.replace(/e([+-])(\d)$/, "e$10$2"); + if (Math.abs(x) < 1e-4 && x !== 0) { + const [m, e] = x.toExponential().split("e"); + return `${m}e${e[0]}${e.slice(1).padStart(2, "0")}`; + } + return s; +} + +export function create_write_settings_toml(func_name, compiler_type, filename, objdump_command = null) { + const rand_weights = get_default_randomization_weights(compiler_type); + let s = `func_name = "${func_name}"\ncompiler_type = "${compiler_type}"\n`; + if (objdump_command) s += `objdump_command = "${objdump_command}"\n`; + s += "\n# uncomment lines below to customize randomization pass weights\n# see --help=randomization-passes for descriptions\n[weight_overrides]\n"; + for (const [key, weight] of Object.entries(rand_weights)) s += `# ${key} = ${pyFloat(weight)}\n`; + writeFileSync(filename, s); +} + +/** A TOML value as the permuter's settings reader sees it (ints unwrapped). */ +function plain(v) { + if (v && typeof v === "object" && !Array.isArray(v)) { + if ("int" in v && Object.keys(v).length === 1) return v.int; + return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, plain(x)])); + } + return v; +} + +/** + * The adapter that runs build/cpp/as/compile.sh. Order: an explicit module, + * ROMDEV_PERMUTER_TOOLCHAIN, then romdev's own (romdevtools' + * src/decomp/permuter-toolchain.js) when this package sits in the romdev tree + * or beside an installed romdevtools. + */ +export function resolveToolchainUrl(spec = process.env.ROMDEV_PERMUTER_TOOLCHAIN) { + const candidates = []; + if (spec) candidates.push(spec); + candidates.push(path.join(here, "..", "..", "romdevtools", "src", "decomp", "permuter-toolchain.js")); + try { candidates.push(fileURLToPath(new URL("./src/decomp/permuter-toolchain.js", import.meta.resolve("romdevtools/package.json")))); } catch { /* not installed */ } + for (const c of candidates) { + const file = c.startsWith("file:") ? fileURLToPath(c) : path.resolve(c); + if (existsSync(file)) return pathToFileURL(file).href; + } + return null; +} + +export async function resolveToolchain(spec) { + const url = resolveToolchainUrl(spec); + return url ? import(url) : null; +} + +/** + * import.py main(). + * @param {string[]} arg_list + * @param {{log?: (s:string)=>void, toolchain?: object, cwd?: string}} [opts] + * @returns {Promise} the created directory (null for --decompme) + */ +export async function importMain(arg_list, { log = (s) => console.log(s), toolchain = null, cwd = process.cwd() } = {}) { + const args = parseImportArgs(arg_list); + toolchain ??= await resolveToolchain(); + if (!toolchain) throw new ImportExit("no toolchain adapter: import needs romdev's (romdevtools) or ROMDEV_PERMUTER_TOOLCHAIN"); + const c_file = path.resolve(cwd, args.c_file); + const root_dir = find_root_dir(c_file, [...SETTINGS_FILES, "Makefile", "makefile", "build.ninja"]); + if (!root_dir) throw new ImportExit("Can't find root dir of project!"); + let settings = {}; + if (args.settings_file) { + const sf = path.resolve(cwd, args.settings_file); + if (!existsSync(sf)) throw new ImportExit("Can't find settings file!"); + settings = plain(parseToml(readFileSync(sf, "utf8"))); + } else { + for (const filename of SETTINGS_FILES) { + const f = path.join(root_dir, filename); + if (existsSync(f)) { settings = plain(parseToml(readFileSync(f, "utf8"))); break; } + } + } + const get_setting = (key) => { + const value = settings[key]; + if (value == null) return null; + if (typeof value !== "string") throw new ImportExit(`Value of ${key} in settings.toml must be a string, but found: ${value}`); + return value; + }; + const build_system_raw = get_setting("build_system"); + const build_system = build_system_raw || "make"; + const compiler_str = get_setting("compiler_command") || ""; + const assembler_str = get_setting("assembler_command") || ""; + let asm_prelude_file = get_setting("asm_prelude_file"); + const objdump_command = get_setting("objdump_command"); + if (asm_prelude_file != null) asm_prelude_file = path.join(root_dir, asm_prelude_file); + let compiler_type = get_setting("compiler_type"); + if (compiler_type != null) log(`Compiler type: ${compiler_type}`); + else { + compiler_type = "base"; + log("Warning: Compiler type is missing from this project's permuter settings.\n" + + "Defaulting to base compiler randomization settings. For best permutation results,\n" + + "please set 'compiler_type' in this project's permuter_settings.toml."); + } + const asmArg = existsSync(path.resolve(cwd, args.asm_file_or_func_name)) ? path.resolve(cwd, args.asm_file_or_func_name) : args.asm_file_or_func_name; + const [func_name, asm_cont] = parse_asm(root_dir, c_file, asmArg); + log(`Function name: ${func_name}`); + let compiler, assembler; + if (compiler_str || assembler_str) { + if (build_system_raw != null) throw new Error("AssertionError: Must not specify both build system and compiler/assembler"); + compiler = shlexSplit(compiler_str); + assembler = shlexSplit(assembler_str); + } else { + [compiler, assembler] = await find_build_command_line(toolchain, root_dir, c_file, args.make_flags, build_system); + } + log(`Compiler: ${finalize_compile_command(compiler)}`); + log(`Assembler: ${formatcmd(assembler)} "$INPUT" -o "$OUTPUT"`); + const preserve_macros = build_preserve_macros(args.preserve_macros_regex, settings); + let source = await import_c_file(toolchain, compiler, root_dir, c_file, preserve_macros, log); + + if (args.decompme) { + const api_base = process.env.DECOMPME_API_BASE || "https://decomp.me"; + const compiler_name = await get_decompme_compiler_name(compiler, settings, api_base, log); + let context; + [source, context] = prune_and_separate_context(source, args.prune, func_name, log); + try { + const body = new URLSearchParams({ name: func_name, target_asm: asm_cont, context, source_code: source, + compiler: compiler_name, compiler_flags: get_compiler_flags(settings, compiler), diff_label: func_name }); + const r = await fetch(`${api_base}/api/scratch`, { method: "POST", body, headers: { "User-Agent": "decomp-permuter" } }); + const resp = await r.text(); + const json_data = JSON.parse(resp); + if ("slug" in json_data) { + const token = json_data.claim_token; + log(token ? `https://decomp.me/scratch/${json_data.slug}/claim?token=${token}` : `https://decomp.me/scratch/${json_data.slug}`); + } else { + log(`Server error: ${json_data.error ?? resp}`); + } + } catch (e) { + log(String(e.message ?? e)); + } + return null; + } + + let compilable_source; + [source, compilable_source] = prune_source(source, args.prune, func_name, log); + const dirname = create_directory(func_name, cwd); + const abs = (f) => path.join(cwd, f); + const base_c_file = `${dirname}/base.c`; + const compile_script = `${dirname}/compile.sh`; + try { + writeFileSync(abs(base_c_file), source); + create_write_settings_toml(func_name, compiler_type, abs(`${dirname}/settings.toml`), objdump_command); + write_compile_command(compiler, root_dir, abs(compile_script)); + write_asm(asm_prelude_file, asm_cont, abs(`${dirname}/target.s`)); + await compile_asm(toolchain, assembler, root_dir, abs(`${dirname}/target.s`), abs(`${dirname}/target.o`)); + if (compilable_source != null) { + await compile_base(toolchain, abs(compile_script), compilable_source, base_c_file, abs(`${dirname}/base.o`), + path.join(cwd, dirname, ".import-tmp"), log); + rmSync(path.join(cwd, dirname, ".import-tmp"), { recursive: true, force: true }); + } + } catch (e) { + if (!args.keep) { + log(`\nDeleting directory ${dirname} (run with --keep to preserve it).`); + rmSync(abs(dirname), { recursive: true, force: true }); + } + throw e; + } + log(`\nDone. Imported into ${dirname}`); + return path.join(cwd, dirname); +} + +/** import.py's argparse surface. */ +export function parseImportArgs(argv) { + const out = { keep: false, prune: true, decompme: false, preserve_macros_regex: null, settings_file: null, make_flags: [] }; + const pos = []; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const eq = a.startsWith("--") && a.includes("=") ? a.indexOf("=") : -1; + const flag = eq >= 0 ? a.slice(0, eq) : a; + const val = () => { + if (eq >= 0) return a.slice(eq + 1); + if (i + 1 >= argv.length) throw new ImportExit(`argument ${flag}: expected one argument`, 2); + return argv[++i]; + }; + if (flag === "--keep") out.keep = true; + else if (flag === "--no-prune") out.prune = false; + else if (flag === "--decompme") out.decompme = true; + else if (flag === "--preserve-macros") out.preserve_macros_regex = val(); + else if (flag === "--settings") out.settings_file = val(); + else if (a === "--") pos.push(...argv.slice(i + 1)), (i = argv.length); + else pos.push(a); + } + if (pos.length < 2) throw new ImportExit("the following arguments are required: c_file, {asm_file|func_name}", 2); + [out.c_file, out.asm_file_or_func_name] = pos; + out.make_flags = pos.slice(2); + return out; +} diff --git a/packages/romdev-permuter/src/index.js b/packages/romdev-permuter/src/index.js new file mode 100644 index 00000000..2fe554cb --- /dev/null +++ b/packages/romdev-permuter/src/index.js @@ -0,0 +1,29 @@ +// romdev-permuter - a plain-JS port of decomp-permuter +// (https://github.com/simonlindholm/decomp-permuter, pinned +// 41bd0bfc32aa5ea78de4cf28be603163256c2a4c): PERM macros, the randomization +// passes, the objdump-diff scorer and the compile.sh contract, running +// candidate evaluation in node worker threads. +export { run, makeOptions, cycle_seeds, PermuterUsageError, DEFAULT_RAND_KEEP_PROB } from "./main.js"; +export { Permuter } from "./permuter.js"; +export { Candidate } from "./candidate.js"; +export { Compiler } from "./compiler.js"; +export { Scorer, PENALTY_INF } from "./scorer.js"; +export { Randomizer, RANDOMIZATION_PASSES, PASS_DOCS, RandomizationFailure } from "./randomizer.js"; +export { perm_parse } from "./perm/parse.js"; +export { perm_evaluate_one, perm_gen_all_seeds } from "./perm/eval.js"; +export { EvalState } from "./perm/perm.js"; +export { simplify_objdump, get_arch, setObjdumpGlue, resolveObjdumpGlue, objdump, MIPS_SETTINGS, PPC_SETTINGS, ARM32_SETTINGS, X86_SETTINGS } from "./objdump.js"; +export { SequenceMatcher, unified_diff } from "./difflib.js"; +export { runWasmTool } from "./wasm-tool.js"; +export { PyRandom } from "./pyrandom.js"; +export { get_default_randomization_weights, merge_randomization_weights, get_settings, parseToml, trim_source, DEFAULT_WEIGHTS_FILE } from "./helpers.js"; + +/** The upstream this package ports. */ +export const UPSTREAM = Object.freeze({ repo: "https://github.com/simonlindholm/decomp-permuter.git", commit: "41bd0bfc32aa5ea78de4cf28be603163256c2a4c" }); +export { preprocess, PreprocessorRequired } from "./preprocess.js"; +export * as ast_util from "./ast_util.js"; +export * as ast_types from "./ast_types.js"; +export { CandidateConstructionFailure } from "./error.js"; +export { importMain, parseImportArgs, ImportExit, resolveToolchain, resolveToolchainUrl, DEFAULT_ASM_PRELUDE_FILE } from "./import.js"; +export { editops as levenshteinEditops, opcodes as levenshteinOpcodes } from "./levenshtein.js"; +export { libmPow, powNeg15 } from "./pow.js"; diff --git a/packages/romdev-permuter/src/levenshtein.js b/packages/romdev-permuter/src/levenshtein.js new file mode 100644 index 00000000..71ff898a --- /dev/null +++ b/packages/romdev-permuter/src/levenshtein.js @@ -0,0 +1,104 @@ +// levenshtein.js - Levenshtein.opcodes(s1, s2) as the `Levenshtein` package +// (maxbachmann, a wrapper over rapidfuzz) computes it: the permuter's +// --algorithm levenshtein path. A port of rapidfuzz's reference +// implementation (rapidfuzz/distance/Levenshtein_py.py: common-affix +// stripping, Hyyrö's bit-parallel matrix, the documented backtrack order) and +// of Editops.as_opcodes (_initialize_py.py). Sequences are arrays of +// comparable values; bit vectors are BigInts (Python ints). + +function commonAffix(s1, s2) { + let prefix = 0; + while (prefix < s1.length && prefix < s2.length && s1[prefix] === s2[prefix]) prefix++; + let suffix = 0; + while (suffix < s1.length - prefix && suffix < s2.length - prefix + && s1[s1.length - 1 - suffix] === s2[s2.length - 1 - suffix]) suffix++; + return [prefix, suffix]; +} + +function matrix(s1, s2) { + if (!s1.length) return [s2.length, [], []]; + let VP = (1n << BigInt(s1.length)) - 1n; + let VN = 0n; + let currDist = s1.length; + const mask = 1n << BigInt(s1.length - 1); + const block = new Map(); + let x = 1n; + for (const ch1 of s1) { + block.set(ch1, (block.get(ch1) ?? 0n) | x); + x <<= 1n; + } + const matrixVP = [], matrixVN = []; + for (const ch2 of s2) { + const X = block.get(ch2) ?? 0n; + const D0 = (((X & VP) + VP) ^ VP) | X | VN; + let HP = VN | ~(D0 | VP); + let HN = D0 & VP; + if (HP & mask) currDist += 1; + if (HN & mask) currDist -= 1; + HP = (HP << 1n) | 1n; + HN = HN << 1n; + VP = HN | ~(D0 | HP); + VN = HP & D0; + matrixVP.push(VP); + matrixVN.push(VN); + } + return [currDist, matrixVP, matrixVN]; +} + +/** Levenshtein.editops(s1, s2): [tag, src_pos, dest_pos][] */ +export function editops(s1, s2) { + const [prefix, suffix] = commonAffix(s1, s2); + const a = s1.slice(prefix, s1.length - suffix); + const b = s2.slice(prefix, s2.length - suffix); + let [dist, VP, VN] = matrix(a, b); + if (dist === 0) return []; + const ops = new Array(dist); + let col = a.length, row = b.length; + while (row !== 0 && col !== 0) { + if (VP[row - 1] & (1n << BigInt(col - 1))) { + dist--; col--; + ops[dist] = ["delete", col + prefix, row + prefix]; + } else { + row--; + if (row && (VN[row - 1] & (1n << BigInt(col - 1)))) { + dist--; + ops[dist] = ["insert", col + prefix, row + prefix]; + } else { + col--; + if (a[col] !== b[row]) { + dist--; + ops[dist] = ["replace", col + prefix, row + prefix]; + } + } + } + } + while (col !== 0) { dist--; col--; ops[dist] = ["delete", col + prefix, row + prefix]; } + while (row !== 0) { dist--; row--; ops[dist] = ["insert", col + prefix, row + prefix]; } + return ops; +} + +/** Editops.as_opcodes: [tag, i1, i2, j1, j2][] covering both sequences. */ +export function opcodes(s1, s2) { + const ops = editops(s1, s2); + const srcLen = s1.length, destLen = s2.length; + const blocks = []; + let src = 0, dest = 0, i = 0; + while (i < ops.length) { + if (src < ops[i][1] || dest < ops[i][2]) { + blocks.push(["equal", src, ops[i][1], dest, ops[i][2]]); + src = ops[i][1]; + dest = ops[i][2]; + } + const srcBegin = src, destBegin = dest; + const tag = ops[i][0]; + while (i < ops.length && ops[i][0] === tag && src === ops[i][1] && dest === ops[i][2]) { + if (tag === "replace") { src++; dest++; } + else if (tag === "insert") dest++; + else if (tag === "delete") src++; + i++; + } + blocks.push([tag, srcBegin, src, destBegin, dest]); + } + if (src < srcLen || dest < destLen) blocks.push(["equal", src, srcLen, dest, destLen]); + return blocks; +} diff --git a/packages/romdev-permuter/src/main.js b/packages/romdev-permuter/src/main.js new file mode 100644 index 00000000..a4b60c1e --- /dev/null +++ b/packages/romdev-permuter/src/main.js @@ -0,0 +1,515 @@ +// main.js - decomp-permuter's src/main.py: load permuter directories, score +// their bases, then evaluate seeds until done (non-random), a zero is found +// (--stop-on-zero), or the caller aborts. Multi-threaded mode runs the +// candidate evaluation in node worker threads (upstream: multiprocessing). +// +// Output lines match upstream's so existing log readers keep working: +// "[fn] base score = N", "found new best score! (N vs M)", "wrote to ", ... +import { existsSync, mkdirSync, writeFileSync, readFileSync, statSync, rmSync } from "node:fs"; +import path from "node:path"; +import { Worker } from "node:worker_threads"; +import { Compiler } from "./compiler.js"; +import { CandidateConstructionFailure } from "./error.js"; +import { + get_settings, get_default_randomization_weights, json_prop, json_dict, merge_randomization_weights, trim_source, +} from "./helpers.js"; +import { Permuter } from "./permuter.js"; +import { preprocess as defaultPreprocess } from "./preprocess.js"; +import { Scorer, PENALTY_INF } from "./scorer.js"; +import { setObjdumpGlue, resolveObjdumpGlue } from "./objdump.js"; + +export const DEFAULT_RAND_KEEP_PROB = 0.6; + +/** Options with upstream's defaults (main.Options), plus the in-process hooks. */ +export function makeOptions(o) { + return { + directories: o.directories, + show_errors: false, show_timings: false, print_diffs: false, stack_differences: false, + algorithm: "difflib", abort_exceptions: false, better_only: false, best_only: false, + score_threshold: null, quiet: false, stop_on_zero: false, keep_prob: DEFAULT_RAND_KEEP_PROB, + force_seed: null, threads: 1, use_network: false, network_debug: false, network_priority: 1.0, + no_context_output: false, debug_mode: false, speed: 100, ign_branch_targets: true, + // In-process extensions (not upstream flags): + out: null, // (s: string) => void, receives everything upstream prints to stdout + signal: null, // AbortSignal: stop like Ctrl+C ("Exiting.") + pahConfig: null, // permuter@home Config (default: pah.conf in the working directory) + workers: null, // force worker threads even for threads == 1 (keeps the caller's event loop free) + preprocess: null, // (filename) => string: `cpp -P -nostdinc -DPERMUTER` equivalent + compileFn: null, // (cPath, oPath) => Promise instead of compile.sh + compileModule: null, // {url, name, config?}: module export fn(cPath, oPath, config, compileScript) (worker threads import it) + compileTimeoutMs: 0, + tmpDir: null, // scratch dir for candidate .c/.o (default: /.permuter-tmp) + objdumpGlue: null, // {mips: "/path/to/objdump.mjs", ...} + onResult: null, // (info) => void for every scored candidate (stats) + ...o, + }; +} + +class Printer { + constructor(write) { + this.write = write; + this._last_progress = null; + } + + progress(message) { + let clear = ""; + if (this._last_progress != null) { + const pad = Math.max(this._last_progress.length - message.length + 10, 0); + clear = "\b".repeat(pad) + " ".repeat(pad) + "\r"; + } + this.write(clear + message); + this._last_progress = message; + } + + print(message, permuter, who, { color = "", keep_progress = false } = {}) { + if (this._last_progress != null) { + if (keep_progress) this.write("\n"); + else { + const pad = this._last_progress.length + 10; + this.write("\r" + " ".repeat(pad) + "\r"); + } + } + if (permuter != null) message = `[${permuter.unique_name}] ${message}`; + if (who != null) message = `[${who}] ${message}`; + if (color) message = `${color}${message}\u001b[0m`; + this.write(message + "\n"); + this._last_progress = null; + } +} + +function writeCandidate(perm, result, no_context_output, print) { + let ctr = 0; + let output_dir; + for (;;) { + ctr += 1; + output_dir = path.join(perm.dir, `output-${result.score}-${ctr}`); + try { + mkdirSync(output_dir); + break; + } catch (e) { + if (e.code !== "EEXIST") throw e; + } + } + const source = result.source; + if (source == null) throw new Error("Permuter._need_to_send_source is wrong!"); + writeFileSync(path.join(output_dir, "source.c"), no_context_output ? trim_source(source, perm.fn_name) : source, { flag: "wx" }); + writeFileSync(path.join(output_dir, "score.txt"), `${result.score}\n`, { flag: "wx" }); + writeFileSync(path.join(output_dir, "diff.txt"), perm.diff(source) + "\n", { flag: "wx" }); + print(`wrote to ${output_dir}`); + return output_dir; +} + +/** + * Run the permuter over `options.directories`. Resolves to each permuter's + * best score (like main.run) and a `stats` record for the caller. + */ +export async function run(options) { + const o = makeOptions(options); + const write = o.out ?? ((s) => process.stdout.write(s)); + const print = (s = "") => write(s + "\n"); + if (o.compileModule && !o.compileFn) o.compileFn = await loadCompileModule(o.compileModule); + if (o.objdumpGlue) for (const [arch, glue] of Object.entries(o.objdumpGlue)) setObjdumpGlue(arch, glue); + const context = { + printer: new Printer(write), iteration: 0, errors: 0, internal_errors: 0, + internal_error_stack_traces: new Set(), permuters: [], timings: { perm: 0, stringify: 0, compile: 0, score: 0 }, + improvements: [], outputs: [], + }; + const stats = { iterations: 0, compileFailures: 0, internalErrors: 0, improvements: context.improvements, outputs: context.outputs, + stopReason: null, foundZero: false, passCounts: {} }; + print("Loading..."); + let force_seed = null, force_rng_seed = null; + if (o.force_seed) { + const seed_parts = String(o.force_seed).split(",").map((s) => BigInt(s.trim())); + force_rng_seed = seed_parts[seed_parts.length - 1]; + force_seed = seed_parts.length === 1 ? 0n : seed_parts[0]; + } + const name_counts = new Map(); + const configs = []; + for (const d of o.directories) { + const compile_cmd = path.join(d, "compile.sh"); + const target_o = path.join(d, "target.o"); + const base_c = path.join(d, "base.c"); + for (const fname of o.compileFn ? [target_o, base_c] : [compile_cmd, target_o, base_c]) { + if (!existsSync(fname) || !statSync(fname).isFile()) throw new PermuterUsageError(`Missing file ${fname}`); + } + const settings = get_settings(d); + const compiler_type = json_prop(settings, "compiler_type", "str", "base"); + const default_weights = get_default_randomization_weights(compiler_type); + const weight_overrides = json_dict(json_prop(settings, "weight_overrides", "dict", {}), "float"); + const randomization_weights = merge_randomization_weights(default_weights, weight_overrides); + let fn_name = null; + if ("func_name" in settings) fn_name = json_prop(settings, "func_name", "str"); + if (!fn_name) { + try { fn_name = readFileSync(path.join(d, "function.txt"), "utf8").trim(); } catch (e) { if (e.code !== "ENOENT") throw e; } + } + print(fn_name ? `${base_c} (${fn_name})` : base_c); + const tmpDir = o.tmpDir ?? path.join(d, ".permuter-tmp"); + const compilerOpts = { show_errors: o.show_errors, debug_mode: o.debug_mode, tmpDir, timeoutMs: o.compileTimeoutMs, + log: (s) => write(s) }; + const compiler = new Compiler(compile_cmd, { ...compilerOpts, compileFn: o.compileFn }); + const objdump_command = json_prop(settings, "objdump_command", "str", "") || null; + const scorerOpts = { target_o, stack_differences: o.stack_differences, algorithm: o.algorithm, debug_mode: o.debug_mode, + ign_branch_targets: o.ign_branch_targets, objdump_command }; + const scorer = await Scorer.create(scorerOpts); + const c_source = await (o.preprocess ?? defaultPreprocess)(base_c); + const permOpts = { + dir: d, fn_name, source_file: base_c, source: c_source, randomization_weights, force_seed, force_rng_seed, + keep_prob: o.keep_prob, need_profiler: o.show_timings, need_all_sources: o.print_diffs, show_errors: o.show_errors, + best_only: o.best_only, better_only: o.better_only, score_threshold: o.score_threshold, debug_mode: o.debug_mode, + speed: o.speed, + }; + let permuter; + try { + permuter = await Permuter.create({ ...permOpts, compiler, scorer, log: print }); + } catch (e) { + if (e instanceof CandidateConstructionFailure) throw new PermuterUsageError(e.message); + throw e; + } + context.permuters.push(permuter); + configs.push({ permOpts: { ...permOpts, fn_name: permuter.fn_name }, compile_cmd, compileModule: o.compileModule, compilerOpts: { ...compilerOpts, log: undefined }, + scorerOpts, base: { score: permuter.base_score, hash: permuter.base_hash, source: permuter.base_source } }); + name_counts.set(permuter.fn_name, (name_counts.get(permuter.fn_name) ?? 0) + 1); + } + print(); + if (!context.permuters.length) { + print("No permuters!"); + return { bestScores: [], stats }; + } + for (const permuter of context.permuters) { + if (name_counts.get(permuter.fn_name) > 1) permuter.unique_name += ` (${permuter.dir})`; + print(`[${permuter.unique_name}] base score = ${permuter.best_score}`); + } + stats.baseScores = context.permuters.map((p) => p.base_score); + if (o.debug_mode) { + for (const p of context.permuters) { + for (const block of p.scorer.debugLog) write(block + "\n"); + } + print("End of Debug Mode... Exiting"); + return { bestScores: context.permuters.map((p) => p.best_score), stats: { ...stats, stopReason: "debug" } }; + } + + const post_score = (permuter, result, who) => { + if (result.isEvalError) { + context.internal_errors += 1; + stats.internalErrors += 1; + if (result.exc_str != null) { + if (context.internal_error_stack_traces.has(result.exc_str)) return false; + context.internal_error_stack_traces.add(result.exc_str); + context.printer.print("internal permuter failure.", permuter, who, { keep_progress: true }); + print(result.exc_str); + } + if (result.seed != null) { + let seed_str = String(result.seed[1]); + if (result.seed[0] !== 0n) seed_str = `${result.seed[0]},${seed_str}`; + print(`To reproduce the failure, rerun with: --seed ${seed_str}`); + } + if (o.abort_exceptions) throw new PermuterAbort("internal permuter failure (--abort-exceptions)"); + return false; + } + if (o.print_diffs) { + print(); + print(permuter.diff(result.source)); + } + if (result.profiler) for (const k of Object.keys(context.timings)) context.timings[k] += result.profiler[k] ?? 0; + const score_value = result.score; + context.iteration += 1; + stats.iterations = context.iteration; + if (result.pass) stats.passCounts[result.pass] = (stats.passCounts[result.pass] ?? 0) + 1; + let disp_score; + if (score_value === PENALTY_INF) { + disp_score = "inf"; + context.errors += 1; + stats.compileFailures += 1; + } else disp_score = String(score_value); + let status_line = `iteration ${context.iteration}, ${context.errors} errors, `; + if (context.internal_errors) status_line += `${context.internal_errors} permuter failures, `; + status_line += `score = ${disp_score}`; + if (o.show_timings) { + const total = Object.values(context.timings).reduce((a, b) => a + b, 0) || 1; + status_line += " \t" + Object.entries(context.timings).map(([k, v]) => `${Math.round(100 * v / total)}% ${k}`).join(", "); + } + if (o.onResult) o.onResult({ score: score_value, pass: result.pass ?? null, iteration: context.iteration }); + if (permuter.should_output(result)) { + const former_best = permuter.best_score; + permuter.record_result(result); + let color, msg; + if (score_value < former_best) { color = "\u001b[32;1m"; msg = `found new best score! (${score_value} vs ${permuter.base_score})`; } + else if (score_value === former_best) { color = "\u001b[32;1m"; msg = `tied best score! (${score_value} vs ${permuter.base_score})`; } + else if (score_value < permuter.base_score) { color = "\u001b[33m"; msg = `found a better score! (${score_value} vs ${permuter.base_score})`; } + else { color = "\u001b[33m"; msg = `found different asm with same score (${score_value})`; } + context.printer.print(msg, permuter, who, { color }); + const dir = writeCandidate(permuter, result, o.no_context_output, print); + context.outputs.push({ dir, score: score_value, pass: result.pass ?? null, iteration: context.iteration }); + if (score_value < permuter.base_score) context.improvements.push({ score: score_value, previous: permuter.base_score, iteration: context.iteration, pass: result.pass ?? null, dir }); + } + if (!o.quiet) context.printer.progress(status_line); + return score_value === 0; + }; + + let found_zero = false; + const aborted = () => o.signal?.aborted; + const useWorkers = o.workers ?? (o.threads > 1 || o.use_network); + if (useWorkers && o.compileFn && !o.compileModule) throw new PermuterUsageError("worker threads need options.compileModule ({url, name}); a compileFn closure cannot cross threads"); + try { + if (!useWorkers) { + for (const [permuter_index, seed] of cycle_seeds(context.permuters)) { + if (aborted()) { stats.stopReason = "aborted"; break; } + const permuter = context.permuters[permuter_index]; + const start = performance.now(); + const result = await permuter.try_eval_candidate(seed); + if (post_score(permuter, result, null)) { + found_zero = true; + if (o.stop_on_zero) { stats.stopReason = "zero"; break; } + } + if (permuter.speed !== 100) await sleep((performance.now() - start) * (100 / permuter.speed - 1)); + // Yield so an abort signal can land between candidates. + await new Promise((r) => setImmediate(r)); + } + } else { + const r = await runWorkers({ o, context, configs, post_score }); + found_zero = r.found_zero; + stats.stopReason = r.stopReason; + } + } catch (e) { + if (e instanceof PermuterAbort) { stats.stopReason = "abort-exceptions"; print(e.message); } + else throw e; + } finally { + for (const cfg of configs) { + try { rmSync(cfg.compilerOpts.tmpDir, { recursive: true, force: true }); } catch { /* ignore */ } + } + } + if (!stats.stopReason) stats.stopReason = aborted() ? "aborted" : "exhausted"; + if (stats.stopReason === "aborted") { + print(); + print("Exiting."); + } + stats.foundZero = found_zero; + if (found_zero) print("\nFound zero score! Exiting."); + stats.bestScores = context.permuters.map((p) => p.best_score); + return { bestScores: stats.bestScores, stats }; +} + +class PermuterAbort extends Error {} + +/** Import a compile module ({url, name, config}) as a (cPath, oPath) => Promise function. */ +export async function loadCompileModule({ url, name, config = null }) { + const fn = (await import(url))[name]; + if (typeof fn !== "function") throw new PermuterUsageError(`compile module ${url} has no function ${name}`); + return (cPath, oPath, script) => fn(cPath, oPath, config, script); +} + +export class PermuterUsageError extends Error { + constructor(message) { super(message); this.name = "PermuterUsageError"; } +} + +const sleep = (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms))); + +/** All (permuter index, seed) pairs, cycling over permuters (main.cycle_seeds). */ +export function* cycle_seeds(permuters) { + const iterators = permuters.map((p, i) => [i, p.seed_iterator()]); + let i = 0; + while (iterators.length) { + i %= iterators.length; + const [perm_ind, it] = iterators[i]; + const item = it.next(); + if (item.done) { + iterators.splice(i, 1); + i -= 1; + } else { + yield [perm_ind, item.value]; + } + i += 1; + } +} + +const WORKER_URL = new URL("./worker.js", import.meta.url); + +/** + * Multi-threaded evaluation: local worker threads and permuter@home + * connections pull seeds from the parent, which scores and writes results. + */ +async function runWorkers({ o, context, configs, post_score }) { + const seed_iterators = context.permuters.map((p) => p.seed_iterator()); + let seed_iterators_remaining = seed_iterators.length; + let next_iterator_index = 0; + // get_task(-1): round-robin over permuters (local workers); get_task(i): permuter i (a p@h connection). + const get_task = (perm_index = -1) => { + if (perm_index !== -1) { + const it = seed_iterators[perm_index]; + if (it == null) return null; + const n = it.next(); + if (n.done) { seed_iterators[perm_index] = null; seed_iterators_remaining -= 1; return null; } + return [perm_index, n.value]; + } + while (seed_iterators_remaining > 0) { + const idx = next_iterator_index; + next_iterator_index = (next_iterator_index + 1) % seed_iterators.length; + const task = get_task(idx); + if (task) return task; + } + return null; + }; + const threads = Math.max(0, o.threads); + const glue = {}; + for (const p of context.permuters) glue[p.scorer.arch.name] = await resolveObjdumpGlue(p.scorer.arch.name); + let found_zero = false; + let stopReason = null; + let stopping = false; + const workers = []; + const netConns = []; + // Connect to permuter@home first (upstream does, before starting workers). + if (o.use_network) { + const { connect, enable_debug_mode, EOFError } = await import("./net/core.js"); + const { start_client } = await import("./net/client.js"); + const print = (s) => context.printer.write(s + "\n"); + print("Connecting to permuter@home..."); + if (o.network_debug) enable_debug_mode(); + let first_stats = null; + for (let perm_index = 0; perm_index < context.permuters.length; perm_index++) { + let port; + try { + port = await connect(o.pahConfig ?? null); + } catch (e) { + if (e instanceof EOFError || e.name === "ServerError") throw new PermuterUsageError(`Error: ${e.message}`); + throw e; + } + const conn = { queue: [], waiter: null, finished: false, done: null, outstanding: 0, exhausted: false }; + conn.nextTask = () => new Promise((resolve) => { + if (conn.queue.length) resolve(conn.queue.shift()); + else conn.waiter = resolve; + }); + conn.put = (task) => { + if (conn.waiter) { const w = conn.waiter; conn.waiter = null; w(task); } else conn.queue.push(task); + }; + conn.port = port; + netConns.push(conn); + const { done, stats } = await start_client(port, context.permuters[perm_index], perm_index, conn.nextTask, + (item, source, who) => onNetFeedback(item, source, who), o.network_priority); + conn.done = done; + first_stats ??= stats; + } + const plural = (n, noun) => `${n} ${noun}${n !== 1 ? "s" : ""}`; + print(`Connected! ${plural(first_stats[1], "server")} online (${plural(Math.trunc(first_stats[2]), "core")}, ${plural(first_stats[0], "other client")})`); + } + if (!threads && !netConns.length) throw new PermuterUsageError("No workers available! Exiting."); + + let finishAll = () => {}; + let rejectAll = () => {}; + let resolveAll = () => {}; + function onNetFeedback(item, source, who) { + try { + if (item.type === "need_work") { + if (stopping) return; + const conn = netConns[source]; + if (conn.exhausted) return; + const task = get_task(source); + if (task) { conn.outstanding += 1; conn.put(task[1]); } else if (seed_iterators_remaining === 0 || seed_iterators[source] == null) { + // No more seeds for this connection: stop sending, but keep the + // connection until the work already out comes back (upstream never + // hangs up and waits forever; hanging up at once loses results). + stopReason ??= "exhausted"; + conn.exhausted = true; + conn.put(null); + if (conn.outstanding <= 0) conn.port.shutdown(); + } + } else if (item.type === "message") { + context.printer.print(item.text, null, who, { keep_progress: true }); + // A server that disconnects takes its share of the outstanding work with it. + const conn = netConns[source]; + if (conn.exhausted && item.text === "disconnected") conn.port.shutdown(); + } else if (item.type === "done") { + const conn = netConns[source]; + conn.outstanding -= 1; + if (conn.exhausted && conn.outstanding <= 0) conn.port.shutdown(); + if (stopping && o.stop_on_zero && found_zero) return; + if (post_score(context.permuters[source], item.result, who)) { + found_zero = true; + if (o.stop_on_zero) { stopReason = "zero"; finishAll(); } + } + } else if (item.type === "finished") { + const conn = netConns[source]; + conn.finished = true; + if (item.reason) context.printer.print(item.reason, context.permuters.length > 1 ? context.permuters[source] : null, null, { keep_progress: true }); + checkDone(); + } + } catch (e) { + finishAll(); + rejectAll(e); + } + } + let live = 0; + const checkDone = () => { + if (live === 0 && (stopping || netConns.every((c) => c.finished))) resolveAll(); + }; + await new Promise((resolveP, rejectP) => { + resolveAll = resolveP; + rejectAll = rejectP; + finishAll = () => { + if (stopping) return; + stopping = true; + for (const w of workers) w.postMessage({ type: "finish" }); + // Signal the connections that no more work is coming, and hang up. + for (const c of netConns) { c.put(null); c.port.shutdown(); } + checkDone(); + }; + // Abort: let each worker finish the candidate it is on (a compile can own a + // WASM child process that must not be orphaned mid-request), then force it. + const onAbort = () => { + stopReason = "aborted"; + finishAll(); + const t = setTimeout(() => { for (const w of workers) w.terminate(); }, 2000); + t.unref?.(); + }; + if (o.signal) { + if (o.signal.aborted) { stopReason = "aborted"; finishAll(); } + else o.signal.addEventListener("abort", onAbort, { once: true }); + } + for (let k = 0; k < threads && !stopping; k++) { + const w = new Worker(WORKER_URL, { workerData: { configs, glue, keep_prob: o.keep_prob } }); + workers.push(w); + live += 1; + w.on("message", (msg) => { + try { + if (msg.type === "need") { + // Hand out a batch, so a busy parent event loop (the host process + // may be serving other work) does not stall the worker per candidate. + if (stopping) { w.postMessage({ type: "finish" }); return; } + const tasks = []; + for (let q = 0; q < (msg.count ?? 1); q++) { + const task = get_task(); + if (!task) break; + tasks.push({ perm_index: task[0], seed: task[1] }); + } + // An empty, exhausted batch means: drain what you hold, then stop. + if (!tasks.length) stopReason ??= "exhausted"; + w.postMessage({ type: "tasks", tasks, exhausted: !tasks.length }); + } else if (msg.type === "done") { + if (stopping && o.stop_on_zero && found_zero) return; + if (post_score(context.permuters[msg.perm_index], msg.result, null)) { + found_zero = true; + if (o.stop_on_zero) { stopReason = "zero"; finishAll(); } + } + } else if (msg.type === "fatal") { + stopReason = "worker-failed"; + context.printer.print(`worker failed: ${msg.error}`, null, null, { keep_progress: true }); + finishAll(); + } + } catch (e) { + finishAll(); + rejectAll(e); + } + }); + w.on("error", (e) => { context.printer.print(`worker error: ${e.message}`, null, null, { keep_progress: true }); }); + w.on("exit", () => { + live -= 1; + if (live === 0 && (stopping || !netConns.length)) { + o.signal?.removeEventListener?.("abort", onAbort); + if (!netConns.length) resolveAll(); else checkDone(); + } + }); + } + checkDone(); + }); + for (const c of netConns) { c.port.close(); await c.done; } + return { found_zero, stopReason }; +} diff --git a/packages/romdev-permuter/src/net/client.js b/packages/romdev-permuter/src/net/client.js new file mode 100644 index 00000000..378cf263 --- /dev/null +++ b/packages/romdev-permuter/src/net/client.js @@ -0,0 +1,162 @@ +// client.js - the -J side of permuter@home, a port of decomp-permuter's +// src/net/client.py: hand one permuter to the controller, then relay seeds +// out and results back into the local search loop. +import { readFileSync } from "node:fs"; +import { deflateSync, inflateSync } from "node:zlib"; +import { json_prop, permuter_data_to_json, EOFError } from "./core.js"; + +function _result_from_json(obj, source) { + if ("error" in obj) return { isEvalError: true, exc_str: json_prop(obj, "error", "string"), seed: null }; + let profiler = null; + if ("profiler" in obj) { + profiler = {}; + for (const [k, v] of Object.entries(json_prop(obj, "profiler", "dict"))) { + if (!["perm", "stringify", "compile", "score"].includes(k)) throw new Error(`KeyError: '${k}'`); + if (typeof v !== "number") throw new Error(`Member ${k} must have type float`); + profiler[k] = v; + } + } + return { score: json_prop(obj, "score", "int"), hash: "hash" in obj ? json_prop(obj, "hash", "string") : null, source, profiler }; +} + +/** + * Strip the machine-specific parts import.py puts in compile.sh: absolute + * `cd`s, and absolute program paths become `$(which )`. + */ +export function _make_script_portable(source) { + const lines = []; + for (let line of source.split("\n")) { + if (/^cd '?\//.test(line)) continue; + if (/^'?\//.test(line)) { + const quote = line[0] === "'" ? "'" : ""; + let ind = line.indexOf(quote + " "); + if (ind === -1) ind = line.length; + else ind += quote.length; + const lastind = line.lastIndexOf("/", ind - 1); + if (lastind === -1) throw new Error("AssertionError"); + line = "$(which " + quote + line.slice(lastind + 1, ind) + ")" + line.slice(ind); + } + lines.push(line); + } + return lines.join("\n"); +} + +export function make_portable_permuter(permuter) { + return { + base_score: permuter.base_score, + base_hash: permuter.base_hash, + fn_name: permuter.fn_name, + filename: permuter.source_file, + keep_prob: permuter.keep_prob, + need_profiler: permuter.need_profiler, + stack_differences: permuter.scorer.stack_differences, + algorithm: permuter.scorer.algorithm, + randomization_weights: permuter.randomization_weights, + compile_script: _make_script_portable(readFileSync(permuter.compiler.compile_cmd, "utf8")), + source: permuter.source, + target_o_bin: readFileSync(permuter.scorer.target_o), + ign_branch_targets: permuter.scorer.ign_branch_targets, + objdump_command: permuter.scorer.objdump_command, + }; +} + +/** + * One permuter's connection. Feedback goes to `feedback(item, permIndex, serverNick)` + * with items {type:"need_work"} | {type:"message", text} | {type:"done", result} | + * {type:"finished", reason}; tasks are pulled with `nextTask()` (null = no more). + */ +export class Connection { + constructor(port, permuter_data, perm_index, nextTask, feedback) { + this._port = port; + this._permuter_data = permuter_data; + this._perm_index = perm_index; + this._nextTask = nextTask; + this._feedbackFn = feedback; + } + + async _send_permuter() { + const data = this._permuter_data; + await this._port.send_json(permuter_data_to_json(data)); + await this._port.send(deflateSync(Buffer.from(data.source, "utf8"))); + await this._port.send(deflateSync(data.target_o_bin)); + } + + _feedback(item, server_nick) { this._feedbackFn(item, this._perm_index, server_nick); } + + async _receive_one() { + const msg = await this._port.receive_json(); + const msg_type = json_prop(msg, "type", "string"); + if (msg_type === "need_work") return true; + const server_nick = json_prop(msg, "server", "string"); + if (msg_type === "init_done") { + const base_hash = json_prop(msg, "hash", "string"); + let text = "connected"; + if (base_hash !== this._permuter_data.base_hash) text += " (note: mismatching hash)"; + this._feedback({ type: "message", text }, server_nick); + return true; + } + if (msg_type === "init_failed") { + this._feedback({ type: "message", text: "failed to initialize: " + json_prop(msg, "reason", "string") }, server_nick); + return false; + } + if (msg_type === "disconnect") { + this._feedback({ type: "message", text: "disconnected" }, server_nick); + return false; + } + if (msg_type === "result") { + let source = null; + if (msg.has_source === true) { + const compressed = await this._port.receive(); + try { + source = inflateSync(compressed).toString("utf8"); + } catch (e) { + this._feedback({ type: "message", text: "failed to decompress: " + (e.message || e.name) }, server_nick); + return true; + } + } + try { + this._feedback({ type: "done", result: _result_from_json(msg, source) }, server_nick); + } catch (e) { + this._feedback({ type: "message", text: "failed to parse result message: " + (e.message || e.name) }, server_nick); + } + return true; + } + throw new Error(`Invalid message type ${msg_type}`); + } + + async run() { + let finish_reason = null; + try { + await this._send_permuter(); + await this._port.receive_json(); + let finished = false; + for (;;) { + if (!await this._receive_one()) continue; + this._feedback({ type: "need_work" }, null); + if (!finished) { + const task = await this._nextTask(); + if (task == null) finished = true; + else await this._port.send_json({ type: "work", work: { seed: task } }); + } + } + } catch (e) { + if (e instanceof EOFError) finish_reason = "disconnected from permuter@home"; + else finish_reason = `permuter@home error: ${e.message || e.name}`; + } finally { + this._feedback({ type: "finished", reason: finish_reason }, null); + this._port.shutdown(); + this._port.close(); + } + } +} + +/** start_client: announce ourselves and start the relay. Returns {done, stats}. */ +export async function start_client(port, permuter, perm_index, nextTask, feedback, priority) { + await port.send_json({ method: "connect_client", priority }); + const obj = await port.receive_json(); + if ("error" in obj) throw new Error(`Failed to connect: ${json_prop(obj, "error", "string")}`); + const stats = [json_prop(obj, "clients", "int"), json_prop(obj, "servers", "int"), json_prop(obj, "cores", "float")]; + const conn = new Connection(port, make_portable_permuter(permuter), perm_index, nextTask, feedback); + const done = conn.run(); + return { done, stats }; +} diff --git a/packages/romdev-permuter/src/net/controller.js b/packages/romdev-permuter/src/net/controller.js new file mode 100644 index 00000000..4740afc1 --- /dev/null +++ b/packages/romdev-permuter/src/net/controller.js @@ -0,0 +1,648 @@ +// controller.js - the permuter@home control server, a port of +// decomp-permuter's Rust controller (src/net/controller/src/*.rs): accepts +// authenticated clients (-J permuters) and worker servers, schedules clients' +// seeds across servers by priority-weighted energy, relays results back, and +// keeps a JSON database of users and statistics. +import { readFileSync, renameSync, openSync, closeSync, fsyncSync, writeSync } from "node:fs"; +import net from "node:net"; +import path from "node:path"; +import sodium from "libsodium-wrappers"; +import { Box, SigningKey, VerifyKey, SocketPort, StreamReader, nacl, pyJsonDumps, pyJsonLoads, EOFError } from "./core.js"; +import { parseToml } from "../helpers.js"; + +export const HEARTBEAT_TIME_SEC = 300; +const SAVE_INTERVAL_MS = 30_000; +const MIN_PERMUTER_VERSION = 1; +const CLIENT_MAX_QUEUES_SIZE = 100; +const MIN_PRIORITY = 0.001; +const MAX_PRIORITY = 10.0; +const SERVER_WORK_QUEUE_SIZE = 100; +const TIME_US_GUESS = 100_000.0; +const MIN_OVERHEAD_US = 100_000.0; +const MAX_OVERHEAD_FACTOR = 2; + +class ControllerError extends Error {} + +// -- async primitives (tokio's Notify, mpsc, and the flimsy semaphore) ---------- + +/** tokio::sync::Notify: notify_waiters wakes current waiters; notify_one stores a permit. */ +class Notify { + constructor() { this.waiters = []; this.permit = false; } + notified() { + if (this.permit) { this.permit = false; return Promise.resolve(); } + return new Promise((r) => this.waiters.push(r)); + } + notify_waiters() { const w = this.waiters; this.waiters = []; for (const r of w) r(); } + notify_one() { if (this.waiters.length) this.waiters.shift()(); else this.permit = true; } +} + +class Queue { + constructor(capacity = Infinity) { this.items = []; this.waiters = []; this.cap = capacity; this.closed = false; } + put(x) { if (this.waiters.length) this.waiters.shift()(x); else this.items.push(x); } + /** try_send: false when full (the item is dropped). */ + try_put(x) { if (this.items.length >= this.cap) return false; this.put(x); return true; } + get() { + if (this.items.length) return Promise.resolve(this.items.shift()); + if (this.closed) return Promise.resolve(null); + return new Promise((r) => this.waiters.push(r)); + } + close() { this.closed = true; for (const w of this.waiters.splice(0)) w(null); } + /** mpsc capacity(): free slots. */ + capacity() { return this.cap - this.items.length; } +} + +/** An unfair semaphore that allows overdrafts (flimsy_semaphore.rs). */ +class FlimsySemaphore { + constructor(limit) { this.slots = limit; this.notify = new Notify(); } + acquire_ignore_limit() { this.slots -= 1; } + async acquire(isClosed) { + while (this.slots <= 0) { + await this.notify.notified(); + if (isClosed()) throw new EOFError("closed"); + } + this.slots -= 1; + if (this.slots > 0 && this.notify.waiters.length) this.notify.notify_one(); + } + release() { if (this.slots++ === 0) this.notify.notify_one(); } +} + +// -- database (db.rs, save.rs, stats.rs) ---------------------------------------- + +const newStats = () => [0, 0, 0, 0]; // [iterations, improvements, matches, functions] + +export function emptyDb() { return { users: {}, func_stats: {}, total_stats: newStats() }; } + +/** The JSON database, saved atomically (temp file + rename), batched every 30 s. */ +export class SaveableDB { + constructor(file, { saveIntervalMs = SAVE_INTERVAL_MS } = {}) { + this.file = file; + this.db = JSON.parse(readFileSync(file, "utf8")); + this.saveIntervalMs = saveIntervalMs; + this.timer = null; + this.stale = false; + } + + read(fn) { return fn(this.db); } + + async write(immediate, fn) { + const ret = fn(this.db); + if (immediate) { + if (this.timer) { clearTimeout(this.timer); this.timer = null; } + this._save(); + } else if (!this.stale) { + this.stale = true; + this.timer = setTimeout(() => { this.timer = null; this._save(); }, this.saveIntervalMs); + this.timer.unref?.(); + } + return ret; + } + + _save() { + this.stale = false; + const dir = path.dirname(this.file); + const tmp = path.join(dir, `.${path.basename(this.file)}.${process.pid}.tmp`); + const fd = openSync(tmp, "w"); + try { + writeSync(fd, JSON.stringify(this.db)); + fsyncSync(fd); + } finally { + closeSync(fd); + } + renameSync(tmp, this.file); + } + + flush() { + if (this.timer) { clearTimeout(this.timer); this.timer = null; } + if (this.stale) this._save(); + } +} + +function add_stats(stats, outcome) { + if (outcome === "matched") stats[2] += 1; + if (outcome === "matched" || outcome === "improved") stats[1] += 1; + stats[0] += 1; +} + +function func_stat(db, fn_name) { + if (!Object.hasOwn(db.func_stats, fn_name)) db.func_stats[fn_name] = newStats(); + return db.func_stats[fn_name]; +} + +function log_stats(state, record) { + state.db.write(false, (db) => { + if (record.kind === "work_done") { + add_stats(db.total_stats, record.outcome); + add_stats(func_stat(db, record.fn_name), record.outcome); + if (db.users[record.client]) add_stats(db.users[record.client].client_stats, record.outcome); + if (db.users[record.server]) add_stats(db.users[record.server].server_stats, record.outcome); + } else if (record.kind === "client_new_function") { + func_stat(db, record.fn_name)[3] += 1; + if (db.users[record.client]) db.users[record.client].client_stats[3] += 1; + db.total_stats[3] += 1; + } else if (record.kind === "server_new_function") { + if (db.users[record.server]) db.users[record.server].server_stats[3] += 1; + } + }); +} + +// -- setup (setup.rs) ------------------------------------------------------------ + +/** + * Create the database with a root user; returns the text to show (the server's + * priv_seed for config.toml and the root client's pah.conf lines). + */ +export async function run_setup(dbFile) { + await nacl(); + let fd; + try { + fd = openSync(dbFile, "wx"); + } catch (e) { + throw new ControllerError(`Cannot create database file ${dbFile}: ${e.message}. Aborting.`); + } + const server_seed = sodium.randombytes_buf(32); + const client_seed = sodium.randombytes_buf(32); + const server = new SigningKey(server_seed); + const client = new SigningKey(client_seed); + const db = emptyDb(); + db.users[client.verify_key.hex()] = { trusted_by: null, name: "root", client_stats: newStats(), server_stats: newStats() }; + writeSync(fd, JSON.stringify(db)); + closeSync(fd); + return "Setup successful!\n\n" + + "Put the following in the server's config.toml:\n\n" + + `priv_seed = "${server.hex()}"\n\n` + + "Put the following in the root client's pah.conf:\n\n" + + `secret_key = "${client.hex()}"\n` + + `server_public_key = "${server.verify_key.hex()}"\n` + + "server_address = \"server.example:port\""; +} + +// -- handshake and requests (main.rs) --------------------------------------------- + +async function handshake(sock, reader, sign_sk) { + const buffer = await reader.readExact(4 + 32); + if (buffer.subarray(0, 4).toString("latin1") !== "p@h0") throw new ControllerError("Invalid protocol version"); + const their_pk = buffer.subarray(4); + const ours = sodium.crypto_box_keypair(); + const signature = sign_sk.sign(Buffer.concat([Buffer.from("HELLO:"), their_pk, Buffer.from(ours.publicKey)])); + sock.write(Buffer.concat([Buffer.from(ours.publicKey), Buffer.from(signature)])); + const port = new SocketPort(sock, reader, new Box(ours.privateKey, their_pk), "client", { is_client: false }); + const reply = await port.receive(); + if (reply.length !== 32 + 64 + 4) throw new ControllerError("Failed to perform secret handshake"); + const client_ver_key = new VerifyKey(reply.subarray(0, 32)); + const client_signature = reply.subarray(32, 96); + const permuter_version = reply.readUInt32BE(96); + if (!sodium.crypto_sign_verify_detached(client_signature, Buffer.concat([Buffer.from("WORLD:"), Buffer.from(ours.publicKey)]), client_ver_key.pk)) { + throw new ControllerError("Spoofed client signature!"); + } + return { port, user_id: client_ver_key.hex(), permuter_version }; +} + +function current_load(state, priority) { + let servers = 0, cores = 0.0; + for (const server of state.servers.values()) { + if (priority == null || priority >= server.min_priority) { servers += 1; cores += server.num_cores; } + } + return { clients: state.permuters.size, servers, cores }; +} + +const send_error = (port, message) => port.send(Buffer.from(JSON.stringify(message))); +const send_json = (port, v) => port.send(Buffer.from(pyJsonDumps(v), "utf8")); +const recv_json = async (port) => pyJsonLoads((await port.receive()).toString("utf8")); + +function num(obj, k) { + if (typeof obj?.[k] !== "number") throw new ControllerError(`invalid type or missing field \`${k}\``); + return obj[k]; +} + +async function handle_connection(sock, state, who) { + const reader = new StreamReader(sock); + const { port, user_id, permuter_version } = await handshake(sock, reader, state.sign_sk); + const user = state.db.read((db) => db.users[user_id]); + if (!user) { + await send_error(port, "Access denied!"); + throw new ControllerError("Unknown client!"); + } + const name = user.name; + who.name = name; + state.log(`[${name}] connected (v ${permuter_version})`); + if (state.debug) port._who = name; + await send_json(port, {}); + + const request = await recv_json(port); + switch (request?.method) { + case "ping": + state.log(`[${name}] ping`); + await send_json(port, current_load(state, null)); + break; + case "vouch": + await handle_vouch(port, user_id, name, state, request); + break; + case "connect_server": + await handle_connect_server(port, user_id, name, permuter_version, state, { min_priority: num(request, "min_priority"), num_cores: num(request, "num_cores") }); + break; + case "connect_client": + await handle_connect_client(port, user_id, name, permuter_version, state, { priority: num(request, "priority") }); + break; + default: + throw new ControllerError(`unknown variant \`${request?.method}\``); + } +} + +// -- vouch (vouch.rs) ------------------------------------------------------------- + +function parse_signed_name(signed_name, who) { + if (typeof signed_name !== "string" || !/^([0-9a-fA-F]{2})*$/.test(signed_name)) throw new ControllerError("not a valid hex string"); + const data = Buffer.from(signed_name, "hex"); + if (data.length < 64) throw new ControllerError("signature too short"); + const sig = data.subarray(0, 64); + const rest = data.subarray(64); + if (!sodium.crypto_sign_verify_detached(sig, Buffer.concat([Buffer.from("NAME:"), rest]), Buffer.from(who, "hex"))) { + throw new ControllerError("bad signature"); + } + const name = new TextDecoder("utf-8", { fatal: true }).decode(rest); + if (!name) throw new ControllerError("name is empty"); + if (/\p{Cc}/u.test(name)) throw new ControllerError("name cannot contain control characters"); + return name; +} + +async function handle_vouch(port, who_id, who_name, state, data) { + if (typeof data.who !== "string" || !/^[0-9a-fA-F]{64}$/.test(data.who)) throw new ControllerError("byte string has wrong size"); + const who = data.who.toLowerCase(); + let vouchee_name; + try { + vouchee_name = parse_signed_name(data.signed_name, who); + } catch (e) { + await send_error(port, e.message); + throw e; + } + await send_json(port, {}); + await port.receive(); + await state.db.write(true, (db) => { + if (!db.users[who]) db.users[who] = { trusted_by: who_id, name: vouchee_name, client_stats: newStats(), server_stats: newStats() }; + }); + await send_json(port, {}); + state.log(`[${who_name}] vouch ${vouchee_name}`); +} + +// -- clients (client.rs) ----------------------------------------------------------- + +function send_result(perm, res) { + perm.result_q.put(res); + perm.semaphore.acquire_ignore_limit(); +} + +async function handle_connect_client(port, who_id, who_name, permuter_version, state, data) { + if (permuter_version < MIN_PERMUTER_VERSION) throw new ControllerError("Permuter version too old!"); + if (!(MIN_PRIORITY <= data.priority && data.priority <= MAX_PRIORITY)) throw new ControllerError("Priority out of range"); + await send_json(port, current_load(state, data.priority)); + + const permuter_data = await recv_json(port); + if (typeof permuter_data?.fn_name !== "string") throw new ControllerError("missing field `fn_name`"); + const compressed_source = await port.receive(); + const compressed_target_o_bin = await port.receive(); + await send_json(port, {}); + state.log(`[${who_name}] start client (${permuter_data.fn_name}, ${data.priority})`); + log_stats(state, { kind: "client_new_function", client: who_id, fn_name: permuter_data.fn_name }); + + const fn_name = permuter_data.fn_name; + const semaphore = new FlimsySemaphore(CLIENT_MAX_QUEUES_SIZE); + const id = state.next_permuter_id++; + const perm = { + data: { json: permuter_data, compressed_source, compressed_target_o_bin }, + client_id: who_id, + client_name: who_name, + work_queue: [], + result_q: new Queue(), + semaphore, + priority: data.priority, + energy_add: 1.0 / data.priority, + }; + state.permuters.set(id, perm); + state.new_work_notification.notify_waiters(); + + let closed = false; + const isClosed = () => closed; + const client_read = async () => { + for (;;) { + const msg = await recv_json(port); + if (msg?.type !== "work" || msg.work == null || (typeof msg.work.seed !== "number" && typeof msg.work.seed !== "bigint")) { + throw new ControllerError("invalid client message"); + } + await semaphore.acquire(isClosed); + if (perm.work_queue.length === 0) state.new_work_notification.notify_waiters(); + perm.work_queue.push({ seed: msg.work.seed }); + } + }; + const client_write = async () => { + for (;;) { + const res = await perm.result_q.get(); + if (res == null) throw new EOFError("closed"); + semaphore.release(); + if (res.kind === "need_work") { + await send_json(port, { type: "need_work" }); + } else { + const { update } = res; + const out = { server: res.server_name, type: update.type }; + if (update.type === "result") { + out.has_source = update.has_source; + Object.assign(out, update.more_props); + } else if (update.type === "init_done") out.hash = update.hash; + else if (update.type === "init_failed") out.reason = update.reason; + await send_json(port, out); + if (update.type === "result") { + if (update.compressed_source != null) await port.send(update.compressed_source); + const score = update.more_props.score; + const outcome = update.compressed_source == null ? "unhelpful" : score === 0 ? "matched" : "improved"; + log_stats(state, { kind: "work_done", server: res.server_id, client: who_id, fn_name, outcome }); + } + } + } + }; + try { + await try_join([client_read(), client_write()]); + } finally { + closed = true; + perm.result_q.close(); + semaphore.notify.notify_waiters(); + state.permuters.delete(id); + state.new_work_notification.notify_waiters(); + port.close(); + } +} + +/** tokio::try_join!: resolves when all do, rejects on the first failure. */ +function try_join(promises) { + return Promise.all(promises); +} + +// -- servers (server.rs) ------------------------------------------------------------- + +function parse_update(u) { + if (u == null || typeof u !== "object") throw new ControllerError("invalid update"); + switch (u.type) { + case "result": { + const { type: _t, overhead_us, has_source, ...more_props } = u; + return { type: "result", overhead_us: typeof overhead_us === "number" ? Math.trunc(overhead_us) : 0, has_source: has_source === true, more_props, compressed_source: null }; + } + case "init_done": + if (typeof u.hash !== "string") throw new ControllerError("missing field `hash`"); + return { type: "init_done", hash: u.hash }; + case "init_failed": + if (typeof u.reason !== "string") throw new ControllerError("missing field `reason`"); + return { type: "init_failed", reason: u.reason }; + case "disconnect": + return { type: "disconnect" }; + default: + throw new ControllerError(`unknown variant \`${u.type}\``); + } +} + +function try_next_work_message(state, ss) { + const skip = new Set(); + for (;;) { + for (const [perm_id, perm] of state.permuters) { + if (!ss.jobs.has(perm_id)) { + ss.jobs.set(perm_id, { state: "loading", energy: 0.0, active_work: 0 }); + return { permuter: perm_id, kind: "add", perm }; + } + } + let best_cost = 0.0; + let best = null; + for (const [perm_id, job] of ss.jobs) { + const perm = state.permuters.get(perm_id); + if (!perm) { + ss.active_work -= job.active_work; + ss.jobs.delete(perm_id); + return { permuter: perm_id, kind: "remove" }; + } + const energy = job.energy + job.active_work * perm.energy_add * TIME_US_GUESS; + if (job.state === "loaded" && !skip.has(perm_id) && perm.priority >= ss.min_priority && (best == null || energy < best_cost)) { + best_cost = energy; + best = [perm_id, job]; + } + } + if (best == null) return null; + const [perm_id, job] = best; + const perm = state.permuters.get(perm_id); + if (perm.work_queue.length === 0) { + send_result(perm, { kind: "need_work" }); + skip.add(perm_id); + continue; + } + const work = perm.work_queue.shift(); + perm.semaphore.release(); + const min_energy = job.energy; + job.active_work += 1; + ss.active_work += 1; + for (const j of ss.jobs.values()) j.energy -= min_energy; + return { permuter: perm_id, kind: "work", work }; + } +} + +async function handle_connect_server(port, who_id, who_name, permuter_version, state, data) { + if (permuter_version < MIN_PERMUTER_VERSION) throw new ControllerError("Permuter version too old!"); + state.log(`[${who_name}] start server (${data.min_priority}, ${data.num_cores})`); + await send_json(port, { docker_image: state.docker_image, heartbeat_interval: state.heartbeat_sec }); + + const more_work = new Queue(SERVER_WORK_QUEUE_SIZE); + const writer_q = new Queue(); + const wrote_message = new Notify(); + const new_permuter = new Notify(); + const ss = { min_priority: data.min_priority, active_work: 0, more_work_acc: 0.0, jobs: new Map() }; + const server_key = Symbol(who_name); + state.servers.set(server_key, { min_priority: data.min_priority, num_cores: data.num_cores, writer_q }); + let closed = false; + const check = () => { if (closed) throw new EOFError("closed"); }; + + const server_read = async () => { + for (;;) { + const msg = await recv_json(port); + let update = null, perm_id = null, time_us = 0; + if (msg?.type === "update") { + if (!Number.isInteger(msg.permuter)) throw new ControllerError("invalid type: `permuter`"); + perm_id = msg.permuter; + time_us = num(msg, "time_us"); + update = parse_update(msg.update); + if (update.type === "result" && update.has_source) update.compressed_source = await port.receive(); + } else if (msg?.type !== "need_work") { + throw new ControllerError(`unknown variant \`${msg?.type}\``); + } + let has_new = false; + let more = 1.0; + if (update) { + const job = ss.jobs.get(perm_id); + const perm = job ? state.permuters.get(perm_id) : null; + if (job && perm) { + job.energy += perm.energy_add * time_us; + if (update.type === "init_done") { + if (job.state !== "loading") throw new ControllerError("Got InitDone while not in Loading state"); + job.state = "loaded"; + has_new = true; + } else if (update.type === "init_failed") { + if (job.state !== "loading") throw new ControllerError("Got InitFailed while not in Loading state"); + job.state = "failed"; + } else if (update.type === "disconnect") { + if (job.state !== "loaded") throw new ControllerError("Got Disconnect while not in Loaded state"); + job.state = "failed"; + ss.active_work -= job.active_work; + job.active_work = 0; + more = 0.0; + } else { + if (job.state !== "loaded") throw new ControllerError("Got result while not in Loaded state"); + job.active_work -= 1; + ss.active_work -= 1; + const min_overhead_us = Math.trunc(time_us + MIN_OVERHEAD_US); + if (update.overhead_us === 0) { + // Legacy server, skip this logic. + } else if (update.overhead_us > MAX_OVERHEAD_FACTOR * min_overhead_us) more = 0.5; + else if (update.overhead_us < min_overhead_us) more = 1.5; + } + send_result(perm, { kind: "result", server_id: who_id, server_name: who_name, update }); + } + } + more += ss.more_work_acc; + let request_work = Math.trunc(more); + ss.more_work_acc = more - request_work; + if (request_work === 0 && ss.active_work === 0 && more_work.capacity() === SERVER_WORK_QUEUE_SIZE) request_work = 1; + if (has_new) { + new_permuter.notify_waiters(); + log_stats(state, { kind: "server_new_function", server: who_id }); + } + for (let k = 0; k < request_work; k++) more_work.try_put(true); + } + }; + + const next_work_message = async () => { + for (;;) { + check(); + const message = try_next_work_message(state, ss); + if (message) return message; + await Promise.race([state.new_work_notification.notified(), new_permuter.notified(), closedPromise]); + } + }; + + let signalClosed; + const closedPromise = new Promise((r) => { signalClosed = r; }); + + const server_choose_work = async () => { + for (;;) { + const message = await next_work_message(); + check(); + const requires_response = message.kind !== "remove"; + writer_q.put(message); + await Promise.race([wrote_message.notified(), closedPromise]); + check(); + if (requires_response) { + await more_work.get(); + check(); + } + } + }; + + const server_write = async () => { + for (;;) { + const item = await writer_q.get(); + if (item == null) throw new EOFError("closed"); + if (item.kind === "heartbeat") { + await send_json(port, { type: "heartbeat" }); + continue; + } + if (item.kind === "work") { + await send_json(port, { permuter: item.permuter, type: "work", seed: item.work.seed }); + } else if (item.kind === "add") { + await send_json(port, { permuter: item.permuter, type: "add", client_id: item.perm.client_id, client_name: item.perm.client_name, data: item.perm.data.json }); + await port.send(item.perm.data.compressed_source); + await port.send(item.perm.data.compressed_target_o_bin); + } else { + await send_json(port, { permuter: item.permuter, type: "remove" }); + } + wrote_message.notify_one(); + } + }; + + writer_q.put({ kind: "heartbeat" }); + const loops = [server_read(), server_choose_work(), server_write()]; + try { + await Promise.race(loops.map((p) => p.then(() => { throw new ControllerError("loop exited"); }))); + } finally { + closed = true; + signalClosed(); + writer_q.close(); + more_work.close(); + port.close(); + for (const [perm_id, job] of ss.jobs) { + if (job.state === "loaded") { + const perm = state.permuters.get(perm_id); + if (perm) send_result(perm, { kind: "result", server_id: who_id, server_name: who_name, update: { type: "disconnect" } }); + } + } + state.servers.delete(server_key); + await Promise.allSettled(loops); + } +} + +// -- run (main.rs run_server) ----------------------------------------------------------- + +/** + * Start the controller. Returns {address, close()}. + * @param {{listen_on: string, config: string, db: string, debug?: boolean, + * heartbeat_sec?: number, log?: (s: string) => void, saveIntervalMs?: number}} opts + */ +export async function run_controller(opts) { + await nacl(); + const config = parseToml(readFileSync(opts.config, "utf8")); + if (typeof config.docker_image !== "string") throw new ControllerError("missing field `docker_image`"); + if (typeof config.priv_seed !== "string" || !/^[0-9a-fA-F]{64}$/.test(config.priv_seed)) throw new ControllerError("priv_seed: byte string has wrong size"); + const sign_sk = new SigningKey(Buffer.from(config.priv_seed, "hex")); + const log = opts.log ?? ((s) => process.stderr.write(s + "\n")); + const state = { + docker_image: config.docker_image, + debug: !!opts.debug, + sign_sk, + db: new SaveableDB(opts.db, { saveIntervalMs: opts.saveIntervalMs }), + heartbeat_sec: opts.heartbeat_sec ?? HEARTBEAT_TIME_SEC, + new_work_notification: new Notify(), + servers: new Map(), + permuters: new Map(), + next_permuter_id: 0, + log, + }; + const sockets = new Set(); + const heartbeat = setInterval(() => { + for (const s of state.servers.values()) s.writer_q.put({ kind: "heartbeat" }); + }, state.heartbeat_sec * 1000); + heartbeat.unref?.(); + + const server = net.createServer((sock) => { + sockets.add(sock); + sock.setNoDelay(true); + sock.on("error", () => {}); + sock.on("close", () => sockets.delete(sock)); + const who = { name: "anonymous" }; + handle_connection(sock, state, who).catch((e) => { + if (e instanceof EOFError || ["ECONNRESET", "ETIMEDOUT", "EPIPE"].includes(e?.code)) log(`[${who.name}] disconnected`); + else log(`[${who.name}] error: ${e?.message ?? e}`); + }).finally(() => sock.destroy()); + }); + const idx = opts.listen_on.lastIndexOf(":"); + const host = opts.listen_on.slice(0, idx); + const portNum = Number(opts.listen_on.slice(idx + 1)); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(portNum, host.replace(/^\[|\]$/g, ""), resolve); + }); + const addr = server.address(); + return { + address: `${host}:${addr.port}`, + port: addr.port, + state, + async close() { + clearInterval(heartbeat); + for (const s of sockets) s.destroy(); + await new Promise((r) => server.close(r)); + state.db.flush(); + }, + }; +} + +export { ControllerError }; diff --git a/packages/romdev-permuter/src/net/core.js b/packages/romdev-permuter/src/net/core.js new file mode 100644 index 00000000..da86b9c4 --- /dev/null +++ b/packages/romdev-permuter/src/net/core.js @@ -0,0 +1,434 @@ +// core.js - permuter@home's wire protocol and configuration, a port of +// decomp-permuter's src/net/core.py (and the matching half of the Rust +// controller's port.rs). Crypto is libsodium (libsodium.js, WASM), the same +// primitives PyNaCl / sodiumoxide use: +// handshake X25519 ephemeral keys, Ed25519 signatures ("HELLO:", "WORLD:") +// messages 8-byte big-endian length + crypto_box (xsalsa20-poly1305) +// with counter nonces (16 zero bytes + u64 BE; client even, +// server odd), or crypto_secretbox for the evaluator pipe +import { readFileSync, writeFileSync } from "node:fs"; +import net from "node:net"; +import sodium from "libsodium-wrappers"; +import { parseToml } from "../helpers.js"; +import { ServerError } from "../error.js"; + +export const PERMUTER_VERSION = 2; +export const CONFIG_FILENAME = "pah.conf"; + +let DEBUG_MODE = false; +export function enable_debug_mode() { DEBUG_MODE = true; } +export function debug_print(message) { + if (DEBUG_MODE) { + const d = new Date(); + const t = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}:${String(d.getSeconds()).padStart(2, "0")}:${String(d.getMilliseconds() * 1000).padStart(6, "0")}`; + process.stdout.write(`\n${t} debug: ${message}\n`); + } +} + +/** libsodium, initialised. */ +export async function nacl() { + await sodium.ready; + return sodium; +} + +export class EOFError extends Error { + constructor(message = "EOF") { super(message); this.name = "EOFError"; } +} + +export class CancelToken { + constructor() { this.cancelled = false; } +} + +// -- keys -------------------------------------------------------------------- + +export class SigningKey { + /** @param {Uint8Array} seed 32 bytes (what pah.conf stores as secret_key) */ + constructor(seed) { + if (seed.length !== 32) throw new Error("The seed must be exactly 32 bytes long"); + const kp = sodium.crypto_sign_seed_keypair(seed); + this.seed = Uint8Array.from(seed); + this.sk = kp.privateKey; + this.verify_key = new VerifyKey(kp.publicKey); + } + + static generate() { return new SigningKey(sodium.randombytes_buf(32)); } + + /** Detached Ed25519 signature (64 bytes). */ + sign(msg) { return sodium.crypto_sign_detached(msg, this.sk); } + + to_curve25519_private_key() { return sodium.crypto_sign_ed25519_sk_to_curve25519(this.sk); } + + hex() { return Buffer.from(this.seed).toString("hex"); } +} + +export class VerifyKey { + constructor(pk) { + if (pk.length !== 32) throw new Error("The key must be exactly 32 bytes long"); + this.pk = Uint8Array.from(pk); + } + + verify(msg, signature) { + if (!sodium.crypto_sign_verify_detached(signature, msg, this.pk)) throw new Error("Signature was forged or corrupt"); + return msg; + } + + to_curve25519_public_key() { return sodium.crypto_sign_ed25519_pk_to_curve25519(this.pk); } + + encode() { return this.pk; } + + hex() { return Buffer.from(this.pk).toString("hex"); } +} + +/** A crypto_box between two X25519 keys (precomputed). */ +export class Box { + constructor(privateKey, publicKey) { this.k = sodium.crypto_box_beforenm(publicKey, privateKey); } + encrypt(msg, nonce) { return sodium.crypto_box_easy_afternm(msg, nonce, this.k); } + decrypt(ct, nonce) { return sodium.crypto_box_open_easy_afternm(ct, nonce, this.k); } +} + +export class SecretBox { + constructor(key) { this.k = Uint8Array.from(key); } + encrypt(msg, nonce) { return sodium.crypto_secretbox_easy(msg, nonce, this.k); } + decrypt(ct, nonce) { return sodium.crypto_secretbox_open_easy(ct, nonce, this.k); } +} + +export const sealedBoxEncrypt = (msg, curvePk) => sodium.crypto_box_seal(msg, curvePk); +export function sealedBoxDecrypt(ct, curveSk) { + const pk = sodium.crypto_scalarmult_base(curveSk); + return sodium.crypto_box_seal_open(ct, pk, curveSk); +} + +const concat = (...parts) => Buffer.concat(parts.map((p) => Buffer.from(p))); +const enc = (s) => Buffer.from(s, "utf8"); + +export function sign_with_magic(magic, signing_key, data) { + const signature = signing_key.sign(concat(magic, enc(":"), data)); + return concat(signature, data); +} + +export function verify_with_magic(magic, verify_key, data) { + if (data.length < 64) throw new Error("String is too small to contain a signature"); + const signature = data.subarray(0, 64); + const rest = data.subarray(64); + verify_key.verify(concat(magic, enc(":"), rest), signature); + return rest; +} + +// -- permuter data ------------------------------------------------------------- + +/** json_prop with Python's typing: ints are integral JSON numbers, floats accept ints. */ +function prop(obj, key, type, dflt) { + if (!(key in obj)) { + if (dflt !== undefined) return dflt; + throw new Error(`Member ${key} does not exist`); + } + const v = obj[key]; + const ok = type === "int" ? Number.isInteger(v) || typeof v === "bigint" : type === "float" ? typeof v === "number" : type === "dict" + ? v != null && typeof v === "object" && !Array.isArray(v) : typeof v === type; + if (!ok) throw new Error(`Member ${key} must have type ${type === "string" ? "str" : type}`); + return v; +} +export { prop as json_prop }; + +export function permuter_data_from_json(obj, source, target_o_bin) { + return { + base_score: prop(obj, "base_score", "int"), + base_hash: prop(obj, "base_hash", "string"), + fn_name: prop(obj, "fn_name", "string"), + filename: prop(obj, "filename", "string"), + keep_prob: prop(obj, "keep_prob", "float"), + need_profiler: prop(obj, "need_profiler", "boolean"), + stack_differences: prop(obj, "stack_differences", "boolean"), + algorithm: prop(obj, "algorithm", "string"), + compile_script: prop(obj, "compile_script", "string"), + randomization_weights: Object.fromEntries(Object.entries(prop(obj, "randomization_weights", "dict", {})).map(([k, v]) => { + if (typeof v !== "number") throw new Error("Dict entries must have type float"); + return [k, v]; + })), + source, + target_o_bin, + ign_branch_targets: prop(obj, "ign_branch_targets", "boolean", true), + objdump_command: prop(obj, "objdump_command", "string", ""), + }; +} + +export function permuter_data_to_json(perm) { + return { + base_score: perm.base_score, + base_hash: perm.base_hash, + fn_name: perm.fn_name, + filename: perm.filename, + keep_prob: perm.keep_prob, + need_profiler: perm.need_profiler, + stack_differences: perm.stack_differences, + algorithm: perm.algorithm, + randomization_weights: perm.randomization_weights, + compile_script: perm.compile_script, + ign_branch_targets: perm.ign_branch_targets, + objdump_command: perm.objdump_command, + }; +} + +/** + * JSON as Python's json.dumps writes it (", " / ": " separators, ASCII-only), + * so float fields keep a decimal point: a JS float that is integral prints as + * `1.0`, which the Rust controller and the Python peers both read as a float. + */ +export function pyJsonDumps(v, floatKeys = FLOAT_KEYS) { + const esc = (s) => JSON.stringify(s).replace(/[\u007f-￿]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")); + const num = (x, isFloat) => { + if (!Number.isFinite(x)) return x > 0 ? "Infinity" : x < 0 ? "-Infinity" : "NaN"; + if (isFloat && Number.isInteger(x)) return x.toFixed(1); + if (isFloat) { + const s = String(x); + return /e/.test(s) ? s.replace(/e([+-])(\d)$/, "e$10$2") : s; + } + return String(x); + }; + const walk = (x, key, parentFloatDict) => { + if (x === null || x === undefined) return "null"; + if (typeof x === "boolean") return x ? "true" : "false"; + if (typeof x === "number") return num(x, parentFloatDict || floatKeys.has(key)); + if (typeof x === "bigint") return x.toString(); + if (typeof x === "string") return esc(x); + if (Array.isArray(x)) return "[" + x.map((e) => walk(e, null, false)).join(", ") + "]"; + const floatDict = key === "randomization_weights" || key === "profiler"; + return "{" + Object.entries(x).map(([k, e]) => `${esc(k)}: ${walk(e, k, floatDict)}`).join(", ") + "}"; + }; + return walk(v, null, false); +} +const FLOAT_KEYS = new Set(["keep_prob", "priority", "min_priority", "num_cores", "cores", "heartbeat_interval"]); + +/** + * JSON.parse that keeps integers beyond 2**53 exact (as BigInt), like Python's + * json and serde_json do for u64 seeds. + */ +export function pyJsonLoads(text) { + return JSON.parse(text, (_k, v, ctx) => (typeof v === "number" && !Number.isSafeInteger(v) && ctx?.source && /^-?\d+$/.test(ctx.source) ? BigInt(ctx.source) : v)); +} + +// -- config ------------------------------------------------------------------ + +export class Config { + constructor() { + this.server_address = null; + /** @type {VerifyKey|null} */ + this.server_verify_key = null; + /** @type {SigningKey|null} */ + this.signing_key = null; + this.initial_setup_nickname = null; + } +} + +export async function read_config(file = CONFIG_FILENAME) { + await nacl(); + const config = new Config(); + let text; + try { text = readFileSync(file, "utf8"); } catch (e) { + if (e.code === "ENOENT") return config; + throw e; + } + try { + const obj = parseToml(text); + const str = (k) => (typeof obj[k] === "string" ? obj[k] : null); + if (str("server_public_key")) config.server_verify_key = new VerifyKey(Buffer.from(str("server_public_key"), "hex")); + if (str("secret_key")) config.signing_key = new SigningKey(Buffer.from(str("secret_key"), "hex")); + config.initial_setup_nickname = str("initial_setup_nickname"); + config.server_address = str("server_address"); + } catch (e) { + process.stdout.write(`Malformed configuration file ${file}.\n\n`); + throw e; + } + return config; +} + +/** toml.dump of pah.conf's flat string table. */ +export function write_config(config, file = CONFIG_FILENAME) { + const obj = []; + const write = (k, v) => { if (v != null) obj.push([k, v]); }; + write("initial_setup_nickname", config.initial_setup_nickname); + write("server_address", config.server_address); + if (config.server_verify_key) write("server_public_key", config.server_verify_key.hex()); + if (config.signing_key) write("secret_key", config.signing_key.hex()); + writeFileSync(file, obj.map(([k, v]) => `${k} = ${JSON.stringify(v)}\n`).join("")); +} + +// -- byte streams ---------------------------------------------------------------- + +/** Promise-based exact reads from a Readable (net.Socket, process.stdin, a child's stdout). */ +export class StreamReader { + constructor(stream) { + this.chunks = []; + this.len = 0; + this.ended = false; + this.error = null; + this.waiter = null; + stream.on("data", (d) => { this.chunks.push(d); this.len += d.length; this._wake(); }); + stream.on("end", () => { this.ended = true; this._wake(); }); + stream.on("close", () => { this.ended = true; this._wake(); }); + stream.on("error", (e) => { this.error = e; this.ended = true; this._wake(); }); + } + + _wake() { if (this.waiter) { const w = this.waiter; this.waiter = null; w(); } } + + _take(n) { + const all = this.chunks.length === 1 ? this.chunks[0] : Buffer.concat(this.chunks); + const out = all.subarray(0, n); + const rest = all.subarray(n); + this.chunks = rest.length ? [rest] : []; + this.len = rest.length; + return Buffer.from(out); + } + + async readExact(n) { + while (this.len < n) { + if (this.ended) throw new EOFError(this.error ? String(this.error.message) : "EOF"); + await new Promise((r) => { this.waiter = r; }); + } + return this._take(n); + } + + /** Whatever is buffered, up to n bytes (socket_read_max's error-context use). */ + async readMax(n) { + if (!this.len && !this.ended) await new Promise((r) => { this.waiter = r; setTimeout(r, 100).unref?.(); }); + return this._take(Math.min(n, this.len)); + } +} + +function nonceFor(n) { + const b = Buffer.alloc(24); + b.writeBigUInt64BE(BigInt(n), 16); + return b; +} + +/** An encrypted, length-framed message channel (core.Port). */ +export class Port { + constructor(box, who, { is_client }) { + this._box = box; + this._who = who; + this._send_nonce = is_client ? 0 : 1; + this._receive_nonce = is_client ? 1 : 0; + } + + async send(msg) { + msg = Buffer.from(msg); + if (DEBUG_MODE) debug_print(msg.length <= 300 ? `Send to ${this._who}: ${JSON.stringify(msg.toString("latin1"))}` : `Send to ${this._who}: ${msg.length} bytes`); + const nonce = nonceFor(this._send_nonce); + this._send_nonce += 2; + const data = Buffer.from(this._box.encrypt(msg, nonce)); + const len = Buffer.alloc(8); + len.writeBigUInt64BE(BigInt(data.length)); + await this._send(Buffer.concat([len, data])); + } + + send_json(msg) { return this.send(Buffer.from(pyJsonDumps(msg), "utf8")); } + + async receive() { + let length_data = await this._receive(8); + if (length_data[0]) { + length_data = Buffer.concat([length_data, await this._receive_max(1024)]); + throw new Error(`Got unexpected data from ${this._who}: ${JSON.stringify(length_data.toString("latin1"))}`); + } + const length = Number(length_data.readBigUInt64BE()); + const data = await this._receive(length); + const nonce = nonceFor(this._receive_nonce); + this._receive_nonce += 2; + let msg; + try { msg = Buffer.from(this._box.decrypt(data, nonce)); } catch { throw new Error("Decryption failed. Ciphertext failed verification"); } + if (DEBUG_MODE) debug_print(msg.length <= 300 ? `Receive from ${this._who}: ${JSON.stringify(msg.toString("latin1"))}` : `Receive from ${this._who}: ${msg.length} bytes`); + return msg; + } + + async receive_json() { + const ret = pyJsonLoads((await this.receive()).toString("utf8")); + if (typeof ret === "string") throw new ServerError(ret); + if (ret == null || typeof ret !== "object" || Array.isArray(ret)) throw new Error("Top-level JSON value must be a dictionary"); + return ret; + } +} + +export class SocketPort extends Port { + constructor(sock, reader, box, who, { is_client }) { + super(box, who, { is_client }); + this._sock = sock; + this._reader = reader; + } + + _send(data) { + return new Promise((resolve, reject) => { + if (this._sock.destroyed || this._sock.writableEnded) { reject(new EOFError("broken pipe")); return; } + this._sock.write(data, (e) => (e ? reject(new EOFError(e.message)) : resolve())); + }); + } + + _receive(n) { return this._reader.readExact(n); } + + _receive_max(n) { return this._reader.readMax(n); } + + shutdown() { try { this._sock.end(); } catch { /* closed */ } } + + close() { try { this._sock.destroy(); } catch { /* closed */ } } +} + +/** A Port over a pair of byte streams (the evaluator's stdin/stdout). */ +export class FilePort extends Port { + constructor(input, output, box, who, { is_client }) { + super(box, who, { is_client }); + this._reader = new StreamReader(input); + this._out = output; + } + + _send(data) { + return new Promise((resolve, reject) => { + this._out.write(data, (e) => (e ? reject(new EOFError(e.message)) : resolve())); + }); + } + + _receive(n) { return this._reader.readExact(n); } + + _receive_max(n) { return this._reader.readMax(n); } +} + +function connectTcp(host, port) { + return new Promise((resolve, reject) => { + const sock = net.createConnection({ host, port }); + sock.once("connect", () => { sock.removeAllListeners("error"); resolve(sock); }); + sock.once("error", (e) => { + if (e.code === "ECONNREFUSED") reject(new EOFError("connection refused")); + else if (e.code === "ENOTFOUND" || e.code === "EAI_AGAIN") reject(new EOFError(`DNS lookup failed: ${e.message}`)); + else reject(new EOFError("unable to connect: " + (e.message || e.code))); + }); + }); +} + +/** The client side of the controller handshake (core._do_connect). */ +async function _do_connect(config) { + await nacl(); + if (!config.server_verify_key || !config.signing_key || !config.server_address) { + throw new EOFError("Using permuter@home requires someone to give you access to a central -J server.\nRun `romdev-permuter-remote setup` to set this up."); + } + const [host, port_str] = config.server_address.split(":"); + const sock = await connectTcp(host, Number(port_str)); + sock.setNoDelay(true); + const reader = new StreamReader(sock); + const eph = sodium.crypto_box_keypair(); + sock.write(concat(enc("p@h0"), eph.publicKey)); + const msg = await reader.readExact(32 + 64); + const server_enc_key_data = msg.subarray(0, 32); + config.server_verify_key.verify(concat(enc("HELLO:"), eph.publicKey, server_enc_key_data), msg.subarray(32)); + const box = new Box(eph.privateKey, server_enc_key_data); + const port = new SocketPort(sock, reader, box, "controller", { is_client: true }); + const signature = config.signing_key.sign(concat(enc("WORLD:"), server_enc_key_data)); + const ver = Buffer.alloc(4); + ver.writeUInt32BE(PERMUTER_VERSION); + await port.send(concat(config.signing_key.verify_key.encode(), signature, ver)); + const obj = await port.receive_json(); + if ("message" in obj) process.stdout.write(`${obj.message}\n`); + return port; +} + +/** Authenticate and connect to the permuter@home controller server. */ +export async function connect(config = null) { + if (!config) config = await read_config(); + return _do_connect(config); +} diff --git a/packages/romdev-permuter/src/net/evaluator-worker.js b/packages/romdev-permuter/src/net/evaluator-worker.js new file mode 100644 index 00000000..7a12f327 --- /dev/null +++ b/packages/romdev-permuter/src/net/evaluator-worker.js @@ -0,0 +1,32 @@ +// evaluator-worker.js - one evaluation thread of the permuter@home evaluator +// (upstream: evaluator.multiprocess_worker). Holds a Permuter per job and +// evaluates seeds sent by the evaluator's main thread. +import { parentPort, workerData } from "node:worker_threads"; +import { Compiler } from "../compiler.js"; +import { Permuter } from "../permuter.js"; +import { Scorer } from "../scorer.js"; + +const { compileWithScript } = await import(workerData.toolchainUrl); +const permuters = new Map(); +let chain = Promise.resolve(); + +parentPort.on("message", (msg) => { + chain = chain.then(async () => { + if (msg.type === "add") { + const cfg = msg.config; + const compiler = new Compiler(cfg.compile_cmd, { tmpDir: cfg.tmpDir, compileFn: (c, o, script) => compileWithScript(c, o, null, script), log: () => {} }); + const scorer = await Scorer.create(cfg.scorerOpts); + permuters.set(msg.perm_id, await Permuter.create({ ...cfg.permOpts, compiler, scorer, log: () => {} }, cfg.base)); + } else if (msg.type === "remove") { + permuters.delete(msg.perm_id); + } else if (msg.type === "work") { + const t0 = performance.now(); + const permuter = permuters.get(msg.perm_id); + const result = await permuter.try_eval_candidate(BigInt(msg.seed)); + if (!result.isEvalError && permuter.should_output(result)) permuter.record_result(result); + if (!result.isEvalError) delete result.pass; + if (result.seed) result.seed = null; + parentPort.postMessage({ type: "result", perm_id: msg.perm_id, id: msg.id, time_us: Math.trunc((performance.now() - t0) * 1000), result }); + } + }); +}); diff --git a/packages/romdev-permuter/src/net/evaluator.js b/packages/romdev-permuter/src/net/evaluator.js new file mode 100644 index 00000000..e9a48f18 --- /dev/null +++ b/packages/romdev-permuter/src/net/evaluator.js @@ -0,0 +1,216 @@ +#!/usr/bin/env node +// evaluator.js - permuter@home's sandboxed evaluator, a port of +// decomp-permuter's src/net/evaluator.py. It runs as its own process, talks +// to the worker server over stdin/stdout (SecretBox, key in $SECRET), and +// evaluates candidates in worker threads. +// +// Upstream runs this inside a Docker container that provides the compiler. +// Here the compiler is romdev's WASM toolchain: a job's (portable) compile.sh +// is run through the toolchain adapter, never through bash, with its program +// names resolved by the server's toolchain profile, and it is refused if it +// names any path outside the job's own working directory. +import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs"; +import path from "node:path"; +import { Worker } from "node:worker_threads"; +import { deflateSync } from "node:zlib"; +import { FilePort, SecretBox, nacl, json_prop, permuter_data_from_json } from "./core.js"; +import { Permuter } from "../permuter.js"; +import { Scorer } from "../scorer.js"; +import { Compiler } from "../compiler.js"; +import { CandidateConstructionFailure } from "../error.js"; +import { resolveToolchainUrl } from "../import.js"; +import { shlexSplit } from "../scorer.js"; + +const EVAL_WORKER = new URL("./evaluator-worker.js", import.meta.url); + +/** + * Bind a portable compile script to this machine: `$(which NAME)` becomes the + * profile's program path for NAME, and any other absolute path or `..` + * component is refused (the script comes from someone else's machine). + */ +export function bindScript(script, programs) { + const out = []; + for (let line of script.split("\n")) { + line = line.replace(/\$\(which '?([^')]+)'?\)/g, (_m, name) => { + if (!(name in programs)) throw new CandidateConstructionFailure(`compile script needs program '${name}', which this server's toolchain profile does not provide`); + return programs[name]; + }); + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#") || /^(set|export)\s/.test(trimmed) || /^[A-Za-z_][A-Za-z0-9_]*="\$\(realpath "\$[13]"\)"$/.test(trimmed)) { + out.push(line); + continue; + } + if (/^cd\s/.test(trimmed)) throw new CandidateConstructionFailure("compile script may not change directory"); + const words = shlexSplit(trimmed.replaceAll('"$INPUT"', "@IN@").replaceAll('"$OUTPUT"', "@OUT@")); + for (const w of words) { + if (w === "@IN@" || w === "@OUT@") continue; + const bare = w.replace(/^-[A-Za-z]+=?/, ""); + if (path.isAbsolute(bare) || bare.split("/").includes("..")) { + throw new CandidateConstructionFailure(`compile script names a path outside its job directory: ${w}`); + } + } + out.push(line); + } + return out.join("\n"); +} + +/** Toolchain profiles a server offers (the controller's "docker_image"). */ +export function profilePrograms(image) { + const presets = { + "romdev:ido5.3": { cc: "ido/5.3/cc" }, + "romdev:ido7.1": { cc: "ido/7.1/cc" }, + }; + if (presets[image]) return presets[image]; + const m = /^romdev:(.+)$/.exec(image); + if (m && m[1].includes("=")) { + return Object.fromEntries(m[1].split(",").map((kv) => kv.split("=")).map(([k, v]) => [k.trim(), v.trim()])); + } + throw new Error(`unsupported toolchain image '${image}': romdev servers run 'romdev:ido5.3', 'romdev:ido7.1' or 'romdev:=,...'`); +} + +async function main() { + await nacl(); + const secret = Buffer.from(process.env.SECRET, "base64"); + delete process.env.SECRET; + process.env.PERMUTER_IS_REMOTE = "1"; + const programs = profilePrograms(process.env.PAH_IMAGE ?? ""); + const out = process.stdout; + // print() debugging goes to stderr; stdout is the protocol. + console.log = (...a) => process.stderr.write(a.join(" ") + "\n"); + const port = new FilePort(process.stdin, out, new SecretBox(secret), "server", { is_client: false }); + const magic = await port.receive(); + await port.send(magic); + const obj = await port.receive_json(); + const num_threads = Math.ceil(json_prop(obj, "num_cores", "float")); + const workRoot = process.env.PAH_WORKDIR ?? path.join(process.cwd(), ".pah-work"); + mkdirSync(workRoot, { recursive: true }); + const jail = mkdtempSync(path.join(workRoot, "pah-eval-")); + const toolchainUrl = resolveToolchainUrl(); + if (!toolchainUrl) throw new Error("the evaluator needs romdev's toolchain adapter (romdevtools)"); + + const permuters = new Map(); // perm_id -> {dir, config} + const remaining = new Map(); + const shouldRemove = new Set(); + const workers = []; + const idle = []; + const queue = []; + const dispatch = () => { + while (idle.length && queue.length) { + const w = idle.pop(); + w.postMessage({ type: "work", ...queue.shift() }); + } + }; + const removeNow = (perm_id) => { + if (!shouldRemove.has(perm_id) || (remaining.get(perm_id) ?? 0) !== 0) return; + shouldRemove.delete(perm_id); + remaining.delete(perm_id); + for (const w of workers) w.postMessage({ type: "remove", perm_id }); + rmSync(permuters.get(perm_id).dir, { recursive: true, force: true }); + permuters.delete(perm_id); + }; + let sendChain = Promise.resolve(); + const send = (fn) => { sendChain = sendChain.then(fn).catch(() => process.exit(1)); return sendChain; }; + for (let k = 0; k < num_threads; k++) { + const w = new Worker(EVAL_WORKER, { workerData: { toolchainUrl } }); + w.on("message", (msg) => { + if (msg.type === "result") { + remaining.set(msg.perm_id, (remaining.get(msg.perm_id) ?? 0) - 1); + send(async () => { + const o = { type: "result", permuter: msg.perm_id, id: msg.id, time_us: msg.time_us }; + const res = msg.result; + if (res.isEvalError) { + o.error = res.exc_str ?? ""; + await port.send_json(o); + } else { + o.score = res.score; + o.has_source = res.source != null; + if (res.hash != null) o.hash = res.hash; + if (res.profiler) o.profiler = res.profiler; + await port.send_json(o); + if (res.source != null) await port.send(deflateSync(Buffer.from(res.source, "utf8"))); + } + }); + if (permuters.has(msg.perm_id)) removeNow(msg.perm_id); + idle.push(w); + dispatch(); + } + }); + w.on("error", (e) => { process.stderr.write(`evaluator worker: ${e.stack ?? e}\n`); process.exit(1); }); + workers.push(w); + idle.push(w); + } + + const cleanup = () => { try { rmSync(jail, { recursive: true, force: true }); } catch { /* ignore */ } }; + process.on("exit", cleanup); + try { + for (;;) { + const item = await port.receive_json(); + const msg_type = json_prop(item, "type", "string"); + if (msg_type === "add") { + const perm_id = json_prop(item, "permuter", "string"); + const source = (await port.receive()).toString("utf8"); + const target_o_bin = await port.receive(); + const data = permuter_data_from_json(item, source, target_o_bin); + const msg = { type: "init", permuter: perm_id }; + const t0 = performance.now(); + const dir = path.join(jail, `p${perm_id.replace(/[^0-9A-Za-z_-]/g, "_")}`); + try { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "target.o"), target_o_bin); + writeFileSync(path.join(dir, "compile.sh"), bindScript(data.compile_script, programs), { mode: 0o755 }); + const config = { + permOpts: { dir: "unused", fn_name: data.fn_name, source_file: data.filename, source: data.source, + randomization_weights: data.randomization_weights, force_seed: null, force_rng_seed: null, + keep_prob: data.keep_prob, need_profiler: data.need_profiler, need_all_sources: false, show_errors: false, + best_only: false, better_only: false, score_threshold: null, debug_mode: false, speed: 100 }, + scorerOpts: { target_o: path.join(dir, "target.o"), stack_differences: data.stack_differences, algorithm: data.algorithm, + debug_mode: false, ign_branch_targets: data.ign_branch_targets, objdump_command: data.objdump_command }, + compile_cmd: path.join(dir, "compile.sh"), + tmpDir: path.join(dir, "tmp"), + }; + // Construct once here (compiles the base) to check the base score. + const { compileWithScript } = await import(toolchainUrl); + const compiler = new Compiler(config.compile_cmd, { tmpDir: config.tmpDir, compileFn: (c, o, script) => compileWithScript(c, o, null, script), log: () => {} }); + const scorer = await Scorer.create(config.scorerOpts); + const permuter = await Permuter.create({ ...config.permOpts, compiler, scorer, log: () => {} }); + if (permuter.base_score !== data.base_score) { + rmSync(dir, { recursive: true, force: true }); + const hash_str = permuter.base_hash === data.base_hash ? "same hash; different Python or permuter versions?" : "different hash; different objdump versions?"; + throw new CandidateConstructionFailure(`mismatching score: ${permuter.base_score} vs ${data.base_score} (${hash_str})`); + } + config.base = { score: permuter.base_score, hash: permuter.base_hash, source: permuter.base_source }; + permuters.set(perm_id, { dir, config }); + for (const w of workers) w.postMessage({ type: "add", perm_id, config }); + Object.assign(msg, { success: true, base_score: permuter.base_score, base_hash: permuter.base_hash }); + } catch (e) { + msg.success = false; + msg.error = e.message || e.name; + if (e instanceof CandidateConstructionFailure) process.stderr.write(e.message + "\n"); + else process.stderr.write(String(e.stack ?? e) + "\n"); + } + msg.time_us = Math.trunc((performance.now() - t0) * 1000); + await send(() => port.send_json(msg)); + } else if (msg_type === "remove") { + const perm_id = json_prop(item, "permuter", "string"); + if (permuters.has(perm_id)) { + shouldRemove.add(perm_id); + removeNow(perm_id); + } + } else if (msg_type === "work") { + const perm_id = json_prop(item, "permuter", "string"); + const id = json_prop(item, "id", "int"); + const seed = json_prop(item, "seed", "int"); + remaining.set(perm_id, (remaining.get(perm_id) ?? 0) + 1); + queue.push({ perm_id, id, seed }); + dispatch(); + } else { + throw new Error(`Invalid message type ${msg_type}`); + } + } + } catch (e) { + if (e?.name !== "EOFError") process.stderr.write(String(e.stack ?? e) + "\n"); + process.exit(1); + } +} + +if (import.meta.url === `file://${process.argv[1]}`) main(); diff --git a/packages/romdev-permuter/src/net/icons/notok.ico b/packages/romdev-permuter/src/net/icons/notok.ico new file mode 100644 index 00000000..2825d0d9 Binary files /dev/null and b/packages/romdev-permuter/src/net/icons/notok.ico differ diff --git a/packages/romdev-permuter/src/net/icons/ok.ico b/packages/romdev-permuter/src/net/icons/ok.ico new file mode 100644 index 00000000..bc0b0534 Binary files /dev/null and b/packages/romdev-permuter/src/net/icons/ok.ico differ diff --git a/packages/romdev-permuter/src/net/icons/okthink.ico b/packages/romdev-permuter/src/net/icons/okthink.ico new file mode 100644 index 00000000..d3a8eacf Binary files /dev/null and b/packages/romdev-permuter/src/net/icons/okthink.ico differ diff --git a/packages/romdev-permuter/src/net/server.js b/packages/romdev-permuter/src/net/server.js new file mode 100644 index 00000000..c8f85736 --- /dev/null +++ b/packages/romdev-permuter/src/net/server.js @@ -0,0 +1,469 @@ +// server.js - a permuter@home worker server, a port of decomp-permuter's +// src/net/server.py: connect to the controller as a server, start the +// evaluator (evaluator.js, a separate node process instead of upstream's +// Docker container), and shuttle jobs, seeds and results between them. +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; +import { inflateSync } from "node:zlib"; +import sodium from "libsodium-wrappers"; +import { FilePort, SecretBox, connect, nacl, json_prop, permuter_data_from_json, permuter_data_to_json, CancelToken, EOFError } from "./core.js"; +import { get_default_randomization_weights, merge_randomization_weights } from "../helpers.js"; +import { ServerError } from "../error.js"; + +const HEARTBEAT_INTERVAL_SLACK_SEC = 50.0; +const EVALUATOR = fileURLToPath(new URL("./evaluator.js", import.meta.url)); + +/** An async FIFO. */ +export class AsyncQueue { + constructor() { this.items = []; this.waiters = []; } + put(x) { if (this.waiters.length) this.waiters.shift()(x); else this.items.push(x); } + get() { return this.items.length ? Promise.resolve(this.items.shift()) : new Promise((r) => this.waiters.push(r)); } +} + +/** + * The evaluator child, as upstream's DockerPort: a SecretBox-encrypted pipe + * over its stdin/stdout. `num_cores` bounds its worker threads and + * `max_memory_gb` its heap (node --max-old-space-size). + */ +class EvaluatorPort extends FilePort { + constructor(child, secret) { + super(child.stdout, child.stdin, new SecretBox(secret), "evaluator", { is_client: true }); + this._child = child; + this._closed = false; + } + + shutdown() { + if (this._closed) return; + this._closed = true; + try { this._child.stdin.end(); } catch { /* gone */ } + try { this._child.kill("SIGKILL"); } catch { /* gone */ } + } +} + +export async function _start_evaluator(image, options, log = (s) => process.stdout.write(s + "\n")) { + log("Starting evaluator..."); + await nacl(); + const secret = sodium.randombytes_buf(32); + const child = spawn(process.execPath, [`--max-old-space-size=${Math.max(256, Math.floor(options.max_memory_gb * 1024))}`, EVALUATOR], { + stdio: ["pipe", "pipe", "pipe"], + env: { ...process.env, SECRET: Buffer.from(secret).toString("base64"), PAH_IMAGE: image, PAH_WORKDIR: options.workdir ?? path.join(process.cwd(), ".pah-work") }, + }); + child.stderr.on("data", (d) => process.stderr.write(Buffer.concat([Buffer.from("Evaluator stderr: "), d]))); + const port = new EvaluatorPort(child, secret); + try { + const magic = Buffer.alloc(1000); + await port.send(magic); + const r = await port.receive(); + if (!r.equals(magic)) throw new Error("Failed initial sanity check."); + await port.send_json({ num_cores: options.num_cores }); + } catch (e) { + port.shutdown(); + throw e; + } + log("Started."); + return port; +} + +/** One connected session: controller <-> this server <-> evaluator (ServerInner + NetThread). */ +class ServerInner { + constructor(net_port, evaluator_port, io_queue, heartbeat_interval) { + this._net = net_port; + this._eval = evaluator_port; + this._io_queue = io_queue; + this._active = new Set(); + this._time_starts = new Map(); + this._token = new CancelToken(); + this._handles = new Map(); + this._next_work_id = 0; + this._main = new AsyncQueue(); + this._out = new AsyncQueue(); + this._heartbeat_interval = heartbeat_interval; + this._last_heartbeat = Date.now() / 1000; + this._stopped = false; + this._loops = [this._read_loop(), this._write_loop(), this._read_eval_loop(), this._main_loop(), this._heartbeat_loop()]; + } + + /** PermuterHandle: (id, token), one stable object per id per session so it can key a Map. */ + _handle_obj(handle) { + if (!this._handles.has(handle)) this._handles.set(handle, [handle, this._token]); + return this._handles.get(handle); + } + + _send_io(handle, msg) { this._io_queue.put([this._token, [this._handle_obj(handle), msg]]); } + + _send_io_global(msg) { this._io_queue.put([this._token, msg]); } + + // -- controller reader (NetThread.read_loop) -- + async _read_one() { + const msg = await this._net.receive_json(); + const time_start = Date.now() / 1000; + const msg_type = json_prop(msg, "type", "string"); + if (msg_type === "heartbeat") return { kind: "heartbeat" }; + const handle = json_prop(msg, "permuter", "int"); + if (msg_type === "work") { + const seed = json_prop(msg, "seed", "int"); + return { kind: "work", handle, id: this._next_work_id++, time_start, seed }; + } + if (msg_type === "add") { + const client = { id: json_prop(msg, "client_id", "string"), nickname: json_prop(msg, "client_name", "string") }; + const data = json_prop(msg, "data", "dict"); + const compressed_source = await this._net.receive(); + const compressed_target_o_bin = await this._net.receive(); + let permuter; + try { + permuter = permuter_data_from_json(data, inflateSync(compressed_source).toString("utf8"), inflateSync(compressed_target_o_bin)); + } catch (e) { + return { kind: "immediate_disconnect", handle, client, reason: `Failed to parse permuter: ${e.message || e.name}` }; + } + permuter.randomization_weights = merge_randomization_weights(get_default_randomization_weights("base"), permuter.randomization_weights); + return { kind: "add", handle, time_start, client, permuter_data: permuter }; + } + if (msg_type === "remove") return { kind: "remove", handle }; + throw new Error(`Bad message type: ${msg_type}`); + } + + async _read_loop() { + try { + for (;;) this._main.put(await this._read_one()); + } catch (e) { + if (e instanceof EOFError) this._main.put({ kind: "net_disconnected", graceful: true }); + else if (e instanceof ServerError) this._main.put({ kind: "net_disconnected", graceful: false, message: e.message }); + else { + if (!this._stopped) process.stderr.write(String(e.stack ?? e) + "\n"); + this._main.put({ kind: "net_disconnected", graceful: false }); + } + } + } + + // -- controller writer (NetThread.write_loop) -- + async _write_loop() { + try { + for (;;) { + const item = await this._out.get(); + if (item.kind === "shutdown") break; + if (item.kind === "init_fail") { + await this._net.send_json({ type: "update", permuter: item.handle, time_us: 0, update: { type: "init_failed", reason: item.error } }); + } else if (item.kind === "init_success") { + await this._net.send_json({ type: "update", permuter: item.handle, time_us: item.time_us, update: { type: "init_done", hash: item.base_hash } }); + } else if (item.kind === "disconnect") { + await this._net.send_json({ type: "update", permuter: item.handle, time_us: 0, update: { type: "disconnect" } }); + } else if (item.kind === "need_work") { + await this._net.send_json({ type: "need_work" }); + } else if (item.kind === "work") { + const overhead_us = Math.trunc((Date.now() / 1000 - item.time_start) * 1e6) - item.time_us; + await this._net.send_json({ type: "update", permuter: item.handle, time_us: item.time_us, update: { type: "work", overhead_us, ...item.obj } }); + if (item.compressed_source != null) await this._net.send(item.compressed_source); + } + } + } catch (e) { + if (e instanceof EOFError) this._main.put({ kind: "net_disconnected", graceful: true }); + else { + if (!this._stopped) process.stderr.write(String(e.stack ?? e) + "\n"); + this._main.put({ kind: "net_disconnected", graceful: false }); + } + } + } + + // -- evaluator reader -- + async _read_eval_loop() { + try { + for (;;) { + const msg = await this._eval.receive_json(); + const msg_type = json_prop(msg, "type", "string"); + if (msg_type === "init") { + const perm_id = json_prop(msg, "permuter", "string"); + const time_us = json_prop(msg, "time_us", "int"); + if (json_prop(msg, "success", "boolean")) { + this._main.put({ kind: "perm_init_success", perm_id, base_score: json_prop(msg, "base_score", "int"), base_hash: json_prop(msg, "base_hash", "string"), time_us }); + } else { + this._main.put({ kind: "perm_init_fail", perm_id, error: json_prop(msg, "error", "string") }); + } + } else if (msg_type === "result") { + let compressed_source = null; + if (msg.has_source === true) compressed_source = await this._eval.receive(); + const perm_id = json_prop(msg, "permuter", "string"); + const id = json_prop(msg, "id", "int"); + const time_us = json_prop(msg, "time_us", "int"); + delete msg.permuter; delete msg.id; delete msg.time_us; + this._main.put({ kind: "work_done", perm_id, id, obj: msg, time_us, compressed_source }); + } else { + throw new Error(`Unknown message type from evaluator: ${msg_type}`); + } + } + } catch (e) { + if (!(e instanceof EOFError) && !this._stopped) process.stderr.write(String(e.stack ?? e) + "\n"); + } + } + + _need_work() { this._out.put({ kind: "need_work" }); } + + async _remove(handle) { + await this._eval.send_json({ type: "remove", permuter: String(handle) }); + this._active.delete(handle); + } + + async _handle(msg) { + switch (msg.kind) { + case "heartbeat": + this._last_heartbeat = Date.now() / 1000; + break; + case "work": + if (!this._active.has(msg.handle)) { this._need_work(); return; } + this._time_starts.set(msg.id, msg.time_start); + await this._eval.send_json({ type: "work", permuter: String(msg.handle), id: msg.id, seed: msg.seed }); + break; + case "add": { + if (this._active.has(msg.handle)) throw new Error("Repeated AddPermuter!"); + this._active.add(msg.handle); + const perm = msg.permuter_data; + await this._eval.send_json({ type: "add", permuter: String(msg.handle), ...permuter_data_to_json(perm) }); + await this._eval.send(Buffer.from(perm.source, "utf8")); + await this._eval.send(perm.target_o_bin); + this._send_io(msg.handle, { kind: "connect", fn_name: perm.fn_name, client: msg.client }); + break; + } + case "remove": + if (!this._active.has(msg.handle)) return; + await this._remove(msg.handle); + this._send_io(msg.handle, { kind: "disconnect", reason: "disconnected" }); + break; + case "user_disconnect": + if (!this._active.has(msg.handle)) return; + await this._remove(msg.handle); + this._send_io(msg.handle, { kind: "disconnect", reason: "kicked" }); + this._out.put({ kind: "disconnect", handle: msg.handle }); + break; + case "immediate_disconnect": + if (this._active.has(msg.handle)) throw new Error("ImmediateDisconnect is not immediate"); + this._send_io(msg.handle, { kind: "immediate_disconnect", reason: msg.reason, client: msg.client }); + this._out.put({ kind: "init_fail", handle: msg.handle, error: msg.reason }); + break; + case "perm_init_fail": { + const handle = Number(msg.perm_id); + if (!this._active.has(handle)) { this._need_work(); return; } + this._active.delete(handle); + this._send_io(handle, { kind: "disconnect", reason: "failed to compile" }); + this._out.put({ kind: "init_fail", handle, error: msg.error }); + break; + } + case "perm_init_success": { + const handle = Number(msg.perm_id); + if (!this._active.has(handle)) { this._need_work(); return; } + this._out.put({ kind: "init_success", handle, time_us: msg.time_us, base_score: msg.base_score, base_hash: msg.base_hash }); + break; + } + case "work_done": { + const handle = Number(msg.perm_id); + const time_start = this._time_starts.get(msg.id); + this._time_starts.delete(msg.id); + if (!this._active.has(handle)) { this._need_work(); return; } + const obj = msg.obj; + obj.permuter = handle; + const score = "score" in obj ? json_prop(obj, "score", "int") : null; + const is_improvement = msg.compressed_source != null; + this._send_io(handle, { kind: "work_done", score, is_improvement }); + this._out.put({ kind: "work", handle, time_start, time_us: msg.time_us, obj, compressed_source: msg.compressed_source }); + break; + } + case "net_disconnected": + this._send_io_global({ kind: "server_failed", graceful: msg.graceful, message: msg.message ?? null }); + break; + default: + throw new Error(`unreachable ${msg.kind}`); + } + } + + async _main_loop() { + for (;;) { + const msg = await this._main.get(); + if (msg.kind === "shutdown") break; + try { await this._handle(msg); } catch (e) { + if (!this._stopped) process.stderr.write(String(e.stack ?? e) + "\n"); + this._send_io_global({ kind: "server_failed", graceful: false, message: String(e.message) }); + } + } + } + + async _heartbeat_loop() { + let second_attempt = false; + while (!this._stopped) { + const delay = this._last_heartbeat + this._heartbeat_interval + HEARTBEAT_INTERVAL_SLACK_SEC / 2 - Date.now() / 1000; + if (delay <= 0) { + if (second_attempt) { this._main.put({ kind: "net_disconnected", graceful: true }); return; } + second_attempt = true; + await this._sleep(HEARTBEAT_INTERVAL_SLACK_SEC / 2); + } else { + second_attempt = false; + await this._sleep(delay); + } + } + } + + _sleep(sec) { + return new Promise((r) => { + const t = setTimeout(r, sec * 1000); + t.unref?.(); + this._wakeSleep = () => { clearTimeout(t); r(); }; + }); + } + + remove_permuter(handle) { this._main.put({ kind: "user_disconnect", handle }); } + + async stop() { + this._token.cancelled = true; + this._stopped = true; + this._main.put({ kind: "shutdown" }); + this._out.put({ kind: "shutdown" }); + this._wakeSleep?.(); + this._net.shutdown(); + this._net.close(); + this._eval.shutdown(); + await Promise.allSettled(this._loops); + } +} + +/** A server that may or may not be connected to the controller and the evaluator. */ +export class Server { + /** + * @param {{num_cores: number, max_memory_gb: number, min_priority: number, workdir?: string}} options + */ + constructor(options, config, io_queue) { + this._server = null; + this._options = options; + this._config = config; + this._io_queue = io_queue; + } + + async start() { + if (this._server) throw new Error("AssertionError: already started"); + const net_port = await connect(this._config); + await net_port.send_json({ method: "connect_server", min_priority: this._options.min_priority, num_cores: this._options.num_cores }); + const obj = await net_port.receive_json(); + const image = json_prop(obj, "docker_image", "string"); + const heartbeat_interval = json_prop(obj, "heartbeat_interval", "float"); + const evaluator_port = await _start_evaluator(image, this._options); + try { + this._server = new ServerInner(net_port, evaluator_port, this._io_queue, heartbeat_interval); + } catch (e) { + evaluator_port.shutdown(); + throw e; + } + } + + async stop() { + if (!this._server) return; + await this._server.stop(); + this._server = null; + } + + remove_permuter(handle) { + if (this._server && !handle[1].cancelled) this._server.remove_permuter(handle[0]); + } +} + +/** The Reconnector of run_server.py. */ +export class Reconnector { + constructor(io_queue, random = Math.random) { + this._io_queue = io_queue; + this._random = random; + this._token = new CancelToken(); + this._delay = 5.0; + this._timer = null; + this._start = this._stop = Date.now() / 1000; + } + + mark_start() { this._start = Date.now() / 1000; } + + mark_stop() { this._stop = Date.now() / 1000; } + + stop() { + this._token.cancelled = true; + if (this._timer) { clearTimeout(this._timer); this._timer = null; } + } + + reconnect_eventually() { + let delay; + if (this._stop - this._start > 60.0) delay = this._delay = 5.0; + else { + delay = this._delay; + this._delay = this._delay * 2.0 + (1.0 + (60.0 - 1.0) * this._random()); + } + const token = new CancelToken(); + this._token = token; + this._timer = setTimeout(() => this._io_queue.put([token, { kind: "reconnect" }]), delay * 1000); + return Math.trunc(delay); + } +} + +/** run_server.main_loop: print connections/disconnections, reconnect with backoff. */ +export async function server_main_loop(io_queue, server, systray, log = (s) => process.stdout.write(s + "\n")) { + const reconnector = new Reconnector(io_queue); + const handle_clients = new Map(); + for (;;) { + const [token, activity] = await io_queue.get(); + if (token && token.cancelled) continue; + if (!Array.isArray(activity)) { + if (activity.kind === "shutdown") break; + if (activity.kind === "reconnect") { + log("reconnecting..."); + try { + systray.server_reconnecting(); + reconnector.mark_start(); + await server.start(); + systray.server_connected(); + } catch (e) { + if (e instanceof EOFError) { + const delay = reconnector.reconnect_eventually(); + log(`failed again, reconnecting in ${delay} seconds...`); + systray.server_failed(true); + } else if (e instanceof ServerError) { + log(`failed! ${e.message}`); + systray.server_failed(false, e.message); + } else { + log("failed!"); + process.stderr.write(String(e.stack ?? e) + "\n"); + systray.server_failed(false); + } + } + } else if (activity.kind === "server_failed") { + if (activity.message) log(`Server error: ${activity.message}`); + log("disconnected from permuter@home"); + await server.stop(); + reconnector.mark_stop(); + systray.server_failed(activity.graceful, activity.message); + if (activity.graceful) log(`will reconnect in ${reconnector.reconnect_eventually()} seconds...`); + } + continue; + } + const [handle, msg] = activity; + if (msg.kind === "connect") { + handle_clients.set(handle, msg.client); + systray.connect(handle, msg.client.nickname, msg.fn_name); + log(`[${msg.client.nickname}] connected (${msg.fn_name})`); + } else if (msg.kind === "disconnect") { + systray.disconnect(handle); + const nickname = handle_clients.get(handle)?.nickname; + handle_clients.delete(handle); + log(`[${nickname}] ${msg.reason}`); + } else if (msg.kind === "immediate_disconnect") { + log(`[${msg.client.nickname}] ${msg.reason}`); + } else if (msg.kind === "work_done") { + systray.work_done(handle, msg.is_improvement); + } else if (msg.kind === "user_remove") { + server.remove_permuter(handle); + } + } + reconnector.stop(); +} + +/** A systray state that does nothing (run-server without --systray). */ +export class SystrayState { + server_reconnecting() {} + server_connected() {} + server_failed() {} + connect() {} + disconnect() {} + work_done() {} + stop() {} +} diff --git a/packages/romdev-permuter/src/net/systray.js b/packages/romdev-permuter/src/net/systray.js new file mode 100644 index 00000000..4ada2a1b --- /dev/null +++ b/packages/romdev-permuter/src/net/systray.js @@ -0,0 +1,198 @@ +// systray.js - `romdev-permuter-remote run-server --systray`, a port of RealSystrayState from +// decomp-permuter's src/net/cmd/run_server.py. The tray itself is upstream's +// external helper (src/net/cmd/systray/tray.go, built with Go), driven over +// newline-delimited JSON on its stdin/stdout. romdev does not ship that binary: +// point $ROMDEV_PAH_SYSTRAY at it, or put it at /systray/permuter-systray. +import { spawn } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +import { fileURLToPath } from "node:url"; +import { SystrayState } from "./server.js"; + +const CLIENT_SLOTS = 10; +const UPDATE_INTERVAL = 2.0; +const MENU_TOOLTIP = "permuter@home"; + +export function systrayHelperPath() { + if (process.env.ROMDEV_PAH_SYSTRAY) return process.env.ROMDEV_PAH_SYSTRAY; + const suffix = process.platform === "win32" ? ".exe" : ""; + const p = fileURLToPath(new URL(`../../systray/permuter-systray${suffix}`, import.meta.url)); + return existsSync(p) ? p : null; +} + +export class RealSystrayState extends SystrayState { + /** Resolves once the helper reports ready. */ + static async create(io_queue) { + const s = new RealSystrayState(io_queue); + await s._ready; + return s; + } + + constructor(io_queue) { + super(); + this._io_queue = io_queue; + this._permuters = new Map(); + this._onclick = new Map(); + this._status = "connecting"; + this._fail_message = null; + const icon = (f) => readFileSync(fileURLToPath(new URL(`./icons/${f}`, import.meta.url))).toString("base64"); + this._icons = { working: icon("okthink.ico"), passive: icon("ok.ico"), fail: icon("notok.ico") }; + this._current_icon = "working"; + let next_id = 100; + const add_item = (menu, title, onclick = null, { submenu = null, hidden = false } = {}) => { + next_id += 1; + const obj = { title, enabled: onclick != null || submenu != null, hidden, __id: next_id }; + if (onclick) this._onclick.set(next_id, onclick); + if (submenu) obj.items = submenu; + menu.push(obj); + return next_id; + }; + const menu = []; + this._status_id = add_item(menu, "Connecting..."); + this._client_slots = []; + for (let i = 0; i < CLIENT_SLOTS; i++) { + const submenu = []; + const iterations_id = add_item(submenu, ""); + const improvements_id = add_item(submenu, ""); + const stop_id = add_item(submenu, "Stop", () => this._remove_permuter(i)); + const menu_id = add_item(menu, "", null, { submenu, hidden: true }); + this._client_slots.push({ menu_id, iterations_id, improvements_id, stop_id, permuter: null }); + } + this._more_id = add_item(menu, "", null, { hidden: true }); + add_item(menu, "Quit", () => this._io_queue.put([null, { kind: "shutdown" }])); + + const helper = systrayHelperPath(); + if (!helper) { + throw new Error("An external helper binary is required for systray support.\n" + + "Build it from decomp-permuter's src/net/cmd/systray (requires Go), then set\n" + + "ROMDEV_PAH_SYSTRAY to its path or place it at romdev-permuter/systray/permuter-systray."); + } + this._proc = spawn(helper, [], { stdio: ["pipe", "pipe", "inherit"] }); + this._exited = new Promise((r) => this._proc.on("exit", r)); + const rl = createInterface({ input: this._proc.stdout }); + let first = true; + this._ready = new Promise((resolve, reject) => { + this._proc.on("error", reject); + rl.on("line", (line) => { + let resp; + try { resp = JSON.parse(line); } catch { reject(new Error(`Failed to parse systray JSON: ${line}`)); return; } + if (first) { + first = false; + if (resp?.type === "ready") resolve(); + else reject(new Error("Failed to initialize systray!")); + return; + } + if (resp.type === "clicked") this._onclick.get(resp.__id)?.(); + }); + rl.on("close", () => { if (first) reject(new Error("Failed to initialize systray!")); }); + }); + this._send({ icon: this._icons[this._current_icon], tooltip: MENU_TOOLTIP, items: menu }); + } + + _send(msg) { try { this._proc.stdin.write(JSON.stringify(msg) + "\n"); } catch { /* helper gone */ } } + + _update_item(id, title, { hidden = false, enabled = false } = {}) { + this._send({ type: "update-item", item: { title, enabled, hidden, __id: id }, seq_id: -1 }); + } + + _remove_permuter(slot_index) { + const slot = this._client_slots[slot_index]; + if (!slot.permuter) return; + this._io_queue.put([null, [slot.permuter, { kind: "user_remove" }]]); + } + + _update_permuter(perm, slot) { + this._update_item(slot.iterations_id, `Iterations: ${perm.iterations}`); + this._update_item(slot.improvements_id, `Improvements found: ${perm.improvements}`); + } + + _update_status() { + let status, icon; + if (this._status === "connecting") { status = "Reconnecting..."; icon = "working"; } + else if (this._status === "reconnecting") { status = "Disconnected, will reconnect..."; icon = "fail"; } + else if (this._status === "connected") { + if (this._permuters.size) { status = "Currently permuting:"; icon = "working"; } + else { status = "Not running"; icon = "passive"; } + } else { + status = this._fail_message ? `Error: ${this._fail_message}` : "Error occurred"; + icon = "fail"; + } + this._update_item(this._status_id, status); + if (this._current_icon !== icon) { + this._current_icon = icon; + this._send({ type: "update-menu", menu: { tooltip: MENU_TOOLTIP, icon: this._icons[icon] } }); + } + } + + _fill_slots() { + let has_more = false; + for (;;) { + let key = null; + for (const [k, p] of this._permuters) if (p.slot == null) { key = k; break; } + if (key == null) break; + let chosen = null; + for (let i = CLIENT_SLOTS - 1; i >= 0; i--) { + const slot = this._client_slots[i]; + if (slot.permuter == null) chosen = slot; + else if (chosen != null) break; + } + if (chosen == null) { has_more = true; break; } + const perm = this._permuters.get(key); + perm.slot = chosen; + chosen.permuter = key; + this._update_permuter(perm, chosen); + this._update_item(chosen.menu_id, `${perm.fn_name} (${perm.nickname})`, { enabled: true }); + } + this._update_item(this._more_id, "More...", { hidden: !has_more }); + } + + _hide_slot(slot) { + if (slot.permuter != null) this._update_item(slot.menu_id, "", { hidden: true }); + slot.permuter = null; + } + + server_reconnecting() { this._status = "connecting"; this._update_status(); } + + server_connected() { this._status = "connected"; this._update_status(); } + + server_failed(graceful, message = null) { + this._status = graceful ? "reconnecting" : "failed"; + this._fail_message = message; + this._permuters = new Map(); + this._update_status(); + for (const slot of this._client_slots) this._hide_slot(slot); + this._fill_slots(); + } + + connect(handle, nickname, fn_name) { + this._permuters.set(handle, { nickname, fn_name, iterations: 0, improvements: 0, last_systray_update: 0, slot: null }); + this._fill_slots(); + this._update_status(); + } + + disconnect(handle) { + const slot = this._permuters.get(handle)?.slot; + this._permuters.delete(handle); + this._update_status(); + if (slot) this._hide_slot(slot); + this._fill_slots(); + } + + work_done(handle, is_improvement) { + const perm = this._permuters.get(handle); + if (!perm) return; + perm.iterations += 1; + if (is_improvement) perm.improvements += 1; + const now = Date.now() / 1000; + if (perm.slot && now > perm.last_systray_update + UPDATE_INTERVAL) { + perm.last_systray_update = now; + this._update_permuter(perm, perm.slot); + } + } + + async stop() { + this._send({ type: "exit" }); + try { this._proc.stdin.end(); } catch { /* gone */ } + await this._exited; + } +} diff --git a/packages/romdev-permuter/src/objdump.js b/packages/romdev-permuter/src/objdump.js new file mode 100644 index 00000000..051391ce --- /dev/null +++ b/packages/romdev-permuter/src/objdump.js @@ -0,0 +1,423 @@ +// objdump.js - a port of decomp-permuter's src/objdump.py: per-arch settings, +// the objdump text simplifier the scorer diffs, relocation folding, and the +// ELF machine sniff. Disassembly itself runs romdev's WASM binutils (never a +// host objdump); see runObjdump(). +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { runWasmTool, runRawFsTool } from "./wasm-tool.js"; + +// Ignore registers, for cleaner output. (Upstream: False.) +const ign_regs = false; +// Skip branch-likely delay slots. (Upstream: False.) +const skip_bl_delay_slots = false; +const skip_lines = 1; +const re_int = /-?[0-9]+/g; +const re_int_full = /(?} branch_instructions + * @property {Set} forbidden + * @property {Set} branch_likely_instructions + */ + +const forbiddenDefault = () => new Set((ASCII_LETTERS + "_").split("")); + +export const MIPS_BRANCH_LIKELY_INSTRUCTIONS = new Set([ + "beql", "bnel", "beqzl", "bnezl", "bgezl", "bgtzl", "blezl", "bltzl", "bc1tl", "bc1fl", +]); +export const MIPS_BRANCH_INSTRUCTIONS = new Set([ + "b", "j", "beq", "bne", "beqz", "bnez", "bgez", "bgtz", "blez", "bltz", "bc1t", "bc1f", + ...MIPS_BRANCH_LIKELY_INSTRUCTIONS, +]); +const PPC_BRANCH_INSTRUCTIONS = new Set([ + "b", "beq", "beq+", "beq-", "bne", "bne+", "bne-", "blt", "blt+", "blt-", "ble", "ble+", "ble-", + "bdnz", "bdnz+", "bdnz-", "bge", "bge+", "bge-", "bgt", "bgt+", "bgt-", +]); +const ARM32_BRANCH_INSTRUCTIONS = new Set(); +for (const prefix of ["b", "bl"]) { + for (const cond of ["", "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al"]) { + for (const suffix of ["", ".n", ".w"]) ARM32_BRANCH_INSTRUCTIONS.add(prefix + cond + suffix); + } +} +const X86_BRANCH_INSTRUCTIONS = new Set([ + "jmp", "ljmp", "ja", "jae", "jb", "jbe", "jc", "jcxz", "jecxz", "jrcxz", "je", "jg", "jge", "jl", "jle", + "jna", "jnae", "jnb", "jnbe", "jnc", "jne", "jng", "jnge", "jnl", "jnle", "jno", "jnp", "jns", "jnz", + "jo", "jp", "jpe", "jpo", "js", "jz", "call", +]); + +/** @type {ArchSettings} */ +export const MIPS_SETTINGS = { + name: "mips", + re_comment: /<.*?>/g, + re_reg: /\$?\b(a[0-3]|t[0-9]|s[0-8]|at|v[01]|f[12]?[0-9]|f3[01]|k[01]|fp|ra)\b/g, + re_sprel: /(?<=,)([0-9]+|0x[0-9a-f]+)\((sp|s8)\)/g, + re_includes_sp: /\b(sp|s8)\b/, + sp_ref_insns: ["addiu"], + reloc_str: "R_MIPS_", + executable: ["mips-linux-gnu-objdump", "mips64-linux-gnu-objdump", "mips64-elf-objdump"], + arguments: ["-drz", "-m", "mips:4300"], + branch_likely_instructions: MIPS_BRANCH_LIKELY_INSTRUCTIONS, + branch_instructions: MIPS_BRANCH_INSTRUCTIONS, + forbidden: forbiddenDefault(), +}; + +/** @type {ArchSettings} */ +export const PPC_SETTINGS = { + name: "ppc", + re_includes_sp: /\b(r1)\b/, + sp_ref_insns: [], + re_comment: /(<.*>|\/\/.*$)/g, + re_reg: /\$?\b([rf](?:[02-9]|[1-9][0-9]+)|f1)\b/g, + re_sprel: /(?<=,)(-?[0-9]+|-?0x[0-9a-f]+)\(r1\)/g, + reloc_str: "R_PPC_", + executable: ["powerpc-eabi-objdump"], + arguments: ["-dr", "-EB", "-mpowerpc", "-M", "broadway"], + branch_instructions: PPC_BRANCH_INSTRUCTIONS, + branch_likely_instructions: new Set(), + forbidden: forbiddenDefault(), +}; + +/** @type {ArchSettings} */ +export const ARM32_SETTINGS = { + name: "arm32", + re_includes_sp: /\b(sp)\b/, + sp_ref_insns: ["add", "sub"], + re_comment: /(<.*>|\/\/.*$)/g, + re_reg: /\$?\b([rq][0-9]|[rq]1[0-5]|pc|lr|[ds][12]?[0-9]|[ds]3[01]|fp(scr|exc|sid))\b/g, + re_sprel: /sp, #-?(0x[0-9a-fA-F]+|[0-9]+)\b/g, + reloc_str: "R_ARM_", + executable: ["arm-none-eabi-objdump"], + arguments: ["-drz"], + branch_instructions: ARM32_BRANCH_INSTRUCTIONS, + branch_likely_instructions: new Set(), + forbidden: forbiddenDefault(), +}; + +/** @type {ArchSettings} */ +export const X86_SETTINGS = { + name: "x86", + re_comment: /<.*>/g, + re_includes_sp: /\b(%esp)\b/, + sp_ref_insns: ["add", "sub"], + re_reg: /%?\b(e?(?:(?:[sd]i|[sb]p)l?|[abcd][xhl])|[cdesfg]s|cr[0-7]|x?mm[0-7]|st)\b/g, + re_sprel: /-?(0x[0-9a-f]+|[0-9]+)(?=\((%ebp|%esi)\))/g, + reloc_str: "R_386_", + executable: ["objdump"], + arguments: ["-d", "--no-show-raw-insn"], + branch_instructions: X86_BRANCH_INSTRUCTIONS, + branch_likely_instructions: new Set(), + forbidden: forbiddenDefault(), +}; + +/** Pick arch settings from the ELF header's e_machine (objdump.get_arch). */ +export function get_arch(o_file) { + const data = typeof o_file === "string" ? readFileSync(o_file).subarray(0, 20) : o_file.subarray(0, 20); + const arch = data[5] === 2 ? (data[18] << 8) + data[19] : (data[19] << 8) + data[18]; + if (arch === 3) return X86_SETTINGS; + if (arch === 8) return MIPS_SETTINGS; + if (arch === 20) return PPC_SETTINGS; + if (arch === 40) return ARM32_SETTINGS; + throw new Error("Bad ELF"); +} + +export class PermuterAssertionError extends Error { + constructor(message = "") { super(message); this.name = "AssertionError"; } +} +function assert(cond, msg) { if (!cond) throw new PermuterAssertionError(msg); } + +/** Python str.split() with no arguments. */ +export function pySplitWs(s) { return s.split(/\s+/).filter((x) => x !== ""); } + +/** Python str.split(None, 1). */ +export function pySplitWs1(s) { + const t = s.replace(/^\s+/, ""); + if (!t) return []; + const m = /\s+/.exec(t); + if (!m) return [t]; + const rest = t.slice(m.index + m[0].length); + return rest ? [t.slice(0, m.index), rest] : [t.slice(0, m.index)]; +} + +export function parse_relocated_line(line) { + let ind2 = -1; + let found = false; + for (const c of ",\t ") { + if (line.includes(c)) { ind2 = line.lastIndexOf(c); found = true; break; } + } + if (!found) throw new Error(`failed to parse relocated line: ${line}`); + const before = line.slice(0, ind2 + 1); + let after = line.slice(ind2 + 1); + const ind3 = after.indexOf("("); + let imm; + if (ind3 === -1) { imm = after; after = ""; } + else { imm = after.slice(0, ind3); after = after.slice(ind3); } + if (imm === "0x0") imm = "0"; + return [before, imm, after]; +} + +export function pre_process(mnemonic, args, next_row) { + if (next_row && next_row.includes("R_PPC_EMB_SDA21")) { + args = args.replaceAll("(r2)", "(0)").replaceAll("(r13)", "(0)").replaceAll(",r2,", ",0,").replaceAll(",r13,", ",0,"); + if (mnemonic === "li" || mnemonic === "lis") { + mnemonic = mnemonic.replace("li", "addi"); + const args_parts = args.split(","); + args = args_parts[0] + ",0," + args_parts[1]; + } + } + return [mnemonic, args]; +} + +export function process_mips_reloc(reloc_row, prev, repl, imm) { + if (reloc_row.includes("R_MIPS_JALR") || reloc_row.includes("R_MIPS_NONE")) return repl; + if (imm !== "0" && imm !== "imm" && imm !== "addr") repl += (imm.startsWith("-") ? "" : "+") + imm; + if (["R_MIPS_LO16", "R_MIPS_LITERAL", "R_MIPS_GPREL16"].some((r) => reloc_row.includes(r))) repl = `%lo(${repl})`; + else if (reloc_row.includes("R_MIPS_GOT16")) repl = `%got(${repl})`; + else if (reloc_row.includes("R_MIPS_CALL16")) repl = `%call16(${repl})`; + else if (reloc_row.includes("R_MIPS_HI16")) repl = `%hi(${repl})`; + else assert(reloc_row.includes("R_MIPS_26"), `unknown relocation type '${reloc_row}'`); + return repl; +} + +export function process_ppc_reloc(reloc_row, prev, repl) { + assert(["R_PPC_REL24", "R_PPC_ADDR16", "R_PPC_EMB_SDA21"].some((r) => reloc_row.includes(r)), + `unknown relocation type '${reloc_row}' for line '${prev}'`); + if (reloc_row.includes("R_PPC_REL24")) return repl; + if (reloc_row.includes("R_PPC_ADDR16_HI")) return `${repl}@h`; + if (reloc_row.includes("R_PPC_ADDR16_HA")) return `${repl}@ha`; + if (reloc_row.includes("R_PPC_ADDR16_LO")) return `${repl}@l`; + if (reloc_row.includes("R_PPC_ADDR16")) { + if (repl.includes("+0x7")) { + if (parseInt(repl.split("+")[1], 16) > 0x70000000) return repl.split("+")[0]; + } + } else if (reloc_row.includes("R_PPC_EMB_SDA21")) { + return `${repl}@sda21`; + } + return repl; +} + +export function process_arm32_reloc(reloc_row, prev, repl) { + assert(["R_ARM_THM_CALL", "R_ARM_CALL", "R_ARM_ABS32"].some((r) => reloc_row.includes(r)), + `unknown relocation type '${reloc_row}' for line '${prev}'`); + return repl; +} + +export function process_x86_reloc(reloc_row, prev, repl) { + const ignore = ["WRTSEG", "FIWRQQ", "FIDRQQ", "FIERQQ", "FICRQQ", "FISRQQ", "FIARQQ", "FIFRQQ", "FIGRQQ", + "FJCRQQ", "FJSRQQ", "FJARQQ", "FJFRQQ", "FJGRQQ"]; + if (ignore.some((x) => reloc_row.includes(x))) return repl; + repl = pySplitWs(reloc_row).at(-1); + const [mnemonic, args] = pySplitWs1(prev); + let offset = false; + let addr_imm = null; + if (mnemonic.includes("lcall")) addr_imm = /.*/.exec(args); + else if (X86_BRANCH_INSTRUCTIONS.has(mnemonic) || mnemonic.includes("call")) { + addr_imm = /(^|(?<=\*)|(?<=\*%cs:))[0-9a-f]+(?!x)/.exec(args); + } + if (!addr_imm) addr_imm = /(?:0x)?(? reloc_row.includes(s); + if (has("R_386_NONE") || has("R_386_32") || has("R_386_PC32") || has("R_386_16") || has("R_386_PC16") + || has("R_386_8") || has("R_386_PC8")) { /* pass */ } + else if (has("dir32")) { if (repl.includes("+")) repl = repl.split("+")[0]; } + else if (has("DISP32") || has("OFF16") || has("OFF32")) { /* pass */ } + else if (has("OFFPC16") || has("OFFPC32")) { if (repl.includes("+")) repl = repl.split("+")[0]; } + else if (has("R_386_GOT32")) repl = `%got(${repl})`; + else if (has("R_386_PLT32")) repl = `%plt(${repl})`; + else if (has("R_386_RELATIVE")) repl = `%rel(${repl})`; + else if (has("R_386_GOTOFF") || has("R_386_GOTPC")) repl = `%got(${repl})`; + else if (has("R_386_32PLT")) repl = `%plt(${repl})`; + else if (has("FAR16")) { if (repl.includes("+")) repl = repl.split("+")[0]; } + else if (has("SEG")) { /* pass */ } + else assert(false, `unknown relocation type '${reloc_row}' for line '${prev}'`); + if (offset) { + let of = addr_imm[0]; + if (of[0] === "$") of = of.slice(1); + repl = of[0] === "-" ? `${repl}${of}` : `${repl}+${of}`; + } + return repl; +} + +export function process_reloc(reloc_row, prev, ign_branch_targets) { + if (prev === "") return null; + const [before, imm, after] = parse_relocated_line(prev); + const repl = pySplitWs(reloc_row).at(-1); + if (imm === "") { + assert(ign_branch_targets); + return null; + } + let new_repl; + if (reloc_row.includes("R_MIPS_")) new_repl = process_mips_reloc(reloc_row, prev, repl, imm); + else if (reloc_row.includes("R_PPC_")) new_repl = process_ppc_reloc(reloc_row, prev, repl); + else if (reloc_row.includes("R_ARM_")) new_repl = process_arm32_reloc(reloc_row, prev, repl); + else if (reloc_row.includes("R_386_")) new_repl = process_x86_reloc(reloc_row, prev, repl); + else throw new Error(`unknown relocation type: ${reloc_row}`); + return before + new_repl + after; +} + +/** Python hex(int(s)) for a decimal digit string with optional '-'. */ +function pyHexOfDecimal(s) { + const neg = s.startsWith("-"); + const v = BigInt(neg ? s.slice(1) : s); + return (neg && v !== 0n ? "-" : "") + "0x" + v.toString(16); +} + +/** + * simplify_objdump: objdump -dr text lines -> Line[] the scorer diffs. + * @param {string[]} input_lines + * @param {ArchSettings} arch + * @param {{stack_differences: boolean, ign_branch_targets: boolean}} opts + * @returns {Line[]} + */ +export function simplify_objdump(input_lines, arch, { stack_differences, ign_branch_targets }) { + /** @type {Line[]} */ + const output_lines = []; + let skip_next = false; + const noRawInsn = arch.arguments.includes("--no-show-raw-insn"); + for (let index = 0; index < input_lines.length; index++) { + let row = input_lines[index]; + if (index < skip_lines) continue; + row = row.replace(/\s+$/, ""); + if (row.includes(">:") || !row) continue; + row = row.replace(arch.re_comment, ""); + row = row.replace(/\s+$/, ""); + const tabs = row.split("\t"); + row = noRawInsn ? tabs.slice(1).join("\t") : tabs.slice(2).join("\t"); + if (!row) continue; + let row_parts; + if (row.includes("\t")) { + const k = row.indexOf("\t"); + row_parts = [row.slice(0, k), row.slice(k + 1)]; + } else { + const k = row.indexOf(" "); + row_parts = (k === -1 ? [row] : [row.slice(0, k), row.slice(k + 1)]).map((part) => part.replace(/^\s+/, "")); + } + let mnemonic = row_parts[0].trim(); + let args = row_parts.length >= 2 ? row_parts[1].trim() : ""; + const next_line = index + 1 < input_lines.length ? input_lines[index + 1] : null; + [mnemonic, args] = pre_process(mnemonic, args, next_line); + row = mnemonic + "\t" + args.replaceAll("\t", " "); + if (row.includes(arch.reloc_str)) { + const modified_prev = process_reloc(row, output_lines[output_lines.length - 1].row, ign_branch_targets); + if (modified_prev) { + output_lines[output_lines.length - 1].row = modified_prev; + output_lines[output_lines.length - 1].has_symbol = true; + } + continue; + } + if (skip_next) { + skip_next = false; + row = ""; + mnemonic = ""; + } + if (ign_regs) row = row.replace(arch.re_reg, ""); + if (!stack_differences) { + if (arch.sp_ref_insns.includes(mnemonic) && arch.re_includes_sp.test(args)) row = row.replace(re_int_full, "imm"); + } + if (arch.branch_instructions.has(mnemonic)) { + if (ign_branch_targets) { + const instr_parts = args.split(","); + instr_parts[instr_parts.length - 1] = ""; + args = instr_parts.join(","); + row = `${mnemonic}\t${args}`; + } + // The last part is in hex, so skip the dec->hex conversion + } else { + const cur = row; + row = cur.replace(re_int, (full, offset) => { + if (full.length <= 1) return full; + const start = offset, end = offset + full.length; + if (start && arch.forbidden.has(cur[start - 1])) return full; + if (end < cur.length && arch.forbidden.has(cur[end])) return full; + return pyHexOfDecimal(full); + }); + } + if (arch.branch_likely_instructions.has(mnemonic) && skip_bl_delay_slots) skip_next = true; + if (!stack_differences) row = row.replace(arch.re_sprel, "addr(sp)"); + output_lines.push({ row, has_symbol: false, mnemonic }); + } + while (output_lines.length && output_lines[output_lines.length - 1].mnemonic === "nop") output_lines.pop(); + return output_lines; +} + +/** + * WASM objdump glue per arch. The caller (romdev) resolves these from its + * toolchain packages; `setObjdumpGlue` lets it register them. + * @type {Record} + */ +const objdumpGlue = {}; + +export function setObjdumpGlue(archName, gluePath) { objdumpGlue[archName] = gluePath; } + +/** Resolve the glue for an arch: registered path, else the romdev toolchain package. */ +export async function resolveObjdumpGlue(archName) { + if (objdumpGlue[archName]) return objdumpGlue[archName]; + if (archName === "mips") { + // The mips-linux-gnu build: the same objdump romdev's compare path runs. + try { + const { toolchain } = await import("romdev-toolchain-mips-gcc"); + objdumpGlue.mips = toolchain["mips-linux-gnu-objdump"].gluePath; + return objdumpGlue.mips; + } catch { /* not installed */ } + } + throw new Error(`no WASM objdump registered for arch '${archName}' (romdev runs binutils as WASM only; register one with setObjdumpGlue)`); +} + +/** + * Disassemble an object with the WASM objdump and simplify it (objdump.objdump). + * `objdump_command` is the settings.toml string split into argv: its first + * element names the host tool upstream would run and is replaced by the WASM + * build; the flags are kept. + * @param {string|Uint8Array} o_file path or object bytes + * @param {ArchSettings} arch + * @param {{objdump_command?: string[]|null, stack_differences?: boolean, ign_branch_targets?: boolean}} opts + * @returns {Promise} + */ +export async function objdump(o_file, arch, { objdump_command = null, stack_differences = false, ign_branch_targets = false } = {}) { + const args = objdump_command ? objdump_command.slice(1) : arch.arguments; + const glue = await resolveObjdumpGlue(arch.name); + let r; + if (usesRawFs(glue)) { + if (typeof o_file !== "string") throw new Error("a NODERAWFS objdump reads the object from disk: pass a path"); + r = await runRawFsTool(glue, [...args, path.resolve(o_file)], { argv0: "mips-linux-gnu-objdump" }); + } else { + const bytes = typeof o_file === "string" ? readFileSync(o_file) : o_file; + r = await runWasmTool(glue, [...args, "/work/in.o"], { "/work/in.o": bytes }); + } + if (r.exitCode !== 0) throw new Error(`objdump exited ${r.exitCode}: ${r.stderr.slice(0, 400)}`); + const lines = splitlines(r.stdout); + return simplify_objdump(lines, arch, { stack_differences, ign_branch_targets }); +} + +const rawFs = new Map(); +/** Was this emscripten tool built with NODERAWFS (host filesystem) rather than MEMFS? */ +function usesRawFs(glue) { + if (!rawFs.has(glue)) rawFs.set(glue, /NODERAWFS/.test(readFileSync(glue, "utf8"))); + return rawFs.get(glue); +} + +/** Python str.splitlines() for \n / \r\n / \r text. */ +export function splitlines(s) { + const out = s.split(/\r\n|\r|\n/); + if (out.length && out[out.length - 1] === "") out.pop(); + return out; +} diff --git a/packages/romdev-permuter/src/perm/ast.js b/packages/romdev-permuter/src/perm/ast.js new file mode 100644 index 00000000..05b1aa14 --- /dev/null +++ b/packages/romdev-permuter/src/perm/ast.js @@ -0,0 +1,40 @@ +// ast.js - late (AST-level) PERM macros, a port of decomp-permuter's src/perm/ast.py. +import { c_ast as ca } from "romdev-pycparser"; +import * as ast_util from "../ast_util.js"; +import { CandidateConstructionFailure } from "../error.js"; + +class Done extends Error {} + +/** Find and apply a single late perm macro in the AST. */ +function _apply_perm(fn, perm_id, perm, seed) { + const wanted_pragma = `_permuter ast_perm ${perm_id}`; + const try_handle_block = (block, where) => { + if (!(block instanceof ca.Compound) || !ast_util.truthy(block.block_items)) return; + const pragma = block.block_items[0]; + if (!(pragma instanceof ca.Pragma) || pragma.string !== wanted_pragma) return; + const args = block.block_items.slice(1); + const stmts = perm.eval_statement_ast(args, seed); + if (where) where[0].splice(where[1], 1, ...stmts); + else block.block_items = stmts; + throw new Done(); + }; + const rec = (block) => { + try_handle_block(block, null); + const stmts = ast_util.get_block_stmts(block, false); + stmts.forEach((stmt, i) => { + try_handle_block(stmt, [stmts, i]); + ast_util.for_nested_blocks(stmt, rec); + }); + }; + try { + rec(fn.body); + throw new CandidateConstructionFailure("Failed to find PERM macro in AST."); + } catch (e) { + if (!(e instanceof Done)) throw e; + } +} + +/** Find all late perm macros in the AST and apply them (lowest id first). */ +export function apply_ast_perms(fn, eval_state) { + eval_state.ast_perms.forEach(([perm, seed], perm_id) => _apply_perm(fn, perm_id, perm, seed)); +} diff --git a/packages/romdev-permuter/src/perm/eval.js b/packages/romdev-permuter/src/perm/eval.js new file mode 100644 index 00000000..a04c3cef --- /dev/null +++ b/packages/romdev-permuter/src/perm/eval.js @@ -0,0 +1,33 @@ +// eval.js - seed enumeration, a port of decomp-permuter's src/perm/eval.py. +import { EvalState } from "./perm.js"; +import { globalRandom } from "../pyrandom.js"; + +/** All numbers 0..total_count-1 in random order, in expected O(1) time each. */ +export function* _gen_all_seeds(total_count, random = globalRandom) { + const seen = new Set(); + const half = total_count / 2n; + while (BigInt(seen.size) < half) { + const seed = random.randrange(total_count); + const key = BigInt(seed); + if (!seen.has(key)) { + seen.add(key); + yield key; + } + } + const remaining = []; + for (let seed = 0n; seed < total_count; seed++) if (!seen.has(seed)) remaining.push(seed); + random.shuffle(remaining); + yield* remaining; +} + +export function* perm_gen_all_seeds(perm, random = globalRandom) { + for (;;) { + yield* _gen_all_seeds(perm.perm_count, random); + if (!perm.is_random()) break; + } +} + +export function perm_evaluate_one(perm) { + const eval_state = new EvalState(); + return [perm.evaluate(0n, eval_state), eval_state]; +} diff --git a/packages/romdev-permuter/src/perm/parse.js b/packages/romdev-permuter/src/perm/parse.js new file mode 100644 index 00000000..dfc8c76c --- /dev/null +++ b/packages/romdev-permuter/src/perm/parse.js @@ -0,0 +1,133 @@ +// parse.js - PERM macro parsing, a port of decomp-permuter's src/perm/parse.py. +import { + CombinePerm, ForceSamelinePerm, GeneralPerm, IgnorePerm, IntPerm, LineSwapPerm, LineSwapAstPerm, + OncePerm, PretendPerm, RandomizerPerm, RootPerm, TextPerm, VarPerm, +} from "./perm.js"; + +class ParseAssertionError extends Error { + constructor(message = "") { super(message); this.name = "AssertionError"; } +} + +function _split_by_comma(text) { + let level = 0; + let current = ""; + const args = []; + for (const c of text) { + if (c === "," && level === 0) { + args.push(current); + current = ""; + } else { + if (c === "(") level += 1; + else if (c === ")") { + level -= 1; + if (!(level >= 0)) throw new ParseAssertionError("Bad nesting"); + } + current += c; + } + } + if (level !== 0) throw new ParseAssertionError("Mismatched parentheses"); + args.push(current); + return args; +} + +const _split_args = (text) => _split_by_comma(text).map(_rec_perm_parse); + +const _split_args_newline = (text) => text.split("\n").filter((line) => line.trim()).map(_rec_perm_parse); + +function _split_args_text(text) { + return _split_args(text).map((perm) => { + if (!(perm instanceof TextPerm)) throw new ParseAssertionError(); + return perm.text; + }); +} + +function _make_once_perm(text) { + const args = _split_by_comma(text); + if (args.length !== 1 && args.length !== 2) throw new Error("PERM_ONCE takes 1 or 2 arguments"); + const key = args[0].trim(); + const value = _rec_perm_parse(args[args.length - 1]); + return new OncePerm(key, value); +} + +function _make_var_perm(text) { + const args = _split_by_comma(text); + if (args.length !== 1 && args.length !== 2) throw new Error("PERM_VAR takes 1 or 2 arguments"); + const var_name = _rec_perm_parse(args[0]); + const value = args.length === 2 ? _rec_perm_parse(args[1]) : null; + return new VarPerm(var_name, value); +} + +/** int() of a PERM_INT bound. */ +function pyInt(s) { + const t = s.trim().replaceAll("_", ""); + if (!/^[+-]?\d+$/.test(t)) throw new Error(`invalid literal for int() with base 10: '${s}'`); + return BigInt(t); +} + +export const PERM_FACTORIES = { + PERM_GENERAL: (text) => new GeneralPerm(_split_args(text)), + PERM_ONCE: (text) => _make_once_perm(text), + PERM_RANDOMIZE: (text) => new RandomizerPerm(_rec_perm_parse(text)), + PERM_FORCE_SAMELINE: (text) => new ForceSamelinePerm(_rec_perm_parse(text)), + PERM_VAR: (text) => _make_var_perm(text), + PERM_LINESWAP_TEXT: (text) => new LineSwapPerm(_split_args_newline(text)), + PERM_LINESWAP: (text) => new LineSwapAstPerm(_split_args_newline(text)), + PERM_INT: (text) => { + const args = _split_args_text(text).map(pyInt); + if (args.length !== 2) throw new TypeError(`IntPerm takes 2 arguments (${args.length} given)`); + return new IntPerm(args[0], args[1]); + }, + PERM_IGNORE: (text) => new IgnorePerm(_rec_perm_parse(text)), + PERM_PRETEND: (text) => new PretendPerm(_rec_perm_parse(text)), +}; + +function _consume_arg_parens(text) { + let level = 0; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (c === "(") level += 1; + else if (c === ")") { + level -= 1; + if (level === -1) return [text.slice(0, i), text.slice(i + 1)]; + } + } + throw new Error("Failed to find closing parenthesis when parsing PERM macro"); +} + +function _rec_perm_parse(text) { + let remain = text; + const macro_search = /(PERM_.+?)\(/; + const perms = []; + while (remain.length > 0) { + const match = macro_search.exec(remain); + if (match == null) { + perms.push(new TextPerm(remain)); + break; + } + const perm_type = match[1]; + if (!Object.hasOwn(PERM_FACTORIES, perm_type)) throw new Error("Unrecognized PERM macro: " + perm_type); + const between = remain.slice(0, match.index); + let args; + [args, remain] = _consume_arg_parens(remain.slice(match.index + match[0].length)); + perms.push(new TextPerm(between)); + perms.push(PERM_FACTORIES[perm_type](args)); + } + if (perms.length === 1) return perms[0]; + return new CombinePerm(perms); +} + +/** + * Parse PERM macros out of a source text. `log` receives upstream's + * informational lines ("No perm macros found...", "Will try N ..."). + */ +export function perm_parse(text, log = (s) => console.log(s)) { + let ret = _rec_perm_parse(text); + if (new RootPerm(ret).perm_count <= 1n && !ret.is_random()) { + ret = new RandomizerPerm(ret); + log("No perm macros found. Defaulting to randomization."); + } + ret = new RootPerm(ret); + if (!ret.is_random()) log(`Will run for ${ret.perm_count} iterations.`); + else log(`Will try ${ret.perm_count} different base sources.`); + return ret; +} diff --git a/packages/romdev-permuter/src/perm/perm.js b/packages/romdev-permuter/src/perm/perm.js new file mode 100644 index 00000000..65c227d9 --- /dev/null +++ b/packages/romdev-permuter/src/perm/perm.js @@ -0,0 +1,315 @@ +// perm.js - PERM macro evaluation, a port of decomp-permuter's src/perm/perm.py. +// +// Seeds and permutation counts are BigInts: a PERM_LINESWAP of n lines has n! +// variants, which leaves Number's exact range quickly (Python ints are exact). +import { c_ast as ca } from "romdev-pycparser"; + +export class PreprocessState { + constructor() { + /** @type {Map} (a defaultdict(list) in upstream) */ + this.once_options = new Map(); + } +} + +export class EvalState { + constructor() { + /** @type {Map} */ + this.vars = new Map(); + /** @type {Map} */ + this.once_choices = new Map(); + /** @type {[Perm, bigint][]} */ + this.ast_perms = []; + } + + register_ast_perm(perm, seed) { + const ret = this.ast_perms.length; + this.ast_perms.push([perm, seed]); + return ret; + } + + gen_ast_statement_perm(perm, seed, { statements }) { + const perm_id = this.register_ast_perm(perm, seed); + return ["{", `#pragma _permuter ast_perm ${perm_id}`, ...statements.map((s) => "{" + s + "}"), "}"].join("\n"); + } +} + +class PermAssertionError extends Error { + constructor(message = "") { super(message); this.name = "AssertionError"; } +} + +export class Perm { + constructor() { + /** @type {bigint} */ + this.perm_count = 1n; + /** @type {Perm[]} */ + this.children = []; + } + + // eslint-disable-next-line no-unused-vars + evaluate(seed, state) { return ""; } + + // eslint-disable-next-line no-unused-vars + eval_statement_ast(args, seed) { throw new Error("NotImplementedError"); } + + preprocess(state) { for (const p of this.children) p.preprocess(state); } + + is_random() { return this.children.some((p) => p.is_random()); } +} + +/** divmod for BigInts (both operands non-negative here). */ +const divmod = (a, b) => [a / b, a % b]; + +function _eval_all(seed, perms, state) { + const ret = []; + for (const p of perms) { + let sub_seed; + [seed, sub_seed] = divmod(seed, p.perm_count); + ret.push(p.evaluate(sub_seed, state)); + } + if (seed !== 0n) throw new PermAssertionError("seed must be in [0, prod(counts))"); + return ret; +} + +function _count_all(perms) { + let res = 1n; + for (const p of perms) res *= p.perm_count; + return res; +} + +function _eval_either(seed, perms, state) { + for (const p of perms) { + if (seed < p.perm_count) return p.evaluate(seed, state); + seed -= p.perm_count; + } + throw new PermAssertionError("seed must be in [0, sum(counts))"); +} + +function _count_either(perms) { + let s = 0n; + for (const p of perms) s += p.perm_count; + return s; +} + +export function _shuffle(items, seed) { + items = items.slice(); + const output = []; + while (items.length) { + const len = BigInt(items.length); + const ind = Number(seed % len); + seed /= len; + output.push(items[ind]); + items.splice(ind, 1); + } + return output; +} + +function factorial(n) { + let r = 1n; + for (let i = 2n; i <= BigInt(n); i++) r *= i; + return r; +} + +export class RootPerm extends Perm { + constructor(inner) { + super(); + this.children = [inner]; + this.perm_count = inner.perm_count; + this.preprocess_state = new PreprocessState(); + this.preprocess(this.preprocess_state); + for (const [key, options] of this.preprocess_state.once_options) { + if (options.length === 1) throw new Error(`PERM_ONCE(${key}) occurs only once, possible error?`); + this.perm_count *= BigInt(options.length); + } + } + + evaluate(seed, state) { + for (const [key, options] of this.preprocess_state.once_options) { + let choice; + [seed, choice] = divmod(seed, BigInt(options.length)); + state.once_choices.set(key, options[Number(choice)]); + } + return this.children[0].evaluate(seed, state); + } +} + +export class TextPerm extends Perm { + constructor(text) { + super(); + // Comma escape sequence + this.text = text.replaceAll("(,)", ","); + this.children = []; + this.perm_count = 1n; + } + + evaluate() { return this.text; } +} + +export class IgnorePerm extends Perm { + constructor(inner) { + super(); + this.children = [inner]; + this.perm_count = inner.perm_count; + } + + evaluate(seed, state) { + const text = this.children[0].evaluate(seed, state); + if (!text) return ""; + const encoded = Buffer.from(text, "utf8").toString("base64"); + return `\n#pragma _permuter b64literal ${encoded}\n`; + } +} + +export class PretendPerm extends Perm { + constructor(inner) { + super(); + this.children = [inner]; + this.perm_count = inner.perm_count; + } + + evaluate(seed, state) { + const text = this.children[0].evaluate(seed, state); + return ["", "#pragma _permuter latedefine start", text, "#pragma _permuter latedefine end", ""].join("\n"); + } +} + +export class CombinePerm extends Perm { + constructor(parts) { + super(); + this.children = parts; + this.perm_count = _count_all(parts); + } + + evaluate(seed, state) { return _eval_all(seed, this.children, state).join(""); } +} + +export class RandomizerPerm extends Perm { + constructor(inner) { + super(); + this.children = [inner]; + this.perm_count = inner.perm_count; + } + + evaluate(seed, state) { + const text = this.children[0].evaluate(seed, state); + return ["", "#pragma _permuter randomizer start", text, "#pragma _permuter randomizer end", ""].join("\n"); + } + + is_random() { return true; } +} + +export class ForceSamelinePerm extends Perm { + constructor(inner) { + super(); + this.children = [inner]; + this.perm_count = inner.perm_count; + } + + evaluate(seed, state) { + const text = this.children[0].evaluate(seed, state); + return ["", "#pragma _permuter sameline start", text, "#pragma _permuter sameline end", ""].join("\n"); + } +} + +export class GeneralPerm extends Perm { + constructor(candidates) { + super(); + this.perm_count = _count_either(candidates); + this.children = candidates; + } + + evaluate(seed, state) { return _eval_either(seed, this.children, state); } +} + +export class OncePerm extends Perm { + constructor(key, inner) { + super(); + this.key = key; + this.children = [inner]; + this.perm_count = inner.perm_count; + } + + preprocess(state) { + if (!state.once_options.has(this.key)) state.once_options.set(this.key, []); + state.once_options.get(this.key).push(this); + super.preprocess(state); + } + + evaluate(seed, state) { + if (!state.once_choices.has(this.key)) throw new Error(`KeyError: ${this.key}`); + if (state.once_choices.get(this.key) === this) return this.children[0].evaluate(seed, state); + return ""; + } +} + +export class VarPerm extends Perm { + constructor(var_name, expansion) { + super(); + this.children = expansion ? [var_name, expansion] : [var_name]; + this.perm_count = _count_all(this.children); + } + + evaluate(seed, state) { + const var_name_perm = this.children[0]; + let sub_seed; + [seed, sub_seed] = divmod(seed, var_name_perm.perm_count); + const var_name = var_name_perm.evaluate(sub_seed, state).trim(); + if (this.children.length > 1) { + const ret = this.children[1].evaluate(seed, state); + state.vars.set(var_name, ret); + return ""; + } + if (!state.vars.has(var_name)) throw new Error(`Tried to read undefined PERM_VAR ${var_name}`); + return state.vars.get(var_name); + } +} + +export class LineSwapPerm extends Perm { + constructor(lines) { + super(); + this.children = lines; + this.own_count = factorial(lines.length); + this.perm_count = this.own_count * _count_all(this.children); + } + + evaluate(seed, state) { + const [sub_seed, variation] = divmod(seed, this.own_count); + const texts = _eval_all(sub_seed, this.children, state); + return _shuffle(texts, variation).join("\n"); + } +} + +export class LineSwapAstPerm extends Perm { + constructor(lines) { + super(); + this.children = lines; + this.own_count = factorial(lines.length); + this.perm_count = this.own_count * _count_all(this.children); + } + + evaluate(seed, state) { + const [sub_seed, variation] = divmod(seed, this.own_count); + const texts = _eval_all(sub_seed, this.children, state); + return state.gen_ast_statement_perm(this, variation, { statements: texts }); + } + + eval_statement_ast(args, seed) { + const ret = []; + for (const item of _shuffle(args, seed)) { + if (!(item instanceof ca.Compound)) throw new PermAssertionError(); + ret.push(...(item.block_items || [])); + } + return ret; + } +} + +export class IntPerm extends Perm { + constructor(low, high) { + super(); + if (!(low <= high)) throw new PermAssertionError(); + this.low = low; + this.children = []; + this.perm_count = high - low + 1n; + } + + evaluate(seed) { return String(this.low + seed); } +} diff --git a/packages/romdev-permuter/src/permuter.js b/packages/romdev-permuter/src/permuter.js new file mode 100644 index 00000000..ad6c6e9a --- /dev/null +++ b/packages/romdev-permuter/src/permuter.js @@ -0,0 +1,190 @@ +// permuter.js - decomp-permuter's src/permuter.py: one source from which +// candidates are generated, tracking the best scores seen so far. +import { createHash } from "node:crypto"; +import { Candidate } from "./candidate.js"; +import { CandidateConstructionFailure } from "./error.js"; +import { EvalState } from "./perm/perm.js"; +import { perm_evaluate_one, perm_gen_all_seeds } from "./perm/eval.js"; +import { perm_parse } from "./perm/parse.js"; +import { trim_source } from "./helpers.js"; +import { unified_diff } from "./difflib.js"; +import { globalRandom } from "./pyrandom.js"; +import { PENALTY_INF } from "./scorer.js"; + +/** @typedef {{exc_str: string|null, seed: [bigint, bigint]|null, isEvalError: true}} EvalError */ + +class CompileFailure extends Error {} + +/** Python str.strip() for the whitespace-insensitive diff. */ +const strip = (s) => s.replace(/^\s+|\s+$/g, ""); + +export class Permuter { + /** + * Use Permuter.create(): scoring the base is asynchronous. + * @param {object} a + */ + constructor({ dir, fn_name, compiler, scorer, source_file, source, randomization_weights, force_seed = null, + force_rng_seed = null, keep_prob, need_profiler = false, need_all_sources = false, show_errors = false, + best_only = false, better_only = false, score_threshold = null, debug_mode = false, speed = 100, + log = (s) => console.log(s), random = globalRandom }) { + this.dir = dir; + this.compiler = compiler; + this.scorer = scorer; + this.source_file = source_file; + this.source = source; + this.randomization_weights = randomization_weights; + this.log = log; + this.random = random; + if (fn_name == null) { + const fns = _find_fns(source); + if (fns.length === 0) throw new Error(`${this.source_file} does not contain any function!`); + this.fn_name = fns[fns.length - 1]; + log(`Defaulting to function: ${this.fn_name}`); + } else { + this.fn_name = fn_name; + } + this.unique_name = this.fn_name; + this._permutations = perm_parse(source, log); + this._force_seed = force_seed; + this._force_rng_seed = force_rng_seed; + this._cur_seed = null; + this.keep_prob = keep_prob; + this.need_profiler = need_profiler; + this._need_all_sources = need_all_sources; + this._show_errors = show_errors; + this._best_only = best_only; + this._better_only = better_only; + this._score_threshold = score_threshold; + this._debug_mode = debug_mode; + this._cur_cand = null; + this._last_score = null; + /** @type {Map} */ + this._score_for_source = new Map(); + this.speed = speed; + } + + /** + * Build a permuter and score its base (compiling it). `base` may carry an + * already-computed {score, hash, source} (worker threads reuse the parent's). + */ + static async create(opts, base = null) { + const p = new Permuter(opts); + if (base) [p.base_score, p.base_hash, p.base_source] = [base.score, base.hash, base.source]; + else [p.base_score, p.base_hash, p.base_source] = await p._create_and_score_base(); + p.best_score = p.base_score; + p.hashes = new Set([p.base_hash]); + return p; + } + + async _create_and_score_base() { + const [base_source, eval_state] = perm_evaluate_one(this._permutations); + const base_cand = Candidate.from_source(base_source, eval_state, this.fn_name, this.randomization_weights, 0); + if (this._debug_mode) this.log(trim_source(base_cand.get_source(), this.fn_name)); + const o_file = await base_cand.compile(this.compiler, true); + if (!o_file) throw new CandidateConstructionFailure(`Unable to compile ${this.source_file}`); + const base_result = await base_cand.score(this.scorer, o_file); + if (base_result.hash == null) throw new Error("AssertionError: base hash"); + return [base_result.score, base_result.hash, base_cand.get_source()]; + } + + _need_to_send_source(result) { return this._need_all_sources || this.should_output(result); } + + async _eval_candidate(seed) { + const timings = { perm: 0, stringify: 0, compile: 0, score: 0 }; + let t = performance.now(); + const tick = () => { const now = performance.now(); const d = (now - t) / 1000; t = now; return d; }; + // Keep the previous candidate with probability keep_prob (never a zero or + // failed one: those only breed worse zeroes / more failures). + const keep = (this._permutations.is_random() && this.random.uniform(0, 1) < this.keep_prob + && this._last_score !== 0 && this._last_score !== PENALTY_INF) || !!this._force_rng_seed; + this._last_score = null; + if (!this._cur_cand || !keep) { + const eval_state = new EvalState(); + const cand_c = this._permutations.evaluate(BigInt(seed), eval_state); + const rng_seed = this._force_rng_seed ? this._force_rng_seed : this.random.randrange(1n, 10n ** 20n); + this._cur_seed = [BigInt(seed), BigInt(rng_seed)]; + this._cur_cand = Candidate.from_source(cand_c, eval_state, this.fn_name, this.randomization_weights, rng_seed); + } + if (this._permutations.is_random()) this._cur_cand.randomize_ast(); + timings.perm += tick(); + const cand_source = this._cur_cand.get_source(); + const source_hash = createHash("sha256").update(cand_source, "utf8").digest("hex"); + timings.stringify += tick(); + const old_score = this._score_for_source.get(source_hash); + let result; + if (old_score !== undefined) { + result = { score: old_score, hash: null, source: cand_source }; + } else { + const o_file = await this._cur_cand.compile(this.compiler); + if (!o_file && this._show_errors) throw new CompileFailure(); + timings.compile += tick(); + result = await this._cur_cand.score(this.scorer, o_file); + timings.score += tick(); + if (this._score_for_source.size < 100000) this._score_for_source.set(source_hash, result.score); + } + if (this.need_profiler) result.profiler = timings; + result.pass = this._cur_cand.randomizer.lastPass ?? null; + this._last_score = result.score; + if (!this._need_to_send_source(result)) { + result.source = null; + result.hash = null; + } + return result; + } + + /** Whether a result should be written out (more liberal in workers than in the parent). */ + should_output(result) { + return result.score <= this.base_score + && result.hash != null + && result.source != null + && !(result.score > this.best_score && this._best_only) + && (result.score < this.base_score || (result.score === this.base_score && !this._better_only)) + && (this._score_threshold == null || result.score < this._score_threshold) + && !this.hashes.has(result.hash); + } + + /** Record a result: best score, and its hash (except zeroes: every zero is interesting). */ + record_result(result) { + this.best_score = Math.min(this.best_score, result.score); + if (result.score !== 0 && result.hash != null) this.hashes.add(result.hash); + } + + /** Seeds for this permuter: infinite when randomizing. */ + *seed_iterator() { + if (this._force_seed == null) { + yield* perm_gen_all_seeds(this._permutations, this.random); + return; + } + if (this._permutations.is_random()) { + for (;;) yield BigInt(this._force_seed); + } + yield BigInt(this._force_seed); + } + + /** @returns {Promise} */ + async try_eval_candidate(seed) { + try { + return await this._eval_candidate(seed); + } catch (e) { + if (e instanceof CompileFailure) return { isEvalError: true, exc_str: null, seed: this._cur_seed }; + return { isEvalError: true, exc_str: formatException(e), seed: this._cur_seed }; + } + } + + /** Unified, whitespace-insensitive diff of the base source against another source. */ + diff(other_source) { + const a = this.base_source.split("\n"); + const b = other_source.split("\n"); + return unified_diff(a, b, { fromfile: "before", tofile: "after", lineterm: "", key: strip }).join("\n"); + } +} + +export function formatException(e) { + if (e && e.stack) return String(e.stack); + return String(e); +} + +function _find_fns(source) { + const fns = [...source.matchAll(/(\w+)\([^()\n]*\)\s*?{/g)].map((m) => m[1]); + return fns.filter((fn) => !fn.startsWith("PERM") && !["if", "for", "switch", "while"].includes(fn)); +} diff --git a/packages/romdev-permuter/src/pow-data.js b/packages/romdev-permuter/src/pow-data.js new file mode 100644 index 00000000..90d1ca1d --- /dev/null +++ b/packages/romdev-permuter/src/pow-data.js @@ -0,0 +1,280 @@ +// Generated by scripts/gen-pow-data.mjs from the ARM optimized-routines pow +// tables (Copyright (c) 2018, Arm Limited, MIT; as shipped in musl and glibc). +// IEEE-754 bit patterns; do not edit. +const b = new DataView(new ArrayBuffer(8)); +const d = (h) => { b.setBigUint64(0, BigInt(h)); return b.getFloat64(0); }; + +export const POW_LOG = { + ln2hi: d("0x3fe62e42fefa3800"), + ln2lo: d("0x3d2ef35793c76730"), + poly: [d("0xbfe0000000000000"), d("0xbfe5555555555560"), d("0x3fe0000000000006"), d("0x3fe999999959554e"), d("0xbfe555555529a47a"), d("0xbff2495b9b4845e9"), d("0x3ff0002b8b263fc3")], + // [invc, logc, logctail] per subinterval + tab: [ + [d("0x3ff6a00000000000"), d("0xbfd62c82f2b9c800"), d("0x3cfab42428375680")], + [d("0x3ff6800000000000"), d("0xbfd5d1bdbf580800"), d("0xbd1ca508d8e0f720")], + [d("0x3ff6600000000000"), d("0xbfd5767717455800"), d("0xbd2362a4d5b6506d")], + [d("0x3ff6400000000000"), d("0xbfd51aad872df800"), d("0xbce684e49eb067d5")], + [d("0x3ff6200000000000"), d("0xbfd4be5f95777800"), d("0xbd041b6993293ee0")], + [d("0x3ff6000000000000"), d("0xbfd4618bc21c6000"), d("0x3d13d82f484c84cc")], + [d("0x3ff5e00000000000"), d("0xbfd404308686a800"), d("0x3cdc42f3ed820b3a")], + [d("0x3ff5c00000000000"), d("0xbfd3a64c55694800"), d("0x3d20b1c686519460")], + [d("0x3ff5a00000000000"), d("0xbfd347dd9a988000"), d("0x3d25594dd4c58092")], + [d("0x3ff5800000000000"), d("0xbfd2e8e2bae12000"), d("0x3d267b1e99b72bd8")], + [d("0x3ff5600000000000"), d("0xbfd2895a13de8800"), d("0x3d15ca14b6cfb03f")], + [d("0x3ff5600000000000"), d("0xbfd2895a13de8800"), d("0x3d15ca14b6cfb03f")], + [d("0x3ff5400000000000"), d("0xbfd22941fbcf7800"), d("0xbd165a242853da76")], + [d("0x3ff5200000000000"), d("0xbfd1c898c1699800"), d("0xbd1fafbc68e75404")], + [d("0x3ff5000000000000"), d("0xbfd1675cababa800"), d("0x3d1f1fc63382a8f0")], + [d("0x3ff4e00000000000"), d("0xbfd1058bf9ae4800"), d("0xbd26a8c4fd055a66")], + [d("0x3ff4c00000000000"), d("0xbfd0a324e2739000"), d("0xbd0c6bee7ef4030e")], + [d("0x3ff4a00000000000"), d("0xbfd0402594b4d000"), d("0xbcf036b89ef42d7f")], + [d("0x3ff4a00000000000"), d("0xbfd0402594b4d000"), d("0xbcf036b89ef42d7f")], + [d("0x3ff4800000000000"), d("0xbfcfb9186d5e4000"), d("0x3d0d572aab993c87")], + [d("0x3ff4600000000000"), d("0xbfcef0adcbdc6000"), d("0x3d2b26b79c86af24")], + [d("0x3ff4400000000000"), d("0xbfce27076e2af000"), d("0xbd172f4f543fff10")], + [d("0x3ff4200000000000"), d("0xbfcd5c216b4fc000"), d("0x3d21ba91bbca681b")], + [d("0x3ff4000000000000"), d("0xbfcc8ff7c79aa000"), d("0x3d27794f689f8434")], + [d("0x3ff4000000000000"), d("0xbfcc8ff7c79aa000"), d("0x3d27794f689f8434")], + [d("0x3ff3e00000000000"), d("0xbfcbc286742d9000"), d("0x3d194eb0318bb78f")], + [d("0x3ff3c00000000000"), d("0xbfcaf3c94e80c000"), d("0x3cba4e633fcd9066")], + [d("0x3ff3a00000000000"), d("0xbfca23bc1fe2b000"), d("0xbd258c64dc46c1ea")], + [d("0x3ff3a00000000000"), d("0xbfca23bc1fe2b000"), d("0xbd258c64dc46c1ea")], + [d("0x3ff3800000000000"), d("0xbfc9525a9cf45000"), d("0xbd2ad1d904c1d4e3")], + [d("0x3ff3600000000000"), d("0xbfc87fa06520d000"), d("0x3d2bbdbf7fdbfa09")], + [d("0x3ff3400000000000"), d("0xbfc7ab890210e000"), d("0x3d2bdb9072534a58")], + [d("0x3ff3400000000000"), d("0xbfc7ab890210e000"), d("0x3d2bdb9072534a58")], + [d("0x3ff3200000000000"), d("0xbfc6d60fe719d000"), d("0xbd10e46aa3b2e266")], + [d("0x3ff3000000000000"), d("0xbfc5ff3070a79000"), d("0xbd1e9e439f105039")], + [d("0x3ff3000000000000"), d("0xbfc5ff3070a79000"), d("0xbd1e9e439f105039")], + [d("0x3ff2e00000000000"), d("0xbfc526e5e3a1b000"), d("0xbd20de8b90075b8f")], + [d("0x3ff2c00000000000"), d("0xbfc44d2b6ccb8000"), d("0x3d170cc16135783c")], + [d("0x3ff2c00000000000"), d("0xbfc44d2b6ccb8000"), d("0x3d170cc16135783c")], + [d("0x3ff2a00000000000"), d("0xbfc371fc201e9000"), d("0x3cf178864d27543a")], + [d("0x3ff2800000000000"), d("0xbfc29552f81ff000"), d("0xbd248d301771c408")], + [d("0x3ff2600000000000"), d("0xbfc1b72ad52f6000"), d("0xbd2e80a41811a396")], + [d("0x3ff2600000000000"), d("0xbfc1b72ad52f6000"), d("0xbd2e80a41811a396")], + [d("0x3ff2400000000000"), d("0xbfc0d77e7cd09000"), d("0x3d0a699688e85bf4")], + [d("0x3ff2400000000000"), d("0xbfc0d77e7cd09000"), d("0x3d0a699688e85bf4")], + [d("0x3ff2200000000000"), d("0xbfbfec9131dbe000"), d("0xbd2575545ca333f2")], + [d("0x3ff2000000000000"), d("0xbfbe27076e2b0000"), d("0x3d2a342c2af0003c")], + [d("0x3ff2000000000000"), d("0xbfbe27076e2b0000"), d("0x3d2a342c2af0003c")], + [d("0x3ff1e00000000000"), d("0xbfbc5e548f5bc000"), d("0xbd1d0c57585fbe06")], + [d("0x3ff1c00000000000"), d("0xbfba926d3a4ae000"), d("0x3d253935e85baac8")], + [d("0x3ff1c00000000000"), d("0xbfba926d3a4ae000"), d("0x3d253935e85baac8")], + [d("0x3ff1a00000000000"), d("0xbfb8c345d631a000"), d("0x3d137c294d2f5668")], + [d("0x3ff1a00000000000"), d("0xbfb8c345d631a000"), d("0x3d137c294d2f5668")], + [d("0x3ff1800000000000"), d("0xbfb6f0d28ae56000"), d("0xbd269737c93373da")], + [d("0x3ff1600000000000"), d("0xbfb51b073f062000"), d("0x3d1f025b61c65e57")], + [d("0x3ff1600000000000"), d("0xbfb51b073f062000"), d("0x3d1f025b61c65e57")], + [d("0x3ff1400000000000"), d("0xbfb341d7961be000"), d("0x3d2c5edaccf913df")], + [d("0x3ff1400000000000"), d("0xbfb341d7961be000"), d("0x3d2c5edaccf913df")], + [d("0x3ff1200000000000"), d("0xbfb16536eea38000"), d("0x3d147c5e768fa309")], + [d("0x3ff1000000000000"), d("0xbfaf0a30c0118000"), d("0x3d2d599e83368e91")], + [d("0x3ff1000000000000"), d("0xbfaf0a30c0118000"), d("0x3d2d599e83368e91")], + [d("0x3ff0e00000000000"), d("0xbfab42dd71198000"), d("0x3d1c827ae5d6704c")], + [d("0x3ff0e00000000000"), d("0xbfab42dd71198000"), d("0x3d1c827ae5d6704c")], + [d("0x3ff0c00000000000"), d("0xbfa77458f632c000"), d("0xbd2cfc4634f2a1ee")], + [d("0x3ff0c00000000000"), d("0xbfa77458f632c000"), d("0xbd2cfc4634f2a1ee")], + [d("0x3ff0a00000000000"), d("0xbfa39e87b9fec000"), d("0x3cf502b7f526feaa")], + [d("0x3ff0a00000000000"), d("0xbfa39e87b9fec000"), d("0x3cf502b7f526feaa")], + [d("0x3ff0800000000000"), d("0xbf9f829b0e780000"), d("0xbd2980267c7e09e4")], + [d("0x3ff0800000000000"), d("0xbf9f829b0e780000"), d("0xbd2980267c7e09e4")], + [d("0x3ff0600000000000"), d("0xbf97b91b07d58000"), d("0xbd288d5493faa639")], + [d("0x3ff0400000000000"), d("0xbf8fc0a8b0fc0000"), d("0xbcdf1e7cf6d3a69c")], + [d("0x3ff0400000000000"), d("0xbf8fc0a8b0fc0000"), d("0xbcdf1e7cf6d3a69c")], + [d("0x3ff0200000000000"), d("0xbf7fe02a6b100000"), d("0xbd19e23f0dda40e4")], + [d("0x3ff0200000000000"), d("0xbf7fe02a6b100000"), d("0xbd19e23f0dda40e4")], + [d("0x3ff0000000000000"), d("0x0000000000000000"), d("0x0000000000000000")], + [d("0x3ff0000000000000"), d("0x0000000000000000"), d("0x0000000000000000")], + [d("0x3fefc00000000000"), d("0x3f80101575890000"), d("0xbd10c76b999d2be8")], + [d("0x3fef800000000000"), d("0x3f90205658938000"), d("0xbd23dc5b06e2f7d2")], + [d("0x3fef400000000000"), d("0x3f98492528c90000"), d("0xbd2aa0ba325a0c34")], + [d("0x3fef000000000000"), d("0x3fa0415d89e74000"), d("0x3d0111c05cf1d753")], + [d("0x3feec00000000000"), d("0x3fa466aed42e0000"), d("0xbd2c167375bdfd28")], + [d("0x3fee800000000000"), d("0x3fa894aa149fc000"), d("0xbd197995d05a267d")], + [d("0x3fee400000000000"), d("0x3faccb73cdddc000"), d("0xbd1a68f247d82807")], + [d("0x3fee200000000000"), d("0x3faeea31c006c000"), d("0xbd0e113e4fc93b7b")], + [d("0x3fede00000000000"), d("0x3fb1973bd1466000"), d("0xbd25325d560d9e9b")], + [d("0x3feda00000000000"), d("0x3fb3bdf5a7d1e000"), d("0x3d2cc85ea5db4ed7")], + [d("0x3fed600000000000"), d("0x3fb5e95a4d97a000"), d("0xbd2c69063c5d1d1e")], + [d("0x3fed400000000000"), d("0x3fb700d30aeac000"), d("0x3cec1e8da99ded32")], + [d("0x3fed000000000000"), d("0x3fb9335e5d594000"), d("0x3d23115c3abd47da")], + [d("0x3fecc00000000000"), d("0x3fbb6ac88dad6000"), d("0xbd1390802bf768e5")], + [d("0x3feca00000000000"), d("0x3fbc885801bc4000"), d("0x3d2646d1c65aacd3")], + [d("0x3fec600000000000"), d("0x3fbec739830a2000"), d("0xbd2dc068afe645e0")], + [d("0x3fec400000000000"), d("0x3fbfe89139dbe000"), d("0xbd2534d64fa10afd")], + [d("0x3fec000000000000"), d("0x3fc1178e8227e000"), d("0x3d21ef78ce2d07f2")], + [d("0x3febe00000000000"), d("0x3fc1aa2b7e23f000"), d("0x3d2ca78e44389934")], + [d("0x3feba00000000000"), d("0x3fc2d1610c868000"), d("0x3d039d6ccb81b4a1")], + [d("0x3feb800000000000"), d("0x3fc365fcb0159000"), d("0x3cc62fa8234b7289")], + [d("0x3feb400000000000"), d("0x3fc4913d8333b000"), d("0x3d25837954fdb678")], + [d("0x3feb200000000000"), d("0x3fc527e5e4a1b000"), d("0x3d2633e8e5697dc7")], + [d("0x3feae00000000000"), d("0x3fc6574ebe8c1000"), d("0x3d19cf8b2c3c2e78")], + [d("0x3feac00000000000"), d("0x3fc6f0128b757000"), d("0xbd25118de59c21e1")], + [d("0x3feaa00000000000"), d("0x3fc7898d85445000"), d("0xbd1c661070914305")], + [d("0x3fea600000000000"), d("0x3fc8beafeb390000"), d("0xbd073d54aae92cd1")], + [d("0x3fea400000000000"), d("0x3fc95a5adcf70000"), d("0x3d07f22858a0ff6f")], + [d("0x3fea000000000000"), d("0x3fca93ed3c8ae000"), d("0xbd28724350562169")], + [d("0x3fe9e00000000000"), d("0x3fcb31d8575bd000"), d("0xbd0c358d4eace1aa")], + [d("0x3fe9c00000000000"), d("0x3fcbd087383be000"), d("0xbd2d4bc4595412b6")], + [d("0x3fe9a00000000000"), d("0x3fcc6ffbc6f01000"), d("0xbcf1ec72c5962bd2")], + [d("0x3fe9600000000000"), d("0x3fcdb13db0d49000"), d("0xbd2aff2af715b035")], + [d("0x3fe9400000000000"), d("0x3fce530effe71000"), d("0x3cc212276041f430")], + [d("0x3fe9200000000000"), d("0x3fcef5ade4dd0000"), d("0xbcca211565bb8e11")], + [d("0x3fe9000000000000"), d("0x3fcf991c6cb3b000"), d("0x3d1bcbecca0cdf30")], + [d("0x3fe8c00000000000"), d("0x3fd07138604d5800"), d("0x3cf89cdb16ed4e91")], + [d("0x3fe8a00000000000"), d("0x3fd0c42d67616000"), d("0x3d27188b163ceae9")], + [d("0x3fe8800000000000"), d("0x3fd1178e8227e800"), d("0xbd2c210e63a5f01c")], + [d("0x3fe8600000000000"), d("0x3fd16b5ccbacf800"), d("0x3d2b9acdf7a51681")], + [d("0x3fe8400000000000"), d("0x3fd1bf99635a6800"), d("0x3d2ca6ed5147bdb7")], + [d("0x3fe8200000000000"), d("0x3fd214456d0eb800"), d("0x3d0a87deba46baea")], + [d("0x3fe7e00000000000"), d("0x3fd2bef07cdc9000"), d("0x3d2a9cfa4a5004f4")], + [d("0x3fe7c00000000000"), d("0x3fd314f1e1d36000"), d("0xbd28e27ad3213cb8")], + [d("0x3fe7a00000000000"), d("0x3fd36b6776be1000"), d("0x3d116ecdb0f177c8")], + [d("0x3fe7800000000000"), d("0x3fd3c25277333000"), d("0x3d183b54b606bd5c")], + [d("0x3fe7600000000000"), d("0x3fd419b423d5e800"), d("0x3d08e436ec90e09d")], + [d("0x3fe7400000000000"), d("0x3fd4718dc271c800"), d("0xbd2f27ce0967d675")], + [d("0x3fe7200000000000"), d("0x3fd4c9e09e173000"), d("0xbd2e20891b0ad8a4")], + [d("0x3fe7000000000000"), d("0x3fd522ae0738a000"), d("0x3d2ebe708164c759")], + [d("0x3fe6e00000000000"), d("0x3fd57bf753c8d000"), d("0x3d1fadedee5d40ef")], + [d("0x3fe6c00000000000"), d("0x3fd5d5bddf596000"), d("0xbd0a0b2a08a465dc")], + ], +}; + +export const EXP = { + invln2N: d("0x40671547652b82fe"), + negln2hiN: d("0xbf762e42fefa0000"), + negln2loN: d("0xbd0cf79abc9e3b3a"), + shift: d("0x4338000000000000"), + poly: [d("0x3fdffffffffffdbd"), d("0x3fc555555555543c"), d("0x3fa55555cf172b91"), d("0x3f81111167a4d017")], + tab: [ + 0x0n, 0x3ff0000000000000n, + 0x3c9b3b4f1a88bf6en, 0x3feff63da9fb3335n, + 0xbc7160139cd8dc5dn, 0x3fefec9a3e778061n, + 0xbc905e7a108766d1n, 0x3fefe315e86e7f85n, + 0x3c8cd2523567f613n, 0x3fefd9b0d3158574n, + 0xbc8bce8023f98efan, 0x3fefd06b29ddf6den, + 0x3c60f74e61e6c861n, 0x3fefc74518759bc8n, + 0x3c90a3e45b33d399n, 0x3fefbe3ecac6f383n, + 0x3c979aa65d837b6dn, 0x3fefb5586cf9890fn, + 0x3c8eb51a92fdeffcn, 0x3fefac922b7247f7n, + 0x3c3ebe3d702f9cd1n, 0x3fefa3ec32d3d1a2n, + 0xbc6a033489906e0bn, 0x3fef9b66affed31bn, + 0xbc9556522a2fbd0en, 0x3fef9301d0125b51n, + 0xbc5080ef8c4eea55n, 0x3fef8abdc06c31ccn, + 0xbc91c923b9d5f416n, 0x3fef829aaea92de0n, + 0x3c80d3e3e95c55afn, 0x3fef7a98c8a58e51n, + 0xbc801b15eaa59348n, 0x3fef72b83c7d517bn, + 0xbc8f1ff055de323dn, 0x3fef6af9388c8dean, + 0x3c8b898c3f1353bfn, 0x3fef635beb6fcb75n, + 0xbc96d99c7611eb26n, 0x3fef5be084045cd4n, + 0x3c9aecf73e3a2f60n, 0x3fef54873168b9aan, + 0xbc8fe782cb86389dn, 0x3fef4d5022fcd91dn, + 0x3c8a6f4144a6c38dn, 0x3fef463b88628cd6n, + 0x3c807a05b0e4047dn, 0x3fef3f49917ddc96n, + 0x3c968efde3a8a894n, 0x3fef387a6e756238n, + 0x3c875e18f274487dn, 0x3fef31ce4fb2a63fn, + 0x3c80472b981fe7f2n, 0x3fef2b4565e27cddn, + 0xbc96b87b3f71085en, 0x3fef24dfe1f56381n, + 0x3c82f7e16d09ab31n, 0x3fef1e9df51fdee1n, + 0xbc3d219b1a6fbffan, 0x3fef187fd0dad990n, + 0x3c8b3782720c0ab4n, 0x3fef1285a6e4030bn, + 0x3c6e149289cecb8fn, 0x3fef0cafa93e2f56n, + 0x3c834d754db0abb6n, 0x3fef06fe0a31b715n, + 0x3c864201e2ac744cn, 0x3fef0170fc4cd831n, + 0x3c8fdd395dd3f84an, 0x3feefc08b26416ffn, + 0xbc86a3803b8e5b04n, 0x3feef6c55f929ff1n, + 0xbc924aedcc4b5068n, 0x3feef1a7373aa9cbn, + 0xbc9907f81b512d8en, 0x3feeecae6d05d866n, + 0xbc71d1e83e9436d2n, 0x3feee7db34e59ff7n, + 0xbc991919b3ce1b15n, 0x3feee32dc313a8e5n, + 0x3c859f48a72a4c6dn, 0x3feedea64c123422n, + 0xbc9312607a28698an, 0x3feeda4504ac801cn, + 0xbc58a78f4817895bn, 0x3feed60a21f72e2an, + 0xbc7c2c9b67499a1bn, 0x3feed1f5d950a897n, + 0x3c4363ed60c2ac11n, 0x3feece086061892dn, + 0x3c9666093b0664efn, 0x3feeca41ed1d0057n, + 0x3c6ecce1daa10379n, 0x3feec6a2b5c13cd0n, + 0x3c93ff8e3f0f1230n, 0x3feec32af0d7d3den, + 0x3c7690cebb7aafb0n, 0x3feebfdad5362a27n, + 0x3c931dbdeb54e077n, 0x3feebcb299fddd0dn, + 0xbc8f94340071a38en, 0x3feeb9b2769d2ca7n, + 0xbc87deccdc93a349n, 0x3feeb6daa2cf6642n, + 0xbc78dec6bd0f385fn, 0x3feeb42b569d4f82n, + 0xbc861246ec7b5cf6n, 0x3feeb1a4ca5d920fn, + 0x3c93350518fdd78en, 0x3feeaf4736b527dan, + 0x3c7b98b72f8a9b05n, 0x3feead12d497c7fdn, + 0x3c9063e1e21c5409n, 0x3feeab07dd485429n, + 0x3c34c7855019c6ean, 0x3feea9268a5946b7n, + 0x3c9432e62b64c035n, 0x3feea76f15ad2148n, + 0xbc8ce44a6199769fn, 0x3feea5e1b976dc09n, + 0xbc8c33c53bef4da8n, 0x3feea47eb03a5585n, + 0xbc845378892be9aen, 0x3feea34634ccc320n, + 0xbc93cedd78565858n, 0x3feea23882552225n, + 0x3c5710aa807e1964n, 0x3feea155d44ca973n, + 0xbc93b3efbf5e2228n, 0x3feea09e667f3bcdn, + 0xbc6a12ad8734b982n, 0x3feea012750bdabfn, + 0xbc6367efb86da9een, 0x3fee9fb23c651a2fn, + 0xbc80dc3d54e08851n, 0x3fee9f7df9519484n, + 0xbc781f647e5a3ecfn, 0x3fee9f75e8ec5f74n, + 0xbc86ee4ac08b7db0n, 0x3fee9f9a48a58174n, + 0xbc8619321e55e68an, 0x3fee9feb564267c9n, + 0x3c909ccb5e09d4d3n, 0x3feea0694fde5d3fn, + 0xbc7b32dcb94da51dn, 0x3feea11473eb0187n, + 0x3c94ecfd5467c06bn, 0x3feea1ed0130c132n, + 0x3c65ebe1abd66c55n, 0x3feea2f336cf4e62n, + 0xbc88a1c52fb3cf42n, 0x3feea427543e1a12n, + 0xbc9369b6f13b3734n, 0x3feea589994cce13n, + 0xbc805e843a19ff1en, 0x3feea71a4623c7adn, + 0xbc94d450d872576en, 0x3feea8d99b4492edn, + 0x3c90ad675b0e8a00n, 0x3feeaac7d98a6699n, + 0x3c8db72fc1f0eab4n, 0x3feeace5422aa0dbn, + 0xbc65b6609cc5e7ffn, 0x3feeaf3216b5448cn, + 0x3c7bf68359f35f44n, 0x3feeb1ae99157736n, + 0xbc93091fa71e3d83n, 0x3feeb45b0b91ffc6n, + 0xbc5da9b88b6c1e29n, 0x3feeb737b0cdc5e5n, + 0xbc6c23f97c90b959n, 0x3feeba44cbc8520fn, + 0xbc92434322f4f9aan, 0x3feebd829fde4e50n, + 0xbc85ca6cd7668e4bn, 0x3feec0f170ca07ban, + 0x3c71affc2b91ce27n, 0x3feec49182a3f090n, + 0x3c6dd235e10a73bbn, 0x3feec86319e32323n, + 0xbc87c50422622263n, 0x3feecc667b5de565n, + 0x3c8b1c86e3e231d5n, 0x3feed09bec4a2d33n, + 0xbc91bbd1d3bcbb15n, 0x3feed503b23e255dn, + 0x3c90cc319cee31d2n, 0x3feed99e1330b358n, + 0x3c8469846e735ab3n, 0x3feede6b5579fdbfn, + 0xbc82dfcd978e9db4n, 0x3feee36bbfd3f37an, + 0x3c8c1a7792cb3387n, 0x3feee89f995ad3adn, + 0xbc907b8f4ad1d9fan, 0x3feeee07298db666n, + 0xbc55c3d956dcaeban, 0x3feef3a2b84f15fbn, + 0xbc90a40e3da6f640n, 0x3feef9728de5593an, + 0xbc68d6f438ad9334n, 0x3feeff76f2fb5e47n, + 0xbc91eee26b588a35n, 0x3fef05b030a1064an, + 0x3c74ffd70a5fddcdn, 0x3fef0c1e904bc1d2n, + 0xbc91bdfbfa9298acn, 0x3fef12c25bd71e09n, + 0x3c736eae30af0cb3n, 0x3fef199bdd85529cn, + 0x3c8ee3325c9ffd94n, 0x3fef20ab5fffd07an, + 0x3c84e08fd10959acn, 0x3fef27f12e57d14bn, + 0x3c63cdaf384e1a67n, 0x3fef2f6d9406e7b5n, + 0x3c676b2c6c921968n, 0x3fef3720dcef9069n, + 0xbc808a1883ccb5d2n, 0x3fef3f0b555dc3fan, + 0xbc8fad5d3ffffa6fn, 0x3fef472d4a07897cn, + 0xbc900dae3875a949n, 0x3fef4f87080d89f2n, + 0x3c74a385a63d07a7n, 0x3fef5818dcfba487n, + 0xbc82919e2040220fn, 0x3fef60e316c98398n, + 0x3c8e5a50d5c192acn, 0x3fef69e603db3285n, + 0x3c843a59ac016b4bn, 0x3fef7321f301b460n, + 0xbc82d52107b43e1fn, 0x3fef7c97337b9b5fn, + 0xbc892ab93b470dc9n, 0x3fef864614f5a129n, + 0x3c74b604603a88d3n, 0x3fef902ee78b3ff6n, + 0x3c83c5ec519d7271n, 0x3fef9a51fbc74c83n, + 0xbc8ff7128fd391f0n, 0x3fefa4afa2a490dan, + 0xbc8dae98e223747dn, 0x3fefaf482d8e67f1n, + 0x3c8ec3bc41aa2008n, 0x3fefba1bee615a27n, + 0x3c842b94c3a9eb32n, 0x3fefc52b376bba97n, + 0x3c8a64a931d185een, 0x3fefd0765b6e4540n, + 0xbc8e37bae43be3edn, 0x3fefdbfdad9cbe14n, + 0x3c77893b4d91cd9dn, 0x3fefe7c1819e90d8n, + 0x3c5305c14160cc89n, 0x3feff3c22b8f71f1n, + ], +}; diff --git a/packages/romdev-permuter/src/pow.js b/packages/romdev-permuter/src/pow.js new file mode 100644 index 00000000..688a00b9 --- /dev/null +++ b/packages/romdev-permuter/src/pow.js @@ -0,0 +1,211 @@ +// pow.js - the C library pow() CPython's float `**` calls, so the permuter's +// reorder weights `(dist + 1) ** -1.5` are the same doubles upstream computes. +// +// glibc (and musl) implement pow with the ARM optimized-routines algorithm +// (Szabolcs Nagy, 2018): a table-driven log with a ~15-bit tail, a scaled +// y*log(x), and a table-driven exp. That algorithm is ported here step for +// step, with every intermediate a double exactly as in C (JS evaluates double +// arithmetic without contraction or extended precision, like the C source +// compiled with -ffp-contract=off). The source has two code paths selected by +// __FP_FAST_FMA; glibc on x86-64 ships both and picks the FMA one at load time +// on CPUs with FMA. Both are here (`fma: true` uses an exactly rounded fused +// multiply-add), and test/pow.test.js checks them against the host libm. +// +// V8's Math.pow / `**` is a different algorithm with its own last-bit +// behaviour, which is why the permuter does not use it for these weights. +import { POW_LOG, EXP } from "./pow-data.js"; + +const buf = new DataView(new ArrayBuffer(8)); +const asuint64 = (d) => { buf.setFloat64(0, d); return buf.getBigUint64(0); }; +const asdouble = (u) => { buf.setBigUint64(0, BigInt.asUintN(64, u)); return buf.getFloat64(0); }; +const top12 = (d) => Number(asuint64(d) >> 52n); + +// -- exact fused multiply-add ------------------------------------------------ + +/** A finite double as sign * M * 2**E with M a BigInt (0 for zero). */ +function split(d) { + const u = asuint64(d); + const sign = u >> 63n ? -1n : 1n; + const e = Number((u >> 52n) & 0x7ffn); + const f = u & 0xfffffffffffffn; + if (e === 0) return [sign * f, -1074]; + return [sign * (f | (1n << 52n)), e - 1075]; +} + +/** Round sign-carrying integer M * 2**E to the nearest double (ties to even). */ +function roundToDouble(M, E) { + if (M === 0n) return 0; + const neg = M < 0n; + let m = neg ? -M : M; + let e = E; + const len = m.toString(2).length; + // target 53 significant bits (subnormals: exponent floor -1074) + let drop = len - 53; + if (e + drop < -1074) drop = -1074 - e; + if (drop > 0) { + const half = 1n << BigInt(drop - 1); + const rem = m & ((1n << BigInt(drop)) - 1n); + m >>= BigInt(drop); + e += drop; + if (rem > half || (rem === half && (m & 1n))) m += 1n; + } else if (drop < 0) { + m <<= BigInt(-drop); + e += drop; + } + // m * 2**e now fits (m may have become 2**53 after rounding; Number handles it exactly) + const v = Number(m) * 2 ** e; + return neg ? -v : v; +} + +/** fma(a, b, c) = a*b + c with a single rounding. */ +export function fma(a, b, c) { + const [ma, ea] = split(a), [mb, eb] = split(b), [mc, ec] = split(c); + const ep = ea + eb; + const e = Math.min(ep, ec); + const M = ((ma * mb) << BigInt(ep - e)) + (mc << BigInt(ec - e)); + if (M === 0n) return (a * b) + c; // signed-zero rules + return roundToDouble(M, e); +} + +// -- the algorithm ------------------------------------------------------------- + +const OFF = 0x3fe6955500000000n; +const T_LOG = POW_LOG.tab; +const A = POW_LOG.poly; +const N_EXP = 128n; +const [C2, C3, C4, C5] = EXP.poly; + +function log_inline(ix, useFma) { + const tmp = BigInt.asUintN(64, ix - OFF); + const i = Number((tmp >> 45n) % 128n); + const k = Number(BigInt.asIntN(64, tmp) >> 52n); + const iz = BigInt.asUintN(64, ix - (tmp & (0xfffn << 52n))); + const z = asdouble(iz); + const kd = k; + const [invc, logc, logctail] = T_LOG[i]; + let r, rhi, rlo; + if (useFma) { + r = fma(z, invc, -1.0); + } else { + const zhi = asdouble((iz + (1n << 31n)) & (BigInt.asUintN(64, -1n) << 32n)); + const zlo = z - zhi; + rhi = zhi * invc - 1.0; + rlo = zlo * invc; + r = rhi + rlo; + } + const t1 = useFma ? fma(kd, POW_LOG.ln2hi, logc) : kd * POW_LOG.ln2hi + logc; + const t2 = t1 + r; + const lo1 = useFma ? fma(kd, POW_LOG.ln2lo, logctail) : kd * POW_LOG.ln2lo + logctail; + const lo2 = t1 - t2 + r; + const ar = A[0] * r; + const ar2 = r * ar; + const ar3 = r * ar2; + let hi, lo3, lo4; + if (useFma) { + hi = t2 + ar2; + lo3 = fma(ar, r, -ar2); + lo4 = t2 - hi + ar2; + } else { + const arhi = A[0] * rhi; + const arhi2 = rhi * arhi; + hi = t2 + arhi2; + lo3 = rlo * (ar + arhi); + lo4 = t2 - hi + arhi2; + } + let lo; + if (useFma) { + const inner = fma(ar2, fma(r, A[6], A[5]), fma(r, A[4], A[3])); + const outer = fma(ar2, inner, fma(r, A[2], A[1])); + lo = fma(ar3, outer, lo1 + lo2 + lo3 + lo4); + } else { + const p = ar3 * (A[1] + r * A[2] + ar2 * (A[3] + r * A[4] + ar2 * (A[5] + r * A[6]))); + lo = lo1 + lo2 + lo3 + lo4 + p; + } + const y = hi + lo; + const tail = hi - y + lo; + return [y, tail]; +} + +function exp_inline(x, xtail, useFma) { + const abstop = top12(x) & 0x7ff; + if (abstop - top12(2 ** -54) >= top12(512.0) - top12(2 ** -54) || abstop < top12(2 ** -54)) { + throw new RangeError("pow.js: exp argument outside the range this port handles (|y*log x| in [2^-54, 512))"); + } + let kd = useFma ? fma(EXP.invln2N, x, EXP.shift) : EXP.invln2N * x + EXP.shift; + const ki = asuint64(kd); + kd -= EXP.shift; + let r = useFma ? fma(kd, EXP.negln2loN, fma(kd, EXP.negln2hiN, x)) : x + kd * EXP.negln2hiN + kd * EXP.negln2loN; + r += xtail; + const idx = Number(2n * (ki % N_EXP)); + const top = BigInt.asUintN(64, ki << 45n); + const tail = asdouble(EXP.tab[idx]); + const sbits = BigInt.asUintN(64, EXP.tab[idx + 1] + top); + const r2 = r * r; + const scale = asdouble(sbits); + if (useFma) { + const tmp = fma(r2 * r2, fma(r, C5, C4), fma(r2, fma(r, C3, C2), tail + r)); + return fma(scale, tmp, scale); + } + const tmp = tail + r + r2 * (C2 + r * C3) + r2 * r2 * (C4 + r * C5); + return scale + scale * tmp; +} + +/** + * pow(x, y) for a positive normal x and a y with 2^-54 <= |y log x| < 512 + * (every weight the permuter computes). Other inputs throw rather than guess. + * @param {number} x + * @param {number} y + * @param {{fma?: boolean}} [opts] the __FP_FAST_FMA code path + */ +export function libmPow(x, y, { fma: useFma = hostUsesFma() } = {}) { + if (!(x > 0) || !Number.isFinite(x) || x < 2 ** -1022 || !Number.isFinite(y)) { + throw new RangeError("pow.js: positive normal x and finite y only"); + } + if (x === 1) return 1; + const topy = top12(y) & 0x7ff; + if (topy - 0x3be >= 0x43e - 0x3be) throw new RangeError("pow.js: |y| outside [2^-65, 2^63)"); + const ix = asuint64(x); + const iy = asuint64(y); + const [hi, lo] = log_inline(ix, useFma); + let ehi, elo; + if (useFma) { + ehi = y * hi; + elo = fma(y, lo, fma(y, hi, -ehi)); + } else { + const yhi = asdouble(iy & (BigInt.asUintN(64, -1n) << 27n)); + const ylo = y - yhi; + const lhi = asdouble(asuint64(hi) & (BigInt.asUintN(64, -1n) << 27n)); + const llo = hi - lhi + lo; + ehi = yhi * lhi; + elo = ylo * lhi + y * llo; + } + return exp_inline(ehi, elo, useFma); +} + +let hostFma = null; +/** + * Which pow code path the platform's C library runs. glibc on x86-64 selects + * its FMA build when the CPU has FMA and AVX2; override with + * ROMDEV_PERMUTER_POW=fma|generic. + */ +export function hostUsesFma() { + if (hostFma != null) return hostFma; + const env = process.env.ROMDEV_PERMUTER_POW; + if (env === "fma" || env === "generic") return (hostFma = env === "fma"); + hostFma = false; + if (process.arch === "x64" && process.platform === "linux") { + try { + const flags = /^flags\s*:\s*(.*)$/m.exec(readCpuinfo())?.[1]?.split(/\s+/) ?? []; + hostFma = flags.includes("fma") && flags.includes("avx2"); + } catch { /* keep generic */ } + } else if (process.arch === "arm64") { + hostFma = true; // AArch64 always has fused multiply-add + } + return hostFma; +} + +import { readFileSync } from "node:fs"; +function readCpuinfo() { return readFileSync("/proc/cpuinfo", "utf8"); } + +/** (dist + 1) ** -1.5 as upstream computes it. */ +export function powNeg15(x) { return libmPow(x, -1.5); } diff --git a/packages/romdev-permuter/src/preprocess.js b/packages/romdev-permuter/src/preprocess.js new file mode 100644 index 00000000..f35d5f34 --- /dev/null +++ b/packages/romdev-permuter/src/preprocess.js @@ -0,0 +1,47 @@ +// preprocess.js - upstream runs `cpp -P -nostdinc -DPERMUTER base.c` before +// parsing. romdev never spawns a host cpp: a caller that has a JS +// preprocessor passes it as options.preprocess. Without one, this accepts only +// sources a cpp pass would leave token-for-token unchanged (no directives but +// #pragma / #ident / linemarkers, no comments), which is what an +// already-preprocessed base.c is, and refuses anything else instead of +// guessing. +import { readFileSync } from "node:fs"; + +export class PreprocessorRequired extends Error { + constructor(message) { super(message); this.name = "PreprocessorRequired"; } +} + +/** + * @param {string} filename + * @returns {string} + */ +export function preprocess(filename) { + const text = readFileSync(filename, "utf8"); + const lines = text.split("\n"); + for (let i = 0; i < lines.length; i++) { + const m = /^\s*#\s*(\w*)/.exec(lines[i]); + if (m && !["pragma", "ident", "line", ""].includes(m[1]) && !/^\d/.test(m[1])) { + throw new PreprocessorRequired(`${filename}:${i + 1}: '#${m[1]}' needs a C preprocessor; pass options.preprocess (upstream runs cpp -P -nostdinc -DPERMUTER)`); + } + } + if (hasComment(text)) { + throw new PreprocessorRequired(`${filename} contains comments; pass options.preprocess (upstream runs cpp -P -nostdinc -DPERMUTER)`); + } + return text; +} + +/** A comment start outside string/char literals. */ +function hasComment(text) { + let q = null; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (q) { + if (c === "\\") { i++; continue; } + if (c === q || c === "\n") q = null; + continue; + } + if (c === "\"" || c === "'") { q = c; continue; } + if (c === "/" && (text[i + 1] === "*" || text[i + 1] === "/")) return true; + } + return false; +} diff --git a/packages/romdev-permuter/src/pyrandom.js b/packages/romdev-permuter/src/pyrandom.js new file mode 100644 index 00000000..4151a3d4 --- /dev/null +++ b/packages/romdev-permuter/src/pyrandom.js @@ -0,0 +1,199 @@ +// pyrandom.js - Python's `random.Random` (MT19937 + the pure-Python methods +// the permuter calls), so a given seed produces the same stream of choices as +// upstream. Spec: CPython Modules/_randommodule.c (init_genrand, +// init_by_array, genrand_uint32, random_seed for int seeds, getrandbits, +// random) and Lib/random.py (_randbelow_with_getrandbits, randrange, randint, +// choice, shuffle, sample, uniform). +// +// Integers above 2**53 (the permuter's rng seeds go up to 10**20, and PERM +// macro counts can be factorials) are BigInts; methods accept either. +import { randomBytes } from "node:crypto"; + +const N = 624, M = 397; +const MATRIX_A = 0x9908b0df, UPPER_MASK = 0x80000000, LOWER_MASK = 0x7fffffff; + +export class PyRandom { + constructor(seed) { + this.mt = new Uint32Array(N); + this.mti = N + 1; + this.seed(seed); + } + + /** random.seed(a): an int (Number or BigInt) seeds deterministically; null/undefined seeds from the OS. */ + seed(a) { + let n; + if (a == null) n = BigInt("0x" + randomBytes(32).toString("hex")); + else if (typeof a === "bigint") n = a; + else if (typeof a === "number" && Number.isInteger(a)) n = BigInt(a); + else throw new TypeError("PyRandom.seed: only integer seeds are supported"); + if (n < 0n) n = -n; + const key = []; + if (n === 0n) key.push(0); + while (n > 0n) { key.push(Number(n & 0xffffffffn)); n >>= 32n; } + this.initByArray(key); + } + + initGenrand(s) { + const mt = this.mt; + mt[0] = s >>> 0; + for (let i = 1; i < N; i++) { + const prev = mt[i - 1] ^ (mt[i - 1] >>> 30); + mt[i] = (Math.imul(1812433253, prev) + i) >>> 0; + } + this.mti = N; + } + + initByArray(key) { + const mt = this.mt; + const keyLength = key.length; + this.initGenrand(19650218); + let i = 1, j = 0; + for (let k = N > keyLength ? N : keyLength; k; k--) { + const prev = mt[i - 1] ^ (mt[i - 1] >>> 30); + mt[i] = ((mt[i] ^ Math.imul(prev, 1664525)) + key[j] + j) >>> 0; + i++; j++; + if (i >= N) { mt[0] = mt[N - 1]; i = 1; } + if (j >= keyLength) j = 0; + } + for (let k = N - 1; k; k--) { + const prev = mt[i - 1] ^ (mt[i - 1] >>> 30); + mt[i] = ((mt[i] ^ Math.imul(prev, 1566083941)) - i) >>> 0; + i++; + if (i >= N) { mt[0] = mt[N - 1]; i = 1; } + } + mt[0] = 0x80000000; + this.mti = N; + } + + genrandUint32() { + const mt = this.mt; + let y; + if (this.mti >= N) { + let kk; + for (kk = 0; kk < N - M; kk++) { + y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); + mt[kk] = mt[kk + M] ^ (y >>> 1) ^ (y & 1 ? MATRIX_A : 0); + } + for (; kk < N - 1; kk++) { + y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); + mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ (y & 1 ? MATRIX_A : 0); + } + y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); + mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ (y & 1 ? MATRIX_A : 0); + this.mti = 0; + } + y = mt[this.mti++]; + y ^= y >>> 11; + y ^= (y << 7) & 0x9d2c5680; + y ^= (y << 15) & 0xefc60000; + y ^= y >>> 18; + return y >>> 0; + } + + /** random.random(): 53-bit float in [0, 1). */ + random() { + const a = this.genrandUint32() >>> 5, b = this.genrandUint32() >>> 6; + return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); + } + + /** getrandbits(k) as a Number (k <= 32) or BigInt (k > 32). */ + getrandbits(k) { + if (k < 0) throw new RangeError("number of bits must be non-negative"); + if (k === 0) return 0; + if (k <= 32) return this.genrandUint32() >>> (32 - k); + let result = 0n, shift = 0n; + for (let kk = k; kk > 0; kk -= 32) { + let r = this.genrandUint32(); + if (kk < 32) r >>>= 32 - kk; + result |= BigInt(r) << shift; + shift += 32n; + } + return result; + } + + /** _randbelow_with_getrandbits(n): n > 0, Number or BigInt; returns the same kind. */ + _randbelow(n) { + if (typeof n === "bigint") { + if (n <= 0xffffffffn) return BigInt(this._randbelow(Number(n))); + const k = n.toString(2).length; + let r = this.getrandbits(k); + while (r >= n) r = this.getrandbits(k); + return r; + } + if (n > 0xffffffff) { + if (!Number.isSafeInteger(n)) throw new RangeError("use a BigInt for ranges beyond 2**53"); + return Number(this._randbelow(BigInt(n))); + } + const k = 32 - Math.clz32(n); + let r = this.getrandbits(k); + while (r >= n) r = this.getrandbits(k); + return r; + } + + randrange(start, stop) { + if (stop === undefined) { + if (start > 0 || start > 0n) return this._randbelow(start); + throw new RangeError("empty range for randrange()"); + } + if (typeof start === "bigint" || typeof stop === "bigint") { + const s = BigInt(start), width = BigInt(stop) - s; + if (width > 0n) return s + this._randbelow(width); + throw new RangeError(`empty range in randrange(${start}, ${stop})`); + } + const width = stop - start; + if (width > 0) return start + this._randbelow(width); + throw new RangeError(`empty range in randrange(${start}, ${stop})`); + } + + randint(a, b) { + if (b < a) throw new RangeError(`empty range in randint(${a}, ${b})`); + if (typeof a === "bigint" || typeof b === "bigint") return BigInt(a) + this._randbelow(BigInt(b) - BigInt(a) + 1n); + return a + this._randbelow(b - a + 1); + } + + choice(seq) { + if (!seq.length) throw new PyIndexError("Cannot choose from an empty sequence"); + return seq[this._randbelow(seq.length)]; + } + + shuffle(x) { + for (let i = x.length - 1; i >= 1; i--) { + const j = this._randbelow(i + 1); + const t = x[i]; x[i] = x[j]; x[j] = t; + } + } + + sample(population, k) { + const n = population.length; + if (!(0 <= k && k <= n)) throw new RangeError("Sample larger than population or is negative"); + const result = new Array(k); + let setsize = 21; + if (k > 5) setsize += 4 ** Math.ceil(Math.log(k * 3) / Math.log(4)); + if (n <= setsize) { + const pool = population.slice(); + for (let i = 0; i < k; i++) { + const j = this._randbelow(n - i); + result[i] = pool[j]; + pool[j] = pool[n - i - 1]; + } + } else { + const selected = new Set(); + for (let i = 0; i < k; i++) { + let j = this._randbelow(n); + while (selected.has(j)) j = this._randbelow(n); + selected.add(j); + result[i] = population[j]; + } + } + return result; + } + + uniform(a, b) { return a + (b - a) * this.random(); } +} + +export class PyIndexError extends Error { + constructor(message) { super(message); this.name = "IndexError"; } +} + +/** The module-level `random` (seeded from the OS, like a fresh process). */ +export const globalRandom = new PyRandom(); diff --git a/packages/romdev-permuter/src/randomizer.js b/packages/romdev-permuter/src/randomizer.js new file mode 100644 index 00000000..3cc23c95 --- /dev/null +++ b/packages/romdev-permuter/src/randomizer.js @@ -0,0 +1,1857 @@ +// randomizer.js - the randomization passes, a port of decomp-permuter's +// src/randomizer.py. Every pass draws from the same PyRandom in the same +// order as upstream, so a given rng seed replays the same edits. +import { c_ast as ca, Node } from "romdev-pycparser"; +import * as ast_util from "./ast_util.js"; +import { isa, truthy, deepcopy, shallowCopy, AssertionError, to_c_raw } from "./ast_util.js"; +import { + allowed_basic_type, build_typemap, is_local_var, decayed_expr_type, get_decl_type, resolve_typedefs, + same_type, set_decl_name, pointer_decay, AssertionError as TypesAssertionError, +} from "./ast_types.js"; +import { PyRandom } from "./pyrandom.js"; +import { powNeg15 as libmPowNeg15 } from "./pow.js"; + +// Randomize the type of introduced temporary variable with this probability +const PROB_RANDOMIZE_TYPE = 0.3; +// Reuse an existing var instead of introducing a new temporary one with this probability +const PROB_REUSE_VAR = 0.5; +// When wrapping statements in a new block, use a same-line `do { ... } while(0);` +const PROB_INS_BLOCK_DOWHILE = 0.5; +// Make a pointer to a temporary expression, rather than copy it by value +const PROB_TEMP_PTR = 0.05; +// Assign the temporary within the first expression it's used in +const PROB_TEMP_ASSIGN_AT_FIRST_USE = 0.1; +// Use the temporary for all equal expressions +const PROB_TEMP_REPLACE_ALL = 0.2; +// Use the temporary for an interval with maximal endpoint +const PROB_TEMP_REPLACE_MOST = 0.2; +// When substituting a variable by its value, substitute all instances +const PROB_EXPAND_REPLACE_ALL = 0.3; +// When substituting a variable by its value, keep the variable assignment +const PROB_KEEP_REPLACED_VAR = 0.2; +// Change the return type of an external function to void +const PROB_RET_VOID = 0.2; +// `if (variable1 || variable2)` in perm_var_cond_block +const PROB_VAR_COND_BLOCK_OR = 0.25; +// Number larger than any node index. +const MAX_INDEX = 10 ** 9; + +export class RandomizationFailure extends Error { + constructor() { super("RandomizationFailure"); this.name = "RandomizationFailure"; } +} + +/** Abort the pass if `condition` is false (never after modifying the AST). */ +function ensure(condition) { + if (!truthy(condition)) throw new RandomizationFailure(); +} + +function assert(cond, msg) { if (!cond) throw new AssertionError(msg); } + +const isAssertion = (e) => e instanceof AssertionError || e instanceof TypesAssertionError; + +/** Remove duplicates, keeping the first instance (dict.fromkeys order). */ +function dedup(li) { return [...new Set(li)]; } + +/** bisect.bisect_left */ +function bisect_left(a, x) { + let lo = 0, hi = a.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (a[mid] < x) lo = mid + 1; + else hi = mid; + } + return lo; +} + +/** Python's (x) ** -1.5: the C library pow CPython calls (see pow.js). */ +const powNeg15 = (x) => libmPowNeg15(x); + +class Region { + constructor(start, end, indices) { + this.start = start; + this.end = end; + this.indices = indices; + } + + static unbounded() { return new Region(-1, MAX_INDEX, null); } + + is_unbounded() { return this.indices == null; } + + contains_node(node) { + if (this.indices == null) return true; + return this.start < this.indices.starts.get(node) && this.indices.ends.get(node) < this.end; + } + + contains_pre(node) { + if (this.indices == null) return true; + const s = this.indices.starts.get(node); + return this.start < s && s < this.end; + } + + contains_pre_index(index) { + if (this.indices == null) return true; + return this.start < index && index < this.end; + } +} + +function reverse_start_indices(indices) { + const ret = new Map(); + for (const [k, v] of indices.starts) ret.set(v, k); + return ret; +} + +function get_randomization_region(top_node, indices, random) { + const ret = []; + let cur_start = null; + const visit = (node) => { + if (node instanceof ca.Pragma) { + if (node.string === "_permuter randomizer start") { + if (cur_start != null) throw new Error("nested PERM_RANDOMIZE not supported"); + cur_start = indices.ends.get(node); + } + if (node.string === "_permuter randomizer end") { + assert(cur_start != null, "randomizer end without start"); + ret.push(new Region(cur_start + 1, indices.starts.get(node) - 1, indices)); + cur_start = null; + } + return; + } + for (const c of node) visit(c); + }; + visit(top_node); + assert(cur_start == null, "randomizer start without end"); + if (!ret.length) return Region.unbounded(); + return random.choice(ret); +} + +/** All expressions within a block that are also within a region. */ +function get_block_expressions(block, region) { + const exprs = []; + replace_subexprs(block, (expr) => { + if (region.contains_node(expr)) exprs.push(expr); + return null; + }); + return exprs; +} + +function compute_write_locations(top_node, indices) { + const writes = new Map(); + const add_write = (var_name, loc) => { + if (!writes.has(var_name)) writes.set(var_name, []); + else { + const w = writes.get(var_name); + assert(loc > w[w.length - 1], "consistent traversal order should guarantee monotonicity here"); + } + writes.get(var_name).push(loc); + }; + const visit = (node) => { + if (node instanceof ca.Decl) { + if (truthy(node.name)) add_write(node.name, indices.starts.get(node)); + } else if (node instanceof ca.UnaryOp) { + if (["p++", "p--", "++", "--"].includes(node.op) && node.expr instanceof ca.ID) add_write(node.expr.name, indices.starts.get(node)); + } else if (node instanceof ca.Assignment) { + if (node.lvalue instanceof ca.ID) add_write(node.lvalue.name, indices.starts.get(node)); + } + for (const c of node) visit(c); + }; + visit(top_node); + return writes; +} + +function compute_read_locations(top_node, indices) { + const reads = new Map(); + for (const node of find_var_reads(top_node)) { + const var_name = node.name; + const loc = indices.starts.get(node); + if (!reads.has(var_name)) reads.set(var_name, []); + else { + const r = reads.get(var_name); + assert(loc > r[r.length - 1], "consistent traversal order should guarantee monotonicity here"); + } + reads.get(var_name).push(loc); + } + return reads; +} + +function find_var_reads(top_node) { + const ret = []; + const visit = (node) => { + if (node instanceof ca.Decl) { + if (node.init) visit(node.init); + return; + } + if (node instanceof ca.ID) { ret.push(node); return; } + if (node instanceof ca.UnaryOp) { + if (node.op === "&" && node.expr instanceof ca.ID) return; + } else if (node instanceof ca.StructRef) { + visit(node.name); + return; + } else if (node instanceof ca.Assignment) { + if (node.lvalue instanceof ca.ID) return; + } + for (const c of node) visit(c); + }; + visit(top_node); + return ret; +} + +function get_mentioned_names(fn, region) { + const names = []; + const visit = (node) => { + if (node instanceof ca.ID) { + if (region.contains_node(node)) names.push(node.name); + return; + } + if (node instanceof ca.StructRef) { visit(node.name); return; } + for (const c of node) visit(c); + }; + visit(fn); + return names; +} + +const PASSIVE_NODES = [ + ca.TypeDecl, ca.PtrDecl, ca.ArrayDecl, ca.Typename, ca.IdentifierType, ca.Typeof, ca.Struct, ca.Union, + ca.Enum, ca.EmptyStatement, ca.Pragma, ca.Break, ca.Continue, ca.Goto, ca.CompoundLiteral, ca.Typedef, + ca.FuncDecl, ca.FuncDef, ca.EllipsisParam, ca.Enumerator, ca.EnumeratorList, ca.FileAST, ca.InitList, + ca.NamedInitializer, ca.ParamList, ca.GccAttribute, ca.GccAttributeStatement, ca.Asm, ca.AsmOperand, ca.Range, +]; + +/** + * Walk statements/expressions in evaluation-ish order, letting `callback` + * replace nodes. callback(node, is_expr) returns a replacement or null. + */ +function visit_replace(top_node, callback) { + const empty_statement_to_none = (node) => (node instanceof ca.EmptyStatement ? null : node); + const rec = (node, toplevel = false, lvalue = false) => { + const repl = callback(node, !toplevel && !lvalue); + if (repl) return repl; + if (node instanceof ca.Assignment) { + node.lvalue = rec(node.lvalue, false, true); + node.rvalue = rec(node.rvalue); + } else if (node instanceof ca.StructRef) { + node.name = rec(node.name, false, lvalue && node.type === "."); + } else if (node instanceof ca.Cast) { + if (node.expr) node.expr = rec(node.expr); + } else if (isa(node, ca.Constant, ca.ID)) { + // pass + } else if (node instanceof ca.UnaryOp) { + if (["p++", "p--", "++", "--", "&"].includes(node.op)) node.expr = rec(node.expr, false, true); + else if (node.op !== "sizeof") node.expr = rec(node.expr); + } else if (node instanceof ca.BinaryOp) { + node.left = rec(node.left); + node.right = rec(node.right); + } else if (node instanceof ca.FuncCall) { + if (!(node.name instanceof ca.ID)) node.name = rec(node.name); + if (node.args) rec(node.args, true); + } else if (node instanceof ca.ExprList) { + for (let i = 0; i < node.exprs.length; i++) { + if (!(node.exprs[i] instanceof ca.Typename)) node.exprs[i] = rec(node.exprs[i]); + } + } else if (node instanceof ca.ArrayRef) { + node.name = rec(node.name, false, lvalue); + node.subscript = rec(node.subscript); + } else if (node instanceof ca.TernaryOp) { + node.cond = rec(node.cond); + node.iftrue = rec(node.iftrue, true); + node.iffalse = rec(node.iffalse, true); + } else if (node instanceof ca.Return) { + if (node.expr) node.expr = rec(node.expr); + } else if (node instanceof ca.Decl) { + if (node.init) node.init = rec(node.init, node.init instanceof ca.InitList); + } else if (node instanceof ca.For) { + if (node.init) node.init = empty_statement_to_none(rec(node.init, true)); + if (node.cond) node.cond = rec(node.cond); + if (node.next) node.next = empty_statement_to_none(rec(node.next, true)); + node.stmt = rec(node.stmt, true); + } else if (node instanceof ca.Compound) { + if (truthy(node.block_items)) { + node.block_items.forEach((sub, i) => { node.block_items[i] = rec(sub, true); }); + } + } else if (isa(node, ca.Case, ca.Default)) { + if (truthy(node.stmts)) node.stmts.forEach((sub, i) => { node.stmts[i] = rec(sub, true); }); + } else if (node instanceof ca.While) { + node.cond = rec(node.cond); + node.stmt = rec(node.stmt, true); + } else if (node instanceof ca.DoWhile) { + node.stmt = rec(node.stmt, true); + node.cond = rec(node.cond); + } else if (node instanceof ca.Switch) { + node.cond = rec(node.cond); + node.stmt = rec(node.stmt, true); + } else if (node instanceof ca.Label) { + node.stmt = rec(node.stmt, true); + } else if (node instanceof ca.If) { + node.cond = rec(node.cond); + node.iftrue = rec(node.iftrue, true); + if (node.iffalse) node.iffalse = rec(node.iffalse, true); + } else if (isa(node, ...PASSIVE_NODES)) { + // pass + } else { + assert(false, `Node with unknown type: ${node?.constructor?.name}`); + } + return node; + }; + rec(top_node, true); +} + +function replace_subexprs(top_node, callback) { + visit_replace(top_node, (node, is_expr) => (is_expr ? callback(node) : null)); +} + +function replace_node(top_node, old, neu) { + visit_replace(top_node, (node) => (node === old ? neu : null)); +} + +function random_bool(random, prob) { return random.random() < prob; } + +function random_weighted(random, values) { + let sumprob = 0.0; + for (const [, prob] of values) { + assert(prob >= 0, "Probabilities must be non-negative"); + sumprob += prob; + } + assert(sumprob > 0, "Cannot pick randomly from empty set"); + const targetprob = random.uniform(0, sumprob); + sumprob = 0.0; + for (const [val, prob] of values) { + sumprob += prob; + if (sumprob > targetprob) return val; + } + // Float imprecision + for (const [val, prob] of values) if (prob > 0) return val; + assert(false, "unreachable"); +} + +function random_type(random) { + const new_names = []; + if (random_bool(random, 0.5)) new_names.push("unsigned"); + new_names.push(...random_weighted(random, [ + [["char"], 1], [["short"], 1], [["int"], 2], [["long"], 0.5], [["long", "long"], 0.5], + ])); + const idtype = new ca.IdentifierType({ names: new_names }); + let quals = []; + if (random_bool(random, 0.5)) quals = ["volatile"]; + return new ca.TypeDecl({ declname: null, quals, align: [], type: idtype }); +} + +function randomize_type(type, typemap, random, { ensure_changed = false } = {}) { + if (allowed_basic_type(type, typemap, ["int", "char", "long", "short", "signed", "unsigned"])) return random_type(random); + if (ensure_changed) throw new RandomizationFailure(); + return type; +} + +function randomize_innermost_type(type, typemap, random, { ensure_changed = false } = {}) { + if (type instanceof ca.TypeDecl) return randomize_type(type, typemap, random, { ensure_changed }); + const new_type = shallowCopy(type); + new_type.type = randomize_innermost_type(type.type, typemap, random, { ensure_changed }); + return new_type; +} + +function ensure_arithmetic_type(expr, typemap) { + const type = decayed_expr_type(expr, typemap); + ensure(allowed_basic_type(type, typemap, ["int", "char", "long", "short", "signed", "unsigned", "float", "double"])); +} + +/** int(const.value.strip("uU"), 0), failing the pass on a ValueError. */ +function get_constant_int_value(konst) { + const s = konst.value.replace(/^[uU]+|[uU]+$/g, ""); + const m = /^\s*([+-]?)(0[xX][0-9a-fA-F]+|0[oO][0-7]+|0[bB][01]+|[1-9][0-9]*|0+)\s*$/.exec(s.replaceAll(/(?<=[0-9a-fA-F])_(?=[0-9a-fA-F])/g, "")); + if (!m) throw new RandomizationFailure(); + const body = m[2]; + let v; + if (/^0[xX]/.test(body)) v = BigInt(body); + else if (/^0[oO]/.test(body)) v = BigInt("0o" + body.slice(2)); + else if (/^0[bB]/.test(body)) v = BigInt("0b" + body.slice(2)); + else v = BigInt(body); + return m[1] === "-" ? -v : v; +} + +function get_insertion_points(fn, region, { allow_within_decl = false } = {}) { + let cands = []; + const rec = (block) => { + const stmts = ast_util.get_block_stmts(block, false); + let last_node = null; + stmts.forEach((stmt, i) => { + if (region.contains_pre(stmt)) cands.push([block, i, last_node, stmt]); + ast_util.for_nested_blocks(stmt, rec); + last_node = stmt; + }); + if (region.contains_node(last_node || block)) cands.push([block, stmts.length, last_node, null]); + }; + rec(fn.body); + if (!allow_within_decl) cands = cands.filter((c) => !(c[3] instanceof ca.Decl)); + return cands; +} + +function get_noncolliding_name(ast, name) { + const used_names = new Set(); + for (const item of ast.ext) { + if (item instanceof ca.Decl && truthy(item.name)) used_names.add(item.name); + if (item instanceof ca.FuncDef && truthy(item.decl.name)) used_names.add(item.decl.name); + } + let new_name = name; + let counter = 1; + while (used_names.has(new_name)) { + counter += 1; + new_name = `${new_name}${counter}`; + } + return new_name; +} + +function maybe_reuse_var(varName, assign_before, orig_expr, type, reads, writes, indices, typemap, random) { + if (!random_bool(random, PROB_REUSE_VAR) || varName == null) return null; + const var_type = decayed_expr_type(new ca.ID(varName), typemap); + if (!same_type(var_type, type, typemap, true)) return null; + const find_next = (lst, value) => { + const ind = bisect_left(lst, value); + return ind < lst.length ? lst[ind] : null; + }; + const assignment_ind = indices.starts.get(assign_before); + const expr_ind = indices.starts.get(orig_expr); + const write = find_next(writes.get(varName) ?? [], assignment_ind); + const read = find_next(reads.get(varName) ?? [], assignment_ind); + if (read != null && (write == null || write >= read)) return null; + if (write != null && write < expr_ind) return null; + return varName; +} + +function pick_random_subset(random, cands, mid) { + const all_before = cands.slice(0, mid); + const all_after = cands.slice(mid + 1); + const prob = random_bool(random, 0.5) ? 0.5 : 0; + let before = all_before.filter(() => random_bool(random, prob)); + let after = all_after.filter(() => random_bool(random, prob)); + if (random_bool(random, PROB_TEMP_REPLACE_ALL)) { + before = all_before; + after = all_after; + } else if (random_bool(random, PROB_TEMP_REPLACE_MOST)) { + if (random_bool(random, 0.5)) before = all_before; + else after = all_after; + } + return [...before, cands[mid], ...after]; +} + +// --------------------------------------------------------------------------- +// Randomization passes. Each takes (fn, ast, indices, region, random). + +/** + * Create a temporary variable for a random expression. The variable will be + * assigned at another random point (nearer the expression being more likely), + * possibly reuse an existing variable, possibly be of a different + * size/signedness, and possibly be used for other identical expressions as + * well. Only expressions within the given region may be chosen for + * replacement, but the assignment and the affected identical expressions may + * be outside of it. + */ +function perm_temp_for_expr(fn, ast, indices, region, random) { + const einds = new Map(); + const writes = compute_write_locations(fn, indices); + const reads = compute_read_locations(fn, indices); + const typemap = build_typemap(ast, fn); + const candidates = []; + let should_make_ptr = random_bool(random, PROB_TEMP_PTR); + + const surrounding_writes = (expr, base) => { + const sub_reads = find_var_reads(expr); + let prev_write = -1; + let next_write = MAX_INDEX; + const base_index = indices.starts.get(base); + for (const sub_read of sub_reads) { + const var_name = sub_read.name; + if (!writes.has(var_name)) continue; + const wr = writes.get(var_name); + const ind = bisect_left(wr, base_index); + if (ind > 0) prev_write = Math.max(prev_write, wr[ind - 1]); + if (ind < wr.length) next_write = Math.min(next_write, wr[ind]); + } + return [prev_write, next_write]; + }; + + const rec = (block, reuse_cands_in) => { + const stmts = ast_util.get_block_stmts(block, false); + const reuse_cands = reuse_cands_in.slice(); + const assignment_cands = []; + let past_decls = false; + stmts.forEach((stmt, index) => { + if (stmt instanceof ca.Decl) { + assert(truthy(stmt.name), "Anonymous declarations cannot happen in functions"); + if (!(stmt.type instanceof ca.ArrayDecl)) { + reuse_cands.push(stmt.name); + if (!(stmt.type instanceof ca.PtrDecl)) reuse_cands.push(stmt.name); + } + } else if (!(stmt instanceof ca.Pragma)) { + past_decls = true; + } + if (past_decls) assignment_cands.push([block, index, stmt]); + ast_util.for_nested_blocks(stmt, (b) => rec(b, reuse_cands)); + const visitor = (expr0) => { + if (!region.contains_node(expr0)) return null; + let expr = expr0; + const orig_expr = expr0; + if (should_make_ptr) { + if (!ast_util.is_lvalue(expr)) return null; + expr = new ca.UnaryOp("&", expr); + } + let eind = einds.get(expr) ?? 0; + const [prev_write] = surrounding_writes(expr, orig_expr); + for (let k = assignment_cands.length - 1; k >= 0; k--) { + const place = assignment_cands[k]; + if (indices.starts.get(place[2]) <= prev_write) break; + eind += 1; + let prob = 1 / eind; + if (isa(orig_expr, ca.ID, ca.Constant)) prob *= should_make_ptr ? 0.15 : 0.5; + const reuse_cand = reuse_cands.length ? random.choice(reuse_cands) : null; + candidates.push([[place, expr, reuse_cand], prob]); + } + einds.set(expr, eind); + return null; + }; + replace_subexprs(stmt, visitor); + }); + }; + rec(fn.body, []); + + ensure(candidates); + let [place, expr, reuse_cand] = random_weighted(random, candidates); + if (random_bool(random, PROB_TEMP_ASSIGN_AT_FIRST_USE)) place = null; + let type = decayed_expr_type(expr, typemap); + if (!should_make_ptr && type instanceof ca.TypeDecl && isa(type.type, ca.Struct, ca.Union) && ast_util.is_lvalue(expr)) { + should_make_ptr = true; + expr = new ca.UnaryOp("&", expr); + type = decayed_expr_type(expr, typemap); + } + let orig_expr; + if (should_make_ptr) { + assert(expr instanceof ca.UnaryOp); + assert(!(expr.expr instanceof ca.Typename)); + orig_expr = expr.expr; + } else { + orig_expr = expr; + } + const assign_before = place != null ? place[2] : orig_expr; + const reused_var = maybe_reuse_var(reuse_cand, assign_before, orig_expr, type, reads, writes, indices, typemap, random); + let reused, varName; + if (reused_var != null) { + reused = true; + varName = reused_var; + } else { + reused = false; + varName = "new_var"; + let counter = 1; + while (writes.has(varName)) { + counter += 1; + varName = `new_var${counter}`; + } + } + let [prev_write, next_write] = surrounding_writes(expr, orig_expr); + prev_write = Math.max(prev_write, indices.starts.get(assign_before) - 1); + let replace_cands = []; + const find_duplicates = (e) => { + const s = indices.starts.get(e); + if (prev_write < s && s <= next_write && ast_util.equal_ast(e, orig_expr)) replace_cands.push(e); + return null; + }; + if (ast_util.is_effectful(expr)) replace_cands = [orig_expr]; + else replace_subexprs(fn.body, find_duplicates); + assert(replace_cands.includes(orig_expr)); + const replace_cand_set = new Set(pick_random_subset(random, replace_cands, replace_cands.indexOf(orig_expr))); + const replacer = (e) => { + if (replace_cand_set.has(e)) { + let ret = new ca.ID(varName); + if (place == null && e === orig_expr) ret = new ca.Assignment("=", ret, expr); + if (should_make_ptr) ret = new ca.UnaryOp("*", ret); + return ret; + } + return null; + }; + replace_subexprs(fn.body, replacer); + if (place != null) { + const [block, index] = place; + const assignment = new ca.Assignment("=", new ca.ID(varName), expr); + ast_util.insert_statement(block, index, assignment); + } + if (!reused) { + if (random_bool(random, PROB_RANDOMIZE_TYPE)) type = randomize_type(type, typemap, random); + ast_util.insert_decl(fn, varName, type, random); + } +} + +/** Replace a random variable by its contents. */ +function perm_expand_expr(fn, ast, indices, region, random) { + const all_writes = compute_write_locations(fn, indices); + const all_reads = compute_read_locations(fn, indices); + const rev = new Map(); + for (const [v, locs] of all_reads) { + for (const index of locs) if (region.contains_pre_index(index)) rev.set(index, v); + } + ensure(rev.size); + const index = random.choice([...rev.keys()]); + const varName = rev.get(index); + const reads = all_reads.get(varName); + const writes = all_writes.get(varName) ?? []; + const i = bisect_left(writes, index); + ensure(i > 0); + const before = writes[i - 1]; + const after = i === writes.length ? MAX_INDEX : writes[i]; + const rev_indices = reverse_start_indices(indices); + const write = rev_indices.get(before); + let repl_expr; + if (write instanceof ca.Decl && write.init && !(write.init instanceof ca.InitList)) repl_expr = write.init; + else if (write instanceof ca.Assignment && write.op === "=") repl_expr = write.rvalue; + else throw new RandomizationFailure(); + let repl_cands = reads.filter((j) => before < j && j < after && region.contains_pre_index(j)); + assert(repl_cands.length, "index is always in repl_cands"); + const myi = repl_cands.indexOf(index); + let keep_var; + if (!random_bool(random, PROB_EXPAND_REPLACE_ALL) && repl_cands.length > 1) { + const side = random.randrange(3); + const H = repl_cands.length; + let loi = side === 0 ? 0 : random.randint(0, myi); + let hii = side === 1 ? H : random.randint(myi + 1, H); + if (loi === 0 && hii === H) { loi = myi; hii = myi + 1; } + repl_cands = repl_cands.slice(0, loi).concat(repl_cands.slice(hii)); + keep_var = true; + } else { + keep_var = random_bool(random, PROB_KEEP_REPLACED_VAR); + } + const repl_cands_set = new Set(repl_cands); + if (ast_util.is_effectful(repl_expr)) ensure(repl_cands.length === 1 && !keep_var); + const callback = (expr, is_expr) => { + if (repl_cands_set.has(indices.starts.get(expr))) return deepcopy(repl_expr); + if (expr === write && write instanceof ca.Assignment && !keep_var) { + return is_expr ? write.lvalue : new ca.EmptyStatement(); + } + return null; + }; + visit_replace(fn.body, callback); + if (!keep_var && write instanceof ca.Decl) write.init = null; +} + +/** + * Randomize types of pre-existing local variables. Function parameters are + * not included -- those are handled by perm_randomize_function_type. Only + * variables mentioned within the given region are affected. + */ +function perm_randomize_internal_type(fn, ast, indices, region, random) { + const names = new Set(get_mentioned_names(fn, region)); + const typemap = build_typemap(ast, fn); + const decls = []; + const visit = (node) => { + if (node instanceof ca.Decl) { + if (node.type instanceof ca.TypeDecl && truthy(node.name) && names.has(node.name)) decls.push(node); + } + for (const c of node) visit(c); + }; + visit(fn); + ensure(decls); + const decl = random.choice(decls); + assert(decl.type instanceof ca.TypeDecl, "checked above"); + decl.type = randomize_type(decl.type, typemap, random, { ensure_changed: true }); + set_decl_name(decl); +} + +/** Randomize types of global variables. Only variables mentioned within the given region are affected. */ +function perm_randomize_external_type(fn, ast, indices, region, random) { + const names = get_mentioned_names(fn, region); + ensure(names); + const name = random.choice(dedup(names)); + const decls = []; + for (let i = 0; i < ast.ext.length; i++) { + const item = ast.ext[i]; + if (item instanceof ca.Decl && item.name === name) decls.push([shallowCopy(item), i]); + } + ensure(decls); + const decl0 = random.choice(decls)[0]; + const decl_type = get_decl_type(decl0); + const typemap = build_typemap(ast, fn); + const new_type = randomize_innermost_type(decl_type, typemap, random, { ensure_changed: true }); + for (const [decl, i] of decls) { + decl.type = deepcopy(new_type); + ast.ext[i] = decl; + set_decl_name(decl); + } +} + +/** + * Randomize types of function parameters and returns. Only functions called + * within the given region are affected, plus the current function. + */ +function perm_randomize_function_type(fn, ast, indices, region, random) { + assert(fn.decl.name != null, "function definitions have names"); + const names = [fn.decl.name]; + const visit = (node) => { + if (node instanceof ca.FuncCall) { + if (region.contains_node(node) && node.name instanceof ca.ID) names.push(node.name.name); + } + for (const c of node) visit(c); + }; + visit(fn); + const name = random.choice(dedup(names)); + const all_decls = []; + let main_decl = null; + for (let i = 0; i < ast.ext.length; i++) { + const item = ast.ext[i]; + if (item instanceof ca.Decl && item.type instanceof ca.FuncDecl && item.name === name) { + const new_decl = shallowCopy(item); + all_decls.push([new_decl, i, new_decl]); + } + if (item instanceof ca.FuncDef && item.decl.name === name) { + assert(item.decl.type instanceof ca.FuncDecl, "function definitions have function types"); + const new_fndef = shallowCopy(item); + const new_decl = shallowCopy(item.decl); + new_fndef.decl = new_decl; + all_decls.push([new_decl, i, new_fndef]); + main_decl = new_decl; + } + } + ensure(all_decls); + if (!main_decl) main_decl = random.choice(all_decls)[0]; + const typemap = build_typemap(ast, fn); + const main_fndecl = deepcopy(main_decl.type); + assert(main_fndecl instanceof ca.FuncDecl, "checked above"); + main_decl.type = main_fndecl; + if (random_bool(random, 0.5)) { + const type = pointer_decay(main_fndecl.type, typemap); + if (allowed_basic_type(type, typemap, ["void"])) main_fndecl.type = random_type(random); + else if (random_bool(random, PROB_RET_VOID)) { + const idtype = new ca.IdentifierType({ names: ["void"] }); + main_fndecl.type = new ca.TypeDecl({ declname: null, quals: [], align: [], type: idtype }); + } else { + main_fndecl.type = randomize_type(type, typemap, random, { ensure_changed: true }); + } + set_decl_name(main_decl); + } else { + if (!main_fndecl.args) throw new RandomizationFailure(); + ensure(main_fndecl.args.params); + const ind = random.randrange(main_fndecl.args.params.length); + const arg = main_fndecl.args.params[ind]; + if (isa(arg, ca.ID, ca.EllipsisParam)) throw new RandomizationFailure(); + const arg_type = arg instanceof ca.Typename ? arg.type : get_decl_type(arg); + const type = pointer_decay(arg_type, typemap); + arg.type = randomize_type(type, typemap, random, { ensure_changed: true }); + if (arg instanceof ca.Decl) set_decl_name(arg); + } + for (const [decl, ind, new_node] of all_decls) { + ast.ext[ind] = new_node; + if (decl !== main_decl) decl.type = deepcopy(main_decl.type); + } +} + +/** + * Add `if (variable) {}` or `if (struct.member) {}` in a random place. This + * will get optimized away but may affect regalloc. + */ +function perm_refer_to_var(fn, ast, indices, region, random) { + const cands = get_block_expressions(fn.body, region).filter((expr) => isa(expr, ca.StructRef, ca.ID)); + ensure(cands); + let expr = random.choice(cands); + ensure(!ast_util.is_effectful(expr)); + const typemap = build_typemap(ast, fn); + const type = resolve_typedefs(decayed_expr_type(expr, typemap), typemap); + if (type instanceof ca.TypeDecl && isa(type.type, ca.Struct, ca.Union)) expr = new ca.UnaryOp("&", expr); + if (random_bool(random, 0.5)) expr = new ca.UnaryOp("!", expr); + const ins_cands = get_insertion_points(fn, Region.unbounded()); + ensure(ins_cands); + let cond = deepcopy(expr); + const reps = random.choice([0, 0, 0, 0, 0, 1, 2, 2]); + for (let i = 0; i < reps; i++) cond = new ca.BinaryOp("&&", cond, deepcopy(expr)); + const stmt = new ca.If({ cond, iftrue: new ca.Compound({ block_items: [] }), iffalse: null }); + const [tob, toi] = random.choice(ins_cands); + ast_util.insert_statement(tob, toi, stmt); +} + +/** + * Wrap a random range of statements within `if (1) { ... }` or + * `do { ... } while(0)`. Control flow can have remote effects, so this mostly + * ignores the region restriction. + */ +function perm_ins_block(fn, ast, indices, region, random) { + const cands = []; + const rec = (block) => { + cands.push(block); + for (const stmt of ast_util.get_block_stmts(block, false)) ast_util.for_nested_blocks(stmt, rec); + }; + rec(fn.body); + const block = random.choice(cands); + const stmts = ast_util.get_block_stmts(block, true); + let decl_count = 0; + for (const stmt of stmts) { + if (isa(stmt, ca.Decl, ca.Pragma)) decl_count += 1; + else break; + } + let lo = random.randrange(decl_count, stmts.length + 1); + let hi = random.randrange(decl_count, stmts.length + 1); + if (hi < lo) [lo, hi] = [hi, lo]; + const new_block = new ca.Compound({ block_items: stmts.slice(lo, hi) }); + if (random_bool(random, PROB_INS_BLOCK_DOWHILE) && stmts.slice(lo, hi).every((n) => region.contains_node(n))) { + const cond = new ca.Constant({ type: "int", value: "0" }); + stmts.splice(lo, hi - lo, + new ca.Pragma("_permuter sameline start"), + new ca.DoWhile({ cond, stmt: new_block }), + new ca.Pragma("_permuter sameline end")); + } else { + const cond = new ca.Constant({ type: "int", value: "1" }); + stmts.splice(lo, hi - lo, new ca.If({ cond, iftrue: new_block, iffalse: null })); + } +} + +/** + * Inserts a no-op statement, one of: + * - if (1) {} (sometimes multiple of them) + * - if (0) {} + * - do {} while (0); + * - label: + * - goto label; label:; + * - ; + * Control flow can have remote effects, so this ignores the region restriction. + */ +function perm_empty_stmt(fn, ast, indices, region, random) { + const cands = get_insertion_points(fn, Region.unbounded()); + ensure(cands); + const label_name = `dummy_label_${random.randint(1, 10 ** 6)}`; + let stmts = []; + const kind = random.randrange(6); + if (kind === 0) { + const count = random.choice([1, random.randint(2, 6)]); + for (let k = 0; k < count; k++) { + const cond = new ca.Constant({ type: "int", value: "1" }); + stmts.push(new ca.If({ cond, iftrue: new ca.Compound([]), iffalse: null })); + } + } else if (kind === 1) { + const cond = new ca.Constant({ type: "int", value: "0" }); + stmts = [new ca.If({ cond, iftrue: new ca.Compound([]), iffalse: null })]; + } else if (kind === 2) { + const cond = new ca.Constant({ type: "int", value: "0" }); + stmts = [new ca.DoWhile({ stmt: new ca.Compound([]), cond })]; + } else if (kind === 3) { + stmts = [new ca.Label(label_name, new ca.EmptyStatement())]; + } else if (kind === 4) { + stmts = [new ca.Goto(label_name), new ca.Label(label_name, new ca.EmptyStatement())]; + } else if (kind === 5) { + stmts = [new ca.EmptyStatement()]; + } + const [tob, toi] = random.choice(cands); + stmts.unshift(new ca.Pragma("_permuter sameline start")); + stmts.push(new ca.Pragma("_permuter sameline end")); + for (let k = stmts.length - 1; k >= 0; k--) ast_util.insert_statement(tob, toi, stmts[k]); +} + +/** Put all statements within a random interval on the same line. */ +function perm_sameline(fn, ast, indices, region, random) { + const cands = get_insertion_points(fn, region); + const n = cands.length; + ensure(n >= 3); + let lef = n - 2; + for (let i = 0; i < 4; i++) lef *= random.uniform(0, 1); + const le = Math.trunc(lef) + 2; + const i = random.randrange(n - le); + const j = i + le; + ast_util.insert_statement(cands[j][0], cands[j][1], new ca.Pragma("_permuter sameline end")); + ast_util.insert_statement(cands[i][0], cands[i][1], new ca.Pragma("_permuter sameline start")); +} + +/** Change a+b into b+a, or similar for other commutative operations. */ +function perm_commutative(fn, ast, indices, region, random) { + const cands = []; + const commutative_ops = [..."+*|&^<>", "<=", ">=", "==", "!="]; + const visit = (node) => { + if (node instanceof ca.BinaryOp) { + if (commutative_ops.includes(node.op) && region.contains_node(node)) cands.push(node); + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const node = random.choice(cands); + [node.left, node.right] = [node.right, node.left]; + if (node.op[0] === "<") node.op = ">" + node.op.slice(1); + else if (node.op[0] === ">") node.op = "<" + node.op.slice(1); +} + +/** Change a-b into a+(-b), or a+b into a-(-b). */ +function perm_add_sub(fn, ast, indices, region, random) { + const cands = []; + const visit = (node) => { + if (node instanceof ca.BinaryOp) { + if ((node.op === "+" || node.op === "-") && region.contains_node(node)) cands.push(node); + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const node = random.choice(cands); + if (node.right instanceof ca.Constant) { + const val = node.right.value; + node.right.value = val.startsWith("-") ? val.slice(1) : "-" + val; + } else if (node.right instanceof ca.UnaryOp && node.right.op === "-") { + assert(!(node.right.expr instanceof ca.Typename)); + node.right = node.right.expr; + } else { + const typemap = build_typemap(ast, fn); + const type = resolve_typedefs(decayed_expr_type(node, typemap), typemap); + ensure(!(type instanceof ca.TypeDecl)); + node.right = new ca.UnaryOp("-", node.right); + } + node.op = node.op === "-" ? "+" : "-"; +} + +/** Change if(x) into if(x != 0), or vice versa. Also handles for/while/do-while. */ +function perm_condition(fn, ast, indices, region, random) { + const cands = []; + const visit = (node) => { + if (isa(node, ca.If, ca.While, ca.DoWhile, ca.For)) cands.push(node); + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const node = random.choice(cands); + if (!node.cond) throw new RandomizationFailure(); + if (node.cond instanceof ca.BinaryOp && ["==", "!=", "<", ">", "<=", ">="].includes(node.cond.op) && random_bool(random, 0.9)) { + ensure(node.cond.op === "==" || node.cond.op === "!="); + ensure(node.cond.right instanceof ca.Constant && ["0", "0U", "0.0", "0.0f"].includes(node.cond.right.value)); + if (node.cond.op === "==") node.cond = new ca.UnaryOp("!", node.cond.left); + else node.cond = node.cond.left; + } else { + let expr = node.cond; + let op = "!="; + if (expr instanceof ca.UnaryOp && expr.op === "!" && random_bool(random, 0.9)) { + assert(!(expr.expr instanceof ca.Typename)); + expr = expr.expr; + op = "=="; + } + const zero = random_weighted(random, [ + [new ca.Constant("int", "0"), 0.8], + [new ca.Constant("unsigned int", "0U"), 0.2], + [new ca.Constant("float", "0.0f"), 0.05], + ]); + node.cond = new ca.BinaryOp(op, expr, zero); + } +} + +/** Introduce a "x = x;", "x += 0;" or "x++; x--;" somewhere. */ +function perm_add_self_assignment(fn, ast, indices, region, random) { + const cands = []; + const seen_keys = new Set(); + for (const expr of get_block_expressions(fn.body, region)) { + if (!isa(expr, ca.ID, ca.StructRef)) continue; + const key = to_c_raw(expr); + if (!seen_keys.has(key)) { + seen_keys.add(key); + cands.push(expr); + } + } + ensure(cands); + const expr = random.choice(cands); + ensure(!ast_util.is_effectful(expr)); + const ins_cands = get_insertion_points(fn, region); + ensure(ins_cands); + const where = random.choice(ins_cands); + const kind = random.randrange(3); + let stmts; + if (kind === 0) stmts = [new ca.Assignment("=", deepcopy(expr), deepcopy(expr))]; + else if (kind === 1) stmts = [new ca.Assignment("+=", deepcopy(expr), new ca.Constant("int", "0"))]; + else stmts = [new ca.UnaryOp("p++", deepcopy(expr)), new ca.UnaryOp("p--", deepcopy(expr))]; + ast_util.insert_statements(where[0], where[1], stmts); +} + +/** Change x into (0, x) for a random expression x. */ +function perm_dummy_comma_expr(fn, ast, indices, region, random) { + const cands = get_block_expressions(fn.body, region); + ensure(cands); + const expr = random.choice(cands); + const new_expr = new ca.ExprList([new ca.Constant("int", "0"), expr]); + replace_node(fn.body, expr, new_expr); +} + +/** Move a statement to another random place. */ +function perm_reorder_stmts(fn, ast, indices, region, random) { + let cands = get_insertion_points(fn, region, { allow_within_decl: true }); + cands = cands.filter(([, , , node]) => !(node instanceof ca.Decl) + || (node.name != null && node.init != null && !(node.init instanceof ca.InitList))); + const source_inds = []; + cands.forEach((c, i) => { + const stmt = c[3]; + if (stmt != null && !(stmt instanceof ca.Pragma) && !ast_util.has_nested_block(stmt)) source_inds.push(i); + }); + ensure(source_inds); + const sourcei = random.choice(source_inds); + const [fromb, fromi, , from_stmt] = cands[sourcei]; + let sourcei_after = sourcei + 1; + if (from_stmt instanceof ca.Decl || sourcei_after === cands.length || cands[sourcei_after][2] !== from_stmt) sourcei_after -= 1; + const weighted_cands = []; + for (let i = 0; i < cands.length; i++) { + const dist = Math.max(sourcei - i, i - sourcei_after); + if (dist === 0) continue; + if (cands[i][3] instanceof ca.Decl) continue; + const prob = powNeg15(dist + 1) + 0.5 / cands.length; + weighted_cands.push([i, prob]); + } + ensure(weighted_cands); + const pick = random_weighted(random, weighted_cands); + let [tob, toi] = cands[pick]; + if (fromb === tob) ensure(toi !== fromi && toi !== fromi + 1); + if (from_stmt instanceof ca.Decl) { + assert(truthy(from_stmt.name)); + assert(from_stmt.init != null); + assert(!(from_stmt.init instanceof ca.InitList)); + const assignment = new ca.Assignment("=", new ca.ID(from_stmt.name), from_stmt.init); + ast_util.insert_statement(tob, toi, assignment); + from_stmt.init = null; + } else { + if (fromb === tob && fromi < toi) toi -= 1; + const stmt = ast_util.get_block_stmts(fromb, true).splice(fromi, 1)[0]; + ast_util.insert_statement(tob, toi, stmt); + } +} + +/** Move a declaration to another random place. */ +function perm_reorder_decls(fn, ast, indices, region, random) { + let cands = get_insertion_points(fn, region, { allow_within_decl: true }); + cands = cands.filter(([, i, before, after]) => i === 0 || before instanceof ca.Decl || after instanceof ca.Decl); + const source_inds = []; + cands.forEach((c, i) => { if (c[3] instanceof ca.Decl) source_inds.push(i); }); + ensure(source_inds); + const sourcei = random.choice(source_inds); + const weighted_cands = []; + for (let i = 0; i < cands.length; i++) { + const dist = Math.max(sourcei - i, i - (sourcei + 1)); + if (dist === 0) continue; + const prob = powNeg15(dist + 1) + 1 / cands.length; + weighted_cands.push([i, prob]); + } + ensure(weighted_cands); + const desti = random_weighted(random, weighted_cands); + const [fromb, fromi, , from_stmt] = cands[sourcei]; + let [tob, toi, , to_stmt] = cands[desti]; + if (fromb === tob) { + assert(toi !== fromi); + assert(toi !== fromi + 1); + } + assert(from_stmt instanceof ca.Decl); + ensure(from_stmt.name); + const var_name = from_stmt.name; + const to_index = to_stmt ? indices.starts.get(to_stmt) : indices.ends.get(fromb); + let uses = 0; + const visit = (node) => { + if (node instanceof ca.ID) { + if (node.name === var_name && indices.starts.get(node) < to_index) uses += 1; + return; + } + if (node instanceof ca.TypeDecl) { + if (node.declname === var_name && indices.starts.get(node) < to_index) uses += 1; + return; + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(uses <= 1); + if (fromb === tob && fromi < toi) toi -= 1; + const stmt = ast_util.get_block_stmts(fromb, true).splice(fromi, 1)[0]; + ast_util.insert_statement(tob, toi, stmt); +} + +/** Convert a statement of the form `x = x op y` to `x op= y`, or vice versa. */ +function perm_compound_assignment(fn, ast, indices, region, random) { + const cands = []; + const operators = ["+", "-", "*", "/", "<<", ">>", "^", "|", "&"]; + const visit = (node) => { + if (node instanceof ca.Assignment) { + if (region.contains_node(node)) { + if (node.op !== "=" || (node.rvalue instanceof ca.BinaryOp && ast_util.equal_ast(node.lvalue, node.rvalue.left) + && operators.includes(node.rvalue.op))) cands.push(node); + } + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const node = random.choice(cands); + if (node.op === "=") { + assert(node.rvalue instanceof ca.BinaryOp); + node.op = node.rvalue.op + node.op; + node.rvalue = node.rvalue.right; + } else { + const operator = node.op.slice(0, -1); + node.op = "="; + node.rvalue = new ca.BinaryOp(operator, deepcopy(node.lvalue), node.rvalue); + } +} + +/** + * Adjusts inequalities to equivalent versions that sometimes produce different + * code. For example, a > b and a >= b + 1, a < b to a <= b - 1 (and vice versa) + */ +function perm_inequalities(fn, ast, indices, region, random) { + const cands = []; + const inequalities = ["<", ">", "<=", ">="]; + const visit = (node) => { + if (node instanceof ca.BinaryOp) { + if (inequalities.includes(node.op) && region.contains_node(node)) cands.push(node); + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const node = random.choice(cands); + const plus1 = (n) => new ca.BinaryOp("+", n, new ca.Constant("int", "1")); + const minus1 = (n) => new ca.BinaryOp("-", n, new ca.Constant("int", "1")); + if (random.random() < 0.25) { + const change = random.choice([plus1, minus1]); + node.left = change(node.left); + node.right = change(node.right); + } else if (node.op === "<" || node.op === ">=") { + node.op = { "<": "<=", ">=": ">" }[node.op]; + if (random_bool(random, 0.5)) node.left = plus1(node.left); + else node.right = minus1(node.right); + } else { + node.op = { ">": ">=", "<=": "<" }[node.op]; + if (random_bool(random, 0.5)) node.left = minus1(node.left); + else node.right = plus1(node.right); + } +} + +/** + * Add a random amount of masks of 0xFF[FFFFFFFFFFFFFF] to a random expression + * of integer type. For IDO these masks may get optimized out while still + * affecting regalloc. The regalloc change seems to cycle with slight + * differences every n masks. + */ +function perm_add_mask(fn, ast, indices, region, random) { + const typemap = build_typemap(ast, fn); + const cands = get_block_expressions(fn.body, region); + ensure(cands); + const expr = random.choice(cands); + const type = decayed_expr_type(expr, typemap); + ensure(allowed_basic_type(type, typemap, ["int", "char", "long", "short", "signed", "unsigned"])); + const masks = ["0xFF", "0xFFFF", "0xFFFFFFFF", "0xFFFFFFFFFFFFFFFF"]; + const mask = random.choice(masks) + random.choice(["", "u"]); + let new_expr = new ca.BinaryOp("&", expr, new ca.Constant("int", mask)); + if (random_bool(random, 0.3)) { + const reps = random.randrange(12); + for (let k = 0; k < reps; k++) new_expr = new ca.BinaryOp("&", new_expr, new ca.Constant("int", mask)); + } + replace_node(fn.body, expr, new_expr); +} + +/** Add ^0 to a random expression of integer type, or *1 to floats. */ +function perm_xor_zero(fn, ast, indices, region, random) { + const typemap = build_typemap(ast, fn); + const cands = get_block_expressions(fn.body, region); + ensure(cands); + const expr = random.choice(cands); + const type = decayed_expr_type(expr, typemap); + const int_types = ["int", "char", "long", "short", "signed", "unsigned"]; + let new_expr; + if (allowed_basic_type(type, typemap, int_types)) new_expr = new ca.BinaryOp("^", expr, new ca.Constant("int", "0")); + else if (allowed_basic_type(type, typemap, ["float"])) new_expr = new ca.BinaryOp("*", expr, new ca.Constant("float", "1.0f")); + else if (allowed_basic_type(type, typemap, ["double"])) new_expr = new ca.BinaryOp("*", expr, new ca.Constant("double", "1.0")); + else throw new RandomizationFailure(); + replace_node(fn.body, expr, new_expr); +} + +/** Convert 0 to x*0 for some randomly chosen x. */ +function perm_mult_zero(fn, ast, indices, region, random) { + const typemap = build_typemap(ast, fn); + const cands = get_block_expressions(fn.body, region); + ensure(cands); + const expr = random.choice(cands); + ensure_arithmetic_type(expr, typemap); + ensure(!ast_util.is_effectful(expr)); + const zeroes = cands.filter((e) => e instanceof ca.Constant && ["0", "0.0", "0.0f"].includes(e.value)); + ensure(zeroes); + const zero = random.choice(zeroes); + const new_expr = new ca.BinaryOp("*", deepcopy(expr), zero); + replace_node(fn.body, zero, new_expr); +} + +/** Convert a * b to a * x * (b / x). */ +function perm_factor_mult(fn, ast, indices, region, random) { + const cands = get_block_expressions(fn.body, region).filter((e) => e instanceof ca.BinaryOp && e.op === "*" + && (e.left instanceof ca.Constant || e.right instanceof ca.Constant)); + ensure(cands); + const expr = random.choice(cands); + let scale, expr0; + if (expr.left instanceof ca.Constant) { + scale = expr.left; + expr0 = expr.right; + } else { + assert(expr.right instanceof ca.Constant); + scale = expr.right; + expr0 = expr.left; + } + const val = get_constant_int_value(scale); + const absval = val < 0n ? -val : val; + ensure(absval >= 2n); + const factor_set = new Set(); + const lim = absval < 21n ? absval : 21n; + for (let i = 2n; i < lim; i++) { + if (pyMod(val, i) === 0n) { + factor_set.add(i); + factor_set.add(pyFloorDiv(val, i)); + } + } + let factors = [...factor_set].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + if (val < 0n) factors = factors.concat(factors.map((f) => -f)); + ensure(factors); + const val1 = random.choice(factors); + const val2 = pyFloorDiv(val, val1); + const expr1 = new ca.BinaryOp("*", expr0, new ca.Constant("int", String(val1))); + const expr2 = new ca.BinaryOp("*", expr1, new ca.Constant("int", String(val2))); + for (const e of [expr1, expr2]) { + if (random.randrange(2)) [e.left, e.right] = [e.right, e.left]; + } + replace_node(fn.body, expr, expr2); +} + +/** Python % on BigInts (result has the divisor's sign). */ +function pyMod(a, b) { const r = a % b; return r !== 0n && (r < 0n) !== (b < 0n) ? r + b : r; } +/** Python // on BigInts. */ +function pyFloorDiv(a, b) { return (a - pyMod(a, b)) / b; } + +/** Convert a >> b to a >> x >> (b - x), or similar with <<. */ +function perm_factor_shift(fn, ast, indices, region, random) { + const cands = get_block_expressions(fn.body, region).filter((e) => e instanceof ca.BinaryOp + && (e.op === "<<" || e.op === ">>") && e.right instanceof ca.Constant); + ensure(cands); + const expr = random.choice(cands); + assert(expr.right instanceof ca.Constant); + const lhs = expr.left; + const rhs = get_constant_int_value(expr.right); + ensure(rhs >= 2n); + const val1 = BigInt(random.randint(1n, rhs - 1n)); + const val2 = rhs - val1; + const expr1 = new ca.BinaryOp(expr.op, lhs, new ca.Constant("int", String(val1))); + const expr2 = new ca.BinaryOp(expr.op, expr1, new ca.Constant("int", String(val2))); + replace_node(fn.body, expr, expr2); +} + +/** Converts a Float Literal */ +function perm_float_literal(fn, ast, indices, region, random) { + const cands = []; + const visit = (node) => { + if (node instanceof ca.Constant) { + if (node.type === "float" && region.contains_node(node)) cands.push(node); + return; + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const node = random.choice(cands); + let value = node.value.toLowerCase(); + const choices = [value.slice(0, -1)]; + if (value.endsWith(".0f")) choices.push(value.slice(0, -3) || "0"); + else if (value.endsWith(".f")) choices.push(value.slice(0, -2) || "0"); + if (value.startsWith("0.")) choices.push("." + (value.slice(2) || "0")); + else if (value.startsWith(".")) choices.push("0" + value); + if (value.endsWith(".0f")) choices.push((value.slice(0, -3) || "0") + ".f"); + else choices.push(value.slice(0, -1) + "0f"); + ensure(choices); + value = random.choice(choices); + let type; + if (value.endsWith("f")) type = "float"; + else if (value.includes(".")) type = "double"; + else type = "int"; + replace_node(fn.body, node, new ca.Constant(type, value)); +} + +/** Cast a random expression to a simple type (integral or floating point only). */ +function perm_cast_simple(fn, ast, indices, region, random) { + const typemap = build_typemap(ast, fn); + const cands = get_block_expressions(fn.body, region); + ensure(cands); + const expr = random.choice(cands); + ensure_arithmetic_type(expr, typemap); + const integral_type = [["int"], ["char"], ["long"], ["short"], ["long", "long"]]; + const floating_type = [["float"], ["double"]]; + let new_type; + if (random_bool(random, 0.5)) { + const sign = random.choice([[], ["unsigned"]]); + new_type = sign.concat(random.choice(integral_type)); + } else { + new_type = random.choice(floating_type); + } + const typedecl = new ca.TypeDecl(null, [], [], new ca.IdentifierType(new_type)); + const new_expr = new ca.Cast(new ca.Typename(null, [], null, [], typedecl), expr); + replace_node(fn.body, expr, new_expr); +} + +/** Permute struct references: (a + b)->c, and (*(a + b)).c, a[b].c, (&a[b])->c */ +function perm_struct_ref(fn, ast, indices, region, random) { + const cands = []; + const visit = (node) => { + if (node instanceof ca.StructRef) { + if (region.contains_node(node)) cands.push(node); + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + + const randomize_associative_binop = (left, right) => { + if (random_bool(random, 0.5) && (right.op === "+" || right.op === "-")) { + return new ca.BinaryOp(right.op, new ca.BinaryOp("+", left, right.left), right.right); + } + return new ca.BinaryOp("+", left, right); + }; + const to_array = (node) => { + if (node.op === "-") node.right = new ca.UnaryOp("-", node.right); + return new ca.ArrayRef(node.left, node.right); + }; + const to_binop = (node) => { + if (node.subscript instanceof ca.BinaryOp) return randomize_associative_binop(node.name, node.subscript); + return new ca.BinaryOp("+", node.name, node.subscript); + }; + const deref = (node) => { + if (node instanceof ca.UnaryOp && node.op === "&") { + assert(!(node.expr instanceof ca.Typename)); + return node.expr; + } + return new ca.UnaryOp("*", node); + }; + const addr = (node) => { + if (node instanceof ca.UnaryOp && node.op === "*") { + assert(!(node.expr instanceof ca.Typename)); + return node.expr; + } + return new ca.UnaryOp("&", node); + }; + const rec = (node) => { + if (node instanceof ca.UnaryOp) { + ensure(node.op === "&" || node.op === "*"); + return rec(node.expr) || node; + } + if (node instanceof ca.StructRef) return rec(node.name) || node; + return null; + }; + const apply_child = (parent, func) => { + if (parent instanceof ca.StructRef) parent.name = func(parent.name); + else if (parent instanceof ca.UnaryOp) parent.expr = func(parent.expr); + }; + const get_child = (parent) => { + if (parent instanceof ca.StructRef) return parent.name; + if (parent instanceof ca.UnaryOp) return parent.expr; + return null; + }; + + const struct_ref = random.choice(cands); + let parent = rec(struct_ref); + let changed = false; + if (struct_ref.type === "->") { + struct_ref.type = "."; + if (parent === struct_ref.name && parent instanceof ca.UnaryOp && parent.op === "&") { + struct_ref.name = deref(struct_ref.name); + parent = struct_ref; + } else { + struct_ref.name = deref(struct_ref.name); + if (parent === struct_ref && struct_ref.name instanceof ca.UnaryOp) parent = struct_ref.name; + } + changed = true; + } + if (isa(get_child(parent), ca.ArrayRef, ca.BinaryOp)) { + if (get_child(parent) instanceof ca.ArrayRef) { + apply_child(parent, to_binop); + apply_child(parent, deref); + parent = get_child(parent); + changed = true; + } + if (random_bool(random, 0.5)) { + if (parent instanceof ca.UnaryOp && parent.op === "*") { + apply_child(parent, to_array); + apply_child(parent, addr); + changed = true; + } + } + } + if (random_bool(random, 0.5)) { + struct_ref.name = addr(struct_ref.name); + struct_ref.type = "->"; + changed = true; + } + ensure(changed); +} + +/** + * Split assignments of the form `a = b . c . d ...;` into + * `a = b; a = a . c . d ...;` or `a = c . d ...; a = b . a;` or similar. + */ +function perm_split_assignment(fn, ast, indices, region, random) { + const cands = []; + const visit = (node) => { + if (node instanceof ca.Assignment) { + if (node.op === "=" && node.rvalue instanceof ca.BinaryOp && region.contains_node(node)) cands.push(node); + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const assign = random.choice(cands); + const v = assign.lvalue; + const ins_cands = get_insertion_points(fn, region); + let ins_block, ins_index, found = false; + for (const [b, idx, , node] of ins_cands) { + ins_block = b; ins_index = idx; + if (node === assign) { found = true; break; } + } + if (!found) throw new RandomizationFailure(); + const binops = []; + const collect_binops = (node) => { + if (node.left instanceof ca.BinaryOp) collect_binops(node.left); + binops.push(node); + if (node.right instanceof ca.BinaryOp) collect_binops(node.right); + }; + collect_binops(assign.rvalue); + const split = random.choice(binops); + const typemap = build_typemap(ast, fn); + const vartype = decayed_expr_type(v, typemap); + let side; + if (random_bool(random, 0.5)) { + side = split.left; + const sidetype = decayed_expr_type(side, typemap); + ensure(same_type(vartype, sidetype, typemap, true)); + split.left = deepcopy(v); + } else { + side = split.right; + const sidetype = decayed_expr_type(side, typemap); + ensure(same_type(vartype, sidetype, typemap, true)); + split.right = deepcopy(v); + } + const new_assign = new ca.Assignment("=", deepcopy(v), side); + ast_util.insert_statement(ins_block, ins_index, new_assign); +} + +/** Delete parts of the function that might be unnecessary (mistakes or unnecessary changes from an improved base.c). */ +function perm_remove_ast(fn, ast, indices, region, random) { + const cands = []; + const visit = (node) => { + if (node instanceof ca.Cast) { + if (region.contains_node(node)) cands.push([node, node.expr]); + } else if (node instanceof ca.BinaryOp) { + if (region.contains_node(node) && node.op === "&") { + if (node.left instanceof ca.Constant) cands.push([node, node.right]); + if (node.right instanceof ca.Constant) cands.push([node, node.left]); + } + } else if (node instanceof ca.If) { + if (!node.iffalse && region.contains_node(node)) cands.push([node, node.iftrue]); + } else if (node instanceof ca.While || node instanceof ca.DoWhile) { + if (region.contains_node(node)) cands.push([node, node.stmt]); + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const [cand, expr] = random.choice(cands); + replace_node(fn.body, cand, expr); +} + +/** Duplicate an assignment, sometimes forcing IDO to reuse a register. */ +function perm_duplicate_assignment(fn, ast, indices, region, random) { + const cands = []; + const visit = (node) => { + if (node instanceof ca.Assignment) { + if (region.contains_node(node) && node.op === "=") cands.push(node); + } + for (const c of node) visit(c); + }; + visit(fn.body); + ensure(cands); + const cand = random.choice(cands); + const ins_cands = get_insertion_points(fn, Region.unbounded()); + ensure(ins_cands); + const dup = deepcopy(cand); + const [tob, toi] = random.choice(ins_cands); + ast_util.insert_statement(tob, toi, dup); +} + +/** Combine two assignments into one chain assignment. */ +function perm_chain_assignment(fn, ast, indices, region, random) { + const cands = []; + const rec = (block) => { + const statements = ast_util.get_block_stmts(block, false); + statements.forEach((stmt, i) => { + if (!(stmt instanceof ca.Assignment) || !region.contains_node(stmt)) return; + statements.slice(i + 1, i + 5).forEach((next_stmt, k) => { + const j = i + 1 + k; + if (region.contains_node(next_stmt) && next_stmt instanceof ca.Assignment + && (ast_util.equal_ast(stmt.lvalue, next_stmt.rvalue) || ast_util.equal_ast(stmt.rvalue, next_stmt.rvalue)) + && !ast_util.is_effectful(next_stmt.rvalue)) cands.push([i, j, block]); + }); + }); + for (const stmt of statements) ast_util.for_nested_blocks(stmt, rec); + }; + rec(fn.body); + ensure(cands); + const [chosen_assignment_idx, next_stmt_idx, block] = random.choice(cands); + const statements = ast_util.get_block_stmts(block, true); + const stmt = statements[chosen_assignment_idx]; + const next_stmt = statements[next_stmt_idx]; + assert(stmt instanceof ca.Assignment); + assert(next_stmt instanceof ca.Assignment); + let new_lvalue, new_rvalue; + if (random_bool(random, 0.5)) { + new_lvalue = next_stmt.lvalue; + new_rvalue = stmt; + } else { + new_lvalue = stmt.lvalue; + new_rvalue = new ca.Assignment("=", next_stmt.lvalue, stmt.rvalue); + } + statements[chosen_assignment_idx] = new ca.Assignment("=", new_lvalue, new_rvalue); + statements.splice(next_stmt_idx, 1); +} + +/** Create a long chain assignment out of 3 or more consecutive assignments with equal rvalue */ +function perm_long_chain_assignment(fn, ast, indices, region, random) { + const cands = []; + const rec = (block) => { + const statements = ast_util.get_block_stmts(block, false); + let i = 0; + while (statements.length > i) { + let j = i + 1; + const stmt = statements[i]; + if (stmt instanceof ca.Assignment && region.contains_node(stmt) && !ast_util.is_effectful(stmt.rvalue)) { + while (statements.length > j) { + const additional_stmt = statements[j]; + if (additional_stmt instanceof ca.Assignment && ast_util.equal_ast(stmt.rvalue, additional_stmt.rvalue) + && region.contains_node(additional_stmt)) j += 1; + else break; + } + if (j > i + 2) cands.push([i, j, block]); + } + i = j; + } + for (const s of statements) ast_util.for_nested_blocks(s, rec); + }; + rec(fn.body); + ensure(cands); + let [start_idx, end_idx, block] = random.choice(cands); + const a = random.randint(start_idx, end_idx); + const b = random.randint(start_idx, end_idx); + if (a + 3 <= b) { start_idx = a; end_idx = b; } + const statements = ast_util.get_block_stmts(block, true); + const stmt = statements[start_idx]; + assert(stmt instanceof ca.Assignment); + for (let i = start_idx + 1; i < end_idx; i++) { + const additional_stmt = statements[i]; + assert(additional_stmt instanceof ca.Assignment); + const new_lvalue = additional_stmt.lvalue; + stmt.rvalue = deepcopy(stmt); + stmt.lvalue = new_lvalue; + } + statements.splice(start_idx + 1, end_idx - (start_idx + 1)); +} + +/** Inserts an unused variable to adjust stack offsets. Probably only useful with --stack-diffs enabled. */ +function perm_pad_var_decl(fn, ast, indices, region, random) { + const vars = []; + const visit = (node) => { + if (node instanceof ca.Decl && truthy(node.name)) vars.push(node.name); + for (const c of node) visit(c); + }; + visit(fn.body); + let varName = "pad"; + let counter = 1; + while (vars.includes(varName)) { + counter += 1; + varName = `pad${counter}`; + } + const type = random_type(random); + ast_util.insert_decl(fn, varName, type, random); +} + +function cut_ast(expr, cut_prob, typemap, random) { + const cut_types = new Map(); + const callback = (node, is_expr, prob = cut_prob) => { + let cut; + if (node instanceof ca.ID && is_local_var(node.name, typemap)) { + ensure(is_expr); + cut = true; + } else { + cut = is_expr && random_bool(random, prob); + } + if (cut) { + const tp = decayed_expr_type(node, typemap); + const new_expr = new ca.ID(""); + cut_types.set(new_expr, tp); + return new_expr; + } + return null; + }; + expr = deepcopy(expr); + const toplevel_expr = callback(expr, true, 0.05); + if (toplevel_expr) return [toplevel_expr, cut_types]; + visit_replace(expr, (node, is_expr) => callback(node, is_expr)); + return [expr, cut_types]; +} + +function match_cut(node, cut_node, cut_types, out_exprs, typemap) { + const cmp = (n, cn) => { + if (!(cn instanceof ca.ID)) return null; + const cut_tp = cut_types.get(cn); + if (cut_tp == null) return null; + const expr = ast_util.as_expr(n); + if (expr == null) return null; + const tp = decayed_expr_type(expr, typemap); + if (!same_type(tp, cut_types.get(cn), typemap, true)) return false; + out_exprs.push(expr); + return true; + }; + return ast_util.equal_ast(node, cut_node, cmp); +} + +/** Creates an inline function for a random expression, possibly occurring in multiple places. */ +function perm_inline(fn, ast, indices, region, random) { + const typemap = build_typemap(ast, fn); + const cands = []; + for (const cand of get_block_expressions(fn.body, region)) { + let prob; + if (cand instanceof ca.ID) prob = 0.05; + else if (cand instanceof ca.Constant) prob = 0.01; + else prob = 1.0; + cands.push([cand, prob]); + } + ensure(cands); + const chosen_cand = random_weighted(random, cands); + const ret_type = decayed_expr_type(chosen_cand, typemap); + const new_fn_name = get_noncolliding_name(ast, "inline_fn"); + const cut_prob = random.uniform(0, 1) * random.uniform(0, 1); + const [cut_expr, cut_types] = cut_ast(chosen_cand, cut_prob, typemap, random); + if (!cut_types.size && random_bool(random, 0.5)) throw new RandomizationFailure(); + let cands2 = []; + if (cut_types.has(cut_expr)) cands2 = [chosen_cand]; + else { + for (const [cand2] of cands) if (match_cut(cand2, cut_expr, cut_types, [], typemap)) cands2.push(cand2); + } + assert(cands2.includes(chosen_cand)); + const subset = pick_random_subset(random, cands2, cands2.indexOf(chosen_cand)); + for (const expr of subset) { + const args = []; + if (!match_cut(expr, cut_expr, cut_types, args, typemap)) continue; + const fn_call = new ca.FuncCall(new ca.ID(new_fn_name), new ca.ExprList(args.slice())); + replace_node(fn.body, expr, fn_call); + } + const params = []; + let i = 0; + for (const [cut, tp] of cut_types) { + cut.name = `arg${i}`; + params.push(ast_util.make_decl(cut.name, tp)); + i++; + } + const return_expr = cut_expr; + const fn_def = new ca.FuncDef({ + decl: ast_util.make_decl(new_fn_name, new ca.FuncDecl({ args: new ca.ParamList(params.slice()), type: deepcopy(ret_type) }), + { funcspec: ["inline"] }), + param_decls: [], + body: new ca.Compound({ block_items: [new ca.Return(return_expr)] }), + }); + ast.ext.splice(ast.ext.indexOf(fn), 0, fn_def); +} + +/** + * Wrap a random range of statements within `if (variable) { ... }` or + * `if (struct.member)` and duplicate them in the else block. This can force + * the compiler to emit a useless move. Control flow can have remote effects, + * so this mostly ignores the region restriction. + */ +function perm_var_cond_block(fn, ast, indices, region, random) { + const cands = []; + const rec = (block) => { + cands.push(block); + for (const stmt of ast_util.get_block_stmts(block, false)) ast_util.for_nested_blocks(stmt, rec); + }; + rec(fn.body); + const block = random.choice(cands); + const stmts = ast_util.get_block_stmts(block, true); + let streaks = []; + let streak_start = 0; + stmts.forEach((stmt, i) => { + if (isa(stmt, ca.If, ca.For, ca.While, ca.DoWhile, ca.Switch, ca.Label, ca.Case, ca.Default, ca.Compound, + ca.Decl, ca.Typedef, ca.Pragma)) { + streaks.push([streak_start, i]); + streak_start = i + 1; + } + }); + streaks.push([streak_start, stmts.length]); + streaks = streaks.filter(([i, j]) => i !== j); + ensure(streaks); + const [lo, hi] = random.choice(streaks); + const new_block = new ca.Compound({ block_items: stmts.slice(lo, hi) }); + let cand_exprs = get_block_expressions(fn.body, region).filter((expr) => isa(expr, ca.StructRef, ca.ID)); + ensure(cand_exprs); + const expr = random.choice(cand_exprs); + ensure(!ast_util.is_effectful(expr)); + const typemap = build_typemap(ast, fn); + const make_cond = (e) => { + const type = resolve_typedefs(decayed_expr_type(e, typemap), typemap); + if (type instanceof ca.TypeDecl && isa(type.type, ca.Struct, ca.Union)) e = new ca.UnaryOp("&", e); + return deepcopy(e); + }; + let cond = make_cond(expr); + if (random_bool(random, PROB_VAR_COND_BLOCK_OR)) { + cand_exprs = cand_exprs.filter((e) => !ast_util.equal_ast(e, expr)); + ensure(cand_exprs); + const expr2 = random.choice(cand_exprs); + if (!ast_util.is_effectful(expr2)) cond = new ca.BinaryOp("||", cond, make_cond(expr2)); + } + stmts.splice(lo, hi - lo, new ca.If({ cond, iftrue: new_block, iffalse: deepcopy(new_block) })); +} + +/** Replace two same-type variables by an array. */ +function perm_alias_array(fn, ast, indices, region, random) { + const mentioned_names = new Set(get_mentioned_names(fn, region)); + const typemap = build_typemap(ast, fn); + const cands_by_type = []; + const all_names = new Set(); + const stmts = ast_util.get_block_stmts(fn.body, false); + stmts.forEach((decl, i) => { + if (!(decl instanceof ca.Decl) || !truthy(decl.name)) return; + all_names.add(decl.name); + if (decl.init || !mentioned_names.has(decl.name)) return; + const tp = get_decl_type(decl); + const real_type = resolve_typedefs(tp, typemap); + if (real_type instanceof ca.ArrayDecl) return; + let arr = null; + for (const [t, a] of cands_by_type) { + if (same_type(t, tp, typemap, true)) { arr = a; break; } + } + if (arr == null) { + arr = []; + cands_by_type.push([tp, arr]); + } + arr.push([i, decl]); + }); + const cands = cands_by_type.filter(([, decls]) => decls.length >= 2); + ensure(cands); + const [tp, decls] = random.choice(cands); + const [[i1, decl1], [i2, decl2]] = random.sample(decls, 2); + assert(truthy(decl1.name)); + assert(truthy(decl2.name)); + const array_ind = new Map([[decl1.name, 0], [decl2.name, 1]]); + let varName = "new_var"; + let counter = 1; + while (all_names.has(varName)) { + counter += 1; + varName = `new_var${counter}`; + } + const arr_tp = new ca.ArrayDecl(tp, new ca.Constant("int", "2"), []); + stmts[Math.min(i1, i2)] = ast_util.make_decl(varName, arr_tp); + stmts.splice(Math.max(i1, i2), 1); + const callback = (node) => { + if (!(node instanceof ca.ID) || !array_ind.has(node.name)) return null; + return new ca.ArrayRef(new ca.ID(varName), new ca.Constant("int", String(array_ind.get(node.name)))); + }; + visit_replace(fn.body, callback); +} + +export const RANDOMIZATION_PASSES = [ + perm_temp_for_expr, + perm_expand_expr, + perm_reorder_stmts, + perm_reorder_decls, + perm_add_mask, + perm_xor_zero, + perm_cast_simple, + perm_refer_to_var, + perm_float_literal, + perm_randomize_internal_type, + perm_randomize_external_type, + perm_randomize_function_type, + perm_split_assignment, + perm_sameline, + perm_ins_block, + perm_struct_ref, + perm_empty_stmt, + perm_condition, + perm_mult_zero, + perm_factor_mult, + perm_factor_shift, + perm_dummy_comma_expr, + perm_add_self_assignment, + perm_commutative, + perm_add_sub, + perm_inequalities, + perm_compound_assignment, + perm_remove_ast, + perm_duplicate_assignment, + perm_chain_assignment, + perm_long_chain_assignment, + perm_pad_var_decl, + perm_inline, + perm_var_cond_block, + perm_alias_array, +]; + +/** One-line docs per pass (upstream's docstrings, for --help=randomization-passes). */ +export const PASS_DOCS = { + perm_temp_for_expr: "Create a temporary variable for a random expression. The variable will be assigned at another random point (nearer the expression being more likely), possibly reuse an existing variable, possibly be of a different size/signedness, and possibly be used for other identical expressions as well. Only expressions within the given region may be chosen for replacement, but the assignment and the affected identical expressions may be outside of it.", + perm_expand_expr: "Replace a random variable by its contents.", + perm_reorder_stmts: "Move a statement to another random place.", + perm_reorder_decls: "Move a declaration to another random place.", + perm_add_mask: "Add a random amount of masks of 0xFF[FFFFFFFFFFFFFF] to a random expression of integer type. For IDO these masks may get optimized out while still affecting regalloc. The regalloc change seems to cycle with slight differences every n masks.", + perm_xor_zero: "Add ^0 to a random expression of integer type, or *1 to floats.", + perm_cast_simple: "Cast a random expression to a simple type (integral or floating point only).", + perm_refer_to_var: "Add `if (variable) {}` or `if (struct.member) {}` in a random place. This will get optimized away but may affect regalloc.", + perm_float_literal: "Converts a Float Literal", + perm_randomize_internal_type: "Randomize types of pre-existing local variables. Function parameters are not included -- those are handled by perm_randomize_function_type. Only variables mentioned within the given region are affected.", + perm_randomize_external_type: "Randomize types of global variables. Only variables mentioned within the given region are affected.", + perm_randomize_function_type: "Randomize types of function parameters and returns. Only functions called within the given region are affected, plus the current function.", + perm_split_assignment: "Split assignments of the form `a = b . c . d ...;` into `a = b; a = a . c . d ...;` or `a = c . d ...; a = b . a;` or similar.", + perm_sameline: "Put all statements within a random interval on the same line.", + perm_ins_block: "Wrap a random range of statements within `if (1) { ... }` or `do { ... } while(0)`. Control flow can have remote effects, so this mostly ignores the region restriction.", + perm_struct_ref: "Permute struct references: (a + b)->c, and (*(a + b)).c, a[b].c, (&a[b])->c", + perm_empty_stmt: "Inserts a no-op statement, one of: if (1) {} (sometimes multiple of them); if (0) {}; do {} while (0); label:; goto label; label:;; ;. Control flow can have remote effects, so this ignores the region restriction.", + perm_condition: "Change if(x) into if(x != 0), or vice versa. Also handles for/while/do-while.", + perm_mult_zero: "Convert 0 to x*0 for some randomly chosen x.", + perm_factor_mult: "Convert a * b to a * x * (b / x).", + perm_factor_shift: "Convert a >> b to a >> x >> (b - x), or similar with <<.", + perm_dummy_comma_expr: "Change x into (0, x) for a random expression x.", + perm_add_self_assignment: "Introduce a \"x = x;\", \"x += 0;\" or \"x++; x--;\" somewhere.", + perm_commutative: "Change a+b into b+a, or similar for other commutative operations.", + perm_add_sub: "Change a-b into a+(-b), or a+b into a-(-b).", + perm_inequalities: "Adjusts inequalities to equivalent versions that sometimes produce different code. For example, a > b and a >= b + 1, a < b to a <= b - 1 (and vice versa)", + perm_compound_assignment: "Convert a statement of the form `x = x op y` to `x op= y`, or vice versa.", + perm_remove_ast: "Delete parts of the function that might be unnecessary (mistakes or unnecessary changes from an improved base.c).", + perm_duplicate_assignment: "Duplicate an assignment, sometimes forcing IDO to reuse a register.", + perm_chain_assignment: "Combine two assignments into one chain assignment.", + perm_long_chain_assignment: "Create a long chain assignment out of 3 or more consecutive assignments with equal rvalue", + perm_pad_var_decl: "Inserts an unused variable to adjust stack offsets. Probably only useful with --stack-diffs enabled.", + perm_inline: "Creates an inline function for a random expression, possibly occurring in multiple places.", + perm_var_cond_block: "Wrap a random range of statements within `if (variable) { ... }` or `if (struct.member)` and duplicate them in the else block. This can force the compiler to emit a useless move. Control flow can have remote effects, so this mostly ignores the region restriction.", + perm_alias_array: "Replace two same-type variables by an array.", +}; + +export class Randomizer { + /** + * @param {Record|Map} randomization_weights + * @param {number|bigint} rng_seed + */ + constructor(randomization_weights, rng_seed) { + this.random = new PyRandom(rng_seed); + const w = randomization_weights instanceof Map ? randomization_weights : new Map(Object.entries(randomization_weights)); + for (const method of RANDOMIZATION_PASSES) { + if (!w.has(method.name)) throw new Error(`Error: missing value for ${method.name} in default_weights.toml`); + } + this.methods = RANDOMIZATION_PASSES.map((method) => [method, w.get(method.name)]); + } + + randomize(ast, fn_name) { + const fn = ast_util.extract_fn(ast, fn_name)[0]; + const indices = ast_util.compute_node_indices(fn); + const region = get_randomization_region(fn, indices, this.random); + for (;;) { + const method = random_weighted(this.random, this.methods); + try { + method(fn, ast, indices, region, this.random); + this.lastPass = method.name; + break; + } catch (e) { + if (!(e instanceof RandomizationFailure)) throw e; + } + } + } +} + +// Internals exported for the per-pass tests. +export const _internal = { + Region, get_randomization_region, visit_replace, replace_subexprs, get_insertion_points, get_block_expressions, random_weighted, + compute_write_locations, compute_read_locations, find_var_reads, isAssertion, Node, +}; diff --git a/packages/romdev-permuter/src/scorer.js b/packages/romdev-permuter/src/scorer.js new file mode 100644 index 00000000..111be747 --- /dev/null +++ b/packages/romdev-permuter/src/scorer.js @@ -0,0 +1,263 @@ +// scorer.js - a port of decomp-permuter's src/scorer.py. Scores a candidate +// object against the target by diffing simplified objdump output: difflib +// opcodes over mnemonics, then per-field penalties on "equal" lines and +// reorder/insert/delete penalties for the rest. +import { createHash } from "node:crypto"; +import { SequenceMatcher } from "./difflib.js"; +import { opcodes as levenshteinOpcodes } from "./levenshtein.js"; +import { get_arch, objdump, pySplitWs1 } from "./objdump.js"; + +export const PENALTY_INF = 10 ** 9; +export const PENALTY_STACKDIFF = 1; +export const PENALTY_BRANCHDIFF = 1; +export const PENALTY_REGALLOC = 5; +export const PENALTY_REORDERING = 60; +export const PENALTY_INSERTION = 100; +export const PENALTY_DELETION = 100; + +/** shlex.split for the objdump_command setting (POSIX mode quoting). */ +export function shlexSplit(s) { + const out = []; + let cur = null; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (c === "'") { + cur ??= ""; + const e = s.indexOf("'", i + 1); + if (e < 0) throw new Error("No closing quotation"); + cur += s.slice(i + 1, e); + i = e; + } else if (c === "\"") { + cur ??= ""; + i++; + while (i < s.length && s[i] !== "\"") { + if (s[i] === "\\" && i + 1 < s.length && "\\\"$`\n".includes(s[i + 1])) { cur += s[i + 1]; i += 2; continue; } + cur += s[i++]; + } + if (i >= s.length) throw new Error("No closing quotation"); + } else if (c === "\\") { + cur ??= ""; + if (i + 1 < s.length) { if (s[i + 1] !== "\n") cur += s[i + 1]; i++; } + } else if (/\s/.test(c)) { + if (cur != null) { out.push(cur); cur = null; } + } else { + cur = (cur ?? "") + c; + } + } + if (cur != null) out.push(cur); + return out; +} + +/** int(s, 0) for the stack-offset field (decimal without leading zeros, or 0x/0o/0b). */ +function pyInt0(s) { + const m = /^\s*([+-]?)(0[xX][0-9a-fA-F]+|0[oO][0-7]+|0[bB][01]+|[1-9][0-9]*|0+)\s*$/.exec(s.replaceAll("_", "")); + if (!m) throw new Error(`invalid literal for int() with base 0: '${s}'`); + const body = m[2]; + let v; + if (/^0[xX]/.test(body)) v = parseInt(body.slice(2), 16); + else if (/^0[oO]/.test(body)) v = parseInt(body.slice(2), 8); + else if (/^0[bB]/.test(body)) v = parseInt(body.slice(2), 2); + else v = parseInt(body, 10); + return m[1] === "-" ? -v : v; +} + +function fieldMatchesAnySymbol(field, arch) { + if (arch.name === "ppc") { + if (field.includes("...")) return true; + const k = field.lastIndexOf("@"); + if (k >= 0 && ["l", "h", "ha", "sda21"].includes(field.slice(k + 1))) field = field.slice(0, k); + return /^@\d+$/.test(field); + } + if (arch.name === "mips") return field.includes("."); + if (arch.name === "arm32") return field.includes("."); + return false; +} + +const RE_PAREN = /(? line.mnemonic)); + return s; + } + + async _objdump(o_file) { + const objdump_command = this.objdump_command ? shlexSplit(this.objdump_command) : null; + const lines = await objdump(o_file, this.arch, { + objdump_command, stack_differences: this.stack_differences, ign_branch_targets: this.ign_branch_targets, + }); + return [lines.map((line) => line.row).join("\n"), lines]; + } + + /** + * @param {string|Uint8Array|null} cand_o object path/bytes, or null for a failed compile + * @returns {Promise<[number, string]>} [score, sha256 of the simplified disassembly] + */ + async score(cand_o) { + if (!cand_o) return [PENALTY_INF, ""]; + const [objdump_output, cand_seq] = await this._objdump(cand_o); + return this.scoreLines(objdump_output, cand_seq); + } + + /** The scoring proper, on an already simplified candidate disassembly. */ + scoreLines(objdump_output, cand_seq) { + let num_stack_penalties = 0; + let num_branch_penalties = 0; + let num_regalloc_penalties = 0; + let num_reordering_penalties = 0; + let num_insertion_penalties = 0; + let num_deletion_penalties = 0; + const deletions = []; + const insertions = []; + const arch = this.arch; + + const diff_sameline = (old_line, new_line) => { + const old_stack = num_stack_penalties, old_branch = num_branch_penalties, old_regalloc = num_regalloc_penalties; + const old = old_line.row, neu = new_line.row; + if (old === neu) return false; + let ignore_last_field = false; + if (this.stack_differences) { + const oldsp = this.re_sprel_search.exec(old); + const newsp = this.re_sprel_search.exec(neu); + if (oldsp && newsp) { + const oldrel = pyInt0(oldsp[1] || "0"); + const newrel = pyInt0(newsp[1] || "0"); + num_stack_penalties += Math.abs(oldrel - newrel); + ignore_last_field = true; + } + } + if (!this.ign_branch_targets) { + const b_instr = arch.branch_instructions, bl_instr = arch.branch_likely_instructions; + if (old_line.mnemonic === new_line.mnemonic + && (b_instr.has(old_line.mnemonic) || bl_instr.has(old_line.mnemonic)) + && old_line.row !== new_line.row && !old_line.has_symbol && !new_line.has_symbol) { + const old_target = old_line.row.split(",").at(-1); + const new_target = new_line.row.split(",").at(-1); + if (old_target !== new_target) { + num_branch_penalties += 1; + ignore_last_field = true; + } + } + } + const new_parts = pySplitWs1(neu), old_parts = pySplitWs1(old); + let newfields = new_parts.length > 1 ? new_parts[1].split(",") : []; + let oldfields = old_parts.length > 1 ? old_parts[1].split(",") : []; + if (ignore_last_field) { + newfields = newfields.slice(0, -1); + oldfields = oldfields.slice(0, -1); + } else { + oldfields = oldfields.slice(0, -1).concat(oldfields.length > 0 ? oldfields.at(-1).split(RE_PAREN) : []); + newfields = newfields.slice(0, -1).concat(newfields.length > 0 ? newfields.at(-1).split(RE_PAREN) : []); + } + const n = Math.min(newfields.length, oldfields.length); + for (let k = 0; k < n; k++) { + const nf = newfields[k], of = oldfields[k]; + if (nf !== of) { + if (fieldMatchesAnySymbol(nf, arch) && old_line.has_symbol) continue; + num_regalloc_penalties += 1; + } + } + num_regalloc_penalties += Math.abs(newfields.length - oldfields.length); + return old_regalloc !== num_regalloc_penalties || old_stack !== num_stack_penalties || old_branch !== num_branch_penalties; + }; + + let result_diff; + if (this.algorithm === "levenshtein") { + // Upstream remaps mnemonics to characters (a fresh map per score) and + // diffs the two strings with Levenshtein.opcodes(cand, target). + const remapping = new Map(); + const remap = (seq) => seq.map((m) => { + if (!remapping.has(m)) remapping.set(m, remapping.size); + return remapping.get(m); + }); + result_diff = levenshteinOpcodes(remap(cand_seq.map((l) => l.mnemonic)), remap(this.target_seq.map((l) => l.mnemonic))); + } else { + this.difflib_differ.set_seq1(cand_seq.map((line) => line.mnemonic)); + result_diff = this.difflib_differ.get_opcodes(); + } + const equal_no_diff = new Set(); + for (const [tag, i1, i2, j1, j2] of result_diff) { + if (tag === "equal") { + for (let k = 0; k < i2 - i1; k++) { + if (!diff_sameline(this.target_seq[j1 + k], cand_seq[i1 + k])) equal_no_diff.add(i1 + k); + } + } + if (tag === "replace" || tag === "delete") for (let k = i1; k < i2; k++) insertions.push(cand_seq[k].row); + if (tag === "replace" || tag === "insert") for (let k = j1; k < j2; k++) deletions.push(this.target_seq[k].row); + } + + if (this.debug_mode) this.debugLog.push(this._formatDebugDiff(result_diff, cand_seq, equal_no_diff)); + + // Counter(insertions) + Counter(deletions), iterated in first-seen order. + const ins = new Map(), dels = new Map(), keys = new Map(); + for (const x of insertions) { ins.set(x, (ins.get(x) ?? 0) + 1); keys.set(x, true); } + for (const x of deletions) { dels.set(x, (dels.get(x) ?? 0) + 1); keys.set(x, true); } + for (const item of keys.keys()) { + const i = ins.get(item) ?? 0, d = dels.get(item) ?? 0; + const common = Math.min(i, d); + num_insertion_penalties += i - common; + num_deletion_penalties += d - common; + num_reordering_penalties += common; + } + + const final_score = num_stack_penalties * PENALTY_STACKDIFF + + num_branch_penalties * PENALTY_BRANCHDIFF + + num_regalloc_penalties * PENALTY_REGALLOC + + num_reordering_penalties * PENALTY_REORDERING + + num_insertion_penalties * PENALTY_INSERTION + + num_deletion_penalties * PENALTY_DELETION; + this.lastPenalties = { + stack: num_stack_penalties, branch: num_branch_penalties, regalloc: num_regalloc_penalties, + reordering: num_reordering_penalties, insertion: num_insertion_penalties, deletion: num_deletion_penalties, + }; + return [final_score, createHash("sha256").update(objdump_output, "utf8").digest("hex")]; + } + + _formatDebugDiff(result_diff, cand_seq, equal_no_diff) { + const mnemMax = Math.max(0, ...this.target_seq.map((l) => l.mnemonic.length), ...cand_seq.map((l) => l.mnemonic.length)); + const fmt = (line, maxLen) => { + const k = line.indexOf("\t"); + if (k < 0) return line; + let s = line.slice(0, k).padEnd(mnemMax) + " " + line.slice(k + 1); + if (maxLen) s = s.slice(0, maxLen); + return s; + }; + const out = []; + for (const [tag, i1, i2, j1, j2] of result_diff) { + if (tag === "equal") { + for (let k = 0; k < i2 - i1; k++) { + const same = equal_no_diff.has(i1 + k); + out.push(`${same ? "\u001b[0m" : "\u001b[94m"}${fmt(this.target_seq[j1 + k].row, 40).padEnd(40)}\t${fmt(cand_seq[i1 + k].row)}`); + } + } + if (tag === "replace" || tag === "delete") for (let k = i1; k < i2; k++) out.push(`\u001b[32;1m${"".padEnd(40)}\t${fmt(cand_seq[k].row)}`); + if (tag === "replace" || tag === "insert") for (let k = j1; k < j2; k++) out.push(`\u001b[91;1m${fmt(this.target_seq[k].row)}\t`); + } + out.push("\u001b[0m"); + return out.join("\n"); + } +} diff --git a/packages/romdev-permuter/src/wasm-tool.js b/packages/romdev-permuter/src/wasm-tool.js new file mode 100644 index 00000000..86d24e1d --- /dev/null +++ b/packages/romdev-permuter/src/wasm-tool.js @@ -0,0 +1,144 @@ +// wasm-tool.js - run an emscripten-built command-line tool (binutils objdump) +// in-process, once per call, with its WebAssembly.Module compiled only once. +// +// The permuter disassembles every candidate object, so paying the WASM compile +// per call would dominate a search. Each call still gets a fresh instance +// (emscripten tools are single-shot: callMain once, then the module is spent). +import { readFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; + +/** @type {Map>} */ +const cache = new Map(); + +async function load(gluePath) { + let p = cache.get(gluePath); + if (!p) { + p = (async () => { + const bytes = readFileSync(gluePath.replace(/\.m?js$/, ".wasm")); + const module = await WebAssembly.compile(bytes); + const factory = (await import(pathToFileURL(gluePath).href)).default; + return { factory, module }; + })(); + cache.set(gluePath, p); + } + return p; +} + +/** + * Run a tool. + * @param {string} gluePath emscripten ESM glue (.mjs; the .wasm sits beside it) + * @param {string[]} argv arguments (no argv[0]) + * @param {Record} files MEMFS files to create first + * @param {string[]} [outputs] MEMFS paths to read back after the run + * @returns {Promise<{exitCode: number, stdout: string, stderr: string, outputs: Record}>} + */ +export async function runWasmTool(gluePath, argv, files = {}, outputs = []) { + const { factory, module } = await load(gluePath); + const out = [], err = []; + let exitCode = null; + const mod = await factory({ + noInitialRun: true, + print: (s) => out.push(s), + printErr: (s) => err.push(s), + instantiateWasm(imports, receive) { + WebAssembly.instantiate(module, imports).then((inst) => receive(inst, module)); + return {}; + }, + quit: (status, toThrow) => { exitCode = status; throw toThrow ?? new Error(`exit ${status}`); }, + onExit: (status) => { exitCode = status; }, + }); + for (const [p, data] of Object.entries(files)) { + const dir = p.slice(0, p.lastIndexOf("/")); + if (dir) { + let cur = ""; + for (const part of dir.split("/").filter(Boolean)) { + cur += "/" + part; + try { mod.FS.mkdir(cur); } catch { /* exists */ } + } + } + mod.FS.writeFile(p, data); + } + try { + const r = mod.callMain(argv); + if (exitCode == null) exitCode = typeof r === "number" ? r : 0; + } catch (e) { + if (e && typeof e === "object" && "status" in e) exitCode = e.status; + else if (exitCode == null) { err.push(String(e?.message ?? e)); exitCode = 1; } + } + const read = {}; + for (const p of outputs) { + try { read[p] = mod.FS.readFile(p); } catch { read[p] = null; } + } + return { exitCode: exitCode ?? 0, stdout: out.join("\n") + (out.length ? "\n" : ""), stderr: err.join("\n"), outputs: read }; +} + +// -- NODERAWFS tools --------------------------------------------------------- +// romdev's mips-linux-gnu binutils are NODERAWFS builds (they read the real +// filesystem), the same modules romdev's compile/compare path runs. Their +// glue initialises synchronously when handed a precompiled module; stdio is +// rebound to in-memory streams so output is captured rather than written to +// this process's fds. + +/** @type {Map} */ +const rawCache = new Map(); + +async function loadRaw(gluePath) { + let e = rawCache.get(gluePath); + if (!e) { + const bytes = readFileSync(gluePath.replace(/\.m?js$/, ".wasm")); + const module = new WebAssembly.Module(bytes); + const factory = (await import(pathToFileURL(gluePath).href)).default; + e = { factory, module, bytes }; + rawCache.set(gluePath, e); + } + return e; +} + +const S_IFCHR = 0o020000; +function captureStream(FS, collect) { + return FS.createStream({ + path: "/dev/romdev-out", flags: 1, seekable: false, position: 0, + node: { mode: S_IFCHR | 0o666, id: 0 }, + stream_ops: { + write(_s, buffer, offset, length) { collect.push(Buffer.from(buffer.subarray(offset, offset + length))); return length; }, + read() { return 0; }, + llseek() { throw new FS.ErrnoError(29); }, + close() {}, + }, + }); +} +function bindStd(FS, fd, stream) { + FS.closeStream(stream.fd); + FS.closeStream(fd); + stream.fd = fd; + FS.streams[fd] = stream; +} + +/** + * Run a NODERAWFS tool (paths in argv are real host paths). + * @returns {Promise<{exitCode: number, stdout: string, stderr: string}>} + */ +export async function runRawFsTool(gluePath, argv, { argv0 = "tool" } = {}) { + const e = await loadRaw(gluePath); + const out = [], err = []; + const M = { + noInitialRun: true, thisProgram: argv0, wasmBinary: e.bytes, + print: () => {}, printErr: () => {}, + quit: (_status, toThrow) => { throw toThrow; }, + }; + const RealModule = WebAssembly.Module; + WebAssembly.Module = function (bytes) { return bytes === e.bytes ? e.module : new RealModule(bytes); }; + try { e.factory(M); } finally { WebAssembly.Module = RealModule; } + if (typeof M.callMain !== "function") throw new Error(`${gluePath}: module did not initialise synchronously`); + const FS = M.FS; + bindStd(FS, 1, captureStream(FS, out)); + bindStd(FS, 2, captureStream(FS, err)); + let code; + try { + code = M.callMain(argv); + } catch (x) { + if (x && typeof x === "object" && typeof x.status === "number") code = x.status; + else { err.push(Buffer.from(String(x?.message ?? x))); code = 134; } + } + return { exitCode: code ?? 0, stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8") }; +} diff --git a/packages/romdev-permuter/src/worker.js b/packages/romdev-permuter/src/worker.js new file mode 100644 index 00000000..fcff24df --- /dev/null +++ b/packages/romdev-permuter/src/worker.js @@ -0,0 +1,71 @@ +// worker.js - a candidate-evaluation worker thread (upstream's +// multiprocess_worker). It rebuilds the parent's permuters from plain config +// (reusing the parent's base score instead of recompiling the base), then +// loops: ask for a seed, evaluate it, send the result back. +import { parentPort, workerData } from "node:worker_threads"; +import { Compiler } from "./compiler.js"; +import { Permuter } from "./permuter.js"; +import { Scorer } from "./scorer.js"; +import { setObjdumpGlue } from "./objdump.js"; +import { loadCompileModule } from "./main.js"; + +const { configs, glue } = workerData; +for (const [arch, g] of Object.entries(glue)) setObjdumpGlue(arch, g); + +// Seeds arrive in batches; ask for more before the local queue runs dry. +const BATCH = 8; +let finishing = false; +let exhausted = false; +let requested = false; +const queue = []; +let wake = null; +parentPort.on("message", (msg) => { + if (msg.type === "finish") finishing = true; + else if (msg.type === "tasks") { queue.push(...msg.tasks); requested = false; if (msg.exhausted) exhausted = true; } + if (wake) { const p = wake; wake = null; p(); } +}); +function topUp() { + if (!requested && !finishing && !exhausted && queue.length < BATCH / 2) { + requested = true; + parentPort.postMessage({ type: "need", count: BATCH - queue.length }); + } +} +async function nextTask() { + for (;;) { + if (finishing) return null; + topUp(); + if (queue.length) return queue.shift(); + if (exhausted) return null; + await new Promise((resolve) => { wake = resolve; }); + } +} + +const silent = () => {}; + +async function main() { + const permuters = []; + for (const cfg of configs) { + const compileFn = cfg.compileModule ? await loadCompileModule(cfg.compileModule) : null; + const compiler = new Compiler(cfg.compile_cmd, { ...cfg.compilerOpts, compileFn, log: silent }); + const scorer = await Scorer.create(cfg.scorerOpts); + permuters.push(await Permuter.create({ ...cfg.permOpts, compiler, scorer, log: silent }, cfg.base)); + } + for (;;) { + const msg = await nextTask(); + if (!msg) break; + const permuter = permuters[msg.perm_index]; + const start = performance.now(); + const result = await permuter.try_eval_candidate(msg.seed); + if (!result.isEvalError && permuter.should_output(result)) permuter.record_result(result); + if (permuter.speed !== 100) { + const ms = (performance.now() - start) * (100 / permuter.speed - 1); + await new Promise((r) => setTimeout(r, ms)); + } + parentPort.postMessage({ type: "done", perm_index: msg.perm_index, result }); + } +} + +main().then(() => process.exit(0), (e) => { + parentPort.postMessage({ type: "fatal", error: String(e?.stack ?? e) }); + process.exit(1); +}); diff --git a/packages/romdev-permuter/test/corpus.test.js b/packages/romdev-permuter/test/corpus.test.js new file mode 100644 index 00000000..41e617d1 --- /dev/null +++ b/packages/romdev-permuter/test/corpus.test.js @@ -0,0 +1,95 @@ +// Oracle replay against upstream's own recorded outputs. A romdev decomp +// workspace keeps every search job the Python permuter ran: permuter.log +// ("base score = N"), and output-*/{source.c,score.txt,diff.txt}. Those files +// are upstream's answers, so this port must reproduce them: +// 1. the "before" side of each diff.txt (upstream's pretty-printed base +// source, with line numbers) equals this port's printed base, +// 2. the whole diff.txt is reproduced byte for byte from the candidate, +// 3. (in romdevtools: test/decomp-permuter-corpus.test.js) compiling each +// candidate through romdev's WASM toolchain and scoring it gives +// upstream's score.txt / logged base score. +// The corpus is local data (never committed); without one the test skips. +// ROMDEV_PERMUTER_CORPUS may name a jobs directory; otherwise every +// ~/.romdev/decomp//jobs is used. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { perm_parse } from "../src/perm/parse.js"; +import { perm_evaluate_one } from "../src/perm/eval.js"; +import { Candidate } from "../src/candidate.js"; +import { unified_diff } from "../src/difflib.js"; +import { trim_source, get_default_randomization_weights, get_settings } from "../src/helpers.js"; + +function jobDirs() { + const roots = process.env.ROMDEV_PERMUTER_CORPUS ? [process.env.ROMDEV_PERMUTER_CORPUS] + : (() => { + const base = path.join(os.homedir(), ".romdev", "decomp"); + if (!existsSync(base)) return []; + return readdirSync(base).map((p) => path.join(base, p, "jobs")).filter(existsSync); + })(); + const out = []; + for (const r of roots) { + for (const j of readdirSync(r)) { + const pd = path.join(r, j, "permuter"); + if (existsSync(path.join(pd, "base.c")) && existsSync(path.join(pd, "settings.toml"))) out.push({ job: path.join(r, j), pd }); + } + } + return out; +} + +const JOBS = jobDirs(); +const strip = (s) => s.replace(/^\s+|\s+$/g, ""); +const printed = new Map(); + +function baseSource(pd) { + if (printed.has(pd)) return printed.get(pd); + const settings = get_settings(pd); + const fn = settings.func_name; + const weights = get_default_randomization_weights(settings.compiler_type ?? "base"); + const [text, st] = perm_evaluate_one(perm_parse(readFileSync(path.join(pd, "base.c"), "utf8"), () => {})); + const v = { fn, source: Candidate.from_source(text, st, fn, weights, 0).get_source() }; + printed.set(pd, v); + return v; +} + +/** The candidate upstream scored: source.c is either whole or trimmed at the function (--no-context-output). */ +function reconstruct(base, fn, outputSource) { + if (outputSource.startsWith(base.slice(0, 300))) return outputSource; + const tail = trim_source(base, fn); + return base.slice(0, base.length - tail.length) + outputSource; +} + +const outputs = () => JOBS.flatMap(({ pd }) => readdirSync(pd).filter((d) => /^output-\d+-\d+$/.test(d)).map((o) => ({ pd, o }))); + +test("upstream's printed base source (diff.txt 'before' lines) is reproduced line for line", { skip: !JOBS.length && "no decomp corpus" }, () => { + let checked = 0; + for (const { pd, o } of outputs()) { + const lines = baseSource(pd).source.split("\n"); + let a = null; + for (const line of readFileSync(path.join(pd, o, "diff.txt"), "utf8").split("\n")) { + const h = /^@@ -(\d+)(?:,(\d+))? \+/.exec(line); + if (h) { a = Number(h[1]) - (h[2] === "0" ? 0 : 1); continue; } + if (a == null || line.startsWith("---") || line.startsWith("+++")) continue; + if (line.startsWith(" ") || line.startsWith("-")) { + assert.equal(lines[a], line.slice(1), `${pd}/${o} line ${a + 1}`); + a++; + checked++; + } + } + } + assert.ok(checked > 0); +}); + +test("upstream's diff.txt is reproduced byte for byte", { skip: !JOBS.length && "no decomp corpus" }, () => { + let n = 0; + for (const { pd, o } of outputs()) { + const { fn, source } = baseSource(pd); + const cand = reconstruct(source, fn, readFileSync(path.join(pd, o, "source.c"), "utf8")); + const mine = unified_diff(source.split("\n"), cand.split("\n"), { fromfile: "before", tofile: "after", lineterm: "", key: strip }).join("\n") + "\n"; + assert.equal(mine, readFileSync(path.join(pd, o, "diff.txt"), "utf8"), `${pd}/${o}`); + n++; + } + assert.ok(n > 0); +}); diff --git a/packages/romdev-permuter/test/difflib.test.js b/packages/romdev-permuter/test/difflib.test.js new file mode 100644 index 00000000..0856921c --- /dev/null +++ b/packages/romdev-permuter/test/difflib.test.js @@ -0,0 +1,48 @@ +// The scorer's penalties come from difflib opcodes and the output diff.txt +// from unified_diff: these are CPython's documented examples. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { SequenceMatcher, unified_diff } from "../src/difflib.js"; + +test("get_opcodes: difflib docs example", () => { + const s = new SequenceMatcher({ autojunk: true }); + s.set_seqs([..."qabxcd"], [..."abycdf"]); + assert.deepEqual(s.get_opcodes(), [ + ["delete", 0, 1, 0, 0], ["equal", 1, 3, 0, 2], ["replace", 3, 4, 2, 3], ["equal", 4, 6, 3, 5], ["insert", 6, 6, 5, 6], + ]); +}); + +test("get_matching_blocks: difflib docs example", () => { + const s = new SequenceMatcher(); + s.set_seqs([..."abxcd"], [..."abcd"]); + assert.deepEqual(s.get_matching_blocks(), [[0, 0, 2], [3, 2, 2], [5, 4, 0]]); +}); + +test("find_longest_match: docs example (no junk)", () => { + const s = new SequenceMatcher(); + s.set_seqs([..." abcd"], [..."abcd abcd"]); + assert.deepEqual(s.find_longest_match(0, 5, 0, 9), [0, 4, 5]); +}); + +test("autojunk drops popular elements only for b with >= 200 items", () => { + const b = Array.from({ length: 200 }, (_, i) => (i % 2 ? "x" : `u${i}`)); + const s = new SequenceMatcher({ autojunk: true }); + s.set_seqs(["x"], b); + assert.ok(s.bpopular.has("x")); + const t = new SequenceMatcher({ autojunk: false }); + t.set_seqs(["x"], b); + assert.equal(t.bpopular.size, 0); + assert.deepEqual(t.get_matching_blocks()[0], [0, 1, 1]); +}); + +test("unified_diff: difflib docs example", () => { + const out = unified_diff("one two three four".split(" "), "zero one tree four".split(" "), + { fromfile: "Original", tofile: "Current", lineterm: "" }); + assert.deepEqual(out, ["--- Original", "+++ Current", "@@ -1,4 +1,4 @@", "+zero", " one", "-two", "-three", "+tree", " four"]); +}); + +test("unified_diff with a key compares stripped lines but prints the originals", () => { + const strip = (s) => s.trim(); + const out = unified_diff(["a", " b", "c"], ["a", "b ", "d"], { fromfile: "before", tofile: "after", lineterm: "", key: strip }); + assert.deepEqual(out, ["--- before", "+++ after", "@@ -1,3 +1,3 @@", " a", " b", "-c", "+d"]); +}); diff --git a/packages/romdev-permuter/test/fixtures/asm-processor-build-line.txt b/packages/romdev-permuter/test/fixtures/asm-processor-build-line.txt new file mode 100644 index 00000000..44305aac --- /dev/null +++ b/packages/romdev-permuter/test/fixtures/asm-processor-build-line.txt @@ -0,0 +1 @@ +python3 tools/asm-processor/build.py --input-enc utf-8 tools/cc -- mips-linux-gnu-as -march=vr4300 -- -c -O2 -MD -MF x.d -o build/a.o src/a.c diff --git a/packages/romdev-permuter/test/fixtures/passes.c b/packages/romdev-permuter/test/fixtures/passes.c new file mode 100644 index 00000000..7c1073b2 --- /dev/null +++ b/packages/romdev-permuter/test/fixtures/passes.c @@ -0,0 +1,72 @@ +typedef signed char s8; +typedef unsigned char u8; +typedef short s16; +typedef unsigned short u16; +typedef int s32; +typedef unsigned int u32; +typedef float f32; +typedef struct Vec3f { f32 x, y, z; } Vec3f; +typedef struct Actor { + s16 id; + u8 flags; + s32 timer; + Vec3f pos; + Vec3f vel; + struct Actor *next; + s32 table[4]; +} Actor; +extern Actor *gActorList; +extern s32 gFrameCount; +extern f32 gScale; +extern u8 gBuffer[64]; +s32 helper(s32 a, s32 b); +void notify(Actor *actor, s32 value); +f32 sqrtf(f32 x); + +s32 update_actors(Actor *first, s32 count, f32 dt) { + Actor *actor; + s32 i; + s32 total; + s32 mask; + f32 speed; + u32 bits; + + total = count; + mask = total; + first->vel.x = 0.0f; + first->vel.y = 0.0f; + first->vel.z = 0.0f; + total = 0; + mask = count * 12; + bits = (u32) count << 3; + for (i = 0, actor = first; i < count && actor != 0; i++, actor = actor->next) { + speed = actor->vel.x * actor->vel.x + actor->vel.y * actor->vel.y; + speed = sqrtf(speed) * 0.5f; + if (speed > 2.0f) { + actor->vel.x = actor->vel.x * gScale; + actor->vel.y = actor->vel.y * gScale; + } else if (actor->flags & 1) { + actor->pos.x += actor->vel.x * dt; + } + actor->pos.z = actor->pos.z + actor->vel.z; + actor->timer = actor->timer - 1; + total = total + actor->table[i & 3]; + gBuffer[i] = actor->flags >> 1; + switch (actor->id) { + case 0: + notify(actor, total); + break; + case 3: + total += helper(i, mask); + default: + total -= 1; + break; + } + while (actor->timer > 0) { + actor->timer -= 2; + } + } + gFrameCount = gFrameCount + 1; + mask = mask >> 4; + return total + (s32) bits + mask * 0; +} diff --git a/packages/romdev-permuter/test/fixtures/pow-oracle.json b/packages/romdev-permuter/test/fixtures/pow-oracle.json new file mode 100644 index 00000000..47bab3b6 --- /dev/null +++ b/packages/romdev-permuter/test/fixtures/pow-oracle.json @@ -0,0 +1 @@ +{"note":"pow(x, y) oracle rows [x, y, generic, fma] as IEEE-754 bits. generic: musl's pow (the same ARM optimized-routines code as glibc's generic build) compiled to WASM by emscripten. fma: glibc's x86-64 FMA build (the host libm on an FMA+AVX2 CPU, read through gawk's ^ operator, which calls pow()). Rows are every input in x=2..200000 (y=-1.5) and in 100000 random (x, y) pairs where the two builds disagree, plus a sample where they agree.","rows":[["0x4084580000000000","0xbff8000000000000","0x3f0f9080c9c5d4a2","0x3f0f9080c9c5d4a1"],["0x408f280000000000","0xbff8000000000000","0x3f00a78234f8aa8c","0x3f00a78234f8aa8c"],["0x409f280000000000","0xbff8000000000000","0x3ee78d82ffbdba2b","0x3ee78d82ffbdba2b"],["0x40a75e0000000000","0xbff8000000000000","0x3ed9a419d6bfcf73","0x3ed9a419d6bfcf73"],["0x40aa180000000000","0xbff8000000000000","0x3ed5baa144588e2c","0x3ed5baa144588e2d"],["0x40af280000000000","0xbff8000000000000","0x3ed0a78234f8aa8c","0x3ed0a78234f8aa8c"],["0x40b3790000000000","0xbff8000000000000","0x3ec7d56fd643eb91","0x3ec7d56fd643eb91"],["0x40b75e0000000000","0xbff8000000000000","0x3ec221853136378d","0x3ec221853136378d"],["0x40bb430000000000","0xbff8000000000000","0x3ebcc6a684d0c926","0x3ebcc6a684d0c926"],["0x40bf280000000000","0xbff8000000000000","0x3eb78d82ffbdba2b","0x3eb78d82ffbdba2b"],["0x40c1868000000000","0xbff8000000000000","0x3eb3bd0c18dadd18","0x3eb3bd0c18dadd18"],["0x40c3790000000000","0xbff8000000000000","0x3eb0da5e0cad4f95","0x3eb0da5e0cad4f95"],["0x40c4580000000000","0xbff8000000000000","0x3eaf9080c9c5d4a2","0x3eaf9080c9c5d4a1"],["0x40c4a18000000000","0xbff8000000000000","0x3eaee869adb8c2ce","0x3eaee869adb8c2cf"],["0x40c56b8000000000","0xbff8000000000000","0x3ead37402ef21632","0x3ead37402ef21632"],["0x40c75e0000000000","0xbff8000000000000","0x3ea9a419d6bfcf73","0x3ea9a419d6bfcf73"],["0x40c7970000000000","0xbff8000000000000","0x3ea94762de87d1ba","0x3ea94762de87d1bb"],["0x40c9508000000000","0xbff8000000000000","0x3ea6bd765ac60651","0x3ea6bd765ac60651"],["0x40caf08000000000","0xbff8000000000000","0x3ea4b6c1e016b2f2","0x3ea4b6c1e016b2f1"],["0x40cb430000000000","0xbff8000000000000","0x3ea459022ce96af1","0x3ea459022ce96af1"],["0x40cc5b8000000000","0xbff8000000000000","0x3ea32e0992347a0a","0x3ea32e0992347a0b"],["0x40cd358000000000","0xbff8000000000000","0x3ea258e366ca399c","0x3ea258e366ca399c"],["0x40cf280000000000","0xbff8000000000000","0x3ea0a78234f8aa8c","0x3ea0a78234f8aa8c"],["0x40d08d4000000000","0xbff8000000000000","0x3e9e69cf0c018bba","0x3e9e69cf0c018bba"],["0x40d0b30000000000","0xbff8000000000000","0x3e9e02e8b19fbca4","0x3e9e02e8b19fbca3"],["0x40d1868000000000","0xbff8000000000000","0x3e9bea16846f1589","0x3e9bea16846f1589"],["0x40d27fc000000000","0xbff8000000000000","0x3e99bd69abc2695e","0x3e99bd69abc2695e"],["0x40d3414000000000","0xbff8000000000000","0x3e983d3d7e44c25a","0x3e983d3d7e44c25b"],["0x40d3790000000000","0xbff8000000000000","0x3e97d56fd643eb91","0x3e97d56fd643eb91"],["0x40d4724000000000","0xbff8000000000000","0x3e9626d9a4d39397","0x3e9626d9a4d39397"],["0x40d51a4000000000","0xbff8000000000000","0x3e9520635a583b96","0x3e9520635a583b97"],["0x40d56b8000000000","0xbff8000000000000","0x3e94a8a0ff9257f1","0x3e94a8a0ff9257f1"],["0x40d664c000000000","0xbff8000000000000","0x3e93537eb628d871","0x3e93537eb628d871"],["0x40d75e0000000000","0xbff8000000000000","0x3e9221853136378d","0x3e9221853136378d"],["0x40d79c4000000000","0xbff8000000000000","0x3e91da00195b1d6a","0x3e91da00195b1d69"],["0x40d8574000000000","0xbff8000000000000","0x3e910dd53431d58d","0x3e910dd53431d58d"],["0x40d9508000000000","0xbff8000000000000","0x3e9014653e7cb657","0x3e9014653e7cb657"],["0x40da49c000000000","0xbff8000000000000","0x3e8e63acd8977a9c","0x3e8e63acd8977a9c"],["0x40db430000000000","0xbff8000000000000","0x3e8cc6a684d0c926","0x3e8cc6a684d0c926"],["0x40db594000000000","0xbff8000000000000","0x3e8ca38fbf52e572","0x3e8ca38fbf52e573"],["0x40dc3c4000000000","0xbff8000000000000","0x3e8b4cebb4372da2","0x3e8b4cebb4372da2"],["0x40dd358000000000","0xbff8000000000000","0x3e89f26732a81c52","0x3e89f26732a81c52"],["0x40ddc18000000000","0xbff8000000000000","0x3e893c20ef495e60","0x3e893c20ef495e61"],["0x40de2ec000000000","0xbff8000000000000","0x3e88b39a44a28910","0x3e88b39a44a28910"],["0x40dea78000000000","0xbff8000000000000","0x3e882236850e3a98","0x3e882236850e3a99"],["0x40df280000000000","0xbff8000000000000","0x3e878d82ffbdba2b","0x3e878d82ffbdba2b"],["0x40dff20000000000","0xbff8000000000000","0x3e86af7ff17e7db8","0x3e86af7ff17e7db7"],["0x40e010a000000000","0xbff8000000000000","0x3e867d87a699e8bf","0x3e867d87a699e8bf"],["0x40e08d4000000000","0xbff8000000000000","0x3e858165ef5593cc","0x3e858165ef5593cc"],["0x40e109e000000000","0xbff8000000000000","0x3e8497255f4bbfc1","0x3e8497255f4bbfc1"],["0x40e1868000000000","0xbff8000000000000","0x3e83bd0c18dadd18","0x3e83bd0c18dadd18"],["0x40e1d7c000000000","0xbff8000000000000","0x3e8336d338230b64","0x3e8336d338230b63"],["0x40e2032000000000","0xbff8000000000000","0x3e82f1959d317905","0x3e82f1959d317905"],["0x40e27fc000000000","0xbff8000000000000","0x3e82336b201c4d38","0x3e82336b201c4d38"],["0x40e2fc6000000000","0xbff8000000000000","0x3e81815d2109b837","0x3e81815d2109b837"],["0x40e322e000000000","0xbff8000000000000","0x3e814ca3b721de40","0x3e814ca3b721de41"],["0x40e3790000000000","0xbff8000000000000","0x3e80da5e0cad4f95","0x3e80da5e0cad4f95"],["0x40e3f5a000000000","0xbff8000000000000","0x3e803d7db72943c6","0x3e803d7db72943c6"],["0x40e4580000000000","0xbff8000000000000","0x3e7f9080c9c5d4a2","0x3e7f9080c9c5d4a1"],["0x40e4724000000000","0xbff8000000000000","0x3e7f53cb10a03d02","0x3e7f53cb10a03d02"],["0x40e4a32000000000","0xbff8000000000000","0x3e7ee4c33343e296","0x3e7ee4c33343e295"],["0x40e4eee000000000","0xbff8000000000000","0x3e7e3daa763c9fe9","0x3e7e3daa763c9fe9"],["0x40e56b8000000000","0xbff8000000000000","0x3e7d37402ef21632","0x3e7d37402ef21632"],["0x40e5e82000000000","0xbff8000000000000","0x3e7c3f5523deb860","0x3e7c3f5523deb860"],["0x40e6484000000000","0xbff8000000000000","0x3e7b895122b780b2","0x3e7b895122b780b1"],["0x40e664c000000000","0xbff8000000000000","0x3e7b54d081e6ffa5","0x3e7b54d081e6ffa5"],["0x40e6664000000000","0xbff8000000000000","0x3e7b5211bae04722","0x3e7b5211bae04721"],["0x40e6c00000000000","0xbff8000000000000","0x3e7ab1059c967da0","0x3e7ab1059c967da1"],["0x40e6e16000000000","0xbff8000000000000","0x3e7a76b433f80b81","0x3e7a76b433f80b81"],["0x40e6fce000000000","0xbff8000000000000","0x3e7a4745ae0e6c6e","0x3e7a4745ae0e6c6d"],["0x40e75e0000000000","0xbff8000000000000","0x3e79a419d6bfcf73","0x3e79a419d6bfcf73"],["0x40e7daa000000000","0xbff8000000000000","0x3e78dc30135ccbd3","0x3e78dc30135ccbd3"],["0x40e7ef0000000000","0xbff8000000000000","0x3e78bc77f431031c","0x3e78bc77f431031d"],["0x40e8574000000000","0xbff8000000000000","0x3e781e3851a7a81c","0x3e781e3851a7a81c"],["0x40e8d3e000000000","0xbff8000000000000","0x3e776984b5455303","0x3e776984b5455303"],["0x40e8dcc000000000","0xbff8000000000000","0x3e775cfc9a4cd1ee","0x3e775cfc9a4cd1ed"],["0x40e9508000000000","0xbff8000000000000","0x3e76bd765ac60651","0x3e76bd765ac60651"],["0x40e9cd2000000000","0xbff8000000000000","0x3e76197bcbcc1243","0x3e76197bcbcc1243"],["0x40ea180000000000","0xbff8000000000000","0x3e75baa144588e2c","0x3e75baa144588e2d"],["0x40ea49c000000000","0xbff8000000000000","0x3e757d0fa29f126e","0x3e757d0fa29f126e"],["0x40eac66000000000","0xbff8000000000000","0x3e74e7b756bbbbb4","0x3e74e7b756bbbbb4"],["0x40eaf08000000000","0xbff8000000000000","0x3e74b6c1e016b2f2","0x3e74b6c1e016b2f1"],["0x40eb430000000000","0xbff8000000000000","0x3e7459022ce96af1","0x3e7459022ce96af1"],["0x40ebbd2000000000","0xbff8000000000000","0x3e73d33616e07cfc","0x3e73d33616e07cfb"],["0x40ebbfa000000000","0xbff8000000000000","0x3e73d088462e4570","0x3e73d088462e4570"],["0x40ebd8e000000000","0xbff8000000000000","0x3e73b59b3934dd46","0x3e73b59b3934dd45"],["0x40ec3c4000000000","0xbff8000000000000","0x3e734de9c9a888ae","0x3e734de9c9a888ae"],["0x40ec5b8000000000","0xbff8000000000000","0x3e732e0992347a0a","0x3e732e0992347a0b"],["0x40ec93c000000000","0xbff8000000000000","0x3e72f5846bec10ac","0x3e72f5846bec10ad"],["0x40ecb8e000000000","0xbff8000000000000","0x3e72d0ce25e596a9","0x3e72d0ce25e596a9"],["0x40ed192000000000","0xbff8000000000000","0x3e7273c02eabbc44","0x3e7273c02eabbc43"],["0x40ed358000000000","0xbff8000000000000","0x3e7258e366ca399c","0x3e7258e366ca399c"],["0x40edb22000000000","0xbff8000000000000","0x3e71e5dd9d87775a","0x3e71e5dd9d87775a"],["0x40ee10e000000000","0xbff8000000000000","0x3e719185694684d4","0x3e719185694684d5"],["0x40ee226000000000","0xbff8000000000000","0x3e718239d6b21042","0x3e718239d6b21043"],["0x40ee2ec000000000","0xbff8000000000000","0x3e717776586f507b","0x3e717776586f507b"],["0x40eeab6000000000","0xbff8000000000000","0x3e710d6c28c793a5","0x3e710d6c28c793a5"],["0x40ef280000000000","0xbff8000000000000","0x3e70a78234f8aa8c","0x3e70a78234f8aa8c"],["0x40ef5ee000000000","0xbff8000000000000","0x3e707be26e79d642","0x3e707be26e79d641"],["0x40efa4a000000000","0xbff8000000000000","0x3e70457fd5acbbef","0x3e70457fd5acbbef"],["0x40f010a000000000","0xbff8000000000000","0x3e6fce6079444987","0x3e6fce6079444987"],["0x40f014a000000000","0xbff8000000000000","0x3e6fc2831e576372","0x3e6fc2831e576373"],["0x40f019d000000000","0xbff8000000000000","0x3e6fb32b05426636","0x3e6fb32b05426635"],["0x40f04ef000000000","0xbff8000000000000","0x3e6f18c44838b53e","0x3e6f18c44838b53e"],["0x40f064b000000000","0xbff8000000000000","0x3e6edaf5c754ac4e","0x3e6edaf5c754ac4d"],["0x40f08d4000000000","0xbff8000000000000","0x3e6e69cf0c018bba","0x3e6e69cf0c018bba"],["0x40f0b30000000000","0xbff8000000000000","0x3e6e02e8b19fbca4","0x3e6e02e8b19fbca3"],["0x40f0ca7000000000","0xbff8000000000000","0x3e6dc4284a10914c","0x3e6dc4284a10914b"],["0x40f0cb9000000000","0xbff8000000000000","0x3e6dc12ab395c716","0x3e6dc12ab395c716"],["0x40f109e000000000","0xbff8000000000000","0x3e6d1e86b139751f","0x3e6d1e86b139751f"],["0x40f1367000000000","0xbff8000000000000","0x3e6cadbb07fa5bb0","0x3e6cadbb07fa5baf"],["0x40f1483000000000","0xbff8000000000000","0x3e6c81978d8df964","0x3e6c81978d8df964"],["0x40f148a000000000","0xbff8000000000000","0x3e6c808279a6656a","0x3e6c808279a66569"],["0x40f1868000000000","0xbff8000000000000","0x3e6bea16846f1589","0x3e6bea16846f1589"],["0x40f1c4d000000000","0xbff8000000000000","0x3e6b57c12a9bdd6b","0x3e6b57c12a9bdd6b"],["0x40f2032000000000","0xbff8000000000000","0x3e6aca591b482395","0x3e6aca591b482395"],["0x40f2315000000000","0xbff8000000000000","0x3e6a6493f959b8d2","0x3e6a6493f959b8d1"],["0x40f2374000000000","0xbff8000000000000","0x3e6a57ad8943c062","0x3e6a57ad8943c063"],["0x40f2417000000000","0xbff8000000000000","0x3e6a41a3accc9b16","0x3e6a41a3accc9b16"],["0x40f275e000000000","0xbff8000000000000","0x3e69d213b7d61cc8","0x3e69d213b7d61cc7"],["0x40f2763000000000","0xbff8000000000000","0x3e69d16be35a1614","0x3e69d16be35a1613"],["0x40f27fc000000000","0xbff8000000000000","0x3e69bd69abc2695e","0x3e69bd69abc2695e"],["0x40f293d000000000","0xbff8000000000000","0x3e6993c2aa105512","0x3e6993c2aa105511"],["0x40f297b000000000","0xbff8000000000000","0x3e698bc4156ce7e8","0x3e698bc4156ce7e9"],["0x40f2be1000000000","0xbff8000000000000","0x3e693d771bea9bfc","0x3e693d771bea9bfc"],["0x40f2e9f000000000","0xbff8000000000000","0x3e68e5d6cfeba566","0x3e68e5d6cfeba565"],["0x40f2fc6000000000","0xbff8000000000000","0x3e68c19afe534ab1","0x3e68c19afe534ab1"],["0x40f33ab000000000","0xbff8000000000000","0x3e6849a71c3b6ed3","0x3e6849a71c3b6ed3"],["0x40f3790000000000","0xbff8000000000000","0x3e67d56fd643eb91","0x3e67d56fd643eb91"],["0x40f3b75000000000","0xbff8000000000000","0x3e6764cbf788227b","0x3e6764cbf788227b"],["0x40f3f5a000000000","0xbff8000000000000","0x3e66f7948c42f0c6","0x3e66f7948c42f0c6"],["0x40f433f000000000","0xbff8000000000000","0x3e668da4bbae3fa1","0x3e668da4bbae3fa1"],["0x40f4724000000000","0xbff8000000000000","0x3e6626d9a4d39397","0x3e6626d9a4d39397"],["0x40f4836000000000","0xbff8000000000000","0x3e660b2226c09cc8","0x3e660b2226c09cc9"],["0x40f4b09000000000","0xbff8000000000000","0x3e65c3123e0b5cd9","0x3e65c3123e0b5cd9"],["0x40f4eee000000000","0xbff8000000000000","0x3e65622f36ef5173","0x3e65622f36ef5173"],["0x40f51a4000000000","0xbff8000000000000","0x3e6520635a583b96","0x3e6520635a583b97"],["0x40f52d3000000000","0xbff8000000000000","0x3e650412dc89ebba","0x3e650412dc89ebba"],["0x40f56b8000000000","0xbff8000000000000","0x3e64a8a0ff9257f1","0x3e64a8a0ff9257f1"],["0x40f5a9d000000000","0xbff8000000000000","0x3e644fbedc88bfd4","0x3e644fbedc88bfd4"],["0x40f5e82000000000","0xbff8000000000000","0x3e63f953058b08fd","0x3e63f953058b08fd"],["0x40f5f41000000000","0xbff8000000000000","0x3e63e90a8ecca282","0x3e63e90a8ecca283"],["0x40f6267000000000","0xbff8000000000000","0x3e63a5454dbdd312","0x3e63a5454dbdd312"],["0x40f63cd000000000","0xbff8000000000000","0x3e6387a63b54b8b0","0x3e6387a63b54b8b1"],["0x40f664c000000000","0xbff8000000000000","0x3e63537eb628d871","0x3e63537eb628d871"],["0x40f6a31000000000","0xbff8000000000000","0x3e6303e95be8d2e8","0x3e6303e95be8d2e8"],["0x40f6cc9000000000","0xbff8000000000000","0x3e62d015cb01bb0e","0x3e62d015cb01bb0d"],["0x40f6e16000000000","0xbff8000000000000","0x3e62b670679bb7b0","0x3e62b670679bb7b0"],["0x40f71fb000000000","0xbff8000000000000","0x3e626afffdee8a8d","0x3e626afffdee8a8d"],["0x40f753c000000000","0xbff8000000000000","0x3e622d79beee39c6","0x3e622d79beee39c5"],["0x40f75e0000000000","0xbff8000000000000","0x3e6221853136378d","0x3e6221853136378d"],["0x40f79c4000000000","0xbff8000000000000","0x3e61da00195b1d6a","0x3e61da00195b1d69"],["0x40f79c5000000000","0xbff8000000000000","0x3e61d9edf3fedbc1","0x3e61d9edf3fedbc1"],["0x40f7daa000000000","0xbff8000000000000","0x3e6194290c7ead48","0x3e6194290c7ead48"],["0x40f814d000000000","0xbff8000000000000","0x3e61549907ddeafc","0x3e61549907ddeafd"],["0x40f818f000000000","0xbff8000000000000","0x3e61502608db4f86","0x3e61502608db4f86"],["0x40f8574000000000","0xbff8000000000000","0x3e610dd53431d58d","0x3e610dd53431d58d"],["0x40f8959000000000","0xbff8000000000000","0x3e60cd278c53073c","0x3e60cd278c53073c"],["0x40f8d3e000000000","0xbff8000000000000","0x3e608e0eb826b040","0x3e608e0eb826b040"],["0x40f9123000000000","0xbff8000000000000","0x3e60507cfea9d6f8","0x3e60507cfea9d6f8"],["0x40f9508000000000","0xbff8000000000000","0x3e6014653e7cb657","0x3e6014653e7cb657"],["0x40f98ed000000000","0xbff8000000000000","0x3e5fb375cbec78a4","0x3e5fb375cbec78a4"],["0x40f9a02000000000","0xbff8000000000000","0x3e5f935b0e3c11b2","0x3e5f935b0e3c11b3"],["0x40f9b5e000000000","0xbff8000000000000","0x3e5f6b523f0b9af4","0x3e5f6b523f0b9af5"],["0x40f9cd2000000000","0xbff8000000000000","0x3e5f40e3d7674065","0x3e5f40e3d7674065"],["0x40f9d1a000000000","0xbff8000000000000","0x3e5f38b8782db6d4","0x3e5f38b8782db6d5"],["0x40fa0b7000000000","0xbff8000000000000","0x3e5ed0fd8f36c6ab","0x3e5ed0fd8f36c6ab"],["0x40fa49c000000000","0xbff8000000000000","0x3e5e63acd8977a9c","0x3e5e63acd8977a9c"],["0x40fa881000000000","0xbff8000000000000","0x3e5df8dc81da274e","0x3e5df8dc81da274e"],["0x40faa2c000000000","0xbff8000000000000","0x3e5dcbdc242ceb6c","0x3e5dcbdc242ceb6b"],["0x40fabbd000000000","0xbff8000000000000","0x3e5da1ff69e90a4e","0x3e5da1ff69e90a4f"],["0x40fabe5000000000","0xbff8000000000000","0x3e5d9dd7ca841518","0x3e5d9dd7ca841519"],["0x40fac66000000000","0xbff8000000000000","0x3e5d907836c35e14","0x3e5d907836c35e14"],["0x40fac73000000000","0xbff8000000000000","0x3e5d8f1fc2b2519c","0x3e5d8f1fc2b2519b"],["0x40fb04b000000000","0xbff8000000000000","0x3e5d2a6c7598c94c","0x3e5d2a6c7598c94c"],["0x40fb430000000000","0xbff8000000000000","0x3e5cc6a684d0c926","0x3e5cc6a684d0c926"],["0x40fb517000000000","0xbff8000000000000","0x3e5cafd9abfc1000","0x3e5cafd9abfc0fff"],["0x40fb594000000000","0xbff8000000000000","0x3e5ca38fbf52e572","0x3e5ca38fbf52e573"],["0x40fb815000000000","0xbff8000000000000","0x3e5c651469599b14","0x3e5c651469599b14"],["0x40fbbfa000000000","0xbff8000000000000","0x3e5c05a4dd6e1941","0x3e5c05a4dd6e1941"],["0x40fbfdf000000000","0xbff8000000000000","0x3e5ba84747eedb41","0x3e5ba84747eedb41"],["0x40fc1c9000000000","0xbff8000000000000","0x3e5b7b219ebf4568","0x3e5b7b219ebf4569"],["0x40fc36f000000000","0xbff8000000000000","0x3e5b54a1f901b332","0x3e5b54a1f901b333"],["0x40fc3c4000000000","0xbff8000000000000","0x3e5b4cebb4372da2","0x3e5b4cebb4372da2"],["0x40fc7a9000000000","0xbff8000000000000","0x3e5af382ca65f486","0x3e5af382ca65f486"],["0x40fc897000000000","0xbff8000000000000","0x3e5ade72ecc43daa","0x3e5ade72ecc43dab"],["0x40fc929000000000","0xbff8000000000000","0x3e5ad194ded914be","0x3e5ad194ded914bf"],["0x40fcaea000000000","0xbff8000000000000","0x3e5aaa429c461d80","0x3e5aaa429c461d81"],["0x40fcb35000000000","0xbff8000000000000","0x3e5aa3ba874daaa2","0x3e5aa3ba874daaa1"],["0x40fcb8e000000000","0xbff8000000000000","0x3e5a9bfdc8131f2f","0x3e5a9bfdc8131f2f"],["0x40fcf73000000000","0xbff8000000000000","0x3e5a464e796ad888","0x3e5a464e796ad888"],["0x40fd358000000000","0xbff8000000000000","0x3e59f26732a81c52","0x3e59f26732a81c52"],["0x40fd6d7000000000","0xbff8000000000000","0x3e59a88efe987490","0x3e59a88efe987491"],["0x40fd73d000000000","0xbff8000000000000","0x3e59a03ac9e8ca69","0x3e59a03ac9e8ca69"],["0x40fdb22000000000","0xbff8000000000000","0x3e594fbc9155ba9f","0x3e594fbc9155ba9f"],["0x40fdc18000000000","0xbff8000000000000","0x3e593c20ef495e60","0x3e593c20ef495e61"],["0x40fdcf1000000000","0xbff8000000000000","0x3e592aea069fd756","0x3e592aea069fd755"],["0x40fdf07000000000","0xbff8000000000000","0x3e5900e05199b4ab","0x3e5900e05199b4ab"],["0x40fe2ec000000000","0xbff8000000000000","0x3e58b39a44a28910","0x3e58b39a44a28910"],["0x40fe6d1000000000","0xbff8000000000000","0x3e5867df10a7dab1","0x3e5867df10a7dab1"],["0x40feab6000000000","0xbff8000000000000","0x3e581da3c3737544","0x3e581da3c3737544"],["0x40fed0e000000000","0xbff8000000000000","0x3e57f1ac1479a914","0x3e57f1ac1479a915"],["0x40fee9b000000000","0xbff8000000000000","0x3e57d4ddcde75397","0x3e57d4ddcde75397"],["0x40ff252000000000","0xbff8000000000000","0x3e5790c5f3975838","0x3e5790c5f3975839"],["0x40ff280000000000","0xbff8000000000000","0x3e578d82ffbdba2b","0x3e578d82ffbdba2b"],["0x40ff665000000000","0xbff8000000000000","0x3e57478983800774","0x3e57478983800774"],["0x40ffa4a000000000","0xbff8000000000000","0x3e5702e7dab11332","0x3e5702e7dab11332"],["0x40ffe2f000000000","0xbff8000000000000","0x3e56bf94da282aca","0x3e56bf94da282aca"],["0x410010a000000000","0xbff8000000000000","0x3e567d87a699e8bf","0x3e567d87a699e8bf"],["0x410022f000000000","0xbff8000000000000","0x3e5657499c2049ac","0x3e5657499c2049ad"],["0x41002fc800000000","0xbff8000000000000","0x3e563cb7b14c52ac","0x3e563cb7b14c52ac"],["0x41004ef000000000","0xbff8000000000000","0x3e55fd1cb4f3d2cb","0x3e55fd1cb4f3d2cb"],["0x41006e1800000000","0xbff8000000000000","0x3e55beaeb2b6c905","0x3e55beaeb2b6c905"],["0x41008d4000000000","0xbff8000000000000","0x3e558165ef5593cc","0x3e558165ef5593cc"],["0x41008da800000000","0xbff8000000000000","0x3e55809b4547a270","0x3e55809b4547a26f"],["0x4100ac6800000000","0xbff8000000000000","0x3e55453af0751285","0x3e55453af0751285"],["0x4100cb9000000000","0xbff8000000000000","0x3e550a267a09c2ce","0x3e550a267a09c2ce"],["0x4100eab800000000","0xbff8000000000000","0x3e54d0218be1b703","0x3e54d0218be1b703"],["0x4100eac800000000","0xbff8000000000000","0x3e54d00404fcb27e","0x3e54d00404fcb27d"],["0x410109e000000000","0xbff8000000000000","0x3e5497255f4bbfc1","0x3e5497255f4bbfc1"],["0x4101290800000000","0xbff8000000000000","0x3e545f2b64da3b78","0x3e545f2b64da3b78"],["0x4101483000000000","0xbff8000000000000","0x3e54282d424016eb","0x3e54282d424016eb"],["0x4101675800000000","0xbff8000000000000","0x3e53f224d0469f7e","0x3e53f224d0469f7e"],["0x4101868000000000","0xbff8000000000000","0x3e53bd0c18dadd18","0x3e53bd0c18dadd18"],["0x41018a1800000000","0xbff8000000000000","0x3e53b6fb634ecaf8","0x3e53b6fb634ecaf7"],["0x4101a5a800000000","0xbff8000000000000","0x3e5388dd55313c73","0x3e5388dd55313c73"],["0x4101af7000000000","0xbff8000000000000","0x3e5378aad0b82b7a","0x3e5378aad0b82b79"],["0x4101c4d000000000","0xbff8000000000000","0x3e535592ebfe6505","0x3e535592ebfe6505"],["0x4101d7c000000000","0xbff8000000000000","0x3e5336d338230b64","0x3e5336d338230b63"],["0x4101e3f800000000","0xbff8000000000000","0x3e5323276fc42666","0x3e5323276fc42666"],["0x4101ec7000000000","0xbff8000000000000","0x3e531598d295d24c","0x3e531598d295d24b"],["0x4101edd000000000","0xbff8000000000000","0x3e531366d6a2f09c","0x3e531366d6a2f09b"],["0x4102032000000000","0xbff8000000000000","0x3e52f1959d317905","0x3e52f1959d317905"],["0x4102224800000000","0xbff8000000000000","0x3e52c0d859949cca","0x3e52c0d859949cca"],["0x410231f800000000","0xbff8000000000000","0x3e52a89ccd97e374","0x3e52a89ccd97e373"],["0x4102417000000000","0xbff8000000000000","0x3e5290eab15e6e22","0x3e5290eab15e6e22"],["0x4102609800000000","0xbff8000000000000","0x3e5261c7d6b616f5","0x3e5261c7d6b616f5"],["0x4102729000000000","0xbff8000000000000","0x3e5246f2e7087756","0x3e5246f2e7087757"],["0x41027fc000000000","0xbff8000000000000","0x3e52336b201c4d38","0x3e52336b201c4d38"],["0x41029ee800000000","0xbff8000000000000","0x3e5205d0071d5c48","0x3e5205d0071d5c48"],["0x4102b97800000000","0xbff8000000000000","0x3e51df83ee4922c4","0x3e51df83ee4922c3"],["0x4102be1000000000","0xbff8000000000000","0x3e51d8f2271140e4","0x3e51d8f2271140e4"],["0x4102d0a800000000","0xbff8000000000000","0x3e51be83e3563d6e","0x3e51be83e3563d6d"],["0x4102dd3800000000","0xbff8000000000000","0x3e51accd3be929c3","0x3e51accd3be929c3"],["0x4102ee3000000000","0xbff8000000000000","0x3e51950eaf98e3c4","0x3e51950eaf98e3c5"],["0x4102fc6000000000","0xbff8000000000000","0x3e51815d2109b837","0x3e51815d2109b837"],["0x41031b8800000000","0xbff8000000000000","0x3e51569dd0316528","0x3e51569dd0316528"],["0x410322e000000000","0xbff8000000000000","0x3e514ca3b721de40","0x3e514ca3b721de41"],["0x4103348000000000","0xbff8000000000000","0x3e5134d8c4076c32","0x3e5134d8c4076c31"],["0x41033ab000000000","0xbff8000000000000","0x3e512c8b606a771d","0x3e512c8b606a771d"],["0x41034a6800000000","0xbff8000000000000","0x3e511791f2fd9dee","0x3e511791f2fd9def"],["0x410359d800000000","0xbff8000000000000","0x3e5103220507fddc","0x3e5103220507fddc"],["0x4103790000000000","0xbff8000000000000","0x3e50da5e0cad4f95","0x3e50da5e0cad4f95"],["0x4103982800000000","0xbff8000000000000","0x3e50b23be05f8a85","0x3e50b23be05f8a85"],["0x4103b75000000000","0xbff8000000000000","0x3e508ab802a0a477","0x3e508ab802a0a477"],["0x4103d67800000000","0xbff8000000000000","0x3e5063cf0e9397d8","0x3e5063cf0e9397d8"],["0x4103e21800000000","0xbff8000000000000","0x3e50557171c7f200","0x3e50557171c7f201"],["0x4103f5a000000000","0xbff8000000000000","0x3e503d7db72943c6","0x3e503d7db72943c6"],["0x41040d2800000000","0xbff8000000000000","0x3e5020ef97b42d9e","0x3e5020ef97b42d9f"],["0x410414c800000000","0xbff8000000000000","0x3e5017c0c6559a09","0x3e5017c0c6559a09"],["0x410433f000000000","0xbff8000000000000","0x3e4fe52a38997615","0x3e4fe52a38997615"],["0x4104531800000000","0xbff8000000000000","0x3e4f9bef5d8f49a3","0x3e4f9bef5d8f49a3"],["0x4104580000000000","0xbff8000000000000","0x3e4f9080c9c5d4a2","0x3e4f9080c9c5d4a1"],["0x4104629000000000","0xbff8000000000000","0x3e4f77fb98083290","0x3e4f77fb98083291"],["0x4104724000000000","0xbff8000000000000","0x3e4f53cb10a03d02","0x3e4f53cb10a03d02"],["0x4104800800000000","0xbff8000000000000","0x3e4f3439646475f4","0x3e4f3439646475f5"],["0x4104916800000000","0xbff8000000000000","0x3e4f0cb78f271ca3","0x3e4f0cb78f271ca3"],["0x4104969800000000","0xbff8000000000000","0x3e4f00fc1cc96dbc","0x3e4f00fc1cc96dbd"],["0x4104a18000000000","0xbff8000000000000","0x3e4ee869adb8c2ce","0x3e4ee869adb8c2cf"],["0x4104a32000000000","0xbff8000000000000","0x3e4ee4c33343e296","0x3e4ee4c33343e295"],["0x4104b09000000000","0xbff8000000000000","0x3e4ec6af3d78d7fc","0x3e4ec6af3d78d7fc"],["0x4104c3b800000000","0xbff8000000000000","0x3e4e9c22625c3e62","0x3e4e9c22625c3e61"],["0x4104c65000000000","0xbff8000000000000","0x3e4e9667082bb21e","0x3e4e9667082bb21f"],["0x4104cfb800000000","0xbff8000000000000","0x3e4e81aca5a40b1a","0x3e4e81aca5a40b1a"],["0x4104eee000000000","0xbff8000000000000","0x3e4e3daa763c9fe9","0x3e4e3daa763c9fe9"],["0x410501f800000000","0xbff8000000000000","0x3e4e14795009dabc","0x3e4e14795009dabb"],["0x41050e0800000000","0xbff8000000000000","0x3e4dfaa381330144","0x3e4dfaa381330144"],["0x41052d3000000000","0xbff8000000000000","0x3e4db892bab66047","0x3e4db892bab66047"],["0x41054c5800000000","0xbff8000000000000","0x3e4d777338219296","0x3e4d777338219296"],["0x41056b8000000000","0xbff8000000000000","0x3e4d37402ef21632","0x3e4d37402ef21632"],["0x41058aa800000000","0xbff8000000000000","0x3e4cf7f4f3c8cce5","0x3e4cf7f4f3c8cce5"],["0x4105941800000000","0xbff8000000000000","0x3e4ce4f5e6e97b0a","0x3e4ce4f5e6e97b0b"],["0x4105a15800000000","0xbff8000000000000","0x3e4cca6d41b4a8ba","0x3e4cca6d41b4a8b9"],["0x4105a16000000000","0xbff8000000000000","0x3e4cca5d48c77c7e","0x3e4cca5d48c77c7f"],["0x4105a9d000000000","0xbff8000000000000","0x3e4cb98cf97406ab","0x3e4cb98cf97406ab"],["0x4105c8f800000000","0xbff8000000000000","0x3e4c7c03d0027752","0x3e4c7c03d0027752"],["0x4105e82000000000","0xbff8000000000000","0x3e4c3f5523deb860","0x3e4c3f5523deb860"],["0x4106074800000000","0xbff8000000000000","0x3e4c037cbcf2fca7","0x3e4c037cbcf2fca7"],["0x4106144800000000","0xbff8000000000000","0x3e4beac2a4e00710","0x3e4beac2a4e0070f"],["0x4106267000000000","0xbff8000000000000","0x3e4bc8767dd49f3d","0x3e4bc8767dd49f3d"],["0x41062db800000000","0xbff8000000000000","0x3e4bbac912b67562","0x3e4bbac912b67561"],["0x4106459800000000","0xbff8000000000000","0x3e4b8e3e62f73b81","0x3e4b8e3e62f73b81"],["0x4106484000000000","0xbff8000000000000","0x3e4b895122b780b2","0x3e4b895122b780b1"],["0x410664c000000000","0xbff8000000000000","0x3e4b54d081e6ffa5","0x3e4b54d081e6ffa5"],["0x4106664000000000","0xbff8000000000000","0x3e4b5211bae04722","0x3e4b5211bae04721"],["0x410683e800000000","0xbff8000000000000","0x3e4b1c290889eedc","0x3e4b1c290889eedc"],["0x4106928800000000","0xbff8000000000000","0x3e4b01d458c0fd94","0x3e4b01d458c0fd95"],["0x4106a31000000000","0xbff8000000000000","0x3e4ae4443c67cb9e","0x3e4ae4443c67cb9e"],["0x4106a59800000000","0xbff8000000000000","0x3e4adfc22ccc4c02","0x3e4adfc22ccc4c03"],["0x4106ac0800000000","0xbff8000000000000","0x3e4ad450d2de83b0","0x3e4ad450d2de83b1"],["0x4106c23800000000","0xbff8000000000000","0x3e4aad1e79f865cc","0x3e4aad1e79f865cc"],["0x4106e16000000000","0xbff8000000000000","0x3e4a76b433f80b81","0x3e4a76b433f80b81"],["0x4107008800000000","0xbff8000000000000","0x3e4a4101f2c1de55","0x3e4a4101f2c1de55"],["0x4107041000000000","0xbff8000000000000","0x3e4a3af768117da2","0x3e4a3af768117da3"],["0x410718d800000000","0xbff8000000000000","0x3e4a1798d35f733e","0x3e4a1798d35f733f"],["0x4107199000000000","0xbff8000000000000","0x3e4a1661151ec528","0x3e4a1661151ec529"],["0x41071fb000000000","0xbff8000000000000","0x3e4a0c0453afd198","0x3e4a0c0453afd198"],["0x41073a5000000000","0xbff8000000000000","0x3e49df484853d54e","0x3e49df484853d54f"],["0x41073ed800000000","0xbff8000000000000","0x3e49d7b8088018b6","0x3e49d7b8088018b6"],["0x41075e0000000000","0xbff8000000000000","0x3e49a419d6bfcf73","0x3e49a419d6bfcf73"],["0x41077d2800000000","0xbff8000000000000","0x3e497126973aa80e","0x3e497126973aa80e"],["0x410782c000000000","0xbff8000000000000","0x3e496812afd37b1e","0x3e496812afd37b1f"],["0x4107937800000000","0xbff8000000000000","0x3e494d1105320832","0x3e494d1105320831"],["0x4107970000000000","0xbff8000000000000","0x3e494762de87d1ba","0x3e494762de87d1bb"],["0x41079c5000000000","0xbff8000000000000","0x3e493edb356f6daf","0x3e493edb356f6daf"],["0x4107bb7800000000","0xbff8000000000000","0x3e490d34af092b9f","0x3e490d34af092b9f"],["0x4107d28800000000","0xbff8000000000000","0x3e48e8dc89ce9c02","0x3e48e8dc89ce9c03"],["0x4107daa000000000","0xbff8000000000000","0x3e48dc30135ccbd3","0x3e48dc30135ccbd3"],["0x4107e14800000000","0xbff8000000000000","0x3e48d1cbe4ffb678","0x3e48d1cbe4ffb679"],["0x4107e73000000000","0xbff8000000000000","0x3e48c899820c8e0e","0x3e48c899820c8e0d"],["0x4107ef0000000000","0xbff8000000000000","0x3e48bc77f431031c","0x3e48bc77f431031d"],["0x4107f9c800000000","0xbff8000000000000","0x3e48abca82eb0165","0x3e48abca82eb0165"],["0x410818f000000000","0xbff8000000000000","0x3e487c012ee65544","0x3e487c012ee65544"],["0x4108381800000000","0xbff8000000000000","0x3e484cd158bd2d60","0x3e484cd158bd2d60"],["0x41084ae800000000","0xbff8000000000000","0x3e48309c9807ac78","0x3e48309c9807ac79"],["0x4108574000000000","0xbff8000000000000","0x3e481e3851a7a81c","0x3e481e3851a7a81c"],["0x407efcb71bf3c931","0xc00f3ace00000000","0x3dc089bd7091a8cd","0x3dc089bd7091a8cd"],["0x40065a796f5c056c","0xc015d160e0000000","0x3f6e26d1cd92c648","0x3f6e26d1cd92c648"],["0x411fa20a94b6ccb1","0xc010043d40000000","0x3b2fbc0a3ea0dc8a","0x3b2fbc0a3ea0dc89"],["0x404d8e40b6356550","0x4020f326d0000000","0x430d6732f73e2a2a","0x430d6732f73e2a2a"],["0x3fb6d0a9f99d20f4","0xbfe44fb000000000","0x40128ee40c916360","0x40128ee40c91635f"],["0x4055b62d3db39697","0xc016742780000000","0x3dacc91d3df3c74c","0x3dacc91d3df3c74d"],["0x415ae6023d1ebf53","0xc022ef1d40000000","0x3278c4eebbf20225","0x3278c4eebbf20225"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x400350cb4ef73a8b","0xc01be336c0000000","0x3f618e50f163ffd9","0x3f618e50f163ffd9"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3fff39fe2a30366a","0xc001d01040000000","0x3fcce14e745472da","0x3fcce14e745472da"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x41988beef6066a56","0x40221fdc60000000","0x4f028d0f0730d8fb","0x4f028d0f0730d8fb"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x40e77b32a1761ea6","0xbff1ad5500000000","0x3edc2c8b5baca264","0x3edc2c8b5baca264"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3e31743387db544f","0xc01ccbe61d000000","0x4c797e30de728db7","0x4c797e30de728db7"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3f012be4eb9938d6","0xc013b15a18000000","0x44845656ac4046f8","0x44845656ac4046f8"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3ee015fb835d83a9","0xc00b2335f0000000","0x4388f3b454216077","0x4388f3b454216077"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x3e21bccb33ed0ebe","0x4010a086eba00000","0x3870d1c49c3ac39b","0x3870d1c49c3ac39b"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3eb137ae0071ecd3","0x4018a847e8000000","0x38449ce50586f154","0x38449ce50586f154"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3e37e8940af1833a","0x400d9e4f54000000","0x3996547ca9e8ef26","0x3996547ca9e8ef26"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3fba7ebc83263947","0x3fdef5a000000000","0x3fd55ce019ccc7b6","0x3fd55ce019ccc7b6"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x3e3ed5d4afa1d229","0xc01654cf98000000","0x49606426d579391a","0x49606426d579391a"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x4099c5417318a912","0xbff8808780000000","0x3ee8d0b37139ccb8","0x3ee8d0b37139ccb8"],["0x401b0223c6ede62d","0xc0170d1c60000000","0x3ef1680df05824f0","0x3ef1680df05824f0"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3e340c670dccb9f7","0xc020f7ca8e800000","0x4e9bab7a9ec57a1c","0x4e9bab7a9ec57a1c"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3ee27d05cd726f9e","0xc008756fd0000000","0x4324368eff85fe92","0x4324368eff85fe92"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x41b4556e909b42b3","0x3ffc1c0400000000","0x430bd6c456450cd9","0x430bd6c456450cd9"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x3e941b47848cf751","0x402089f2b4000000","0x34bbd22c6597326a","0x34bbd22c6597326a"],["0x3e3edcd5c8145546","0xc0026fa0b0000000","0x43d447a2e5912197","0x43d447a2e5912197"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x409677b9b7ccfe8e","0x40213492f0000000","0x4592e62f359d1da6","0x4592e62f359d1da6"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x401b51cdbd67d1c5","0xc00b57cb80000000","0x3f570a894df04a05","0x3f570a894df04a05"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x402ca1f65c91b636","0x401ad5c5e0000000","0x418b133e4bd414cd","0x418b133e4bd414cd"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x3ef90492c4484788","0xbffbdb9be0000000","0x419aa17d6a82896d","0x419aa17d6a82896d"],["0x3eb925b5be6b64b3","0xc00cacb0e0000000","0x44445e55b07b0279","0x44445e55b07b0279"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3e2c2410f9f73f37","0xc01bbb12fd000000","0x4c251f2d0555fcdd","0x4c251f2d0555fcdd"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3e8b2248e1c1f674","0x40228b5eb8000000","0x330bf3cfccb610e6","0x330bf3cfccb610e6"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x40849d810e1e5305","0xc00e085e80000000","0x3dbca6fa86c5390c","0x3dbca6fa86c5390c"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3e91de28463ea967","0xc015ef0118000000","0x476b1f4b7daef11d","0x476b1f4b7daef11d"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x40c7074bcce4b083","0x4006189f00000000","0x42447f1f2621e937","0x42447f1f2621e937"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x40935b62f115f756","0x3fe5468100000000","0x405c77bc387b41c8","0x405c77bc387b41c8"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3f325c92c42fab27","0xc023ffe6b0000000","0x475020cfbb578e29","0x475020cfbb578e29"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x40a51a2803a58b22","0x401fd18ca0000000","0x459996d3da03cc02","0x459996d3da03cc02"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x3fa6144875a39cda","0xbfff781f80000000","0x407e47c6f8e3101b","0x407e47c6f8e3101b"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x3ed74d7ef23cdc1c","0xbfe5c3acc0000000","0x40ad506cc1b264d5","0x40ad506cc1b264d5"],["0x4076124d73adee4e","0xbfe5cc4b00000000","0x3f92d26df7696488","0x3f92d26df7696488"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x400512200e48046b","0x401882b140000000","0x40779c4d48a42d53","0x40779c4d48a42d53"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x409afd9773a27863","0x40238a76f0000000","0x4680dabc4cc69f82","0x4680dabc4cc69f82"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x403731feeebef43c","0x4018a626c0000000","0x41aeebd04dff851d","0x41aeebd04dff851d"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x3e78cdb768a90976","0x402248e204000000","0x32949e962fcd0f63","0x32949e962fcd0f63"],["0x3eac91679eb6cef7","0x401d6d1768000000","0x36a95f97d813afa0","0x36a95f97d813afa0"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3ffabce41144bb8d","0x3ff3f93b80000000","0x3ffe5fe208ea79d9","0x3ffe5fe208ea79d9"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x41944ebc019a5959","0xc01caee900000000","0x34210f669c4306a6","0x34210f669c4306a6"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x40bc27f7833d22e0","0x4021d4ad80000000","0x471314a01c8dac8b","0x471314a01c8dac8b"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x41a3b2c752527c67","0xc0130f8d00000000","0x37ce12b2829c2be7","0x37ce12b2829c2be7"],["0x400c98f9f7c05568","0x4006c1a000000000","0x4042bc7a83b413a1","0x4042bc7a83b413a1"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x402420664cd299f9","0x4012cc5440000000","0x40e92e837e882063","0x40e92e837e882063"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3e4bb2718665d858","0xc022899d6c000000","0x4f1e426bd1a7064b","0x4f1e426bd1a7064b"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x418c288224fae9d9","0x4016948980000000","0x490a8917bc5de209","0x490a8917bc5de209"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3eabdef9a3ba88db","0x40093b3fd0000000","0x3bf399a32dd72442","0x3bf399a32dd72442"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x41707c9cae233829","0xc00365a3c0000000","0x3c4a10ce6647fb05","0x3c4a10ce6647fb05"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x40753c1255d2fd90","0xc020231350000000","0x3bb1d77a05157b0a","0x3bb1d77a05157b0a"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3f7b56ddb7f9e435","0xc0171f88a0000000","0x428b7152f8918903","0x428b7152f8918903"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x4177f3a4c900d2aa","0x4019e040c0000000","0x49e03ccee5a660db","0x49e03ccee5a660db"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3f46b46509e943a8","0x3ffadea700000000","0x3ed4bfd47c35509a","0x3ed4bfd47c35509a"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x3f0c748d5b0892be","0x40223eb720000000","0x37dab90c7d06b23f","0x37dab90c7d06b23f"],["0x40d7e3079c3816de","0x3ff6710500000000","0x4135d071347da80d","0x4135d071347da80d"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x4192b1a68b9a1c47","0xc01869af60000000","0x35eed55c87f9a897","0x35eed55c87f9a897"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3f2bc3786d8ffa01","0xc00bd65400000000","0x4296247302c54fed","0x4296247302c54fed"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x3ec7acac32a34481","0xc018c54118000000","0x4711deebb9f1e363","0x4711deebb9f1e363"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x4131fa688c46371d","0xc014b810a0000000","0x39672a4919f92a1f","0x39672a4919f92a1f"],["0x407c2ce2277fce2f","0xc017bc78e0000000","0x3ca9b11739dc4e3e","0x3ca9b11739dc4e3e"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3faedad1f3846f51","0xc01bad2b20000000","0x41b073d7de872dac","0x41b073d7de872dac"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3eb218c9b07a0e95","0xbfe60b32c0000000","0x40c9316989235c1a","0x40c9316989235c1a"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x403b8bdcbe72ac5a","0xc0235152d0000000","0x3d0bbed14795d4a0","0x3d0bbed14795d4a0"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x414867446d54ce6c","0x40144bc800000000","0x46c901a321005674","0x46c901a321005674"],["0x415aa65371ce35f8","0xc011d21fc0000000","0x399a1b720bc26107","0x399a1b720bc26107"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3fdc693cc596accb","0x401a695b30000000","0x3f733647fc52d41a","0x3f733647fc52d41a"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3f3ccc7d939e8fbc","0x40203bea10000000","0x3a464ad57a0ccc46","0x3a464ad57a0ccc46"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x3e49a400623c620b","0xbff86bb4e0000000","0x42720531010f6e65","0x42720531010f6e65"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3e49b4ccaeb9443d","0x401a85b5c8000000","0x3506c92f46524c44","0x3506c92f46524c44"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x40b90c368a5677aa","0x4013990c60000000","0x43cf289b56c62fd7","0x43cf289b56c62fd7"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x411438ab46bf4599","0x4002f0e800000000","0x42a55d518004e331","0x42a55d518004e331"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x4134df86bac74080","0xc02235e3c0000000","0x3455259c43090433","0x3455259c43090433"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x405684398e897b78","0xbff10d9880000000","0x3f80e8bcb7d08b04","0x3f80e8bcb7d08b04"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3f38a4f1578b8ff8","0x4014ba6440000000","0x3c4081fa7fa50175","0x3c4081fa7fa50175"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x4198d604c224f4b2","0xc021cf5600000000","0x311c4a739877f061","0x311c4a739877f061"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x41220eabac70f4a1","0x40214d1fa0000000","0x4a4d4698fa16f185","0x4a4d4698fa16f185"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x414bfd4921d8366c","0x40232feaa0000000","0x4d027315086cf3ee","0x4d027315086cf3ee"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x405791a5b3fed184","0xbff3f42280000000","0x3f6c4183dda3147b","0x3f6c4183dda3147b"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x4161b851e01743a0","0x40062e5200000000","0x43f21bde35d4cbc2","0x43f21bde35d4cbc2"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x419dc47271d02b76","0x4018309cc0000000","0x4a191ec54e4a834b","0x4a191ec54e4a834b"],["0x40b55f7dc21c470b","0xbfcee25400000000","0x3fc00ae22190dbb6","0x3fc00ae22190dbb6"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x412bd5977c789359","0x4021863f60000000","0x4ac654fbf029b3aa","0x4ac654fbf029b3aa"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3e21d9917b6cd3c2","0x40002d3f07400000","0x3c499b721ffa141c","0x3c499b721ffa141c"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x3f0bc3127ac6bada","0xbfdbeab800000000","0x405254c126e9fc67","0x405254c126e9fc67"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x3fc5873ba4595372","0xc00e4f3940000000","0x408acb8294c16ff9","0x408acb8294c16ff9"],["0x3ffab8f1557bf34e","0xc01feca440000000","0x3f91143ae8498f3d","0x3f91143ae8498f3d"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3fd22e93948e95f6","0xc014b973a0000000","0x408535a07bf5ecd0","0x408535a07bf5ecd0"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x40a0a204d3fccb21","0xc005b35c80000000","0x3e101bf96954b49f","0x3e101bf96954b49f"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x3fd472c74a7f8e0d","0xc023583e10000000","0x40ee4e52f59462ac","0x40ee4e52f59462ac"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x40c4116900a99a88","0x401c215040000000","0x45ca611c26ec5dfe","0x45ca611c26ec5dfe"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"],["0x3fc9c7f01720ca2a","0xc0217a57e0000000","0x413268dc8b2afb11","0x413268dc8b2afb11"],["0x3e925e56b235a9ac","0x4016d26368000000","0x382886b69329086e","0x382886b69329086f"],["0x40b7f0572e7ac8d0","0x401f680960000000","0x461b88cd010fb52c","0x461b88cd010fb52b"],["0x3fc261a5b6088f1e","0x400b244800000000","0x3f56a4a176291c27","0x3f56a4a176291c27"],["0x3ed1e1214eda4351","0xc01fe16d50000000","0x48d2322b2a3dbbdc","0x48d2322b2a3dbbdb"],["0x3e9569867385e56c","0x401bcebfb0000000","0x368f91b63778e07a","0x368f91b63778e07a"],["0x408cab6e8a1c81a2","0xc015786a80000000","0x3ca2107eab8809a2","0x3ca2107eab8809a1"],["0x4104ebddcc0b0228","0x4016fe6a80000000","0x462edceabaea975c","0x462edceabaea975c"],["0x3f615624f0be2515","0x3fd6fab200000000","0x3fbc0da19560aefc","0x3fbc0da19560aefd"],["0x40419a67ea66746a","0x4012ad3560000000","0x416fc1a11291850a","0x416fc1a11291850b"],["0x401b14b398d8516d","0x40170a32c0000000","0x40edb5d563f3e6a7","0x40edb5d563f3e6a7"],["0x3e44a656adeda92e","0x4013139008000000","0x37ffc4704aae17b0","0x37ffc4704aae17af"],["0x3f7383874cca97a0","0x3fffffef00000000","0x3ef7cd21c6d025ca","0x3ef7cd21c6d025c9"]]} diff --git a/packages/romdev-permuter/test/helpers/payloads.js b/packages/romdev-permuter/test/helpers/payloads.js new file mode 100644 index 00000000..a86964f9 --- /dev/null +++ b/packages/romdev-permuter/test/helpers/payloads.js @@ -0,0 +1,56 @@ +// payloads.js - the WASM toolchains these tests compile with, or why they are +// absent. +// +// The binary packages (romdev-toolchain-mips-gcc, romdev-toolchain-ido) +// gitignore their wasm/ payloads; a dev box has them built, and CI fills them +// from the published npm tarballs (scripts/fetch-payloads.mjs). A checkout +// with neither must not fail with an opaque ENOENT deep inside a compile, so +// each test that needs a payload skips with the reason below, the same +// contract as romdevtools' test/helpers/test-rom.js. +// +// import { MIPS_GCC, IDO } from "./helpers/payloads.js"; +// test("...", { skip: MIPS_GCC }, async () => { ... }); + +import { existsSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); + +/** The installed package's directory: node resolution first, then the monorepo sibling. */ +function packageDir(name) { + try { return path.dirname(fileURLToPath(import.meta.resolve(name))); } catch { /* not resolvable */ } + const sibling = path.resolve(here, "..", "..", "..", name); + return existsSync(path.join(sibling, "package.json")) ? sibling : null; +} + +/** + * false when every file is present, else the skip reason naming what is missing. + * @param {string} pkg + * @param {string[]} files package-relative paths + */ +export function missingPayload(pkg, files) { + const dir = packageDir(pkg); + if (!dir) return `${pkg} is not installed`; + const absent = files.filter((f) => !existsSync(path.join(dir, f))); + if (!absent.length) return false; + return `${pkg} payload absent (${absent.join(", ")}): gitignored WASM, built locally or filled from npm by scripts/fetch-payloads.mjs`; +} + +const glue = (names) => names.flatMap((n) => [`wasm/${n}.mjs`, `wasm/${n}.wasm`]); + +/** cc1 + as, what helpers/wasm-gcc.js compiles with. */ +export const MIPS_GCC = missingPayload("romdev-toolchain-mips-gcc", glue(["cc1", "mips-elf-as"])); + +/** IDO 5.3, what the import/permuter@home scratch projects build with (plus cpp and binutils from mips-gcc). */ +export const IDO = missingPayload("romdev-toolchain-ido", [...glue(["cc", "cfe", "uopt", "ugen", "as1"].map((p) => `5.3/${p}`)), "wasm/5.3/err.english.cc"]) + || missingPayload("romdev-toolchain-mips-gcc", glue(["cc1", "mips-linux-gnu-as", "mips-linux-gnu-objdump"])); + +/** + * Compile AND score: the scorer disassembles with mips-linux-gnu-objdump + * (src/objdump.js). The npm tarball of romdev-toolchain-mips-gcc 0.1.2 does + * not carry the mips-linux-gnu binutils the in-tree 0.1.2 does, so a tree + * filled from npm can compile but not score until that package is + * republished under a new version. + */ +export const MIPS_GCC_SCORER = MIPS_GCC || missingPayload("romdev-toolchain-mips-gcc", glue(["mips-linux-gnu-objdump"])); diff --git a/packages/romdev-permuter/test/helpers/wasm-gcc.js b/packages/romdev-permuter/test/helpers/wasm-gcc.js new file mode 100644 index 00000000..174b25df --- /dev/null +++ b/packages/romdev-permuter/test/helpers/wasm-gcc.js @@ -0,0 +1,26 @@ +// The compiler upstream's tests use (test/compile.sh): +// mips-linux-gnu-gcc -O2 -fno-PIC -fno-common -ffreestanding -mno-shared -mno-abicalls -G 0 -c +// run as romdev's WASM mips gcc (cc1 + as) instead of a host gcc. +import { readFileSync, writeFileSync } from "node:fs"; +import { runWasmTool } from "../../src/wasm-tool.js"; + +let toolchain = null; +async function tc() { + if (!toolchain) ({ toolchain } = await import("romdev-toolchain-mips-gcc")); + return toolchain; +} + +/** compileFn for Compiler/run(): cPath -> oPath, true on success. */ +export async function wasmGccCompile(cPath, oPath) { + const t = await tc(); + const src = readFileSync(cPath); + const cc1 = await runWasmTool(t.cc1.gluePath, + ["-meb", "-mabi=32", "-quiet", "-O2", "-fno-PIC", "-fno-common", "-ffreestanding", "-mno-abicalls", "-G0", "/work/in.c", "-o", "/work/in.s"], + { "/work/in.c": src }, ["/work/in.s"]); + if (cc1.exitCode !== 0 || !cc1.outputs["/work/in.s"]) return false; + const as = await runWasmTool(t["mips-elf-as"].gluePath, ["-EB", "-mabi=32", "-G0", "/work/in.s", "-o", "/work/in.o"], + { "/work/in.s": cc1.outputs["/work/in.s"] }, ["/work/in.o"]); + if (as.exitCode !== 0 || !as.outputs["/work/in.o"]) return false; + writeFileSync(oPath, as.outputs["/work/in.o"]); + return true; +} diff --git a/packages/romdev-permuter/test/helpers/work.js b/packages/romdev-permuter/test/helpers/work.js new file mode 100644 index 00000000..530f1e43 --- /dev/null +++ b/packages/romdev-permuter/test/helpers/work.js @@ -0,0 +1,16 @@ +// Scratch directories for tests live under test/.work (gitignored), never in +// the system temp dir. +import { mkdirSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { randomBytes } from "node:crypto"; + +const WORK = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".work"); + +export function workDir(tag) { + const d = path.join(WORK, `${tag}-${randomBytes(4).toString("hex")}`); + mkdirSync(d, { recursive: true }); + return d; +} + +export function removeDir(d) { rmSync(d, { recursive: true, force: true }); } diff --git a/packages/romdev-permuter/test/import.test.js b/packages/romdev-permuter/test/import.test.js new file mode 100644 index 00000000..92578f7d --- /dev/null +++ b/packages/romdev-permuter/test/import.test.js @@ -0,0 +1,61 @@ +// import.mjs (upstream import.py) end to end on a scratch project: the +// Makefile is read in JS, cpp / IDO / the assembler run as romdev's WASM, and +// the imported directory then permutes to score 0 through permuter.mjs's +// in-process compile of the generated compile.sh. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { writeFileSync, readFileSync, mkdirSync, existsSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { importMain, resolveToolchainUrl, fixup_build_command, finalize_compile_command, prune_asm, shq, fnmatch } from "../src/import.js"; +import { workDir, removeDir } from "./helpers/work.js"; +import { IDO } from "./helpers/payloads.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const toolchain = resolveToolchainUrl(); + +test("fixup_build_command drops deps flags, the output and the source, and unwraps asm-processor", () => { + // A recorded build line that wraps the compiler in asm-processor (data read + // from a fixture: the command is parsed, never run). + const recorded = readFileSync(path.join(here, "fixtures", "asm-processor-build-line.txt"), "utf8").trim().split(/\s+/); + const [cmd, asm] = fixup_build_command(recorded, "src/a.c"); + assert.deepEqual(cmd, ["tools/cc", "-c", "-O2"]); + assert.deepEqual(asm, ["mips-linux-gnu-as", "-march=vr4300"]); + assert.equal(finalize_compile_command(["cc", "-c", "|", "iconv"]), 'cc -c "$INPUT" | iconv -o "$OUTPUT"'); + assert.equal(shq("a b"), "'a b'"); + assert.ok(fnmatch("tools/ido/5.3/cc", "tools/*/5.3/cc")); +}); + +test("prune_asm moves .late_rodata to a trailing .rodata section", () => { + const [name, asm] = prune_asm("glabel f\n jr $ra\n.late_rodata\n.word 1\n.text\n nop\n"); + assert.equal(name, "f"); + assert.equal(asm, "glabel f\n jr $ra\n.text\n nop\n\n.section .rodata\n.word 1\n"); +}); + +test("import a function from a Make project and permute it to a match", { skip: (!toolchain && "romdev's toolchain adapter (romdevtools) is not available") || IDO }, async () => { + const root = workDir("import"); + try { + mkdirSync(path.join(root, "src")); + mkdirSync(path.join(root, "asm")); + mkdirSync(path.join(root, "tools")); + writeFileSync(path.join(root, "Makefile"), "CC := tools/ido/5.3/cc\nCFLAGS := -c -G 0 -non_shared -O2 -mips2 -32\n" + + "build/%.o: %.c\n\t$(CC) $(CFLAGS) -o $@ $<\n"); + writeFileSync(path.join(root, "tools", "permuter_settings.toml"), "compiler_type = \"ido\"\n\n[preserve_macros]\n\"INC.*\" = \"int\"\n"); + writeFileSync(path.join(root, "src", "a.c"), "#define INC(x) ((x) + 1)\nint other(int b) { return b; }\nint f(int a) {\n return INC(a);\n}\n"); + writeFileSync(path.join(root, "asm", "f.s"), "glabel f\n/* 0 */ jr $ra\n/* 4 */ addiu $v0, $a0, 1\n"); + const lines = []; + const dir = await importMain([path.join(root, "src", "a.c"), path.join(root, "asm", "f.s")], { cwd: root, log: (s) => lines.push(s) }); + const log = lines.join("\n"); + assert.match(log, /Preserving macros: INC\./); + for (const f of ["base.c", "compile.sh", "settings.toml", "target.s", "target.o", "base.o"]) assert.ok(existsSync(path.join(dir, f)), `${f} missing\n${log}`); + const base = readFileSync(path.join(dir, "base.c"), "utf8"); + assert.match(base, /#pragma _permuter define INC\(x\)/); + assert.match(base, /return INC\(a\);/); + assert.match(readFileSync(path.join(dir, "settings.toml"), "utf8"), /^func_name = "f"\ncompiler_type = "ido"\n/); + const out = execFileSync(process.execPath, [path.join(here, "..", "bin", "permuter.mjs"), dir, "--stop-on-zero", "--quiet"], { encoding: "utf8", timeout: 120_000 }); + assert.match(out, /\[f\] base score = 0/); + } finally { + removeDir(root); + } +}); diff --git a/packages/romdev-permuter/test/levenshtein.test.js b/packages/romdev-permuter/test/levenshtein.test.js new file mode 100644 index 00000000..1bd1a89e --- /dev/null +++ b/packages/romdev-permuter/test/levenshtein.test.js @@ -0,0 +1,59 @@ +// --algorithm levenshtein: Levenshtein.opcodes as the `Levenshtein` package +// (rapidfuzz) documents it, and the scorer on top of it. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { editops, opcodes } from "../src/levenshtein.js"; +import { PyRandom } from "../src/pyrandom.js"; + +const chars = (s) => [...s]; + +test("Levenshtein.opcodes docstring: opcodes('spam', 'park')", () => { + assert.deepEqual(opcodes(chars("spam"), chars("park")), [ + ["delete", 0, 1, 0, 0], ["equal", 1, 3, 0, 2], ["insert", 3, 3, 2, 3], ["replace", 3, 4, 3, 4], + ]); +}); + +test("rapidfuzz Levenshtein.opcodes docstring: ('qabxcd', 'abycdf')", () => { + assert.deepEqual(opcodes(chars("qabxcd"), chars("abycdf")), [ + ["delete", 0, 1, 0, 0], ["equal", 1, 3, 0, 2], ["replace", 3, 4, 2, 3], ["equal", 4, 6, 3, 5], ["insert", 6, 6, 5, 6], + ]); +}); + +/** Plain DP edit distance, the quantity the editops must realise. */ +function dp(a, b) { + let prev = Array.from({ length: b.length + 1 }, (_, j) => j); + for (let i = 1; i <= a.length; i++) { + const cur = [i]; + for (let j = 1; j <= b.length; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); + prev = cur; + } + return prev[b.length]; +} + +test("editops are a minimal edit script and opcodes tile both sequences", () => { + const r = new PyRandom(7); + for (let n = 0; n < 400; n++) { + const a = Array.from({ length: r.randrange(0, 90) }, () => r.randrange(0, 5)); + const b = Array.from({ length: r.randrange(0, 90) }, () => r.randrange(0, 5)); + const ops = editops(a, b); + assert.equal(ops.length, dp(a, b)); + // Apply the script: the result must be b. + const out = []; + let i = 0; + for (const [tag, sp, dp_] of ops) { + while (i < sp) out.push(a[i++]); + assert.equal(out.length, dp_); + if (tag === "insert") out.push(b[dp_]); + else if (tag === "replace") { out.push(b[dp_]); i++; } else i++; + } + while (i < a.length) out.push(a[i++]); + assert.deepEqual(out, b); + let si = 0, di = 0; + for (const [tag, i1, i2, j1, j2] of opcodes(a, b)) { + assert.equal(i1, si); assert.equal(j1, di); + if (tag === "equal") assert.deepEqual(a.slice(i1, i2), b.slice(j1, j2)); + si = i2; di = j2; + } + assert.deepEqual([si, di], [a.length, b.length]); + } +}); diff --git a/packages/romdev-permuter/test/passes.test.js b/packages/romdev-permuter/test/passes.test.js new file mode 100644 index 00000000..3fb2941b --- /dev/null +++ b/packages/romdev-permuter/test/passes.test.js @@ -0,0 +1,104 @@ +// Every randomization pass must produce valid C: applied alone (one call, the +// way Randomizer.randomize calls it) to a function exercising structs, +// pointers, floats, loops, switch, shifts and constant multiplies, each +// successful application must print to source that the C parser accepts, and +// it must compile (romdev's WASM mips gcc, the flags upstream's tests use) +// except for the type slips upstream itself makes and scores as a failed +// compile. Those are pinned here by seed, with the upstream reason, so a new +// kind of invalid output fails the test: +// perm_temp_for_expr: same_type(allow_similar=True) treats every +// IdentifierType as similar, so a float temp can be reused for an int. +// perm_randomize_function_type: PROB_RET_VOID turns a used return value +// into void ("perhaps avoid if the function call result is used, but eh"). +// perm_add_self_assignment: x++; x--; or x += 0; on a struct-typed member. +// perm_reorder_stmts: a break is movable (only blocks and pragmas are +// pinned), so it can leave its switch or loop. +// perm_cast_simple: any arithmetic expression may be cast to float, even +// the left operand of a shift. +// perm_mult_zero: the zero replaced may be compared against a pointer. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { Candidate } from "../src/candidate.js"; +import { EvalState } from "../src/perm/perm.js"; +import { RANDOMIZATION_PASSES, RandomizationFailure, _internal } from "../src/randomizer.js"; +import * as ast_util from "../src/ast_util.js"; +import { get_default_randomization_weights } from "../src/helpers.js"; +import { PyRandom } from "../src/pyrandom.js"; +import { wasmGccCompile } from "./helpers/wasm-gcc.js"; +import { MIPS_GCC } from "./helpers/payloads.js"; +import { runWasmTool } from "../src/wasm-tool.js"; +import { workDir, removeDir } from "./helpers/work.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const SOURCE = readFileSync(path.join(here, "fixtures", "passes.c"), "utf8"); +const FN = "update_actors"; +const SEEDS = 24; +// Upstream type slips (see header): pass -> seeds whose output does not compile. +const KNOWN_UPSTREAM_TYPE_SLIPS = { + perm_temp_for_expr: /array subscript is not an integer|invalid operands|incompatible type/, + perm_randomize_function_type: /void value not ignored/, + perm_add_self_assignment: /wrong type argument to (increment|decrement)|invalid operands to binary \+/, + perm_reorder_stmts: /statement not within loop or switch/, + perm_cast_simple: /invalid operands to binary/, + perm_mult_zero: /invalid operands to binary/, +}; +const weights = get_default_randomization_weights("base"); + +/** Compile; on failure return cc1's diagnostics. */ +async function compiles(dir, text, k) { + const c = path.join(dir, `c${k}.c`), o = path.join(dir, `c${k}.o`); + writeFileSync(c, text); + const ok = await wasmGccCompile(c, o); + rmSync(c, { force: true }); + rmSync(o, { force: true }); + if (ok) return { ok }; + const { toolchain } = await import("romdev-toolchain-mips-gcc"); + const r = await runWasmTool(toolchain.cc1.gluePath, ["-meb", "-mabi=32", "-quiet", "-O2", "-G0", "/work/in.c", "-o", "/work/in.s"], { "/work/in.c": text }); + return { ok, errors: r.stderr.split("\n").filter((l) => /error/.test(l)).join("\n") }; +} + +const summary = {}; +for (const pass of RANDOMIZATION_PASSES) { + test(`${pass.name} produces valid C`, { skip: MIPS_GCC }, async () => { + const dir = workDir(pass.name); + let applied = 0, compiled = 0, slips = 0; + const failures = []; + try { + for (let seed = 1; seed <= SEEDS; seed++) { + const cand = Candidate.from_source(SOURCE, new EvalState(), FN, weights, seed); + const random = new PyRandom(seed); + const fn = ast_util.extract_fn(cand.ast, FN)[0]; + const indices = ast_util.compute_node_indices(fn); + const region = _internal.get_randomization_region(fn, indices, random); + try { + pass(fn, cand.ast, indices, region, random); + } catch (e) { + if (e instanceof RandomizationFailure) continue; + throw e; + } + applied++; + const text = ast_util.to_c(cand.ast); + // Syntactically valid: the printed candidate parses again. + ast_util.parse_c(text); + const r = await compiles(dir, text, seed); + if (r.ok) compiled++; + else if (KNOWN_UPSTREAM_TYPE_SLIPS[pass.name]?.test(r.errors)) slips++; + else failures.push(`seed ${seed}: ${r.errors}`); + } + } finally { + removeDir(dir); + } + summary[pass.name] = { applied, compiled, upstreamTypeSlips: slips }; + assert.ok(applied > 0, `${pass.name} never applied to the fixture`); + assert.ok(compiled > 0, `${pass.name}: no output compiled`); + assert.deepEqual(failures, [], `${pass.name}: outputs that do not compile for a reason upstream does not share`); + }); +} + +test("summary", () => { + // Visible in the TAP output for the report. + console.log(JSON.stringify(summary)); +}); diff --git a/packages/romdev-permuter/test/perm.test.js b/packages/romdev-permuter/test/perm.test.js new file mode 100644 index 00000000..5362c0d7 --- /dev/null +++ b/packages/romdev-permuter/test/perm.test.js @@ -0,0 +1,155 @@ +// Port of upstream test/test_perm.py: PERM macro behaviour end to end. Each +// case compiles a target, writes base.c, runs the permuter with +// --stop-on-zero and checks the best score. Upstream compiles with a host +// mips-linux-gnu-gcc (test/compile.sh); this runs the same flags through +// romdev's WASM mips gcc. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { writeFileSync, copyFileSync } from "node:fs"; +import path from "node:path"; +import { run } from "../src/main.js"; +import { Compiler } from "../src/compiler.js"; +import { wasmGccCompile } from "./helpers/wasm-gcc.js"; +import { workDir, removeDir } from "./helpers/work.js"; +import { MIPS_GCC_SCORER } from "./helpers/payloads.js"; + +// Every case compiles through the WASM mips gcc and scores with its objdump; +// without that payload they skip with the reason. +const skip = MIPS_GCC_SCORER; + +async function go(intro, outro, base, target, { fn_name = null, ...kwargs } = {}) { + base = intro + "\n" + base + "\n" + outro; + target = intro + "\n" + target + "\n" + outro; + const dir = workDir("perm"); + try { + const compiler = new Compiler(null, { show_errors: true, tmpDir: path.join(dir, ".cc"), compileFn: wasmGccCompile }); + writeFileSync(path.join(dir, "base.c"), base); + const target_o = await compiler.compile(target, { show_errors: true }); + assert.ok(target_o != null, "target compiles"); + copyFileSync(target_o, path.join(dir, "target.o")); + if (fn_name) writeFileSync(path.join(dir, "function.txt"), fn_name); + const r = await run({ directories: [dir], stop_on_zero: true, compileModule: { url: new URL("./helpers/wasm-gcc.js", import.meta.url).href, name: "wasmGccCompile" }, out: () => {}, ...kwargs }); + return r.bestScores[0]; + } finally { + removeDir(dir); + } +} + +test("general", { skip }, async () => { + assert.equal(await go("int test() {", "}", "return PERM_GENERAL(32,64);", "return 64;"), 0); +}); + +test("not_found", { skip }, async () => { + assert.notEqual(await go("int test() {", "}", "return PERM_GENERAL(32,64);", "return 92;"), 0); +}); + +test("multiple_functions", { skip }, async () => { + const score = await go("", "", ` + int ignoreme() {} + int foo() { return PERM_GENERAL(32,64); } + int ignoreme2() {} + `, "int foo() { return 64; }", { fn_name: "foo" }); + assert.equal(score, 0); +}); + +test("general_multiple", { skip }, async () => { + assert.equal(await go("int test() {", "}", "return PERM_GENERAL(1,2,3) + PERM_GENERAL(3,6,9);", "return 9;"), 0); +}); + +test("general_nested", { skip }, async () => { + assert.equal(await go("int test() {", "}", "return PERM_GENERAL(1,PERM_GENERAL(100,101),3) + PERM_GENERAL(3,6,9);", "return 110;"), 0); +}); + +test("cast", { skip }, async () => { + assert.equal(await go("int test(int a, int b) {", "}", "return a / PERM_GENERAL(,(unsigned int),(float)) b;", "return a / (float) b;"), 0); +}); + +test("cast_threaded", { skip }, async () => { + assert.equal(await go("int test(int a, int b) {", "}", "return a / PERM_GENERAL(,(unsigned int),(float)) b;", "return a / (float) b;", { threads: 2 }), 0); +}); + +test("ignore", { skip }, async () => { + assert.equal(await go("int test(int a, int b) {", "}", "PERM_IGNORE( return a / PERM_GENERAL(a, b); )", "return a / b;"), 0); +}); + +test("pretend", { skip }, async () => { + const score = await go("int global;", "", ` + PERM_IGNORE( inline void foo() { ) + PERM_PRETEND( void foo(); void bar() { ) + PERM_RANDOMIZE( + global = 1; + ) + PERM_IGNORE( } void bar() { ) + PERM_RANDOMIZE( + global = 2; foo(); + ) + } + `, ` + inline void foo() { global = 1; } + void bar() { foo(); global = 2; } + `, { fn_name: "bar" }); + assert.equal(score, 0); +}); + +test("once1", { skip }, async () => { + const score = await go("volatile int A, B, C; void test() {", "}", ` + PERM_ONCE(B = 2;) + A = 1; + PERM_ONCE(B = 2;) + C = 3; + PERM_ONCE(B = 2;) + `, "A = 1; B = 2; C = 3;"); + assert.equal(score, 0); +}); + +test("once2", { skip }, async () => { + const score = await go("volatile int A, B, C; void test() {", "}", ` + PERM_VAR(emit,) + PERM_VAR(bademit,) + PERM_ONCE(1, PERM_VAR(bademit, A = 7;) A = 2;) + PERM_ONCE(1, PERM_VAR(emit, A = 1;)) + PERM_VAR(emit) + PERM_VAR(bademit) + PERM_ONCE(2, B = 2;) + PERM_ONCE(2, B = 1;) + PERM_ONCE(2,) + PERM_ONCE(3, PERM_VAR(bademit, A = 9)) + PERM_ONCE(3, PERM_VAR(bademit, A = 9)) + C = 3; + `, "A = 1; B = 2; C = 3;"); + assert.equal(score, 0); +}); + +test("lineswap", { skip }, async () => { + const score = await go("void a(); void b(); void c(); void test(void) {", "}", ` + PERM_LINESWAP( + a(); + b(); + c(); + ) + `, "b(); a(); c();"); + assert.equal(score, 0); +}); + +test("lineswap_text", { skip }, async () => { + const score = await go("void a(); void b(); void c(); void test(void) {", "}", ` + PERM_LINESWAP_TEXT( + a(); + b(); + c(); + ) + `, "b(); a(); c();"); + assert.equal(score, 0); +}); + +test("randomizer", { skip }, async () => { + assert.equal(await go("void foo(); void bar(); void test(void) {", "}", "PERM_RANDOMIZE(bar(); foo();)", "foo(); bar();"), 0); +}); + +test("auto_randomizer", { skip }, async () => { + assert.equal(await go("void foo(); void bar(); void test(void) {", "}", "bar(); foo();", "foo(); bar();"), 0); +}); + +test("randomizer_threaded", { skip }, async () => { + assert.equal(await go("void foo(); void bar(); void test(void) {", "}", "PERM_RANDOMIZE(bar(); foo();)", "foo(); bar();", { threads: 2 }), 0); +}); diff --git a/packages/romdev-permuter/test/pow.test.js b/packages/romdev-permuter/test/pow.test.js new file mode 100644 index 00000000..c9209259 --- /dev/null +++ b/packages/romdev-permuter/test/pow.test.js @@ -0,0 +1,48 @@ +// The reorder weights `(dist + 1) ** -1.5` must be the doubles CPython gets +// from the C library's pow(). pow.js ports glibc/musl's pow (ARM +// optimized-routines) with both of its builds: the generic one, and the +// x86-64 FMA build glibc selects on FMA+AVX2 CPUs (explicit fmas plus the +// multiply-adds GCC contracts under -mfma). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { libmPow, fma, powNeg15, hostUsesFma } from "../src/pow.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const b = new DataView(new ArrayBuffer(8)); +const d = (h) => { b.setBigUint64(0, BigInt(h)); return b.getFloat64(0); }; + +test("fma rounds once", () => { + // (1 + 2^-52)^2 - 1 = 2^-51 + 2^-104: separate rounding loses the 2^-104 term. + const a = 1 + 2 ** -52; + assert.equal(a * a - 1, 2 ** -51); + assert.equal(fma(a, a, -1), 2 ** -51 + 2 ** -104); + assert.equal(fma(2, 3, 4), 10); + assert.equal(fma(0.1, 10, -1), 5.551115123125783e-17); +}); + +test("both pow builds reproduce the oracle rows (musl-in-WASM generic, host glibc FMA)", () => { + const { rows } = JSON.parse(readFileSync(path.join(here, "fixtures", "pow-oracle.json"), "utf8")); + let gen = 0, fm = 0; + for (const [x, y, g, f] of rows) { + if (libmPow(d(x), d(y), { fma: false }) === d(g)) gen++; + if (libmPow(d(x), d(y), { fma: true }) === d(f)) fm++; + } + assert.equal(gen, rows.length); + assert.equal(fm, rows.length); + assert.ok(rows.some(([, , g, f]) => g !== f), "the fixture must contain inputs where the builds differ"); +}); + +let gawk = null; +try { execFileSync("gawk", ["BEGIN{}"]); gawk = "gawk"; } catch { /* no gawk */ } + +test("powNeg15 equals the host C library's pow for every weight input 2..200000", { skip: !gawk && "gawk (the host libm probe) not installed" }, () => { + const host = execFileSync(gawk, ["BEGIN{for(x=2;x<=200000;x++) printf \"%.17g\\n\", x^-1.5}"], { maxBuffer: 1 << 24 }) + .toString().trim().split("\n").map(Number); + let diff = 0; + for (let x = 2; x <= 200000; x++) if (powNeg15(x) !== host[x - 2]) diff++; + assert.equal(diff, 0, `host FMA build: ${hostUsesFma()}`); +}); diff --git a/packages/romdev-permuter/test/pyrandom.test.js b/packages/romdev-permuter/test/pyrandom.test.js new file mode 100644 index 00000000..379686f0 --- /dev/null +++ b/packages/romdev-permuter/test/pyrandom.test.js @@ -0,0 +1,60 @@ +// PyRandom must replay CPython's random.Random stream exactly: the rng seed a +// permuter run prints ("--seed N") only reproduces a candidate if every draw +// matches upstream's. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { PyRandom } from "../src/pyrandom.js"; + +test("MT19937 reference vector (mt19937ar.c init_by_array {0x123,0x234,0x345,0x456})", () => { + const r = new PyRandom(0); + r.initByArray([0x123, 0x234, 0x345, 0x456]); + assert.deepEqual([1, 2, 3, 4, 5].map(() => r.genrandUint32()), [1067595299, 955945823, 477289528, 4107218783, 4228976476]); +}); + +test("random.Random(n).random() matches CPython for small int seeds", () => { + assert.equal(new PyRandom(0).random(), 0.8444218515250481); + assert.equal(new PyRandom(1).random(), 0.13436424411240122); + assert.equal(new PyRandom(42).random(), 0.6394267984578837); +}); + +test("int seeds are split into 32-bit words little-endian; negative seeds use abs()", () => { + const big = 12345678901234567890n; + const a = new PyRandom(big), b = new PyRandom(-big); + assert.equal(a.random(), b.random()); + const c = new PyRandom(0); + c.initByArray([Number(big & 0xffffffffn), Number((big >> 32n) & 0xffffffffn)]); + const d = new PyRandom(big); + assert.equal(c.genrandUint32(), d.genrandUint32()); +}); + +test("_randbelow draws getrandbits(n.bit_length()) with rejection, as random.py does", () => { + // choice() of a one-element list still consumes a 1-bit draw per attempt. + const r1 = new PyRandom(5), r2 = new PyRandom(5); + r1.choice(["x"]); + let k; + do { k = r2.genrandUint32() >>> 31; } while (k >= 1); + assert.equal(r1.genrandUint32(), r2.genrandUint32()); + // BigInt ranges (the permuter's rng seeds: randrange(1, 10**20)). + const r = new PyRandom(9); + const v = r.randrange(1n, 10n ** 20n); + assert.equal(typeof v, "bigint"); + assert.ok(v >= 1n && v < 10n ** 20n); +}); + +test("sample, shuffle, randint, uniform follow random.py's algorithms", () => { + const r = new PyRandom(3), s = new PyRandom(3); + const got = r.sample([10, 20, 30, 40], 2); + // pool algorithm (n <= setsize): j = randbelow(n - i), pool[j] = pool[n - i - 1] + const pool = [10, 20, 30, 40]; + const want = []; + for (let i = 0; i < 2; i++) { const j = s._randbelow(4 - i); want.push(pool[j]); pool[j] = pool[4 - i - 1]; } + assert.deepEqual(got, want); + const x = [1, 2, 3, 4, 5], y = x.slice(); + new PyRandom(11).shuffle(x); + const t = new PyRandom(11); + for (let i = y.length - 1; i >= 1; i--) { const j = t._randbelow(i + 1); [y[i], y[j]] = [y[j], y[i]]; } + assert.deepEqual(x, y); + const u = new PyRandom(4), w = new PyRandom(4); + assert.equal(u.uniform(2, 5), 2 + 3 * w.random()); + assert.equal(new PyRandom(8).randint(3, 3), 3); +}); diff --git a/packages/romdev-permuter/test/remote.test.js b/packages/romdev-permuter/test/remote.test.js new file mode 100644 index 00000000..79c0ae69 --- /dev/null +++ b/packages/romdev-permuter/test/remote.test.js @@ -0,0 +1,174 @@ +// permuter@home over loopback: the controller (romdev-permuter-remote-controller, bin/remote-controller.mjs), a worker +// server (romdev-permuter-remote run-server, with its evaluator process) and a -J client +// (permuter.mjs -J -j 0, so every candidate is evaluated remotely), all on +// 127.0.0.1. Access is granted the upstream way: `romdev-permuter-remote setup` on the +// worker's side, `romdev-permuter-remote vouch` by the root user, the sealed token pasted back. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { writeFileSync, readFileSync, mkdirSync, existsSync, readdirSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { run_controller, run_setup } from "../src/net/controller.js"; +import { resolveToolchainUrl } from "../src/import.js"; +import { _make_script_portable } from "../src/net/client.js"; +import { bindScript, profilePrograms } from "../src/net/evaluator.js"; +import { pyJsonLoads, pyJsonDumps } from "../src/net/core.js"; +import { workDir, removeDir } from "./helpers/work.js"; +import { IDO } from "./helpers/payloads.js"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const BIN = path.join(here, "..", "bin"); +const toolchain = resolveToolchainUrl(); + +test("compile scripts travel portably and bind to the server's toolchain profile", () => { + const script = "#!/usr/bin/env bash\nINPUT=\"$(realpath \"$1\")\"\nOUTPUT=\"$(realpath \"$3\")\"\ncd '/home/x/proj'\n" + + "/home/x/proj/tools/ido/5.3/cc -c -O2 \"$INPUT\" -o \"$OUTPUT\"\n"; + const portable = _make_script_portable(script); + assert.equal(portable, "#!/usr/bin/env bash\nINPUT=\"$(realpath \"$1\")\"\nOUTPUT=\"$(realpath \"$3\")\"\n$(which cc) -c -O2 \"$INPUT\" -o \"$OUTPUT\"\n"); + assert.match(bindScript(portable, profilePrograms("romdev:ido5.3")), /^ido\/5\.3\/cc -c -O2 "\$INPUT"/m); + assert.throws(() => bindScript("$(which gcc) -c x", profilePrograms("romdev:ido5.3")), /needs program 'gcc'/); + assert.throws(() => bindScript("$(which cc) -I/etc -c \"$INPUT\"", profilePrograms("romdev:ido5.3")), /outside its job directory/); + assert.throws(() => bindScript("cd /\n$(which cc) x", profilePrograms("romdev:ido5.3")), /may not change directory/); +}); + +test("u64 seeds survive the JSON wire format", () => { + const seed = 18446744073709551615n; + const wire = pyJsonDumps({ type: "work", work: { seed } }); + assert.equal(wire, '{"type": "work", "work": {"seed": 18446744073709551615}}'); + assert.equal(pyJsonLoads(wire).work.seed, seed); + assert.equal(pyJsonLoads('{"a": 5}').a, 5); +}); + +/** Spawn a node script; resolves {code, stdout, stderr}. `onOut(text, child)` sees stdout as it arrives. */ +function spawnNode(args, { cwd, onOut, timeoutMs = 240_000 } = {}) { + const child = spawn(process.execPath, args, { cwd, stdio: ["pipe", "pipe", "pipe"] }); + let stdout = "", stderr = ""; + child.stdout.on("data", (d) => { stdout += d; child.out = stdout; onOut?.(stdout, child); }); + child.stderr.on("data", (d) => { stderr += d; child.err = stderr; }); + const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs); + const done = new Promise((resolve) => child.on("exit", (code) => { clearTimeout(timer); resolve({ code, stdout, stderr }); })); + return { child, done }; +} + +test("permuter@home loopback: setup, vouch, run-server and a -J client that finds the match remotely", + { skip: (!toolchain && "romdev's toolchain adapter (romdevtools) is not available") || IDO, timeout: 300_000 }, async () => { + const root = workDir("pah"); + let controller = null; + let worker = null; + try { + const rootDir = path.join(root, "root"); + const workerDir = path.join(root, "worker"); + mkdirSync(rootDir); + mkdirSync(workerDir); + + // Controller: setup prints the server seed and the root client's keys. + const db = path.join(root, "db.json"); + const setupText = await run_setup(db); + const hex = (k) => new RegExp(`${k} = "([0-9a-f]{64})"`).exec(setupText)[1]; + writeFileSync(path.join(root, "config.toml"), `docker_image = "romdev:ido5.3"\npriv_seed = "${hex("priv_seed")}"\n`); + const logs = []; + controller = await run_controller({ listen_on: "127.0.0.1:0", config: path.join(root, "config.toml"), db, log: (s) => logs.push(s), saveIntervalMs: 50 }); + writeFileSync(path.join(rootDir, "pah.conf"), + `secret_key = "${hex("secret_key")}"\nserver_public_key = "${hex("server_public_key")}"\nserver_address = "127.0.0.1:${controller.port}"\n`); + + // ping as root. + // (spawned, not execFileSync: the controller runs on this event loop) + const ping = (await spawnNode([path.join(BIN, "remote.mjs"), "ping"], { cwd: rootDir }).done).stdout; + assert.match(ping, /Connected successfully! Round-trip time: [\d.]+ ms\n0 servers online \(0 cores, 0 clients\)/); + + // The worker's owner asks for access; root vouches; the token goes back. + let vouchCmd = null; + const setup = spawnNode([path.join(BIN, "remote.mjs"), "setup"], { + cwd: workerDir, + onOut: (text, child) => { + if (/Nickname \[default: [^\]]*\]: $/.test(text) && !child.sentNick) { child.sentNick = true; child.stdin.write("worker\n"); } + const m = /romdev-permuter-remote vouch (\S+)\n/.exec(text); + if (m && !vouchCmd) vouchCmd = m[1]; + }, + }); + while (!vouchCmd) await new Promise((r) => setTimeout(r, 50)); + const vouch = spawnNode([path.join(BIN, "remote.mjs"), "vouch", vouchCmd], { + cwd: rootDir, + onOut: (text, child) => { if (/Grant permuter server access to worker \(Y\/n\)\? $/.test(text) && !child.sent) { child.sent = true; child.stdin.write("y\n"); } }, + }); + const v = await vouch.done; + assert.equal(v.code, 0, v.stdout + v.stderr); + const token = /Send them the following token:\n(\S+)\n/.exec(v.stdout)[1]; + setup.child.stdin.write(token + "\n"); + const s = await setup.done; + assert.equal(s.code, 0, s.stdout + s.stderr); + assert.match(s.stdout, new RegExp(`Server: 127\\.0\\.0\\.1:${controller.port}\\nTesting connection...\\npermuter@home successfully set up!`)); + const workerConf = readFileSync(path.join(workerDir, "pah.conf"), "utf8"); + assert.match(workerConf, /secret_key = "[0-9a-f]{64}"/); + assert.doesNotMatch(workerConf, /initial_setup_nickname/); + const users = Object.values(JSON.parse(readFileSync(db, "utf8")).users).map((u) => u.name).sort(); + assert.deepEqual(users, ["root", "worker"]); + + // The worker server (its evaluator runs the WASM IDO toolchain). + let serverUp = false; + worker = spawnNode([path.join(BIN, "remote.mjs"), "run-server", "--cores", "2", "--memory", "2"], { + cwd: workerDir, onOut: (text) => { if (/Started\./.test(text)) serverUp = true; }, + }); + for (let k = 0; k < 600 && !(serverUp && logs.some((l) => /\[worker\] start server \(0\.1, 2\)/.test(l))); k++) await new Promise((r) => setTimeout(r, 50)); + assert.ok(serverUp, logs.join("\n")); + + // A permuter job whose first permutation misses and whose second matches. + const proj = path.join(rootDir, "proj"); + mkdirSync(path.join(proj, "tools", "ido", "5.3"), { recursive: true }); + const job = path.join(rootDir, "job"); + mkdirSync(job); + const compileSh = path.join(job, "compile.sh"); + writeFileSync(compileSh, `#!/usr/bin/env bash\nINPUT="$(realpath "$1")"\nOUTPUT="$(realpath "$3")"\ncd '${proj}'\n` + + `'${proj}/tools/ido/5.3/cc' -c -G 0 -non_shared -O2 -mips2 -32 "$INPUT" -o "$OUTPUT"\n`, { mode: 0o755 }); + writeFileSync(path.join(job, "target.c"), "int f(int a) {\n return a + 1;\n}\n"); + const { compileScript } = await import(toolchain); + assert.ok(await compileScript({ script: compileSh, input: path.join(job, "target.c"), output: path.join(job, "target.o") })); + writeFileSync(path.join(job, "base.c"), "int f(int a) {\n return PERM_GENERAL(a + 2, a + 1);\n}\n"); + writeFileSync(path.join(job, "settings.toml"), "func_name = \"f\"\ncompiler_type = \"ido\"\n"); + + const client = spawnNode([path.join(BIN, "permuter.mjs"), job, "-J", "--stop-on-zero"], { cwd: rootDir, timeoutMs: 120_000 }); + const c = await client.done; + if (process.env.PAH_TEST_SHOW) process.stderr.write(c.stdout); + assert.equal(c.code, 0, `${c.stdout}${c.stderr}\n--- worker:\n${worker.child.out}${worker.child.err}`); + assert.match(c.stdout, /Connecting to permuter@home\.\.\.\nConnected! 1 server online \(2 cores, 0 other clients\)/); + assert.match(c.stdout, /\[f\] base score = \d+/); + assert.match(c.stdout, /\[worker\] connected\n/, "the worker reported the job initialised"); + assert.match(c.stdout, /\[worker\] \[f\] found new best score! \(0 vs 5\)/, "the match was found by the remote worker"); + assert.match(c.stdout, /Found zero score! Exiting\./); + const outDir = readdirSync(job).find((d) => d.startsWith("output-0-")); + assert.ok(outDir, readdirSync(job).join(" ")); + assert.match(readFileSync(path.join(job, outDir, "source.c"), "utf8"), /return a \+ 1;/); + assert.ok(logs.some((l) => /\[root\] start client \(f, 1\)/.test(l)), logs.join("\n")); + + // Without --stop-on-zero the client runs the space out and still collects + // every result that was out on the network before hanging up. + const c2 = await spawnNode([path.join(BIN, "permuter.mjs"), job, "-J"], { cwd: rootDir, timeoutMs: 120_000 }).done; + assert.equal(c2.code, 0, c2.stdout + c2.stderr); + assert.match(c2.stdout, /iteration 2, 0 errors, score = \d+\n/); + assert.match(c2.stdout, /found new best score! \(0 vs 5\)/); + + // Control: a key nobody vouched for is turned away. + const strangerDir = path.join(root, "stranger"); + mkdirSync(strangerDir); + writeFileSync(path.join(strangerDir, "pah.conf"), + `secret_key = "${"ab".repeat(32)}"\nserver_public_key = "${hex("server_public_key")}"\nserver_address = "127.0.0.1:${controller.port}"\n`); + const denied = await spawnNode([path.join(BIN, "remote.mjs"), "ping"], { cwd: strangerDir }).done; + assert.equal(denied.code, 1); + assert.equal(denied.stdout, "Error: Access denied!\n"); + + // The controller counted the remote work for both users. + await new Promise((r) => setTimeout(r, 200)); + controller.state.db.flush(); + const saved = JSON.parse(readFileSync(db, "utf8")); + const byName = Object.fromEntries(Object.values(saved.users).map((u) => [u.name, u])); + assert.ok(saved.func_stats.f[0] >= 1 && saved.func_stats.f[2] >= 1, JSON.stringify(saved)); + assert.equal(saved.func_stats.f[3], 2); + assert.ok(byName.root.client_stats[2] >= 1 && byName.worker.server_stats[2] >= 1, JSON.stringify(saved)); + assert.equal(byName.worker.server_stats[3], 2); + } finally { + if (worker) { worker.child.kill("SIGINT"); await Promise.race([worker.done, new Promise((r) => setTimeout(r, 5000))]); worker.child.kill("SIGKILL"); } + await controller?.close(); + if (!existsSync(path.join(root, "keep"))) removeDir(root); + } + }); diff --git a/packages/romdev-permuter/test/scorer.test.js b/packages/romdev-permuter/test/scorer.test.js new file mode 100644 index 00000000..ae673c35 --- /dev/null +++ b/packages/romdev-permuter/test/scorer.test.js @@ -0,0 +1,131 @@ +// The scorer, checked against upstream's documented algorithm (scorer.py): +// difflib opcodes over mnemonics; on "equal" rows, +1 stack (per byte of +// sp-offset difference, with --stack-diffs), +1 branch (differing branch +// target), +5 per differing operand field (regalloc); unmatched rows become +// insertions/deletions (+100 each) unless the same row text appears on both +// sides, which counts as a reordering (+60). +// +// Fixtures are objdump -dr text as binutils prints it for MIPS, so the +// simplifier (relocation folding, hex conversion, sp masking, trailing nops) +// is exercised on the way in. A second test replays upstream's own scores on +// a local decomp corpus when one is present (see corpus.test.js). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { simplify_objdump, MIPS_SETTINGS } from "../src/objdump.js"; +import { Scorer } from "../src/scorer.js"; +import { SequenceMatcher } from "../src/difflib.js"; + +const HEAD = ["", "x.o: file format elf32-tradbigmips", "", "", "Disassembly of section .text:", "", "00000000 :"]; +const row = (addr, word, text) => `${addr.toString(16).padStart(4, " ")}:\t${word} \t${text}`; +const reloc = (addr, type, sym) => `\t\t\t${addr.toString(16)}: ${type}\t${sym}`; + +/** A scorer over already-simplified target text, bypassing ELF/objdump. */ +function scorerFor(targetLines, { stack_differences = false, ign_branch_targets = true, algorithm = "difflib" } = {}) { + const s = Object.create(Scorer.prototype); + s.algorithm = algorithm; + s.arch = MIPS_SETTINGS; + s.stack_differences = stack_differences; + s.ign_branch_targets = ign_branch_targets; + s.debug_mode = false; + s.re_sprel_search = new RegExp(MIPS_SETTINGS.re_sprel.source); + s.target_seq = simplify_objdump([...HEAD, ...targetLines], MIPS_SETTINGS, { stack_differences, ign_branch_targets }); + s.difflib_differ = new SequenceMatcher({ autojunk: false }); + s.difflib_differ.set_seq2(s.target_seq.map((l) => l.mnemonic)); + return s; +} +function score(s, candLines) { + const cand = simplify_objdump([...HEAD, ...candLines], MIPS_SETTINGS, { stack_differences: s.stack_differences, ign_branch_targets: s.ign_branch_targets }); + return { score: s.scoreLines(cand.map((l) => l.row).join("\n"), cand)[0], penalties: s.lastPenalties, cand }; +} + +const TARGET = [ + row(0, "3c040000", "lui\ta0,0x0"), reloc(0, "R_MIPS_HI16", "sym"), + row(4, "24840000", "addiu\ta0,a0,0"), reloc(4, "R_MIPS_LO16", "sym"), + row(8, "8c820000", "lw\tv0,0(a0)"), + row(12, "00451021", "addu\tv0,v0,a1"), + row(16, "03e00008", "jr\tra"), + row(20, "00000000", "nop"), + row(24, "00000000", "nop"), +]; + +test("simplify: relocations fold into the previous row; trailing nops drop", () => { + const seq = simplify_objdump([...HEAD, ...TARGET], MIPS_SETTINGS, { stack_differences: false, ign_branch_targets: true }); + assert.deepEqual(seq.map((l) => [l.row, l.has_symbol]), [ + ["lui\ta0,%hi(sym)", true], ["addiu\ta0,a0,%lo(sym)", true], ["lw\tv0,0(a0)", false], + ["addu\tv0,v0,a1", false], ["jr\tra", false], + ]); +}); + +test("identical code scores 0", () => { + assert.equal(score(scorerFor(TARGET), TARGET).score, 0); +}); + +test("one differing register field = one regalloc penalty (5)", () => { + const cand = TARGET.slice(); + cand[5] = row(12, "00451821", "addu\tv1,v0,a1"); + const r = score(scorerFor(TARGET), cand); + assert.deepEqual([r.score, r.penalties.regalloc], [5, 1]); +}); + +test("a swapped pair is one reordering (60)", () => { + const cand = TARGET.slice(); + [cand[4], cand[5]] = [row(8, "00451021", "addu\tv0,v0,a1"), row(12, "8c820000", "lw\tv0,0(a0)")]; + const r = score(scorerFor(TARGET), cand); + assert.deepEqual([r.score, r.penalties.reordering, r.penalties.insertion, r.penalties.deletion], [60, 1, 0, 0]); +}); + +test("an extra instruction is an insertion (100), a missing one a deletion (100)", () => { + const extra = TARGET.slice(); + extra.splice(6, 0, row(16, "00801821", "move\tv1,a0")); + assert.deepEqual([score(scorerFor(TARGET), extra).score, score(scorerFor(TARGET), extra).penalties.insertion], [100, 1]); + const missing = TARGET.slice(); + missing.splice(5, 1); + assert.deepEqual([score(scorerFor(TARGET), missing).score, score(scorerFor(TARGET), missing).penalties.deletion], [100, 1]); +}); + +test("branch targets: ignored by default, +1 with --no-ignore-branch-targets", () => { + const t = [row(0, "10800003", "beqz\ta0,10 "), row(4, "00000000", "nop"), row(8, "03e00008", "jr\tra")]; + const c = [row(0, "10800004", "beqz\ta0,14 "), row(4, "00000000", "nop"), row(8, "03e00008", "jr\tra")]; + assert.equal(score(scorerFor(t), c).score, 0); + const s = scorerFor(t, { ign_branch_targets: false }); + const r = score(s, c); + assert.deepEqual([r.score, r.penalties.branch, r.penalties.regalloc], [1, 1, 0]); +}); + +test("stack offsets: masked by default, |delta| with --stack-diffs", () => { + const t = [row(0, "8fa40010", "lw\ta0,16(sp)"), row(4, "03e00008", "jr\tra")]; + const c = [row(0, "8fa40018", "lw\ta0,24(sp)"), row(4, "03e00008", "jr\tra")]; + assert.equal(score(scorerFor(t), c).score, 0); + const r = score(scorerFor(t, { stack_differences: true }), c); + assert.deepEqual([r.score, r.penalties.stack], [8, 8]); +}); + +test("a section-relative relocation matches any symbol the target relocated", () => { + const t = [row(0, "3c040000", "lui\ta0,0x0"), reloc(0, "R_MIPS_HI16", "sym"), row(4, "8c820000", "lw\tv0,0(a0)"), reloc(4, "R_MIPS_LO16", "sym")]; + const c = [row(0, "3c040000", "lui\ta0,0x0"), reloc(0, "R_MIPS_HI16", ".bss"), row(4, "8c820010", "lw\tv0,16(a0)"), reloc(4, "R_MIPS_LO16", ".bss")]; + const r = score(scorerFor(t), c); + assert.deepEqual(r.cand.map((l) => l.row), ["lui\ta0,%hi(.bss)", "lw\tv0,%lo(.bss+0x10)(a0)"]); + assert.equal(r.score, 0); +}); + +test("decimal immediates become hex unless glued to a letter; addiu on sp becomes imm", () => { + const seq = simplify_objdump([...HEAD, row(0, "27bdffe8", "addiu\tsp,sp,-24"), row(4, "24420010", "addiu\tv0,v0,16"), + row(8, "8c820000", "lw\tv0,0(a0)")], MIPS_SETTINGS, { stack_differences: false, ign_branch_targets: true }); + assert.deepEqual(seq.map((l) => l.row), ["addiu\tsp,sp,imm", "addiu\tv0,v0,0x10", "lw\tv0,0(a0)"]); +}); + +test("--algorithm levenshtein: rows come from Levenshtein.opcodes over remapped mnemonics", async () => { + const { opcodes } = await import("../src/levenshtein.js"); + const cand = TARGET.slice(); + [cand[4], cand[5]] = [row(8, "00451021", "addu\tv0,v0,a1"), row(12, "8c820000", "lw\tv0,0(a0)")]; + const lev = score(scorerFor(TARGET, { algorithm: "levenshtein" }), cand); + const t = ["lui", "addiu", "lw", "addu", "jr"], c = ["lui", "addiu", "addu", "lw", "jr"]; + const ids = new Map(); + const remap = (xs) => xs.map((m) => (ids.has(m) ? ids.get(m) : (ids.set(m, ids.size), ids.size - 1))); + const ops = opcodes(remap(c), remap(t)); + // Every non-equal row is paired across the swap, so all of them are reorderings. + const changed = ops.filter((o) => o[0] !== "equal").reduce((n, [, i1, i2]) => n + (i2 - i1), 0); + assert.equal(lev.penalties.reordering, changed); + assert.equal(lev.score, 60 * changed); + assert.equal(score(scorerFor(TARGET, { algorithm: "levenshtein" }), TARGET).score, 0); +}); diff --git a/packages/romdev-permuter/test/seed.test.js b/packages/romdev-permuter/test/seed.test.js new file mode 100644 index 00000000..fb55ffec --- /dev/null +++ b/packages/romdev-permuter/test/seed.test.js @@ -0,0 +1,95 @@ +// Seeding: `--seed [permIndex,]rngSeed` must replay the same candidates, and +// the candidate a seed denotes is the one Candidate.from_source + repeated +// randomize_ast produces for that rng seed (upstream keeps randomizing the +// same candidate when the rng seed is forced). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { writeFileSync, copyFileSync, readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { run } from "../src/main.js"; +import { Compiler } from "../src/compiler.js"; +import { Scorer } from "../src/scorer.js"; +import { Candidate } from "../src/candidate.js"; +import { EvalState } from "../src/perm/perm.js"; +import { perm_parse } from "../src/perm/parse.js"; +import { perm_evaluate_one } from "../src/perm/eval.js"; +import { get_default_randomization_weights, parseToml, get_settings } from "../src/helpers.js"; +import { wasmGccCompile } from "./helpers/wasm-gcc.js"; +import { MIPS_GCC_SCORER } from "./helpers/payloads.js"; +import { workDir, removeDir } from "./helpers/work.js"; + +const INTRO = "int a, b, c; int f(int x) {"; +const BASE = `${INTRO}\n a = x * 3;\n b = a + x;\n c = b << 2;\n return a + b + c;\n}\n`; + +async function setup() { + const dir = workDir("seed"); + writeFileSync(path.join(dir, "base.c"), BASE); + writeFileSync(path.join(dir, "settings.toml"), "func_name = \"f\"\ncompiler_type = \"gcc\"\n"); + const c = new Compiler(null, { tmpDir: path.join(dir, ".cc"), compileFn: wasmGccCompile }); + const t = await c.compile(`${INTRO}\n b = x * 4;\n a = x * 3;\n c = b << 2;\n return a + b + c;\n}\n`); + copyFileSync(t, path.join(dir, "target.o")); + return dir; +} + +async function seededRun(dir, seed, iterations) { + const ac = new AbortController(); + const scores = []; + await run({ directories: [dir], force_seed: seed, compileFn: wasmGccCompile, signal: ac.signal, quiet: true, out: () => {}, + onResult: (r) => { scores.push(r.score); if (r.iteration >= iterations) ac.abort(); } }); + const outs = readdirSync(dir).filter((d) => d.startsWith("output-")).sort() + .map((d) => readFileSync(path.join(dir, d, "source.c"), "utf8")); + return { scores, outs }; +} + +test("a forced seed replays the same scores and outputs", { skip: MIPS_GCC_SCORER }, async () => { + const d1 = await setup(), d2 = await setup(); + try { + const a = await seededRun(d1, "0,4242", 12); + const b = await seededRun(d2, "0,4242", 12); + assert.equal(a.scores.length, 12); + assert.deepEqual(a.scores, b.scores); + assert.deepEqual(a.outs, b.outs); + } finally { + removeDir(d1); + removeDir(d2); + } +}); + +test("the forced rng seed denotes Candidate.from_source + randomize_ast", { skip: MIPS_GCC_SCORER }, async () => { + const dir = await setup(); + try { + const weights = get_default_randomization_weights("gcc"); + const [text, st] = perm_evaluate_one(perm_parse(BASE, () => {})); + const cand = Candidate.from_source(text, st, "f", weights, 777n); + const expected = []; + for (let i = 0; i < 6; i++) { cand.randomize_ast(); expected.push(cand.get_source()); } + // Score each step of the chain directly; the seeded run must report exactly these scores. + const scorer = await Scorer.create({ target_o: path.join(dir, "target.o"), stack_differences: false, algorithm: "difflib", + debug_mode: false, ign_branch_targets: true, objdump_command: null }); + const compiler = new Compiler(null, { tmpDir: path.join(dir, ".cc2"), compileFn: wasmGccCompile }); + const want = []; + for (const src of expected) want.push((await scorer.score(await compiler.compile(src)))[0]); + const { scores, outs } = await seededRun(dir, "777", 6); + assert.deepEqual(scores, want); + for (const o of outs) assert.ok(expected.includes(o), "output not in the seed's randomization chain"); + } finally { + removeDir(dir); + } +}); + +test("settings and default weights: TOML subset and compiler_type merge", () => { + const w = get_default_randomization_weights("ido"); + assert.equal(w.perm_inline, 0); + assert.equal(w.perm_temp_for_expr, 100); + assert.equal(w.perm_alias_array, 0.5); + assert.equal(Object.keys(w).length, 35); + const t = parseToml("func_name = \"f\" # x\ncompiler_type = 'ido'\n[weight_overrides]\nperm_sameline = 2\nperm_inline = 0.5\n"); + assert.equal(t.func_name, "f"); + assert.deepEqual(t.weight_overrides, { perm_sameline: { int: 2 }, perm_inline: 0.5 }); + const dir = workDir("settings"); + try { + writeFileSync(path.join(dir, "settings.toml"), "func_name = \"g\"\n"); + assert.equal(get_settings(dir).func_name, "g"); + } finally { removeDir(dir); } + void EvalState; +}); diff --git a/packages/romdev-platform-atari2600/README.md b/packages/romdev-platform-atari2600/README.md index 28d125bf..fc2f9bbc 100644 --- a/packages/romdev-platform-atari2600/README.md +++ b/packages/romdev-platform-atari2600/README.md @@ -2,19 +2,21 @@ Atari 2600 bundle: stella2014 emulator core + dasm assembler, as WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **stella2014, dasm**. +Bundles: **stella2014** (https://github.com/libretro/stella2014-libretro) and **dasm** (https://github.com/dasm-assembler/dasm). **License:** GPL-2.0-or-later (stella2014 GPL-2.0, dasm GPL-2.0). -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-stella2014.sh + build-dasm.sh` + patch(es) `stella2014-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-stella2014.sh` and `build-dasm.sh` with patch(es) `stella2014-romdev-memory-regions.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-platform-atari2600/package.json b/packages/romdev-platform-atari2600/package.json index 77a58fa7..a4fc562e 100644 --- a/packages/romdev-platform-atari2600/package.json +++ b/packages/romdev-platform-atari2600/package.json @@ -1,6 +1,6 @@ { "name": "romdev-platform-atari2600", - "version": "0.10.1", + "version": "0.10.2", "description": "Atari 2600 binaries for romdev: stella2014 emulator core + dasm assembler (WASM). Atari 2600 uses both only here, so they ship together.", "type": "module", "main": "index.js", diff --git a/packages/romdev-platform-gba/README.md b/packages/romdev-platform-gba/README.md index b474da9b..f7eb3be4 100644 --- a/packages/romdev-platform-gba/README.md +++ b/packages/romdev-platform-gba/README.md @@ -1,38 +1,54 @@ # romdev-platform-gba -Game Boy Advance bundle: mGBA emulator core + arm-none-eabi-gcc toolchain -(cc1/as/ld/objcopy/objdump) - the objdump also powers ARM/Thumb `disassembleRom` + -byte-exact `disassembleProject` - as WebAssembly. Plus the GBA C library tree -(`share/gba/lib/`: libtonc, libgba, maxmod, sysbase, crt0s, ld scripts, ARM -target archives) and the full C build pipeline: +Game Boy Advance bundle, as WebAssembly: the mGBA emulator core and the +arm-none-eabi-gcc toolchain (`cc1`, `as`, `ld`, `objcopy`, `objdump`). The +objdump also serves ARM/Thumb disassembly for `disasm({target:'rom'})` and +byte-exact `disasm({target:'project'})`. The package also carries the GBA C +library tree (`share/gba/lib/`: libtonc, libgba, maxmod, sysbase, crt0s, linker +scripts, ARM target archives) and the C build pipeline: ```js import { buildGbaC, parseBuildLog } from "romdev-platform-gba"; const r = await buildGbaC({ source: '#include \nint main(){ ... }' }); -// r.binary is a hardware-valid .gba ROM; r.log / parseBuildLog(r.log) for issues +// r.binary is a .gba ROM; r.log (or parseBuildLog(r.log)) lists any issues ``` -One dep compiles everything for the target - an SDK or tool building GBA ROMs -needs only this package (romdev's own server builds through the same entry, so -there is exactly one pipeline). `buildGbaC` also accepts an injected `env` -(runTool / share manifest / hash / sdkCache) so the identical pipeline runs in -a browser Web Worker - see `build/gba-c/gba-c.js` for the contract. - -A binary package for [romdev](https://github.com/monteslu/romdev): it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. Install `romdev` for the full dev suite, or this package alone for the -build pipeline. - -## Upstream & license - -Bundles: **mGBA, arm-none-eabi-gcc**. - -**License:** mGBA: MPL-2.0. arm-none-eabi-gcc/binutils: GPL-3.0 with GCC Runtime Library Exception (does not encumber compiled ROMs). - -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. - -**Built by:** `romdevtools/scripts/build-mgba.sh + build-arm-wasm-tools.sh` + patch(es) `mgba-romdev-watchpoint.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +An SDK or tool that builds GBA ROMs needs only this package; romdevtools' +`build({platform:'gba'})` goes through the same entry point. `buildGbaC` also +accepts an injected `env` (runTool, share manifest, hash, sdkCache) so the same +pipeline runs in a browser Web Worker; see `build/gba-c/gba-c.js` for the +contract. + +A binary package for [romdev](https://github.com/monteslu/romdev). The main +`romdevtools` package loads it on demand. Install `romdevtools` +(`npx romdevtools`) for the full tool set, or this package alone for the build +pipeline. + +## Upstream and license + +Bundles: **mGBA** (https://github.com/libretro/mgba) and **arm-none-eabi gcc +14.2.0 with binutils 2.42 and newlib 4.4.0**. + +**License:** + +- mGBA: MPL-2.0 (the package's `license` field). +- gcc and binutils: GPL-3.0-or-later. libgcc carries the GCC Runtime Library + Exception, and newlib uses BSD-style licences, so linking them does not place + conditions on a compiled ROM. +- Libraries in `share/gba/lib/` keep their own licences: libgba (LGPL with a + static-linking exception; it asks that a program credit the devkitPro + project; `libgba/LICENSE`), maxmod (ISC, `maxmod/LICENSE-MAXMOD`), the + devkitPro crt0 (MPL-2.0) and libtonc (MIT, `libtonc/LICENSE`; the upstream + release has no licence file, and the author confirmed MIT to the gbadev-org + fork, which added this one). + +This package redistributes the upstream source built to WebAssembly. The +upstream versions are pinned in `packages/romdevtools/scripts/versions.json` in +the romdev repo, and the repo's `NOTICE` has the full third-party inventory. + +**Built by:** `packages/romdevtools/scripts/build-mgba.sh` (patch +`mgba-romdev-watchpoint.patch`) and `build-arm-wasm-tools.sh` (toolchain built +by `build-arm-toolchain.sh`). See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-platform-gba/build/_worker/pool.js b/packages/romdev-platform-gba/build/_worker/pool.js index 8c204f53..95066dee 100644 --- a/packages/romdev-platform-gba/build/_worker/pool.js +++ b/packages/romdev-platform-gba/build/_worker/pool.js @@ -9,7 +9,7 @@ // gets a fresh one. // // This is the chokepoint that gives MCP the "one bad build can't kill -// the server" property requested in Round 11 feedback. +// the server" property. import { fork } from "node:child_process"; import os from "node:os"; diff --git a/packages/romdev-platform-gba/build/_worker/wasm-worker.js b/packages/romdev-platform-gba/build/_worker/wasm-worker.js index c62361da..04d6125b 100644 --- a/packages/romdev-platform-gba/build/_worker/wasm-worker.js +++ b/packages/romdev-platform-gba/build/_worker/wasm-worker.js @@ -223,7 +223,14 @@ process.on("message", async (msg) => { return; } if (msg.type === "run") { - const result = await runJob(msg.job); + // A job may name a handler module that runs it instead of the single- + // tool MEMFS path above (the decomp domain's NODERAWFS toolchains: IDO's + // cc spawning its passes as sibling modules, binutils over a real tree). + // It still runs HERE, in the isolated worker, so an abort cannot reach + // the server. + const result = msg.job.handler + ? await (await import(msg.job.handler)).runWorkerJob(msg.job) + : await runJob(msg.job); process.send({ type: "result", id: msg.id, result }); // After every job, signal ready again so the pool can recycle us. process.send({ type: "ready" }); diff --git a/packages/romdev-platform-gba/build/common/io.js b/packages/romdev-platform-gba/build/common/io.js index e10abf1d..431dee00 100644 --- a/packages/romdev-platform-gba/build/common/io.js +++ b/packages/romdev-platform-gba/build/common/io.js @@ -31,7 +31,7 @@ function bytesToBase64(u8) { /** Convert binary (Uint8Array / Buffer / base64 string) → InputFile spec. */ export function binaryFile(vfsPath, bytes) { // Accept EITHER raw bytes OR a base64 STRING - the same either/or contract the - // toolchain wrappers honor individually (asar/cc65/vasm68k/wladx all guard with + // toolchain wrappers honor individually (asar/cc65/wladx all guard with // `x instanceof Uint8Array ? x : Buffer.from(x, "base64")`). The MCP // `binaryIncludes` schema delivers base64 STRINGS; decoding them as UTF-8 (the // old bug) made the base64 TEXT itself the file bytes - .incbin then embedded diff --git a/packages/romdev-platform-gba/build/common/share-fs.js b/packages/romdev-platform-gba/build/common/share-fs.js index 41cb735d..cbf5f950 100644 --- a/packages/romdev-platform-gba/build/common/share-fs.js +++ b/packages/romdev-platform-gba/build/common/share-fs.js @@ -14,7 +14,7 @@ // rel paths always use "/" and are relative to the share LIB root (e.g. // "libtonc/gba_crt0.s", "sgdk/md.ld"). // -// ⚠ ORDER MATTERS: list() order feeds SDK compile order → ar member order → +// ORDER MATTERS: list() order feeds SDK compile order → ar member order → // ROM bytes, and the sdk-cache hash keys. dirShare preserves the readdir // walk order the drivers always used; buildShareManifest() materializes a // manifest with the SAME walk, so a browser host that stages its manifest diff --git a/packages/romdev-platform-gba/build/common/wasm-tool.js b/packages/romdev-platform-gba/build/common/wasm-tool.js index 27fdd400..bf8178b1 100644 --- a/packages/romdev-platform-gba/build/common/wasm-tool.js +++ b/packages/romdev-platform-gba/build/common/wasm-tool.js @@ -19,7 +19,7 @@ import path from "node:path"; /** * Resolve a single tool glue FILE from its package, falling back to a local * in-tree copy. This is the arm/m68k/mips/sh-gcc + asar + wladx + rgbds + dasm + - * vasm68k + sjasm + tcc816 shape (one .js/.mjs glue per tool). + * sjasm + tcc816 shape (one .js/.mjs glue per tool). * * @param {Object} a * @param {string} a.pkg npm package the glue ships in (e.g. "romdev-platform-gba") diff --git a/packages/romdev-platform-gba/build/gba-c/gba-c.js b/packages/romdev-platform-gba/build/gba-c/gba-c.js index 4db3c1a6..624b3af4 100644 --- a/packages/romdev-platform-gba/build/gba-c/gba-c.js +++ b/packages/romdev-platform-gba/build/gba-c/gba-c.js @@ -6,7 +6,7 @@ // ld.wasm - link user .o + gba_crt0.o + libgba.a + libgcc → .elf // objcopy.wasm - strip ELF down to raw .gba ROM // -// Each WASM tool runs in a fresh worker (R12 subprocess isolation), so +// Each WASM tool runs in a fresh worker (subprocess isolation), so // a crash in one stage doesn't take out the server. // // ENV INJECTION (0.95.0, browser IDEs): pass `env` to run the identical @@ -114,18 +114,18 @@ async function buildCtx(env) { * `tte_init_chr4c`, `tte_write`, `tte_printf`, `tonccpy`, * `REG_DISPCNT`, the canonical Tonc API every published GBA * tutorial uses. Caveat: tte_iohook (iprintf auto-routing) is - * excluded - use `tte_printf` directly instead. R28. + * excluded - use `tte_printf` directly instead. * * runtime: "libgba" - devkitPro's libgba SDK. Different API * surface (`SetMode`, `oamSet`, etc.), more "thin wrapper over * hardware registers" style. Same iprintf caveat (console.c - * excluded). R24. + * excluded). * * runtime: "none" - minimum-viable. Bare gcc + newlib only. User * writes against raw GBA hardware registers. Smallest binaries. * * Legacy `libgba: true | false` arg still accepted for back-compat - * with R24 (true → libgba, false → none). If both `runtime` and + * (true → libgba, false → none). If both `runtime` and * `libgba` are present, `runtime` wins. * * @param {Object} args diff --git a/packages/romdev-platform-gba/build/parse-errors.js b/packages/romdev-platform-gba/build/parse-errors.js index ab9d8dd2..12520d35 100644 --- a/packages/romdev-platform-gba/build/parse-errors.js +++ b/packages/romdev-platform-gba/build/parse-errors.js @@ -41,8 +41,12 @@ export function parseBuildLog(log) { issues.push(...parseAsar(text)); } else if (/^rgbasm$|^rgblink$|^rgbfix$/.test(baseStage)) { issues.push(...parseRgbds(text, baseStage)); - } else if (/^vasm/.test(baseStage)) { - issues.push(...parseVasm(text)); + } else if (baseStage === "m68k-as") { + // Genesis assembly (Motorola syntax through GNU as): every diagnostic is + // already "file:line: error|warning: message" against the source line, + // plus a few location-less "error: message" lines from the link. + issues.push(...parseCc65Like(text, baseStage)); + issues.push(...parseBareSeverity(text, baseStage)); } else if (/^sdcc$|^sdasz80$|^sdasgb$|^sdld$|^mcpp$/.test(baseStage)) { // SDCC family: sdcc / sdasz80 / sdasgb / sdld / mcpp. Some diagnostics use // the cc65-style `file:line: Error: msg`; SDCC's frontend ALSO emits a @@ -65,10 +69,9 @@ export function parseBuildLog(log) { // Tag everything with the (possibly empty) actual stage name so an // assembler error doesn't mistakenly report as "asar" on a non-SNES // build. - // Try EVERY parser - some toolchains (vasm genesis-asm) emit no - // "--- stage ---" marker, so the whole log lands here unnamed; if we skip - // a parser the error is silently swallowed (issues[] empty on a real - // failure). Include vasm + sdcc + wla, which the old fallback omitted. + // Try EVERY parser - a toolchain that emits no "--- stage ---" marker + // lands here unnamed; if we skip a parser the error is silently + // swallowed (issues[] empty on a real failure). const tag = baseStage || "unknown"; issues.push(...parseCc65Like(text, tag)); issues.push(...parseLd65Linker(text, tag)); @@ -76,7 +79,6 @@ export function parseBuildLog(log) { issues.push(...parseDasm(text)); issues.push(...parseAsar(text, tag)); issues.push(...parseRgbds(text, tag)); - issues.push(...parseVasm(text)); issues.push(...parseWla(text, tag)); issues.push(...parseGnuToolchain(text, tag)); } @@ -89,7 +91,7 @@ export function parseBuildLog(log) { // banners (wlalink prints a 26k-line dump full of them) from being mistaken // for our markers and splitting the real error away from its stage. const KNOWN_STAGE_RE = - /^(cc65|ca65|ld65|dasm|asar|rgbasm|rgblink|rgbfix|vasm|sdcc|sdasz80|sdasgb|sdld|mcpp|tcc-65816|wla-65816|wla|wlalink|wladx|gcc|cc1|as|ld|objcopy|m68k|sjasm|bintos|tcc)\b/i; + /^(cc65|ca65|ld65|dasm|asar|rgbasm|rgblink|rgbfix|m68k-as|sdcc|sdasz80|sdasgb|sdld|mcpp|tcc-65816|wla-65816|wla|wlalink|wladx|gcc|cc1|as|ld|objcopy|m68k|sjasm|bintos|tcc)\b/i; function splitByStage(log) { // Markers like "--- ca65 ---" OR with parenthesized args like @@ -425,23 +427,15 @@ function parseWla(text, stage = "wla") { return out; } -// vasm example: -// error 22 in line 5 of "/work/main.s": ... -// warning 1003 in line 8 of "main.s": ... -// fatal error 13 in line 1 of "/work/main.s": could not open for input -// (← a MISSING incbin asset: the #1 thing an agent forgets to pass) -function parseVasm(text) { +// Location-less diagnostics: a line that is just "error: message" or +// "warning: message" (the m68k-as link stage reports overlapping org blocks +// this way). +function parseBareSeverity(text, stage) { const out = []; - const re = /^(?fatal error|error|warning)\s+\d+\s+in\s+line\s+(?\d+)\s+of\s+"(?[^"]+)":\s*(?.+)$/gm; + const re = /^(?error|warning): (?.+)$/gm; let m; while ((m = re.exec(text))) { - out.push({ - severity: m.groups.sev === "warning" ? "warning" : "error", - file: m.groups.file, - line: parseInt(m.groups.line, 10), - message: m.groups.msg.trim(), - stage: "vasm", - }); + out.push({ severity: m.groups.sev, message: m.groups.msg.trim(), stage }); } return out; } diff --git a/packages/romdev-platform-gba/package.json b/packages/romdev-platform-gba/package.json index 7a3f93c3..84bff669 100644 --- a/packages/romdev-platform-gba/package.json +++ b/packages/romdev-platform-gba/package.json @@ -1,6 +1,6 @@ { "name": "romdev-platform-gba", - "version": "0.14.0", + "version": "0.14.1", "description": "Game Boy Advance binaries + C library tree for romdev: mGBA emulator core + arm-none-eabi-gcc toolchain (cc1 / as / ld / objcopy / objdump) + the GBA C library share/ tree (libtonc, libgba, maxmod, sysbase, crt0, ldscripts). WASM. Single-consumer: the GBA platform.", "type": "module", "main": "index.js", @@ -20,7 +20,7 @@ "engines": { "node": ">=24" }, - "license": "MPL-2.0", + "license": "SEE LICENSE IN README.md", "repository": { "type": "git", "url": "git+https://github.com/monteslu/romdev.git", diff --git a/packages/romdev-platform-gba/share/gba/lib/arm-archives/libc.a b/packages/romdev-platform-gba/share/gba/lib/arm-archives/libc.a index 7a7730c8..426aa2b2 100644 Binary files a/packages/romdev-platform-gba/share/gba/lib/arm-archives/libc.a and b/packages/romdev-platform-gba/share/gba/lib/arm-archives/libc.a differ diff --git a/packages/romdev-platform-gba/share/gba/lib/libgba/LICENSE b/packages/romdev-platform-gba/share/gba/lib/libgba/LICENSE new file mode 100644 index 00000000..21d68601 --- /dev/null +++ b/packages/romdev-platform-gba/share/gba/lib/libgba/LICENSE @@ -0,0 +1,165 @@ +libgba License Agreement + +August 7, 2004 + +The libgba library and included programs are provided under the terms of the GNU Library General Public License (LGPL) with the following exceptions: + +1. Modifications to the build scripts and makefiles by themselves to support a specific platform do not constitute a modified or derivative work. + +The authors do request that such modifications be contributed to the devkitpro project - please submit contributions at http://sourceforge.net/tracker/?group_id=114505&atid=668553 or mail the project manager wntrmute@users.sourceforge.net. + +2. Static linking of applications to the libgba library does not constitute a derivative work and does not require the author to provide source code for the application or link their applications against a user-supplied version of libgba. + +If you link the application to a modified version of libgba, then the changes must be provided under the terms of the LGPL in sections 1, 2, and 4. + +3. You do not have to provide a copy of the libgba license with programs that are linked to the libgba library, nor do you have to identify the libgba license in your program or documentation as required by section 6 of the LGPL. + +However, programs must still identify their use of libgba. The following example statement can be included in user documentation to satisfy this requirement: + +program/work] is based in part on the work of the devkitpro project (http://sourceforge.net/projects/devkitpro). + +GNU LIBRARY GENERAL PUBLIC LICENSE + +Version 2, June 1991 + +Copyright (C) 1991 Free Software Foundation, Inc. +59 Temple Place - Suite 330, Boston, MA 02111-1307, USA +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. + +Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. + +The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. + +Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. + +However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. + +Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + 1. The modified work must itself be a software library. + + 2. You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + 3. You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + 4. If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + + (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + 1. Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + 2. Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + 3. If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + 4. Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + 1. Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + 2. Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/packages/romdev-platform-gba/share/gba/lib/libgba/libgba.seed.a b/packages/romdev-platform-gba/share/gba/lib/libgba/libgba.seed.a index 005f8c25..5035c20d 100644 Binary files a/packages/romdev-platform-gba/share/gba/lib/libgba/libgba.seed.a and b/packages/romdev-platform-gba/share/gba/lib/libgba/libgba.seed.a differ diff --git a/packages/romdev-platform-gba/share/gba/lib/libtonc/LICENSE b/packages/romdev-platform-gba/share/gba/lib/libtonc/LICENSE new file mode 100644 index 00000000..c2526133 --- /dev/null +++ b/packages/romdev-platform-gba/share/gba/lib/libtonc/LICENSE @@ -0,0 +1,18 @@ +Copyright 2005-2009 J Vijn + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/romdev-platform-gba/share/gba/lib/libtonc/libtonc.seed.a b/packages/romdev-platform-gba/share/gba/lib/libtonc/libtonc.seed.a index 94dbe7f4..772fb027 100644 Binary files a/packages/romdev-platform-gba/share/gba/lib/libtonc/libtonc.seed.a and b/packages/romdev-platform-gba/share/gba/lib/libtonc/libtonc.seed.a differ diff --git a/packages/romdev-platform-snes/README.md b/packages/romdev-platform-snes/README.md index e1a0df99..81c8e2b9 100644 --- a/packages/romdev-platform-snes/README.md +++ b/packages/romdev-platform-snes/README.md @@ -1,20 +1,47 @@ # romdev-platform-snes -SNES bundle: snes9x emulator core + asar / tcc816 / wla-dx assemblers, as WebAssembly. +SNES bundle, as WebAssembly: the snes9x emulator core, the asar assembler, the +tcc816 C compiler and the wla-dx assembler and linker (wla-65816, wlalink). -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **snes9x, asar, tcc816, wla-dx**. +Bundles: **snes9x** (https://github.com/libretro/snes9x), **asar** +(https://github.com/RPGHacker/asar), **tcc816** (https://github.com/alekmaul/tcc) +and **wla-dx** (https://github.com/vhelin/wla-dx). -**License:** snes9x: NON-COMMERCIAL (snes9x custom license) - free for non-commercial use; redistribution for profit is not permitted. asar: LGPL-3.0. tcc816: LGPL-2.1. wla-dx: GPL-2.0. +**License:** snes9x: the snes9x license (non-commercial): free for +non-commercial use; redistribution for profit is not permitted. asar: LGPL-3.0. +tcc816: LGPL-2.1. wla-dx: GPL-2.0. -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +The snes9x core also links ares's ST011 / ST018 chip code (ares's +uPD96050 and ARM cores and romdev's driver for them, `snes9x-ares-chips.patch`; +used only when st011.rom / st018.rom is in the system directory). That code is +ISC (ares: Copyright (c) 2004-2025 ares team, Near et al), a permissive +license that only asks for its notice to be kept; the notice is in the romdev +repo `NOTICE`. It adds no condition to snes9x's own license. -**Built by:** `romdevtools/scripts/build-snes9x.sh + build-asar.sh + build-tcc816.sh + build-wladx.sh` + patch(es) `snes9x-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**The snes9x core carries no Nintendo boot ROM or chip data.** Its SPC700 boot +ROM (the 64-byte IPL) is romdev's own, a clean-room reimplementation of the +upload protocol (MIT, `scripts/spc700-ipl/` in romdevtools), in place of the +one upstream embeds. The DSP-1, DSP-3 and ST010 data ROM tables upstream +embeds are emptied at build time; a cart with one of those chips needs the +user's copy of the chip's data ROM in the system directory (`dsp1b.data.rom`, +2048 bytes, the DSP-1B's, which snes9x uses for every DSP-1 cart, or +`dsp1b.rom`, 8192; `dsp3.data.rom` or `dsp3.rom`; `st010.data.rom`, 4096 +bytes, or `st010.rom`) and is refused with the file named without it +(`loadMedia({firmware})` copies a file there). + +This package redistributes the upstream source built to WebAssembly. The +upstream versions are pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. + +**Built by:** `packages/romdevtools/scripts/build-snes9x.sh`, `build-asar.sh`, `build-tcc816.sh` and `build-wladx.sh`, +with patches `snes9x-romdev-memory-regions.patch` and `snes9x-ares-chips.patch`, +`snes9x-romdev-hle-data.patch` (ares is fetched by `fetch-ares.sh` and patched with `ares-romdev.patch`). See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-platform-snes/package.json b/packages/romdev-platform-snes/package.json index 873bdfb8..c1696934 100644 --- a/packages/romdev-platform-snes/package.json +++ b/packages/romdev-platform-snes/package.json @@ -1,6 +1,6 @@ { "name": "romdev-platform-snes", - "version": "0.12.1", + "version": "0.12.2", "description": "SNES binaries for romdev: snes9x emulator core + asar / tcc816 / wla-dx (wla-65816 + wlalink) toolchains (WASM). These ship together because nothing else uses them.", "type": "module", "main": "index.js", diff --git a/packages/romdev-platform-sync32/README.md b/packages/romdev-platform-sync32/README.md index 2c27af9b..f91465c5 100644 --- a/packages/romdev-platform-sync32/README.md +++ b/packages/romdev-platform-sync32/README.md @@ -1,29 +1,37 @@ # romdev-platform-sync32 The **sync32** SDK tree for [romdev](https://github.com/monteslu/romdev): -`crt0.S`, the `ram.ld` / `xip.ld` linker scripts, and `sync32.h`. +`crt0.S`, the `ram.ld` / `xip.ld` linker scripts, `sync32.h` and an ARMv8-M +`libgcc.a`. -sync32 is monteslu's RP2350 console. A game is a freestanding **Cortex-M33** -binary wrapped in a 64-byte header (`.s32`). Building one needs the crt0 (vector -table + `_start`), the linker script for the memory mode, and the console API -header - all small, all text, so they ship here instead of requiring a checkout -of the SDK next door. +sync32 is an open RP2350-based console. A game is a freestanding +**Cortex-M33** binary wrapped in a 64-byte header (`.s32`). Building one needs +the crt0 (vector table and `_start`), the linker script for the memory mode, +and the console API header. All of them are small text files, so they ship here +instead of requiring a checkout of the SDK. + +`sync32.h` defines three video modes, chosen in the cart header: 320x240 (4:3), +320x180 (16:9 letterbox) and 128x128 (shown at 3x, for 128x128 +fantasy-console games). Every mode draws 8-bit indices into a 256-entry RGB565 +palette. The **compiler is not in this package.** sync32 carts are built with the WASM -`arm-none-eabi` toolchain already shipped in `romdev-platform-gba` - the same -gcc, asked for `-mcpu=cortex-m33 -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16` -instead of the GBA's ARM7TDMI flags. That is why this package is ~1.2MB (almost -all of it libgcc) rather than the 155MB the compiler itself weighs. +`arm-none-eabi` toolchain in `romdev-platform-gba`, the same gcc, run with +`-mcpu=cortex-m33 -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16` instead of the +GBA's ARM7TDMI flags. That is why this package is about 1.2MB (almost all of it +libgcc) rather than the size of the compiler itself. romdevtools drives it for +`build({platform:'sync32'})`; you normally install `romdevtools` +(`npx romdevtools`). -A cart links **no libc** - the SDK is freestanding, so there is no `printf`, no -`malloc`, no `string.h`. It does link **libgcc**, which ships here as -`share/sync32/lib/libgcc.a`: the compiler emits calls into it for things the -CPU cannot do in one instruction, such as a 64-bit divide (`__aeabi_uldivmod`) -or double-precision float. It must be the **ARMv8-M** build - the ARM archives -in `romdev-platform-gba` are ARMv4T and are link-incompatible with a Cortex-M33 -object - and it is built by `romdevtools/scripts/build-arm-libgcc-v8m.sh`. +A cart links **no libc**: the SDK is freestanding, so there is no `printf`, no +`malloc` and no `string.h`. It does link **libgcc**, shipped here as +`share/sync32/lib/libgcc.a`: the compiler emits calls into it for operations +the CPU cannot do in one instruction, such as a 64-bit divide +(`__aeabi_uldivmod`) or double-precision float. It must be the **ARMv8-M** +build: the ARM archives in `romdev-platform-gba` are ARMv4T and cannot link with +a Cortex-M33 object. -Two consequences worth knowing when writing a cart: +Two consequences when writing a cart: - **Prefer `float` to `double`.** The FPU is single-precision only (`fpv5-sp-d16`), so a `double` compiles to soft-float library calls that are @@ -32,5 +40,15 @@ Two consequences worth knowing when writing a cart: library call, not an instruction. Builds also pass `-ffreestanding`. Without it the compiler assumes a hosted -environment and may synthesize a `memset` call from a struct initializer, which -then cannot link. +environment and may turn a struct initializer into a `memset` call, which then +cannot link. + +## License + +- The SDK files (`crt0.S`, linker scripts, `sync32.h`): MIT (the package's + `license` field). +- `libgcc.a`: GPL-3.0-or-later with the GCC Runtime Library Exception, so + linking it does not place conditions on a compiled cart. + +**Built by:** `packages/romdevtools/scripts/build-arm-libgcc-v8m.sh` (the +libgcc build) in the romdev repo. diff --git a/packages/romdev-platform-sync32/package.json b/packages/romdev-platform-sync32/package.json index ec4cde75..2fff92c2 100644 --- a/packages/romdev-platform-sync32/package.json +++ b/packages/romdev-platform-sync32/package.json @@ -1,6 +1,6 @@ { "name": "romdev-platform-sync32", - "version": "0.2.1", + "version": "0.2.2", "description": "sync32 SDK tree for romdev: crt0, ram/xip linker scripts and sync32.h, so a Cortex-M33 .s32 cart builds from source with no sibling checkout. The ARM compiler itself is the WASM arm-none-eabi toolchain shipped in romdev-platform-gba.", "type": "module", "main": "index.js", diff --git a/packages/romdev-platform-sync32/share/sync32/crt0/xip.ld b/packages/romdev-platform-sync32/share/sync32/crt0/xip.ld index 9ed24846..bd41acb5 100644 --- a/packages/romdev-platform-sync32/share/sync32/crt0/xip.ld +++ b/packages/romdev-platform-sync32/share/sync32/crt0/xip.ld @@ -5,7 +5,7 @@ MEMORY { /* The top of the game region is the stack, which grows DOWN from 0x20080000. S32_STACK is how much is reserved for it; the default 16 KB suits a game whose call depth is its own, but a ported engine can want - far more (Doom's BSP recursion measured over 23 KB), so a cart can raise + far more (one BSP renderer's recursion measured over 23 KB), so a cart can raise it with -Wl,--defsym=S32_STACK=N at the cost of its own RAM. */ GAME (rwx) : ORIGIN = 0x20030000, LENGTH = 0x50000 - S32_STACK } diff --git a/packages/romdev-platform-sync32/share/sync32/include/sync32.h b/packages/romdev-platform-sync32/share/sync32/include/sync32.h index 151c2850..37e0ae4d 100644 --- a/packages/romdev-platform-sync32/share/sync32/include/sync32.h +++ b/packages/romdev-platform-sync32/share/sync32/include/sync32.h @@ -14,6 +14,22 @@ #define S32_LOAD_XIP 1 #define S32_VIDEO_240 0 // 320x240 4:3 #define S32_VIDEO_180 1 // 320x180 letterbox 16:9 +#define S32_VIDEO_128 2 // 128x128, shown at 3x (384x384) centred; + // the canvas is 128 bytes per row +// Video modes (header byte video_mode). The mode picks the canvas geometry: +// S32_VIDEO_240 canvas 320x240, stride 320 +// S32_VIDEO_180 canvas 320x180, stride 320, black bars above and below +// S32_VIDEO_128 canvas 128x128, stride 128. Each canvas pixel is shown as +// an exact 3x3 block, the 384x384 picture centred in the +// 640x480 HDMI output with a black border. Pixels are still +// indices into the 256-entry palette, and clear(), rect() +// and sprite() clip to 128x128. Made for 128x128 fantasy- +// console games (PICO-8 carts compiled to native ROMs). +// A value the console does not know falls back to S32_VIDEO_240. Mode 2 is +// an append-only extension inside api v2: it adds no function, so it does +// not bump S32_API_VERSION. Firmware that predates it shows a mode-2 cart as +// mode 0 (its 128-byte rows wrapped into 320-wide ones), so a mode-2 game +// needs a console updated to this revision. // canonical pad: SNES-class digital (XInput bit layout) #define S32_PAD_UP 0x0001 @@ -32,7 +48,8 @@ #define S32_SPRITE_FLIP_X 0x01 #define S32_SPRITE_FLIP_Y 0x02 -#define S32_W 320 +#define S32_W 320 // canvas width in modes 0 and 1 +#define S32_W128 128 // canvas width and height in mode 2 #define S32_MAX_SPRITES 128 #define S32_SAVE_SLOTS 8 #define S32_SAVE_MAX 65536 diff --git a/packages/romdev-pycparser/LICENSE b/packages/romdev-pycparser/LICENSE new file mode 100644 index 00000000..17f87949 --- /dev/null +++ b/packages/romdev-pycparser/LICENSE @@ -0,0 +1,73 @@ +This package is a JavaScript port of pycparser and of the parts of PLY it +uses. Both are distributed under the BSD licenses reproduced below. + +================================================================================ +pycparser +================================================================================ + +pycparser -- A C parser in Python + +Copyright (c) 2008-2022, Eli Bendersky +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +* Neither the name of the copyright holder nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ +PLY (Python Lex-Yacc) +================================================================================ + +PLY (Python Lex-Yacc) Version 3.10 + +Copyright (C) 2001-2017 +David M. Beazley (Dabeaz LLC) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +* Neither the name of the David Beazley or Dabeaz LLC may be used to + endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +More information about PLY can be obtained on the PLY webpage at: + + http://www.dabeaz.com/ply diff --git a/packages/romdev-pycparser/NOTICE b/packages/romdev-pycparser/NOTICE new file mode 100644 index 00000000..e4bd9e5c --- /dev/null +++ b/packages/romdev-pycparser/NOTICE @@ -0,0 +1,23 @@ +romdev-pycparser + +A plain JavaScript port of pycparser 2.23 as vendored, with GCC-extension +patches, by m2c (m2c_pycparser, m2c commit +1d1c4454a445326541305f83f2b0cb680a9ecb2d) and by decomp-permuter +(perm_pycparser, decomp-permuter commit +41bd0bfc32aa5ea78de4cf28be603163256c2a4c). The two vendored copies are the +same files under two package names. + +pycparser is Copyright (c) 2008-2022, Eli Bendersky. PLY (Python Lex-Yacc) +is Copyright (C) 2001-2017, David M. Beazley (Dabeaz LLC). Both are +BSD-licensed; the full license texts are in LICENSE. + +src/tables/lextab.json, src/tables/yacctab.json and src/tables/c_ast.json are +data converted from the upstream lextab.py, yacctab.py and c_ast.py by +scripts/gen-tables.mjs (which reads them as Python literals; nothing runs +Python). The lexer and LALR parse loop follow PLY 3.10's ply/lex.py and +ply/yacc.py; the grammar actions, AST, generator and AST transforms follow the +upstream c_parser.py, plyparser.py, c_ast.py, c_generator.py and +ast_transforms.py. + +The test suite under test/ is a port of the upstream pycparser tests; the C +files under test/fixtures/c_files are copied from upstream's tests/c_files. diff --git a/packages/romdev-pycparser/README.md b/packages/romdev-pycparser/README.md new file mode 100644 index 00000000..b6c70686 --- /dev/null +++ b/packages/romdev-pycparser/README.md @@ -0,0 +1,55 @@ +# romdev-pycparser + +A plain JavaScript (ESM) port of [pycparser](https://github.com/eliben/pycparser) +as vendored by m2c (`m2c_pycparser`) and decomp-permuter (`perm_pycparser`): +pycparser 2.23 with GCC extensions (attributes, `asm`, `typeof` and more). It +has the C99 lexer, an LALR parser driven by upstream's own parse tables, the AST +and the C generator, and round-trips C the way upstream does. No Python is +needed. + +It is part of [romdev](https://github.com/monteslu/romdev). + +## Upstream and license + +- Upstream: pycparser 2.23 (Eli Bendersky), https://github.com/eliben/pycparser, + as patched in m2c commit `1d1c4454a445326541305f83f2b0cb680a9ecb2d` and + decomp-permuter commit `41bd0bfc32aa5ea78de4cf28be603163256c2a4c` (the two + vendored copies are the same files under two package names). +- The lexer and parse loop follow PLY 3.10 (David M. Beazley). +- License: BSD-3-Clause (pycparser and PLY). Full texts in `LICENSE`; details in + `NOTICE`. +- `src/tables/*.json` are converted from upstream's `lextab.py`, `yacctab.py` + and `c_ast.py` by a JS script that reads them as Python literals. + +## How romdev uses it + +It is the C parser and printer under +[`romdev-m2c`](https://www.npmjs.com/package/romdev-m2c) (m2c reads type +context with it) and +[`romdev-permuter`](https://www.npmjs.com/package/romdev-permuter) (the permuter +parses, mutates and prints candidate C with it). Both are driven by romdevtools' +`decomp` tool (`decomp({op:'generate'})` and `decomp({op:'search'})`). + +## API + +```js +import { CParser, CGenerator, c_ast } from "romdev-pycparser"; + +const ast = new CParser().parse("int add(int a, int b) { return a + b; }", ""); +const text = new CGenerator().visit(ast); +``` + +Exports from `.`: `CParser`, `CLexer`, `CGenerator`, the `c_ast` namespace +(`Node`, `NodeVisitor`, every node class), `parse_file`, the AST transforms +(`fix_switch_cases`, `fix_atomic_specifiers`) and the error classes +(`ParseError`, `LexError`). `parse_file` never runs a host `cpp`: pass +already-preprocessed C, or a `preprocess` function. + +## Requirements + +Node >= 24, ESM only. No dependencies, no Python, no native code. + +## Versions + +romdev-pycparser 0.1.0 ports pycparser 2.23 as vendored by m2c and +decomp-permuter at the commits above. diff --git a/packages/romdev-pycparser/package.json b/packages/romdev-pycparser/package.json new file mode 100644 index 00000000..f5a14a4f --- /dev/null +++ b/packages/romdev-pycparser/package.json @@ -0,0 +1,32 @@ +{ + "name": "romdev-pycparser", + "version": "0.1.0", + "description": "Plain-JS port of pycparser (the m2c / decomp-permuter fork with GCC extensions): C99 lexer, LALR parser on upstream's own tables, AST and C generator that round-trip like upstream.", + "type": "module", + "main": "src/index.js", + "exports": { + ".": "./src/index.js" + }, + "files": [ + "src", + "LICENSE", + "NOTICE" + ], + "engines": { + "node": ">=24" + }, + "license": "BSD-3-Clause", + "repository": { + "type": "git", + "url": "git+https://github.com/monteslu/romdev.git", + "directory": "packages/romdev-pycparser" + }, + "homepage": "https://github.com/monteslu/romdev#readme", + "bugs": { + "url": "https://github.com/monteslu/romdev/issues" + }, + "author": "Luis Montes", + "scripts": { + "test": "node --test" + } +} diff --git a/packages/romdev-pycparser/scripts/gen-tables.mjs b/packages/romdev-pycparser/scripts/gen-tables.mjs new file mode 100644 index 00000000..9735f293 --- /dev/null +++ b/packages/romdev-pycparser/scripts/gen-tables.mjs @@ -0,0 +1,183 @@ +#!/usr/bin/env node +// Regenerate src/tables/{lextab,yacctab}.json from the upstream pycparser fork +// (m2c_pycparser / perm_pycparser, which are the same files under two names). +// +// The upstream parser runs PLY in optimize mode, which loads the committed +// lextab.py / yacctab.py WITHOUT checking them against the grammar. Those two +// files are therefore the authoritative definition of how upstream lexes and +// parses, so this port reads them as data instead of re-deriving LALR tables. +// Nothing here executes Python: the files are Python literals, and this script +// parses just enough of that literal syntax to read them. +// +// Usage: node scripts/gen-tables.mjs +// (the three generated modules from perm_pycparser/ or m2c_pycparser/, given +// as file paths; they are read as data, never run) + +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const [lextabFile, yacctabFile, castFile] = process.argv.slice(2); +if (!castFile) { + console.error("usage: node scripts/gen-tables.mjs "); + process.exit(2); +} + +/** Parse a Python literal expression (str, int, None, bool, list, tuple, dict, set(...)). */ +export function parsePyLiteral(text) { + let i = 0; + const ws = () => { while (i < text.length && /\s/.test(text[i])) i++; }; + const expect = (c) => { ws(); if (text[i] !== c) throw new Error(`expected '${c}' at ${i}: ${text.slice(i, i + 40)}`); i++; }; + function str() { + const q = text[i++]; + let out = ""; + while (text[i] !== q) { + let c = text[i++]; + if (c === "\\") { + const e = text[i++]; + if (e === "n") c = "\n"; + else if (e === "t") c = "\t"; + else if (e === "r") c = "\r"; + else if (e === "\\") c = "\\"; + else if (e === "'") c = "'"; + else if (e === "\"") c = "\""; + else if (e === "x") { c = String.fromCharCode(parseInt(text.slice(i, i + 2), 16)); i += 2; } + else if (e === "\n") c = ""; + else c = "\\" + e; + } + out += c; + } + i++; + return out; + } + function seq(close) { + const items = []; + for (;;) { + ws(); + if (text[i] === close) { i++; return items; } + items.push(val()); + ws(); + if (text[i] === ",") { i++; continue; } + ws(); + if (text[i] === close) { i++; return items; } + throw new Error(`bad sequence at ${i}: ${text.slice(i, i + 40)}`); + } + } + function val() { + ws(); + const c = text[i]; + if (c === "'" || c === "\"") return str(); + if (c === "[") { i++; return seq("]"); } + if (c === "(") { i++; return seq(")"); } + if (c === "{") { + i++; + const obj = []; + for (;;) { + ws(); + if (text[i] === "}") { i++; return { dict: obj }; } + const k = val(); + expect(":"); + const v = val(); + obj.push([k, v]); + ws(); + if (text[i] === ",") i++; + } + } + if (text.startsWith("None", i)) { i += 4; return null; } + if (text.startsWith("True", i)) { i += 4; return true; } + if (text.startsWith("False", i)) { i += 5; return false; } + if (text.startsWith("set(", i)) { i += 4; const inner = val(); expect(")"); return inner; } + const m = /^-?\d+/.exec(text.slice(i, i + 32)); + if (m) { i += m[0].length; return Number(m[0]); } + throw new Error(`cannot parse literal at ${i}: ${text.slice(i, i + 40)}`); + } + const v = val(); + return v; +} + +/** The value assigned to `name = ` at top level of a Python module. */ +function assignment(py, name) { + const re = new RegExp(`^${name}\\s*=\\s*`, "m"); + const m = re.exec(py); + if (!m) throw new Error(`no ${name}`); + const start = m.index + m[0].length; + // The literal ends where the next top-level statement begins; parse greedily. + return parsePyLiteral(py.slice(start)); +} + +const lextab = readFileSync(lextabFile, "utf8"); +const lex = { + tabversion: assignment(lextab, "_tabversion"), + tokens: assignment(lextab, "_lextokens"), + reflags: assignment(lextab, "_lexreflags"), + literals: assignment(lextab, "_lexliterals"), + stateinfo: Object.fromEntries(assignment(lextab, "_lexstateinfo").dict), + statere: Object.fromEntries(assignment(lextab, "_lexstatere").dict.map(([state, list]) => + [state, list.map(([pattern, names]) => ({ pattern, names }))])), + stateignore: Object.fromEntries(assignment(lextab, "_lexstateignore").dict), + stateerrorf: Object.fromEntries(assignment(lextab, "_lexstateerrorf").dict), + stateeoff: Object.fromEntries(assignment(lextab, "_lexstateeoff").dict), +}; + +const yacctab = readFileSync(yacctabFile, "utf8"); +const actionItems = assignment(yacctab, "_lr_action_items").dict; +const gotoItems = assignment(yacctab, "_lr_goto_items").dict; +const productions = assignment(yacctab, "_lr_productions"); +// Rebuild _lr_action / _lr_goto exactly as the generated module does: states +// in first-seen order, and per state the symbols in item order. +const action = new Map(); +for (const [tok, [states, acts]] of actionItems) { + states.forEach((s, k) => { + if (!action.has(s)) action.set(s, []); + action.get(s).push([tok, acts[k]]); + }); +} +const gotos = new Map(); +for (const [sym, [states, targets]] of gotoItems) { + states.forEach((s, k) => { + if (!gotos.has(s)) gotos.set(s, []); + gotos.get(s).push([sym, targets[k]]); + }); +} +const yacc = { + tabversion: assignment(yacctab, "_tabversion"), + method: assignment(yacctab, "_lr_method"), + signature: assignment(yacctab, "_lr_signature"), + // [state, [[symbol, action]...]] - an array so state order survives JSON. + action: [...action.entries()], + goto: [...gotos.entries()], + // [str, name, len, func, file, line] + productions, +}; + +// c_ast.py is generated from _c_ast.cfg, and the generated file is what runs, +// so the node shapes come from it: constructor fields (__slots__ minus +// coord/__weakref__), children in children() order (single '*' or list '**'), +// and attr_names. +const castPy = readFileSync(castFile, "utf8"); +const nodes = []; +for (const m of castPy.matchAll(/^class (\w+)\(Node\):\n([\s\S]*?)(?=^class |(?![\s\S]))/gm)) { + const [, name, body] = m; + const slots = /__slots__ = \(([^)]*)\)/.exec(body)[1].split(",").map((s) => s.trim().replace(/'/g, "")).filter(Boolean) + .filter((s) => s !== "coord" && s !== "__weakref__"); + const childrenBody = /def children\(self\):\n([\s\S]*?)return (?:tuple\(nodelist\)|\(\))/.exec(body)[1]; + const children = []; + for (const line of childrenBody.split("\n")) { + let c = /if self\.(\w+) is not None: nodelist\.append/.exec(line); + if (c) { children.push([c[1], "single"]); continue; } + c = /for i, child in enumerate\(self\.(\w+) or \[\]\)/.exec(line); + if (c) children.push([c[1], "list"]); + } + const iterBody = /def __iter__\(self\):\n([\s\S]*?)attr_names/.exec(body)[1]; + const iter = [...iterBody.matchAll(/self\.(\w+)/g)].map((x) => x[1]).filter((v, k, a) => a.indexOf(v) === k); + if (iter.join() !== children.map((c) => c[0]).join()) throw new Error(`${name}: __iter__ and children() disagree`); + const attrs = /attr_names = \(([^)]*)\)/.exec(body)[1].split(",").map((s) => s.trim().replace(/'/g, "")).filter(Boolean); + nodes.push({ name, fields: slots, children, attrs }); +} + +const out = path.join(here, "..", "src", "tables"); +writeFileSync(path.join(out, "lextab.json"), JSON.stringify(lex) + "\n"); +writeFileSync(path.join(out, "yacctab.json"), JSON.stringify(yacc) + "\n"); +writeFileSync(path.join(out, "c_ast.json"), JSON.stringify(nodes, null, 1) + "\n"); +console.log(`lextab: ${Object.keys(lex.statere).length} states; yacctab: ${action.size} states, ${productions.length} productions; c_ast: ${nodes.length} node classes`); diff --git a/packages/romdev-pycparser/src/ast_transforms.js b/packages/romdev-pycparser/src/ast_transforms.js new file mode 100644 index 00000000..94b0a1ed --- /dev/null +++ b/packages/romdev-pycparser/src/ast_transforms.js @@ -0,0 +1,90 @@ +// ast_transforms.js - a port of pycparser's ast_transforms.py. +import * as c_ast from "./c_ast.js"; + +/** + * Case statements come out of parsing with one child node, with the following + * statements tucked into the parent Compound (and fall-through cases nested). + * Regroup them so each Case/Default owns its statements. + */ +export function fix_switch_cases(switch_node) { + if (!(switch_node instanceof c_ast.Switch)) throw new Error("AssertionError"); + if (!(switch_node.stmt instanceof c_ast.Compound)) return switch_node; + const new_compound = new c_ast.Compound([], switch_node.stmt.coord); + let last_case = null; + for (const child of switch_node.stmt.block_items || []) { + if (child instanceof c_ast.Case || child instanceof c_ast.Default) { + new_compound.block_items.push(child); + _extract_nested_case(child, new_compound.block_items); + last_case = new_compound.block_items[new_compound.block_items.length - 1]; + } else if (last_case == null) { + new_compound.block_items.push(child); + } else { + last_case.stmts.push(child); + } + } + switch_node.stmt = new_compound; + return switch_node; +} + +function _extract_nested_case(case_node, stmts_list) { + const first = case_node.stmts[0]; + if (first instanceof c_ast.Case || first instanceof c_ast.Default) { + stmts_list.push(case_node.stmts.pop()); + _extract_nested_case(stmts_list[stmts_list.length - 1], stmts_list); + } +} + +class PyAttributeError extends Error { + constructor(message) { super(message); this.name = "AttributeError"; } +} + +/** `x.type` with Python semantics: AttributeError unless x is a node with a `type` field. */ +function typeOf(x) { + if (!c_ast.hasField(x, "type")) throw new PyAttributeError(`'${x == null ? "NoneType" : x.constructor.name}' object has no attribute 'type'`); + return x.type; +} + +/** + * Fix a decl with _Atomic(type) specifiers: drop the spurious + * Typename->TypeDecl pairs and attach the _Atomic qualifier in the right place. + */ +export function fix_atomic_specifiers(decl) { + for (;;) { + const [d, found] = _fix_atomic_specifiers_once(decl); + decl = d; + if (!found) break; + } + let typ = decl; + while (!(typ instanceof c_ast.TypeDecl)) { + try { + typ = typeOf(typ); + } catch (e) { + if (e instanceof PyAttributeError) return decl; + throw e; + } + } + if (typ.quals.includes("_Atomic") && !decl.quals.includes("_Atomic")) decl.quals.push("_Atomic"); + if (typ.declname == null) typ.declname = decl.name; + return decl; +} + +function _fix_atomic_specifiers_once(decl) { + let parent = decl; + let grandparent = null; + let node = decl.type; + while (node != null) { + if (node instanceof c_ast.Typename && node.quals.includes("_Atomic")) break; + try { + grandparent = parent; + parent = node; + node = typeOf(node); + } catch (e) { + if (e instanceof PyAttributeError) return [decl, false]; + throw e; + } + } + if (!(parent instanceof c_ast.TypeDecl)) throw new Error("AssertionError"); + grandparent.type = typeOf(node); + if (!node.type.quals.includes("_Atomic")) node.type.quals.push("_Atomic"); + return [decl, true]; +} diff --git a/packages/romdev-pycparser/src/c_ast.js b/packages/romdev-pycparser/src/c_ast.js new file mode 100644 index 00000000..d322b2e1 --- /dev/null +++ b/packages/romdev-pycparser/src/c_ast.js @@ -0,0 +1,165 @@ +// c_ast.js - AST node classes, a port of pycparser's generated c_ast.py. +// +// The node shapes (constructor fields, children order, attr_names) are read +// from tables/c_ast.json, which scripts/gen-tables.mjs extracts from the +// upstream c_ast.py, so traversal order is exactly upstream's. +// +// Python -> JS conventions used throughout this package: +// None -> null; a node's `coord` defaults to null. +// Nodes compare by identity (upstream defines no __eq__). +// `for c of node` iterates children like Node.__iter__. +import spec from "./tables/c_ast.json" with { type: "json" }; + +export class Node { + /** A sequence of all children that are Nodes: [[name, node], ...]. */ + children() { + const out = []; + for (const [name, kind] of this.constructor.childSpec) { + const v = this[name]; + if (kind === "single") { if (v != null) out.push([name, v]); } + else if (v) for (let i = 0; i < v.length; i++) out.push([`${name}[${i}]`, v[i]]); + } + return out; + } + + *[Symbol.iterator]() { + for (const [name, kind] of this.constructor.childSpec) { + const v = this[name]; + if (kind === "single") { if (v != null) yield v; } + else if (v) yield* v; + } + } + + get attr_names() { return this.constructor.attrNames; } + + /** Pretty print the node and its children, like Node.show(). */ + show({ offset = 0, attrnames = false, showemptyattrs = true, nodenames = false, showcoord = false, _my_node_name = null } = {}) { + let buf = ""; + const lead = " ".repeat(offset); + if (nodenames && _my_node_name != null) buf += lead + this.constructor.name + " <" + _my_node_name + ">: "; + else buf += lead + this.constructor.name + ": "; + if (this.attr_names.length) { + const isEmpty = (v) => v == null || (typeof v === "string" || Array.isArray(v)) && v.length === 0; + const nvlist = this.attr_names.map((n) => [n, this[n]]).filter(([, v]) => showemptyattrs || !isEmpty(v)); + if (attrnames) buf += nvlist.map(([n, v]) => `${n}=${pyStr(v)}`).join(", "); + else buf += nvlist.map(([, v]) => pyStr(v)).join(", "); + } + if (showcoord) buf += ` (at ${this.coord == null ? "None" : String(this.coord)})`; + buf += "\n"; + for (const [childName, child] of this.children()) { + buf += child.show({ offset: offset + 2, attrnames, showemptyattrs, nodenames, showcoord, _my_node_name: childName }); + } + return buf; + } +} + +/** Python str() of an attribute value (lists print as reprs). */ +export function pyStr(v) { + if (v == null) return "None"; + if (Array.isArray(v)) return "[" + v.map(pyRepr).join(", ") + "]"; + if (v === true) return "True"; + if (v === false) return "False"; + return String(v); +} + +export function pyRepr(v) { + if (v == null) return "None"; + if (typeof v === "string") { + const q = v.includes("'") && !v.includes("\"") ? "\"" : "'"; + let s = ""; + for (const ch of v) { + if (ch === "\\") s += "\\\\"; + else if (ch === q) s += "\\" + q; + else if (ch === "\n") s += "\\n"; + else if (ch === "\t") s += "\\t"; + else if (ch === "\r") s += "\\r"; + else s += ch; + } + return q + s + q; + } + if (Array.isArray(v)) return "[" + v.map(pyRepr).join(", ") + "]"; + if (v === true) return "True"; + if (v === false) return "False"; + if (v instanceof Node) return nodeRepr(v); + return String(v); +} + +function listRepr(obj) { + if (Array.isArray(obj)) return "[" + obj.map((e) => listRepr(e).replaceAll("\n", "\n ")).join(",\n ") + "\n]"; + return pyRepr(obj); +} + +/** Node.__repr__ */ +export function nodeRepr(node) { + const cls = node.constructor.name; + let result = cls + "("; + let indent = "", separator = ""; + for (const name of node.constructor.fields) { + result += separator + indent; + result += name + "=" + listRepr(node[name]).replaceAll("\n", "\n " + " ".repeat(name.length + cls.length)); + separator = ","; + indent = "\n " + " ".repeat(cls.length); + } + return result + indent + ")"; +} + +function isPlainObject(x) { + return x != null && typeof x === "object" && Object.getPrototypeOf(x) === Object.prototype; +} + +/** @type {Record} */ +export const nodeClasses = {}; + +for (const def of spec) { + const fields = def.fields; + // Dynamic class with the upstream name (so constructor.name === "Decl" etc.). + const cls = { + [def.name]: class extends Node { + constructor(...args) { + super(); + // Keyword form: new Decl({name, quals, ...}) mirrors Python kwargs. + if (args.length === 1 && isPlainObject(args[0]) && fields.length > 0) { + const kw = args[0]; + for (const f of fields) this[f] = kw[f] === undefined ? null : kw[f]; + this.coord = kw.coord === undefined ? null : kw.coord; + return; + } + for (let i = 0; i < fields.length; i++) this[fields[i]] = args[i] === undefined ? null : args[i]; + this.coord = args[fields.length] === undefined ? null : args[fields.length]; + } + }, + }[def.name]; + cls.fields = fields; + cls.childSpec = def.children; + cls.attrNames = def.attrs; + nodeClasses[def.name] = cls; +} + +export const { + ArrayDecl, ArrayRef, Asm, AsmOperand, Assignment, Alignas, BinaryOp, Break, Case, Cast, Compound, + CompoundLiteral, Constant, Continue, Decl, DeclList, Default, DoWhile, EllipsisParam, EmptyStatement, + Enum, Enumerator, EnumeratorList, ExprList, FileAST, For, FuncCall, FuncDecl, FuncDef, GccAttribute, + GccAttributeStatement, Goto, ID, IdentifierType, If, InitList, Label, NamedInitializer, ParamList, + PtrDecl, Range, Return, StaticAssert, Struct, StructRef, Switch, TernaryOp, TypeDecl, Typedef, Typename, + Typeof, UnaryOp, Union, While, Pragma, +} = nodeClasses; + +/** + * A base NodeVisitor, like c_ast.NodeVisitor: subclass it and define + * visit_XXX methods; generic_visit visits children in order. + */ +export class NodeVisitor { + visit(node) { + const m = this["visit_" + node.constructor.name]; + return m ? m.call(this, node) : this.generic_visit(node); + } + + generic_visit(node) { + for (const c of node) this.visit(c); + } +} + +/** True when `x` has a field named `name` (Python hasattr on a slotted node). */ +export function hasField(x, name) { + return x instanceof Node && x.constructor.fields.includes(name); +} diff --git a/packages/romdev-pycparser/src/c_generator.js b/packages/romdev-pycparser/src/c_generator.js new file mode 100644 index 00000000..a12e6b5f --- /dev/null +++ b/packages/romdev-pycparser/src/c_generator.js @@ -0,0 +1,437 @@ +// c_generator.js - C code generator from AST nodes, a port of pycparser's +// c_generator.py (m2c / decomp-permuter fork). Output must be byte-identical +// to upstream: the permuter hashes it, compiles it, and writes it out. +import * as c_ast from "./c_ast.js"; +import { AssertionError } from "./c_parser.js"; + +// Python truthiness for the values these nodes carry. +const T = (v) => !(v == null || v === false || v === "" || (Array.isArray(v) && v.length === 0)); + +const precedence_map = { + "||": 0, + "&&": 1, + "|": 2, + "^": 3, + "&": 4, + "==": 5, "!=": 5, + ">": 6, ">=": 6, "<": 6, "<=": 6, + ">>": 7, "<<": 7, + "+": 8, "-": 8, + "*": 9, "/": 9, "%": 9, +}; + +const STMT_EXPR_TYPES = new Set([ + c_ast.Decl, c_ast.Assignment, c_ast.Cast, c_ast.UnaryOp, + c_ast.BinaryOp, c_ast.TernaryOp, c_ast.FuncCall, c_ast.ArrayRef, + c_ast.StructRef, c_ast.Constant, c_ast.ID, c_ast.Typedef, + c_ast.ExprList, +]); + +export class CGenerator { + constructor(reduce_parentheses = false) { + this.indent_level = 0; + this.reduce_parentheses = reduce_parentheses; + } + + _make_indent() { return " ".repeat(this.indent_level); } + + visit(node) { + // Upstream dispatches on the class name, so visit(None) reaches + // generic_visit(None) and yields ''. + if (node == null) return this.generic_visit(node); + const m = this["visit_" + node.constructor.name]; + return m ? m.call(this, node) : this.generic_visit(node); + } + + generic_visit(node) { + if (node == null) return ""; + return node.children().map(([, c]) => this.visit(c)).join(""); + } + + visit_Constant(n) { return n.value; } + + visit_ID(n) { return n.name; } + + visit_Pragma(n) { + let ret = "#pragma"; + if (T(n.string)) ret += " " + n.string; + return ret; + } + + visit_ArrayRef(n) { + const arrref = this._parenthesize_unless_simple(n.name); + return arrref + "[" + this.visit(n.subscript) + "]"; + } + + visit_StructRef(n) { + const sref = this._parenthesize_unless_simple(n.name); + return sref + n.type + this.visit(n.field); + } + + visit_FuncCall(n) { + const fref = this._parenthesize_unless_simple(n.name); + return fref + "(" + this.visitOrNone(n.args) + ")"; + } + + /** self.visit(None) in upstream lands in generic_visit(None) -> ''. */ + visitOrNone(n) { return n == null ? "" : this.visit(n); } + + visit_Typeof(n) { return `typeof(${this.visit(n.expr)})`; } + + visit_UnaryOp(n) { + if (n.op === "sizeof") return `sizeof(${this.visit(n.expr)})`; + const operand = this._parenthesize_unless_simple(n.expr); + if (n.op === "p++") return `${operand}++`; + if (n.op === "p--") return `${operand}--`; + return `${n.op}${operand}`; + } + + visit_BinaryOp(n) { + const lval_str = this._parenthesize_if(n.left, (d) => !(this._is_simple_node(d) + || this.reduce_parentheses && d instanceof c_ast.BinaryOp && precedence_map[d.op] >= precedence_map[n.op])); + const rval_str = this._parenthesize_if(n.right, (d) => !(this._is_simple_node(d) + || this.reduce_parentheses && d instanceof c_ast.BinaryOp && precedence_map[d.op] > precedence_map[n.op])); + return `${lval_str} ${n.op} ${rval_str}`; + } + + visit_Assignment(n) { + const rval_str = this._parenthesize_if(n.rvalue, (x) => x instanceof c_ast.Assignment); + return `${this.visit(n.lvalue)} ${n.op} ${rval_str}`; + } + + visit_IdentifierType(n) { return n.names.join(" "); } + + _visit_expr(n) { + if (n instanceof c_ast.InitList) return "{" + this.visit(n) + "}"; + if (n instanceof c_ast.ExprList || n instanceof c_ast.Compound) return "(" + this.visit(n) + ")"; + return this.visit(n); + } + + visit_Decl(n, no_type = false) { + let s = no_type ? n.name : this._generate_decl(n); + if (T(n.asmlabel)) s += " asm(" + this.visit(n.asmlabel) + ")"; + if (T(n.gcc_attributes)) s += this._generate_attrs(n.gcc_attributes); + if (T(n.bitsize)) s += " : " + this.visit(n.bitsize); + if (T(n.init)) s += " = " + this._visit_expr(n.init); + return s; + } + + visit_DeclList(n) { + let s = this.visit(n.decls[0]); + if (n.decls.length > 1) s += ", " + n.decls.slice(1).map((decl) => this.visit_Decl(decl, true)).join(", "); + return s; + } + + visit_Typedef(n) { + let s = ""; + if (T(n.storage)) s += n.storage.join(" ") + " "; + s += this._generate_type(n.type); + return s; + } + + visit_Cast(n) { + const s = "(" + this._generate_type(n.to_type, [], false) + ")"; + return s + " " + this._parenthesize_unless_simple(n.expr); + } + + visit_ExprList(n) { return n.exprs.map((e) => this._visit_expr(e)).join(", "); } + + visit_InitList(n) { return n.exprs.map((e) => this._visit_expr(e)).join(", "); } + + visit_Enum(n) { return this._generate_struct_union_enum(n, "enum"); } + + visit_Alignas(n) { return `_Alignas(${this.visit(n.alignment)})`; } + + visit_Enumerator(n) { + if (!T(n.value)) return `${this._make_indent()}${n.name}${this._generate_attrs(n.gcc_attributes)},\n`; + return `${this._make_indent()}${n.name}${this._generate_attrs(n.gcc_attributes)} = ${this.visit(n.value)},\n`; + } + + visit_FuncDef(n) { + const decl = this.visit(n.decl); + this.indent_level = 0; + const body = this.visit(n.body); + if (T(n.param_decls)) { + const knrdecls = n.param_decls.map((p) => this.visit(p)).join(";\n"); + return decl + "\n" + knrdecls + ";\n" + body + "\n"; + } + return decl + "\n" + body + "\n"; + } + + visit_FileAST(n) { + let s = ""; + for (const ext of n.ext) { + if (ext instanceof c_ast.FuncDef) s += this.visit(ext); + else if (ext instanceof c_ast.Pragma) s += this.visit(ext) + "\n"; + else s += this.visit(ext) + ";\n"; + } + return s; + } + + visit_Compound(n) { + let s = this._make_indent() + "{\n"; + this.indent_level += 2; + if (T(n.block_items)) s += n.block_items.map((stmt) => this._generate_stmt(stmt)).join(""); + this.indent_level -= 2; + s += this._make_indent() + "}\n"; + return s; + } + + visit_CompoundLiteral(n) { return "(" + this.visit(n.type) + "){" + this.visit(n.init) + "}"; } + + visit_GccAttributeStatement(n) { return this._generate_attrs(n.attrs).replace(/^\s+/, "") + ";"; } + + visit_EmptyStatement() { return ";"; } + + visit_ParamList(n) { return n.params.map((param) => this.visit(param)).join(", "); } + + visit_Return(n) { + let s = "return"; + if (T(n.expr)) s += " " + this.visit(n.expr); + return s + ";"; + } + + visit_Break() { return "break;"; } + + visit_Continue() { return "continue;"; } + + visit_TernaryOp(n) { + let s = "(" + this._visit_expr(n.cond) + ") ? "; + s += "(" + this._visit_expr(n.iftrue) + ") : "; + s += "(" + this._visit_expr(n.iffalse) + ")"; + return s; + } + + visit_If(n) { + let s = "if ("; + if (T(n.cond)) s += this.visit(n.cond); + s += ")\n"; + s += this._generate_stmt(n.iftrue, true); + if (T(n.iffalse)) { + s += this._make_indent() + "else\n"; + s += this._generate_stmt(n.iffalse, true); + } + return s; + } + + visit_For(n) { + let s = "for ("; + if (T(n.init)) s += this.visit(n.init); + s += ";"; + if (T(n.cond)) s += " " + this.visit(n.cond); + s += ";"; + if (T(n.next)) s += " " + this.visit(n.next); + s += ")\n"; + s += this._generate_stmt(n.stmt, true); + return s; + } + + visit_While(n) { + let s = "while ("; + if (T(n.cond)) s += this.visit(n.cond); + s += ")\n"; + s += this._generate_stmt(n.stmt, true); + return s; + } + + visit_DoWhile(n) { + let s = "do\n"; + s += this._generate_stmt(n.stmt, true); + s += this._make_indent() + "while ("; + if (T(n.cond)) s += this.visit(n.cond); + s += ");"; + return s; + } + + visit_StaticAssert(n) { + let s = "_Static_assert("; + s += this.visit(n.cond); + if (T(n.message)) { + s += ","; + s += this.visit(n.message); + } + s += ")"; + return s; + } + + visit_Switch(n) { + let s = "switch (" + this.visit(n.cond) + ")\n"; + s += this._generate_stmt(n.stmt, true); + return s; + } + + visit_Case(n) { + let s = "case " + this.visit(n.expr) + ":\n"; + for (const stmt of n.stmts) s += this._generate_stmt(stmt, true); + return s; + } + + visit_Default(n) { + let s = "default:\n"; + for (const stmt of n.stmts) s += this._generate_stmt(stmt, true); + return s; + } + + visit_Label(n) { return n.name + ":\n" + this._generate_stmt(n.stmt); } + + visit_Goto(n) { return "goto " + n.name + ";"; } + + visit_EllipsisParam() { return "..."; } + + visit_Struct(n) { return this._generate_struct_union_enum(n, "struct"); } + + visit_Typename(n) { return this._generate_type(n.type); } + + visit_Union(n) { return this._generate_struct_union_enum(n, "union"); } + + visit_NamedInitializer(n) { + let s = ""; + for (const name of n.name) { + if (name instanceof c_ast.ID) s += "." + name.name; + else s += "[" + this.visit(name) + "]"; + } + s += " = " + this._visit_expr(n.expr); + return s; + } + + visit_FuncDecl(n) { return this._generate_type(n); } + + visit_ArrayDecl(n) { return this._generate_type(n, [], false); } + + visit_TypeDecl(n) { return this._generate_type(n, [], false); } + + visit_PtrDecl(n) { return this._generate_type(n, [], false); } + + visit_Range(n) { return this.visit(n.first) + " ... " + this.visit(n.last); } + + visit_GccAttribute(n) { + if (n.args == null) return n.name; + return n.name + "(" + n.args.map((e) => this.visit(e)).join(", ") + ")"; + } + + visit_Asm(n) { + let s = "asm" + n.quals.map((q) => " " + q).join(""); + s += "(" + this.visit(n.asm); + const parts = [ + n.output_operands.map((op) => this.visit(op)).join(", "), + n.input_operands.map((op) => this.visit(op)).join(", "), + n.clobbers.map((cl) => this.visit(cl)).join(", "), + n.gotos.join(", "), + ]; + if (!n.quals.includes("goto")) { + while (parts.length && !parts[parts.length - 1]) parts.pop(); + } + for (const p of parts) { + s += " :"; + if (p) s += " " + p; + } + s += ");"; + return s; + } + + visit_AsmOperand(n) { + const s = n.symbolic_name != null ? "[" + n.symbolic_name + "]" : ""; + return s + this.visit(n.constraint) + "(" + this.visit(n.expr) + ")"; + } + + _generate_struct_union_enum(n, name) { + let members, body_function; + if (name === "struct" || name === "union") { + members = n.decls; + body_function = (m) => this._generate_struct_union_body(m); + } else { + if (name !== "enum") throw new AssertionError(); + members = n.values == null ? null : n.values.enumerators; + body_function = (m) => this._generate_enum_body(m); + } + let s = name + " " + (T(n.name) ? n.name : ""); + if (members != null) { + s += "\n"; + s += this._make_indent(); + this.indent_level += 2; + s += "{\n"; + s += body_function(members); + this.indent_level -= 2; + s += this._make_indent() + "}"; + } + s += this._generate_attrs(n.gcc_attributes); + return s; + } + + _generate_struct_union_body(members) { return members.map((decl) => this._generate_stmt(decl)).join(""); } + + _generate_enum_body(members) { + return members.map((value) => this.visit(value)).join("").slice(0, -2) + "\n"; + } + + _generate_stmt(n, add_indent = false) { + const typ = n == null ? null : n.constructor; + if (add_indent) this.indent_level += 2; + const indent = this._make_indent(); + if (add_indent) this.indent_level -= 2; + if (STMT_EXPR_TYPES.has(typ)) return indent + this.visit(n) + ";\n"; + if (typ === c_ast.Compound) return this.visit(n); + if (typ === c_ast.If) return indent + this.visit(n); + return indent + this.visit(n) + "\n"; + } + + _generate_decl(n) { + let s = ""; + if (T(n.funcspec)) s = n.funcspec.join(" ") + " "; + if (T(n.storage)) s += n.storage.join(" ") + " "; + if (T(n.align)) s += this.visit(n.align[0]) + " "; + s += this._generate_type(n.type); + return s; + } + + _generate_type(n, modifiers = [], emit_declname = true) { + const typ = n == null ? null : n.constructor; + if (typ === c_ast.TypeDecl) { + let s = ""; + if (T(n.quals)) s += n.quals.join(" ") + " "; + s += this.visitOrNone(n.type); + let nstr = T(n.declname) && emit_declname ? n.declname : ""; + modifiers.forEach((modifier, i) => { + if (modifier instanceof c_ast.ArrayDecl) { + if (i !== 0 && modifiers[i - 1] instanceof c_ast.PtrDecl) nstr = "(" + nstr + ")"; + nstr += "["; + if (T(modifier.dim_quals)) nstr += modifier.dim_quals.join(" ") + " "; + nstr += this.visitOrNone(modifier.dim) + "]"; + } else if (modifier instanceof c_ast.FuncDecl) { + if (i !== 0 && modifiers[i - 1] instanceof c_ast.PtrDecl) nstr = "(" + nstr + ")"; + nstr += "(" + this.visitOrNone(modifier.args) + ")"; + } else if (modifier instanceof c_ast.PtrDecl) { + if (T(modifier.quals)) nstr = `* ${modifier.quals.join(" ")}${nstr ? " " + nstr : ""}`; + else nstr = "*" + nstr; + } + }); + if (nstr) s += " " + nstr; + return s; + } + if (typ === c_ast.Decl) return this._generate_decl(n.type); + if (typ === c_ast.Typename) return this._generate_type(n.type, [], emit_declname); + if (typ === c_ast.IdentifierType) return n.names.join(" ") + " "; + if (typ === c_ast.ArrayDecl || typ === c_ast.PtrDecl || typ === c_ast.FuncDecl) { + return this._generate_type(n.type, modifiers.concat([n]), emit_declname); + } + return this.visitOrNone(n); + } + + _generate_attrs(attrs) { + if (!T(attrs)) return ""; + const li = attrs.map((attr) => this.visit(attr)); + return " __attribute__((" + li.join(", ") + "))"; + } + + _parenthesize_if(n, condition) { + const s = this._visit_expr(n); + return condition(n) ? "(" + s + ")" : s; + } + + _parenthesize_unless_simple(n) { return this._parenthesize_if(n, (d) => !this._is_simple_node(d)); } + + _is_simple_node(n) { + return n instanceof c_ast.Constant || n instanceof c_ast.ID || n instanceof c_ast.ArrayRef + || n instanceof c_ast.StructRef || n instanceof c_ast.FuncCall; + } +} diff --git a/packages/romdev-pycparser/src/c_lexer.js b/packages/romdev-pycparser/src/c_lexer.js new file mode 100644 index 00000000..290f62a0 --- /dev/null +++ b/packages/romdev-pycparser/src/c_lexer.js @@ -0,0 +1,438 @@ +// c_lexer.js - the C lexer, a port of pycparser's c_lexer.py running on a port +// of PLY's lex engine (ply/lex.py, optimized-table mode). +// +// Upstream builds its lexer with optimize=True, which loads the master regexes +// from the committed lextab.py. tables/lextab.json is that file as data; the +// patterns are Python regexes (compiled with re.VERBOSE), translated to JS +// once at load time by pyRegexToJs(). +import lextab from "./tables/lextab.json" with { type: "json" }; + +export class LexToken { + constructor() { + this.type = null; + this.value = null; + this.lineno = 0; + this.lexpos = 0; + } + + toString() { return `LexToken(${this.type},${JSON.stringify(this.value)},${this.lineno},${this.lexpos})`; } +} + +export class LexError extends Error { + constructor(message, text) { + super(message); + this.text = text; + } +} + +/** + * Translate a Python (re.VERBOSE when `verbose`) pattern to a JS RegExp source. + * Handles the constructs the pycparser lexer uses: named groups, `.` (no + * DOTALL: every char but \n), `$` (end, or before a final \n), and verbose + * whitespace/comments outside character classes. + */ +export function pyRegexToJs(pat, verbose) { + let out = ""; + let inClass = false; + for (let i = 0; i < pat.length; i++) { + const c = pat[i]; + if (c === "\\") { + out += c + (pat[i + 1] ?? ""); + i++; + continue; + } + if (inClass) { + if (c === "]" && !(out.endsWith("[") || out.endsWith("[^"))) inClass = false; + out += c; + continue; + } + if (c === "[") { inClass = true; out += c; continue; } + if (verbose && /\s/.test(c)) continue; + if (verbose && c === "#") { + while (i < pat.length && pat[i] !== "\n") i++; + continue; + } + if (c === "(" && pat.startsWith("(?P<", i)) { out += "(?<"; i += 3; continue; } + if (c === ".") { out += "[^\\n]"; continue; } + if (c === "$") { out += "(?=\\n?$)"; continue; } + out += c; + } + return out; +} + +const VERBOSE = 64; + +/** Compiled per-state tables: [{re, names:[[func|null, type]|null,...], groups:[{name, idx}]}] */ +function compileStates() { + const states = {}; + for (const [state, list] of Object.entries(lextab.statere)) { + states[state] = list.map(({ pattern, names }) => { + const src = pyRegexToJs(pattern, (lextab.reflags & VERBOSE) !== 0); + const re = new RegExp(src, "y"); + // Top-level alternatives are named groups; map each name to its entry. + const alts = []; + names.forEach((entry, idx) => { + if (entry) alts.push({ group: groupNameFor(pattern, idx), func: entry[0], type: entry[1] }); + }); + return { re, alts }; + }); + } + return states; +} + +// PLY names each alternative's group after its rule function or token name +// (t_NAME). Recover the group name at a given group index from the pattern. +function groupNameFor(pattern, index) { + let idx = 0; + for (let i = 0; i < pattern.length; i++) { + const c = pattern[i]; + if (c === "\\") { i++; continue; } + if (c === "[") { + // skip the class + i++; + if (pattern[i] === "^") i++; + if (pattern[i] === "]") i++; + while (i < pattern.length && pattern[i] !== "]") { if (pattern[i] === "\\") i++; i++; } + continue; + } + if (c === "(") { + if (pattern[i + 1] === "?") { + if (pattern.startsWith("(?P<", i)) { + idx++; + if (idx === index) return /^\(\?P<(\w+)>/.exec(pattern.slice(i))[1]; + } + continue; + } + idx++; + if (idx === index) throw new Error(`group ${index} is unnamed`); + } + } + throw new Error(`no group ${index}`); +} + +const STATES = compileStates(); + +/** PLY's Lexer object (the subset upstream uses), driving CLexer's rule methods. */ +class PlyLexer { + constructor(owner) { + this.owner = owner; + this.lexdata = null; + this.lexpos = 0; + this.lexlen = 0; + this.lineno = 1; + this.begin("INITIAL"); + } + + input(s) { + if (typeof s !== "string") throw new TypeError("Expected a string"); + this.lexdata = s; + this.lexpos = 0; + this.lexlen = s.length; + } + + begin(state) { + if (!(state in STATES)) throw new Error("Undefined state"); + this.lexre = STATES[state]; + this.lexignore = lextab.stateignore[state] ?? ""; + this.lexerrorf = lextab.stateerrorf[state] ?? null; + this.lexeoff = lextab.stateeoff[state] ?? null; + this.lexstate = state; + } + + skip(n) { this.lexpos += n; } + + token() { + let lexpos = this.lexpos; + const lexlen = this.lexlen; + let lexignore = this.lexignore; + const lexdata = this.lexdata; + const owner = this.owner; + outer: + while (lexpos < lexlen) { + if (lexignore.includes(lexdata[lexpos])) { lexpos++; continue; } + for (const { re, alts } of this.lexre) { + re.lastIndex = lexpos; + const m = re.exec(lexdata); + if (!m) continue; + const tok = new LexToken(); + tok.value = m[0]; + tok.lineno = this.lineno; + tok.lexpos = lexpos; + let alt = null; + for (const a of alts) if (m.groups[a.group] !== undefined) { alt = a; break; } + tok.type = alt.type; + const end = lexpos + m[0].length; + if (!alt.func) { + if (tok.type) { this.lexpos = end; return tok; } + lexpos = end; + continue outer; + } + lexpos = end; + tok.lexer = this; + this.lexmatch = m; + this.lexpos = lexpos; + const newtok = owner[alt.func](tok); + if (!newtok) { + lexpos = this.lexpos; + lexignore = this.lexignore; + continue outer; + } + return newtok; + } + // No match: literals (none in this grammar), then the error rule. + if (lextab.literals.includes(lexdata[lexpos])) { + const tok = new LexToken(); + tok.value = lexdata[lexpos]; + tok.lineno = this.lineno; + tok.type = tok.value; + tok.lexpos = lexpos; + this.lexpos = lexpos + 1; + return tok; + } + if (this.lexerrorf) { + const tok = new LexToken(); + tok.value = lexdata.slice(lexpos); + tok.lineno = this.lineno; + tok.type = "error"; + tok.lexer = this; + tok.lexpos = lexpos; + this.lexpos = lexpos; + const newtok = owner[this.lexerrorf](tok); + if (lexpos === this.lexpos) { + throw new LexError(`Scanning error. Illegal character '${lexdata[lexpos]}'`, lexdata.slice(lexpos)); + } + lexpos = this.lexpos; + if (!newtok) continue; + return newtok; + } + this.lexpos = lexpos; + throw new LexError(`Illegal character '${lexdata[lexpos]}' at index ${lexpos}`, lexdata.slice(lexpos)); + } + this.lexpos = lexpos + 1; + if (this.lexdata == null) throw new Error("No input string given with input()"); + return null; + } +} + +const keywords = [ + "AUTO", "BREAK", "CASE", "CHAR", "CONST", + "CONTINUE", "DEFAULT", "DO", "DOUBLE", "ELSE", "ENUM", "EXTERN", + "FLOAT", "FOR", "GOTO", "IF", "INLINE", "INT", "LONG", + "REGISTER", "OFFSETOF", + "RESTRICT", "RETURN", "SHORT", "SIGNED", "SIZEOF", "STATIC", "STRUCT", + "SWITCH", "TYPEDEF", "UNION", "UNSIGNED", "VOID", + "VOLATILE", "WHILE", "__INT128", + "TYPEOF", + "__ATTRIBUTE__", "ASM", +]; +const keywordsNew = [ + "_BOOL", "_COMPLEX", + "_NORETURN", "_THREAD_LOCAL", "_STATIC_ASSERT", + "_ATOMIC", "_ALIGNOF", "_ALIGNAS", + "_PRAGMA", +]; + +/** @type {Map} */ +const keywordMap = new Map(); +for (const k of keywords) keywordMap.set(k.toLowerCase(), k); +for (const k of keywordsNew) keywordMap.set(k.slice(0, 2).toUpperCase() + k.slice(2).toLowerCase(), k); +// GNU extensions +for (const [k, v] of [ + ["typeof", "TYPEOF"], ["__typeof", "TYPEOF"], ["__typeof__", "TYPEOF"], + ["__alignof", "_ALIGNOF"], ["__alignof__", "_ALIGNOF"], + ["__attribute", "__ATTRIBUTE__"], ["__attribute__", "__ATTRIBUTE__"], + ["asm", "ASM"], ["__asm", "ASM"], ["__asm__", "ASM"], + ["__const", "CONST"], ["__const__", "CONST"], + ["__restrict", "RESTRICT"], ["__restrict__", "RESTRICT"], + ["__signed", "SIGNED"], ["__signed__", "SIGNED"], + ["__inline", "INLINE"], ["__inline__", "INLINE"], + ["__volatile", "VOLATILE"], ["__volatile__", "VOLATILE"], + ["__extension__", ""], +]) keywordMap.set(k, v); + +export const tokens = [...keywords, ...keywordsNew, + "ID", "TYPEID", + "INT_CONST_DEC", "INT_CONST_OCT", "INT_CONST_HEX", "INT_CONST_BIN", "INT_CONST_CHAR", + "FLOAT_CONST", "HEX_FLOAT_CONST", + "CHAR_CONST", "WCHAR_CONST", "U8CHAR_CONST", "U16CHAR_CONST", "U32CHAR_CONST", + "STRING_LITERAL", "WSTRING_LITERAL", "U8STRING_LITERAL", "U16STRING_LITERAL", "U32STRING_LITERAL", + "PLUS", "MINUS", "TIMES", "DIVIDE", "MOD", + "OR", "AND", "NOT", "XOR", "LSHIFT", "RSHIFT", + "LOR", "LAND", "LNOT", + "LT", "LE", "GT", "GE", "EQ", "NE", + "EQUALS", "TIMESEQUAL", "DIVEQUAL", "MODEQUAL", + "PLUSEQUAL", "MINUSEQUAL", + "LSHIFTEQUAL", "RSHIFTEQUAL", "ANDEQUAL", "XOREQUAL", + "OREQUAL", + "PLUSPLUS", "MINUSMINUS", + "ARROW", + "CONDOP", + "LPAREN", "RPAREN", + "LBRACKET", "RBRACKET", + "LBRACE", "RBRACE", + "COMMA", "PERIOD", + "SEMI", "COLON", + "ELLIPSIS", + "PPHASH", + "PPPRAGMA", + "PPPRAGMASTR", +]; + +// Allow either "# line" or "# " to support GCC's cpp output +const linePattern = /([ \t]*line\W)|([ \t]*\d+)/y; +const pragmaPattern = /[ \t]*pragma\W/y; + +/** + * A lexer for the C language (pycparser's CLexer). After build(), set the + * input with input() and call token() for tokens. + */ +export class CLexer { + constructor({ error_func, on_lbrace_func, on_rbrace_func, type_lookup_func }) { + this.error_func = error_func; + this.on_lbrace_func = on_lbrace_func; + this.on_rbrace_func = on_rbrace_func; + this.type_lookup_func = type_lookup_func; + this.filename = ""; + this.last_token = null; + this.pp_line = null; + this.pp_filename = null; + } + + build() { + this.lexer = new PlyLexer(this); + this.tokens = tokens; + } + + reset_lineno() { this.lexer.lineno = 1; } + + input(text) { this.lexer.input(text); } + + token() { + this.last_token = this.lexer.token(); + return this.last_token; + } + + _error(msg, token) { + this.error_func(msg, token.lineno, token.lexpos); + this.lexer.skip(1); + } + + t_PPHASH(t) { + const lx = t.lexer; + linePattern.lastIndex = lx.lexpos; + pragmaPattern.lastIndex = lx.lexpos; + if (linePattern.test(lx.lexdata)) { + lx.begin("ppline"); + this.pp_line = this.pp_filename = null; + } else if (pragmaPattern.test(lx.lexdata)) { + lx.begin("pppragma"); + } else { + t.type = "PPHASH"; + return t; + } + return null; + } + + t_ppline_FILENAME(t) { + if (this.pp_line == null) this._error("filename before line number in #line", t); + else this.pp_filename = t.value.replace(/^"+/, "").replace(/"+$/, ""); + return null; + } + + t_ppline_LINE_NUMBER(t) { + if (this.pp_line == null) this.pp_line = t.value; + // else: GCC's cpp sometimes inserts a numeric flag after the file name + return null; + } + + t_ppline_NEWLINE(t) { + if (this.pp_line == null) this._error("line number missing in #line", t); + else { + this.lexer.lineno = pyInt(this.pp_line); + if (this.pp_filename != null) this.filename = this.pp_filename; + } + t.lexer.begin("INITIAL"); + return null; + } + + t_ppline_PPLINE() { return null; } + + t_ppline_error(t) { this._error("invalid #line directive", t); return null; } + + t_pppragma_NEWLINE(t) { + t.lexer.lineno += 1; + t.lexer.begin("INITIAL"); + return null; + } + + t_pppragma_PPPRAGMA(t) { return t; } + + t_pppragma_STR(t) { + t.type = "PPPRAGMASTR"; + return t; + } + + t_pppragma_error(t) { this._error("invalid #pragma directive", t); return null; } + + t_NEWLINE(t) { + t.lexer.lineno += t.value.split("\n").length - 1; + return null; + } + + t_LBRACE(t) { this.on_lbrace_func(); return t; } + t_RBRACE(t) { this.on_rbrace_func(); return t; } + + t_FLOAT_CONST(t) { return t; } + t_HEX_FLOAT_CONST(t) { return t; } + t_INT_CONST_HEX(t) { return t; } + t_INT_CONST_BIN(t) { return t; } + t_BAD_CONST_OCT(t) { this._error("Invalid octal constant", t); return null; } + t_UNSUPPORTED_C_STYLE_COMMENT(t) { this._error("Comments are not supported, see https://github.com/eliben/pycparser#3using.", t); return null; } + t_UNSUPPORTED_CXX_STYLE_COMMENT(t) { this._error("Comments are not supported, see https://github.com/eliben/pycparser#3using.", t); return null; } + t_INT_CONST_OCT(t) { return t; } + t_INT_CONST_DEC(t) { return t; } + t_INT_CONST_CHAR(t) { return t; } + t_CHAR_CONST(t) { return t; } + t_WCHAR_CONST(t) { return t; } + t_U8CHAR_CONST(t) { return t; } + t_U16CHAR_CONST(t) { return t; } + t_U32CHAR_CONST(t) { return t; } + t_UNMATCHED_QUOTE(t) { this._error("Unmatched '", t); return null; } + t_BAD_CHAR_CONST(t) { this._error(`Invalid char constant ${t.value}`, t); return null; } + t_WSTRING_LITERAL(t) { return t; } + t_U8STRING_LITERAL(t) { return t; } + t_U16STRING_LITERAL(t) { return t; } + t_U32STRING_LITERAL(t) { return t; } + t_BAD_STRING_LITERAL(t) { this._error("String contains invalid escape code", t); return null; } + + t_ID(t) { + let tp = keywordMap.has(t.value) ? keywordMap.get(t.value) : "ID"; + if (!tp) return null; + if (tp === "ID" && this.type_lookup_func(t.value)) tp = "TYPEID"; + t.type = tp; + return t; + } + + t_error(t) { + this._error(`Illegal character ${pyCharRepr(t.value[0])}`, t); + return null; + } +} + +/** int() of a decimal-constant spelling (the #line rule only matches decimals). */ +function pyInt(s) { + const m = /^\d+/.exec(s); + if (!m || m[0].length !== s.length) throw new Error(`invalid literal for int() with base 10: '${s}'`); + return Number(s); +} + +function pyCharRepr(ch) { + if (ch === "'") return "\"'\""; + if (ch === "\\") return "'\\\\'"; + if (ch === "\n") return "'\\n'"; + if (ch === "\t") return "'\\t'"; + if (ch === "\r") return "'\\r'"; + const code = ch.charCodeAt(0); + if (code < 0x20 || code === 0x7f) return `'\\x${code.toString(16).padStart(2, "0")}'`; + return `'${ch}'`; +} diff --git a/packages/romdev-pycparser/src/c_parser.js b/packages/romdev-pycparser/src/c_parser.js new file mode 100644 index 00000000..2ba92158 --- /dev/null +++ b/packages/romdev-pycparser/src/c_parser.js @@ -0,0 +1,760 @@ +// c_parser.js - CParser, a port of pycparser's c_parser.py (the m2c / +// decomp-permuter fork with GCC extensions) and plyparser.py. +// +// The grammar actions below are the p_* methods of the upstream CParser, one +// for one, keyed by the function names the LALR tables (tables/yacctab.json) +// refer to. Parameterized rules (p_xxx_declarator with xxx in id / typeid / +// typeid_noparen) are expanded the way plyparser.template does. +import yacctab from "./tables/yacctab.json" with { type: "json" }; +import * as c_ast from "./c_ast.js"; +import { CLexer } from "./c_lexer.js"; +import { LRParser } from "./ply_yacc.js"; +import { fix_switch_cases, fix_atomic_specifiers } from "./ast_transforms.js"; + +/** Coordinates of a syntactic element (plyparser.Coord). */ +export class Coord { + constructor(file, line, lexdata, lexpos) { + this.file = file; + this.line = line; + this.lexdata = lexdata; + this.lexpos = lexpos; + } + + get column() { + return this.lexpos - rfindNewline(this.lexdata, this.lexpos); + } + + source_line() { + const start = this.lexpos - this.column + 1; + let end = this.lexdata.indexOf("\n", start); + if (end === -1) end = this.lexdata.length; + return this.lexdata.slice(start, end).replace(/\r+$/, ""); + } + + toString() { return `${this.file}:${this.line}:${this.column}`; } +} + +export class ParseError extends Error { + constructor(message, coord) { + super(message); + this.name = "ParseError"; + this.coord = coord; + } +} + +const S = (x) => (x == null ? "None" : String(x)); + +// Python rfind(sub, 0, end) searches s[0:end]; lastIndexOf(sub, end-1) is the +// same for a one-char needle, except that end == 0 must find nothing. +function rfindNewline(s, end) { + if (end <= 0) return -1; + return s.lastIndexOf("\n", end - 1); +} + +const newSpec = () => ({ qual: [], storage: [], type: [], function: [], alignment: [], attr: [] }); + +const RULES_WITH_OPT = [ + "abstract_declarator", "assignment_expression", "declaration_list", "declaration_specifiers_no_type", + "designation", "expression", "identifier_list", "init_declarator_list", "id_init_declarator_list", + "initializer_list", "parameter_type_list", "block_item_list", "type_qualifier_list", + "struct_declarator_list", "asm_label", "asm_qualifiers", "asm_operands", "asm_symbolic_name", + "asm_string_list", "asm_goto_list", "gcc_attributes", +]; + +export class CParser { + constructor() { + this.clex = new CLexer({ + error_func: (msg, line, column) => this._lex_error_func(msg, line, column), + on_lbrace_func: () => this._push_scope(), + on_rbrace_func: () => this._pop_scope(), + type_lookup_func: (name) => this._is_type_in_scope(name), + }); + this.clex.build(); + this.tokens = this.clex.tokens; + this.cparser = new LRParser(yacctab, this._actions(), (p) => this.p_error(p)); + this._scope_stack = [this._make_initial_scope()]; + this._last_yielded_token = null; + } + + /** Parse C code and return a FileAST. */ + parse(text, filename = "", debug = false) { + void debug; + this.clex.filename = filename; + this.clex.reset_lineno(); + this._scope_stack = [this._make_initial_scope()]; + this._last_yielded_token = null; + return this.cparser.parse(text, this.clex); + } + + _make_initial_scope() { return new Map([["__builtin_va_list", true]]); } + + _push_scope() { this._scope_stack.push(new Map()); } + + _pop_scope() { + if (!(this._scope_stack.length > 1)) throw new AssertionError(); + this._scope_stack.pop(); + } + + _add_typedef_name(name, coord) { + const top = this._scope_stack[this._scope_stack.length - 1]; + if (!(top.has(name) ? top.get(name) : true)) { + this._parse_error(`Typedef ${pyQuote(name)} previously declared as non-typedef in this scope`, coord); + } + top.set(name, true); + } + + _add_identifier(name, coord) { + const top = this._scope_stack[this._scope_stack.length - 1]; + if (top.has(name) ? top.get(name) : false) { + this._parse_error(`Non-typedef ${pyQuote(name)} previously declared as typedef in this scope`, coord); + } + top.set(name, false); + } + + _is_type_in_scope(name) { + for (let i = this._scope_stack.length - 1; i >= 0; i--) { + const s = this._scope_stack[i]; + if (s.has(name)) { + const v = s.get(name); + if (v != null) return v; + } + } + return false; + } + + _lex_error_func(msg, line, lexpos) { this._parse_error(msg, this._coord(line, lexpos)); } + + _get_yacc_lookahead_token() { return this.clex.last_token; } + + _coord(lineno, lexpos) { + return new Coord(this.clex.filename, lineno, this.clex.lexer.lexdata, lexpos); + } + + _token_coord(p, token_idx) { return this._coord(p.lineno(token_idx), p.lexpos(token_idx)); } + + _parse_error(msg, coord) { throw new ParseError(`${S(coord)}: ${msg}`, coord); } + + _type_modify_decl(decl, modifier) { + const modifier_head = modifier; + let modifier_tail = modifier; + while (modifier_tail.type) modifier_tail = modifier_tail.type; + if (decl instanceof c_ast.TypeDecl) { + modifier_tail.type = decl; + return modifier; + } + let decl_tail = decl; + while (!(decl_tail.type instanceof c_ast.TypeDecl)) decl_tail = decl_tail.type; + modifier_tail.type = decl_tail.type; + decl_tail.type = modifier_head; + return decl; + } + + _fix_decl_name_type(decl, typename) { + let type = decl; + while (!(type instanceof c_ast.TypeDecl)) type = type.type; + decl.name = type.declname; + type.quals = decl.quals.slice(); + for (const tn of typename) { + if (!(tn instanceof c_ast.IdentifierType)) { + if (typename.length > 1) this._parse_error("Invalid multiple types specified", tn.coord); + else { + type.type = tn; + return decl; + } + } + } + if (!typename.length) { + if (!(decl.type instanceof c_ast.FuncDecl)) this._parse_error("Missing type in declaration", decl.coord); + type.type = new c_ast.IdentifierType(["int"], decl.coord); + } else { + type.type = new c_ast.IdentifierType(typename.flatMap((id) => id.names), typename[0].coord); + } + return decl; + } + + _add_declaration_specifier(declspec, newspec, kind, append = false) { + const spec = declspec || newSpec(); + if (append) spec[kind].push(newspec); + else spec[kind].unshift(newspec); + return spec; + } + + _add_declaration_specifier_list(declspec, newspecs, kind, append = false) { + const spec = declspec || newSpec(); + if (append) spec[kind].push(...newspecs); + else spec[kind].splice(0, 0, ...newspecs); + return spec; + } + + _build_declarations(spec, decls, typedef_namespace = false) { + const is_typedef = spec.storage.includes("typedef"); + const declarations = []; + if (decls[0].bitsize != null) { + // Bit-fields are allowed to be unnamed. + } else if (decls[0].decl == null) { + const ty = spec.type; + if (ty.length < 2 || ty[ty.length - 1].names.length !== 1 || !this._is_type_in_scope(ty[ty.length - 1].names[0])) { + let coord = "?"; + for (const t of ty) { + if (t instanceof c_ast.Node || (t && "coord" in t)) { coord = t.coord; break; } + } + this._parse_error("Invalid declaration", coord); + } + decls[0].decl = new c_ast.TypeDecl(ty[ty.length - 1].names[0], null, null, spec.alignment, ty[ty.length - 1].coord); + ty.splice(ty.length - 1, 1); + } else if (!(decls[0].decl instanceof c_ast.Enum || decls[0].decl instanceof c_ast.Struct + || decls[0].decl instanceof c_ast.Union || decls[0].decl instanceof c_ast.IdentifierType)) { + let decls_0_tail = decls[0].decl; + while (!(decls_0_tail instanceof c_ast.TypeDecl)) decls_0_tail = decls_0_tail.type; + if (decls_0_tail.declname == null) { + decls_0_tail.declname = spec.type[spec.type.length - 1].names[0]; + spec.type.splice(spec.type.length - 1, 1); + } + } + for (const decl of decls) { + if (decl.decl == null) throw new AssertionError(); + const attrs = spec.attr.concat(decl.attr || []); + let declaration; + if (is_typedef) { + declaration = new c_ast.Typedef(null, spec.qual, spec.storage, attrs, decl.decl, decl.decl.coord); + } else { + declaration = new c_ast.Decl(null, spec.qual, spec.alignment, spec.storage, spec.function, attrs, decl.decl, + decl.init ?? null, decl.bitsize ?? null, decl.asmlabel ?? null, decl.decl.coord); + } + let fixed_decl; + const t = declaration.type; + if (t instanceof c_ast.Enum || t instanceof c_ast.Struct || t instanceof c_ast.Union || t instanceof c_ast.IdentifierType) { + fixed_decl = declaration; + } else { + fixed_decl = this._fix_decl_name_type(declaration, spec.type); + } + if (typedef_namespace) { + if (is_typedef) this._add_typedef_name(fixed_decl.name, fixed_decl.coord); + else this._add_identifier(fixed_decl.name, fixed_decl.coord); + } + fixed_decl = fix_atomic_specifiers(fixed_decl); + declarations.push(fixed_decl); + } + return declarations; + } + + _build_function_definition(spec, decl, param_decls, body) { + if (spec.storage.includes("typedef")) this._parse_error("Invalid typedef", decl.coord); + const declaration = this._build_declarations(spec, [{ decl, init: null }], true)[0]; + return new c_ast.FuncDef(declaration, param_decls, body, decl.coord); + } + + _select_struct_union_class(token) { return token === "struct" ? c_ast.Struct : c_ast.Union; } + + p_error(p) { + if (p) this._parse_error(`before: ${p.value}`, this._coord(p.lineno, p.lexpos)); + else this._parse_error("At end of input", this.clex.filename); + } + + /** The grammar actions, keyed by upstream function name. */ + _actions() { + const self = this; + const A = {}; + for (const rule of RULES_WITH_OPT) A[`p_${rule}_opt`] = (p) => p.set(0, p.get(1)); + + A.p_translation_unit_or_empty = (p) => { + p.set(0, p.get(1) == null ? new c_ast.FileAST([]) : new c_ast.FileAST(p.get(1))); + }; + A.p_translation_unit_1 = (p) => p.set(0, p.get(1)); + A.p_translation_unit_2 = (p) => { p.get(1).push(...p.get(2)); p.set(0, p.get(1)); }; + A.p_external_declaration_1 = (p) => p.set(0, [p.get(1)]); + A.p_external_declaration_2 = (p) => p.set(0, p.get(1)); + A.p_external_declaration_3 = (p) => p.set(0, [p.get(1)]); + A.p_external_declaration_4 = (p) => p.set(0, []); + A.p_external_declaration_5 = (p) => p.set(0, p.get(1)); + A.p_external_declaration_6 = (p) => p.set(0, [p.get(1)]); + A.p_global_asm = (p) => p.set(0, new c_ast.Asm([], p.get(3), [], [], [], [], self._token_coord(p, 1))); + A.p_static_assert_declaration = (p) => { + if (p.length === 5) p.set(0, [new c_ast.StaticAssert(p.get(3), null, self._token_coord(p, 1))]); + else p.set(0, [new c_ast.StaticAssert(p.get(3), p.get(5), self._token_coord(p, 1))]); + }; + A.p_pp_directive = (p) => self._parse_error("Directives not supported yet", self._token_coord(p, 1)); + A.p_pppragma_directive = (p) => { + if (p.length === 5) p.set(0, new c_ast.Pragma(p.get(3), self._token_coord(p, 2))); + else if (p.length === 3) p.set(0, new c_ast.Pragma(p.get(2), self._token_coord(p, 2))); + else p.set(0, new c_ast.Pragma("", self._token_coord(p, 1))); + }; + A.p_pppragma_directive_list = (p) => p.set(0, p.length === 2 ? [p.get(1)] : p.get(1).concat([p.get(2)])); + A.p_function_definition_1 = (p) => { + const tp = new c_ast.IdentifierType(["int"], self._token_coord(p, 1)); + const spec = self._add_declaration_specifier(null, tp, "type"); + p.set(0, self._build_function_definition(spec, p.get(1), p.get(2), p.get(3))); + }; + A.p_function_definition_2 = (p) => { + p.set(0, self._build_function_definition(p.get(1), p.get(2), p.get(3), p.get(4))); + }; + A.p_statement = (p) => p.set(0, p.get(1)); + A.p_pragmacomp_or_statement = (p) => { + if (p.length === 3) p.set(0, new c_ast.Compound(p.get(1).concat([p.get(2)]), self._token_coord(p, 1))); + else p.set(0, p.get(1)); + }; + A.p_decl_body = (p) => { + const spec = p.get(1); + let decls; + if (p.get(2) == null) { + const ty = spec.type; + if (ty.length === 1 && (ty[0] instanceof c_ast.Struct || ty[0] instanceof c_ast.Union || ty[0] instanceof c_ast.Enum)) { + decls = [new c_ast.Decl(null, spec.qual, spec.alignment, spec.storage, spec.function, spec.attr, ty[0], + null, null, null, ty[0].coord)]; + } else { + decls = self._build_declarations(spec, [{ decl: null, init: null }], true); + } + } else { + decls = self._build_declarations(spec, p.get(2), true); + } + p.set(0, decls); + }; + A.p_declaration = (p) => p.set(0, p.get(1)); + A.p_declaration_list = (p) => p.set(0, p.length === 2 ? p.get(1) : p.get(1).concat(p.get(2))); + A.p_declaration_specifiers_no_type_1 = (p) => p.set(0, self._add_declaration_specifier(p.get(2), p.get(1), "qual")); + A.p_declaration_specifiers_no_type_2 = (p) => p.set(0, self._add_declaration_specifier(p.get(2), p.get(1), "storage")); + A.p_declaration_specifiers_no_type_3 = (p) => p.set(0, self._add_declaration_specifier(p.get(2), p.get(1), "function")); + A.p_declaration_specifiers_no_type_4 = (p) => p.set(0, self._add_declaration_specifier(p.get(2), p.get(1), "type")); + A.p_declaration_specifiers_no_type_5 = (p) => p.set(0, self._add_declaration_specifier(p.get(2), p.get(1), "alignment")); + A.p_declaration_specifiers_no_type_attrs = (p) => p.set(0, self._add_declaration_specifier_list(p.get(2), p.get(1), "attr")); + A.p_declaration_specifiers_1 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "qual", true)); + A.p_declaration_specifiers_2 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "storage", true)); + A.p_declaration_specifiers_3 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "function", true)); + A.p_declaration_specifiers_4 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "type", true)); + A.p_declaration_specifiers_5 = (p) => p.set(0, self._add_declaration_specifier(null, p.get(1), "type")); + A.p_declaration_specifiers_6 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "type", true)); + A.p_declaration_specifiers_7 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "alignment", true)); + A.p_declaration_specifiers_attrs = (p) => p.set(0, self._add_declaration_specifier_list(p.get(1), p.get(2), "attr", true)); + A.p_storage_class_specifier = (p) => p.set(0, p.get(1)); + A.p_function_specifier = (p) => p.set(0, p.get(1).replaceAll("__", "")); + A.p_type_specifier_no_typeid = (p) => p.set(0, new c_ast.IdentifierType([p.get(1)], self._token_coord(p, 1))); + A.p_type_specifier = (p) => p.set(0, p.get(1)); + A.p_type_specifier_gnu_typeof = (p) => p.set(0, new c_ast.Typeof(p.get(3), self._token_coord(p, 1))); + A.p_atomic_specifier = (p) => { + const typ = p.get(3); + typ.quals.push("_Atomic"); + p.set(0, typ); + }; + A.p_type_qualifier = (p) => p.set(0, p.get(1).replaceAll("__", "")); + A.p_init_declarator_list = (p) => p.set(0, p.length === 4 ? p.get(1).concat([p.get(3)]) : [p.get(1)]); + A.p_init_declarator = (p) => { + p.set(0, { decl: p.get(1), asmlabel: p.get(2), attr: p.get(3), init: p.length > 4 && p.get(4) === "=" ? p.get(5) : null }); + }; + A.p_id_init_declarator_list = (p) => p.set(0, p.length === 4 ? p.get(1).concat([p.get(3)]) : [p.get(1)]); + A.p_id_init_declarator = (p) => { + p.set(0, { decl: p.get(1), asmlabel: p.get(2), attr: p.get(3), init: p.length > 4 ? p.get(5) : null }); + }; + A.p_specifier_qualifier_list_1 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "type", true)); + A.p_specifier_qualifier_list_2 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "qual", true)); + A.p_specifier_qualifier_list_3 = (p) => p.set(0, self._add_declaration_specifier(null, p.get(1), "type")); + A.p_specifier_qualifier_list_4 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "type")); + A.p_specifier_qualifier_list_5 = (p) => p.set(0, self._add_declaration_specifier(null, p.get(1), "alignment")); + A.p_specifier_qualifier_list_6 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "alignment", true)); + A.p_specifier_qualifier_list_attr = (p) => p.set(0, self._add_declaration_specifier_list(p.get(1), p.get(2), "attr", true)); + A.p_struct_or_union_specifier_1 = (p) => { + const klass = self._select_struct_union_class(p.get(1)); + p.set(0, new klass(p.get(2), [], null, self._token_coord(p, 2))); + }; + A.p_struct_or_union_specifier_2 = (p) => { + const klass = self._select_struct_union_class(p.get(1)); + p.set(0, new klass(null, (p.get(2) || []).concat(p.get(p.length - 1) || []), p.length === 6 ? [] : p.get(4), self._token_coord(p, 3))); + }; + A.p_struct_or_union_specifier_3 = (p) => { + const klass = self._select_struct_union_class(p.get(1)); + p.set(0, new klass(p.get(2)[0], p.get(2)[1].concat(p.get(p.length - 1) || []), p.length === 6 ? [] : p.get(4), p.get(2)[2])); + }; + A.p_struct_or_union = (p) => p.set(0, p.get(1)); + A.p_struct_declaration_list = (p) => { + if (p.length === 2) p.set(0, p.get(1) || []); + else p.set(0, p.get(1).concat(p.get(2) || [])); + }; + A.p_struct_declaration_1 = (p) => { + const spec = p.get(1); + if (spec.storage.includes("typedef")) throw new AssertionError(); + let decls; + if (p.get(2) != null) { + decls = self._build_declarations(spec, p.get(2)); + } else if (spec.type.length === 1) { + const node = spec.type[0]; + const decl_type = node instanceof c_ast.Node ? node : new c_ast.IdentifierType(node); + decls = self._build_declarations(spec, [{ decl: decl_type }]); + } else { + decls = self._build_declarations(spec, [{ decl: null, init: null }]); + } + p.set(0, decls); + }; + A.p_struct_declaration_2 = (p) => p.set(0, null); + A.p_struct_declaration_3 = (p) => p.set(0, [p.get(1)]); + A.p_struct_declarator_list = (p) => p.set(0, p.length === 4 ? p.get(1).concat([p.get(3)]) : [p.get(1)]); + A.p_struct_declarator_1 = (p) => p.set(0, { decl: p.get(1), attr: p.get(2), bitsize: null }); + A.p_struct_declarator_2 = (p) => { + if (p.length > 4) p.set(0, { decl: p.get(1), attr: p.get(2), bitsize: p.get(4) }); + else p.set(0, { decl: new c_ast.TypeDecl(null, null, null, null), attr: p.get(1), bitsize: p.get(3) }); + }; + A.p_enum_specifier_1 = (p) => p.set(0, new c_ast.Enum(p.get(2), [], null, self._token_coord(p, 1))); + A.p_enum_specifier_2 = (p) => { + p.set(0, new c_ast.Enum(null, (p.get(2) || []).concat(p.get(6) || []), p.get(4), self._token_coord(p, 1))); + }; + A.p_enum_specifier_3 = (p) => { + p.set(0, new c_ast.Enum(p.get(2)[0], p.get(2)[1].concat(p.get(6) || []), p.get(4), self._token_coord(p, 1))); + }; + A.p_enumerator_list = (p) => { + if (p.length === 2) p.set(0, new c_ast.EnumeratorList([p.get(1)], p.get(1).coord)); + else if (p.length === 3) p.set(0, p.get(1)); + else { p.get(1).enumerators.push(p.get(3)); p.set(0, p.get(1)); } + }; + A.p_alignment_specifier = (p) => p.set(0, new c_ast.Alignas(p.get(3), self._token_coord(p, 1))); + A.p_enumerator = (p) => { + let enumerator; + if (p.length === 3) enumerator = new c_ast.Enumerator(p.get(1), p.get(2) || [], null, self._token_coord(p, 1)); + else enumerator = new c_ast.Enumerator(p.get(1), p.get(2) || [], p.get(4), self._token_coord(p, 1)); + self._add_identifier(enumerator.name, enumerator.coord); + p.set(0, enumerator); + }; + A.p_declarator = (p) => p.set(0, p.get(1)); + + // Parameterized declarator rules (plyparser.template expansion). + for (const xxx of ["id", "typeid", "typeid_noparen"]) { + A[`p_${xxx}_declarator_1`] = (p) => p.set(0, p.get(1)); + A[`p_${xxx}_declarator_2`] = (p) => p.set(0, self._type_modify_decl(p.get(2), p.get(1))); + A[`p_direct_${xxx}_declarator_1`] = (p) => { + p.set(0, new c_ast.TypeDecl(p.get(1), null, null, null, self._token_coord(p, 1))); + }; + if (xxx !== "typeid_noparen") A[`p_direct_${xxx}_declarator_2`] = (p) => p.set(0, p.get(2)); + A[`p_direct_${xxx}_declarator_3`] = (p) => { + const quals = (p.length > 5 ? p.get(3) : []) || []; + const arr = new c_ast.ArrayDecl(null, p.length > 5 ? p.get(4) : p.get(3), quals, p.get(1).coord); + p.set(0, self._type_modify_decl(p.get(1), arr)); + }; + A[`p_direct_${xxx}_declarator_4`] = (p) => { + const listed = [p.get(3), p.get(4)].map((item) => (Array.isArray(item) ? item : [item])); + const dim_quals = listed.flat().filter((q) => q != null); + const arr = new c_ast.ArrayDecl(null, p.get(5), dim_quals, p.get(1).coord); + p.set(0, self._type_modify_decl(p.get(1), arr)); + }; + A[`p_direct_${xxx}_declarator_5`] = (p) => { + const arr = new c_ast.ArrayDecl(null, new c_ast.ID(p.get(4), self._token_coord(p, 4)), p.get(3) != null ? p.get(3) : [], p.get(1).coord); + p.set(0, self._type_modify_decl(p.get(1), arr)); + }; + A[`p_direct_${xxx}_declarator_6`] = (p) => { + const func = new c_ast.FuncDecl(p.get(3), null, p.get(1).coord); + if (self._get_yacc_lookahead_token().type === "LBRACE") { + if (func.args != null) { + for (const param of func.args.params) { + if (param instanceof c_ast.EllipsisParam) break; + self._add_identifier(param.name, param.coord); + } + } + } + p.set(0, self._type_modify_decl(p.get(1), func)); + }; + } + + A.p_pointer = (p) => { + const coord = self._token_coord(p, 1); + const nested_type = new c_ast.PtrDecl(p.get(2) || [], null, coord); + if (p.length > 3) { + let tail_type = p.get(3); + while (tail_type.type != null) tail_type = tail_type.type; + tail_type.type = nested_type; + p.set(0, p.get(3)); + } else { + p.set(0, nested_type); + } + }; + A.p_type_qualifier_list = (p) => p.set(0, p.length === 2 ? [p.get(1)] : p.get(1).concat([p.get(2)])); + A.p_type_qualifier_list_1 = (p) => p.set(0, self._add_declaration_specifier(null, p.get(1), "qual", true)); + A.p_type_qualifier_list_2 = (p) => p.set(0, self._add_declaration_specifier(p.get(1), p.get(2), "qual", true)); + A.p_type_qualifier_list_3 = (p) => p.set(0, self._add_declaration_specifier_list(null, p.get(1), "attr", true)); + A.p_type_qualifier_list_4 = (p) => p.set(0, self._add_declaration_specifier_list(p.get(1), p.get(2), "attr", true)); + A.p_parameter_type_list = (p) => { + if (p.length > 2) p.get(1).params.push(new c_ast.EllipsisParam(self._token_coord(p, 3))); + p.set(0, p.get(1)); + }; + A.p_parameter_list = (p) => { + if (p.length === 2) p.set(0, new c_ast.ParamList([p.get(1)], p.get(1).coord)); + else { p.get(1).params.push(p.get(3)); p.set(0, p.get(1)); } + }; + A.p_parameter_declaration_1 = (p) => { + let spec = p.get(1); + if (truthy(p.get(3))) spec = self._add_declaration_specifier_list(spec, p.get(3), "attr", true); + if (!spec.type.length) spec.type = [new c_ast.IdentifierType(["int"], self._token_coord(p, 1))]; + p.set(0, self._build_declarations(spec, [{ decl: p.get(2) }])[0]); + }; + A.p_parameter_declaration_2 = (p) => { + let spec = p.get(1); + if (truthy(p.get(3))) spec = self._add_declaration_specifier_list(spec, p.get(3), "attr", true); + if (!spec.type.length) spec.type = [new c_ast.IdentifierType(["int"], self._token_coord(p, 1))]; + let decl; + const ty = spec.type; + if (ty.length > 1 && ty[ty.length - 1].names.length === 1 && self._is_type_in_scope(ty[ty.length - 1].names[0])) { + decl = self._build_declarations(spec, [{ decl: p.get(2), init: null }])[0]; + } else { + decl = new c_ast.Typename("", spec.qual, null, spec.attr, p.get(2) || new c_ast.TypeDecl(null, null, null, null), self._token_coord(p, 2)); + decl = self._fix_decl_name_type(decl, spec.type); + } + p.set(0, decl); + }; + A.p_identifier_list = (p) => { + if (p.length === 2) p.set(0, new c_ast.ParamList([p.get(1)], p.get(1).coord)); + else { p.get(1).params.push(p.get(3)); p.set(0, p.get(1)); } + }; + A.p_initializer_1 = (p) => p.set(0, p.get(1)); + A.p_initializer_2 = (p) => { + if (p.get(2) == null) p.set(0, new c_ast.InitList([], self._token_coord(p, 1))); + else p.set(0, p.get(2)); + }; + A.p_initializer_list = (p) => { + if (p.length === 3) { + const init = p.get(1) == null ? p.get(2) : new c_ast.NamedInitializer(p.get(1), p.get(2)); + p.set(0, new c_ast.InitList([init], p.get(2).coord)); + } else { + const init = p.get(3) == null ? p.get(4) : new c_ast.NamedInitializer(p.get(3), p.get(4)); + p.get(1).exprs.push(init); + p.set(0, p.get(1)); + } + }; + A.p_designation = (p) => p.set(0, p.get(1)); + A.p_designator_list = (p) => p.set(0, p.length === 2 ? [p.get(1)] : p.get(1).concat([p.get(2)])); + A.p_designator = (p) => p.set(0, p.get(2)); + A.p_range_designator = (p) => p.set(0, new c_ast.Range(p.get(2), p.get(4), self._token_coord(p, 1))); + A.p_type_name = (p) => { + const typename = new c_ast.Typename("", p.get(1).qual.slice(), null, p.get(1).attr, + p.get(2) || new c_ast.TypeDecl(null, null, null, null), self._token_coord(p, 2)); + p.set(0, self._fix_decl_name_type(typename, p.get(1).type)); + }; + A.p_abstract_declarator_1 = (p) => { + const dummytype = new c_ast.TypeDecl(null, null, null, null); + p.set(0, self._type_modify_decl(dummytype, p.get(1))); + }; + A.p_abstract_declarator_2 = (p) => p.set(0, self._type_modify_decl(p.get(2), p.get(1))); + A.p_abstract_declarator_3 = (p) => p.set(0, p.get(1)); + A.p_direct_abstract_declarator_1 = (p) => p.set(0, p.get(2)); + A.p_direct_abstract_declarator_2 = (p) => { + const arr = new c_ast.ArrayDecl(null, p.get(3), [], p.get(1).coord); + p.set(0, self._type_modify_decl(p.get(1), arr)); + }; + A.p_direct_abstract_declarator_3 = (p) => { + const quals = (p.length > 4 ? p.get(2) : []) || []; + p.set(0, new c_ast.ArrayDecl(new c_ast.TypeDecl(null, null, null, null), p.length > 4 ? p.get(3) : p.get(2), quals, self._token_coord(p, 1))); + }; + A.p_direct_abstract_declarator_4 = (p) => { + const arr = new c_ast.ArrayDecl(null, new c_ast.ID(p.get(3), self._token_coord(p, 3)), [], p.get(1).coord); + p.set(0, self._type_modify_decl(p.get(1), arr)); + }; + A.p_direct_abstract_declarator_5 = (p) => { + p.set(0, new c_ast.ArrayDecl(new c_ast.TypeDecl(null, null, null, null), new c_ast.ID(p.get(3), self._token_coord(p, 3)), [], self._token_coord(p, 1))); + }; + A.p_direct_abstract_declarator_6 = (p) => { + const func = new c_ast.FuncDecl(p.get(3), null, p.get(1).coord); + p.set(0, self._type_modify_decl(p.get(1), func)); + }; + A.p_direct_abstract_declarator_7 = (p) => { + p.set(0, new c_ast.FuncDecl(p.get(2), new c_ast.TypeDecl(null, null, null, null), self._token_coord(p, 1))); + }; + A.p_direct_abstract_declarator_8 = (p) => { + const listed = [p.get(2), p.get(3)].map((item) => (Array.isArray(item) ? item : [item])); + const quals = listed.flat().filter((q) => q != null); + p.set(0, new c_ast.ArrayDecl(new c_ast.TypeDecl(null, null, null, null), p.get(4), quals, self._token_coord(p, 1))); + }; + A.p_block_item = (p) => p.set(0, Array.isArray(p.get(1)) ? p.get(1) : [p.get(1)]); + A.p_block_item_list = (p) => { + const v2 = p.length === 2 ? null : p.get(2); + const isNoneList = Array.isArray(v2) && v2.length === 1 && v2[0] == null; + p.set(0, p.length === 2 || isNoneList ? p.get(1) : p.get(1).concat(v2)); + }; + A.p_compound_statement_1 = (p) => p.set(0, new c_ast.Compound(p.get(2), self._token_coord(p, 1))); + A.p_labeled_statement_1 = (p) => p.set(0, new c_ast.Label(p.get(1), p.get(3), self._token_coord(p, 1))); + A.p_labeled_statement_2 = (p) => p.set(0, new c_ast.Case(p.get(2), [p.get(4)], self._token_coord(p, 1))); + A.p_labeled_statement_range = (p) => { + p.set(0, new c_ast.Case(new c_ast.Range(p.get(2), p.get(4), self._token_coord(p, 2)), [p.get(6)], self._token_coord(p, 1))); + }; + A.p_labeled_statement_3 = (p) => p.set(0, new c_ast.Default([p.get(3)], self._token_coord(p, 1))); + A.p_labeled_statement_4 = (p) => { + p.set(0, new c_ast.Label(p.get(1), new c_ast.EmptyStatement(self._token_coord(p, 1)), self._token_coord(p, 1))); + }; + A.p_labeled_statement_5 = (p) => { + p.set(0, new c_ast.Case(p.get(2), [new c_ast.EmptyStatement(self._token_coord(p, 2))], self._token_coord(p, 1))); + }; + A.p_labeled_statement_range_2 = (p) => { + p.set(0, new c_ast.Case(new c_ast.Range(p.get(2), p.get(4), self._token_coord(p, 2)), + [new c_ast.EmptyStatement(self._token_coord(p, 2))], self._token_coord(p, 1))); + }; + A.p_labeled_statement_6 = (p) => { + p.set(0, new c_ast.Default([new c_ast.EmptyStatement(self._token_coord(p, 1))], self._token_coord(p, 1))); + }; + A.p_selection_statement_1 = (p) => p.set(0, new c_ast.If(p.get(3), p.get(5), null, self._token_coord(p, 1))); + A.p_selection_statement_2 = (p) => p.set(0, new c_ast.If(p.get(3), p.get(5), p.get(7), self._token_coord(p, 1))); + A.p_selection_statement_3 = (p) => p.set(0, fix_switch_cases(new c_ast.Switch(p.get(3), p.get(5), self._token_coord(p, 1)))); + A.p_iteration_statement_1 = (p) => p.set(0, new c_ast.While(p.get(3), p.get(5), self._token_coord(p, 1))); + A.p_iteration_statement_2 = (p) => p.set(0, new c_ast.DoWhile(p.get(5), p.get(2), self._token_coord(p, 1))); + A.p_iteration_statement_3 = (p) => p.set(0, new c_ast.For(p.get(3), p.get(5), p.get(7), p.get(9), self._token_coord(p, 1))); + A.p_iteration_statement_4 = (p) => { + p.set(0, new c_ast.For(new c_ast.DeclList(p.get(3), self._token_coord(p, 1)), p.get(4), p.get(6), p.get(8), self._token_coord(p, 1))); + }; + A.p_jump_statement_1 = (p) => p.set(0, new c_ast.Goto(p.get(2), self._token_coord(p, 1))); + A.p_jump_statement_2 = (p) => p.set(0, new c_ast.Break(self._token_coord(p, 1))); + A.p_jump_statement_3 = (p) => p.set(0, new c_ast.Continue(self._token_coord(p, 1))); + A.p_jump_statement_4 = (p) => p.set(0, new c_ast.Return(p.length === 4 ? p.get(2) : null, self._token_coord(p, 1))); + A.p_expression_statement = (p) => { + if (p.get(1) == null) p.set(0, new c_ast.EmptyStatement(self._token_coord(p, 2))); + else p.set(0, p.get(1)); + }; + A.p_expression = (p) => { + if (p.length === 2) p.set(0, p.get(1)); + else { + if (!(p.get(1) instanceof c_ast.ExprList)) p.set(1, new c_ast.ExprList([p.get(1)], p.get(1).coord)); + p.get(1).exprs.push(p.get(3)); + p.set(0, p.get(1)); + } + }; + A.p_parenthesized_compound_expression = (p) => p.set(0, p.get(2)); + A.p_typedef_name = (p) => p.set(0, new c_ast.IdentifierType([p.get(1)], self._token_coord(p, 1))); + A.p_assignment_expression = (p) => { + if (p.length === 2) p.set(0, p.get(1)); + else p.set(0, new c_ast.Assignment(p.get(2), p.get(1), p.get(3), p.get(1).coord)); + }; + A.p_assignment_operator = (p) => p.set(0, p.get(1)); + A.p_constant_expression = (p) => p.set(0, p.get(1)); + A.p_conditional_expression = (p) => { + if (p.length === 2) p.set(0, p.get(1)); + else p.set(0, new c_ast.TernaryOp(p.get(1), p.get(3), p.get(5), p.get(1).coord)); + }; + A.p_binary_expression = (p) => { + if (p.length === 2) p.set(0, p.get(1)); + else p.set(0, new c_ast.BinaryOp(p.get(2), p.get(1), p.get(3), p.get(1).coord)); + }; + A.p_cast_expression_2 = (p) => p.set(0, new c_ast.Cast(p.get(2), p.get(4), self._token_coord(p, 1))); + A.p_unary_expression_1 = (p) => p.set(0, p.get(1)); + A.p_unary_expression_2 = (p) => p.set(0, new c_ast.UnaryOp(p.get(1), p.get(2), p.get(2).coord)); + A.p_unary_expression_3 = (p) => { + p.set(0, new c_ast.UnaryOp(p.get(1).replaceAll("__alignof", "_Alignof").replaceAll("__", ""), + p.length === 3 ? p.get(2) : p.get(3), self._token_coord(p, 1))); + }; + A.p_unary_operator = (p) => p.set(0, p.get(1)); + A.p_postfix_expression_1 = (p) => p.set(0, p.get(1)); + A.p_postfix_expression_2 = (p) => p.set(0, new c_ast.ArrayRef(p.get(1), p.get(3), p.get(1).coord)); + A.p_postfix_expression_3 = (p) => p.set(0, new c_ast.FuncCall(p.get(1), p.length === 5 ? p.get(3) : null, p.get(1).coord)); + A.p_postfix_expression_4 = (p) => { + const field = new c_ast.ID(p.get(3), self._token_coord(p, 3)); + p.set(0, new c_ast.StructRef(p.get(1), p.get(2), field, p.get(1).coord)); + }; + A.p_postfix_expression_5 = (p) => p.set(0, new c_ast.UnaryOp("p" + p.get(2), p.get(1), p.get(1).coord)); + A.p_postfix_expression_6 = (p) => p.set(0, new c_ast.CompoundLiteral(p.get(2), p.get(5))); + A.p_primary_expression_1 = (p) => p.set(0, p.get(1)); + A.p_primary_expression_2 = (p) => p.set(0, p.get(1)); + A.p_primary_expression_3 = (p) => p.set(0, p.get(1)); + A.p_primary_expression_4 = (p) => p.set(0, p.get(2)); + A.p_primary_expression_5 = (p) => { + const coord = self._token_coord(p, 1); + p.set(0, new c_ast.FuncCall(new c_ast.ID(p.get(1), coord), new c_ast.ExprList([p.get(3), p.get(5)], coord), coord)); + }; + A.p_offsetof_member_designator = (p) => { + if (p.length === 2) p.set(0, p.get(1)); + else if (p.length === 4) p.set(0, new c_ast.StructRef(p.get(1), p.get(2), p.get(3), p.get(1).coord)); + else if (p.length === 5) p.set(0, new c_ast.ArrayRef(p.get(1), p.get(3), p.get(1).coord)); + else throw new Error(`Unexpected parsing state. len(p): ${p.length}`); + }; + A.p_argument_expression_list = (p) => { + if (p.length === 2) p.set(0, new c_ast.ExprList([p.get(1)], p.get(1).coord)); + else { p.get(1).exprs.push(p.get(3)); p.set(0, p.get(1)); } + }; + A.p_identifier = (p) => p.set(0, new c_ast.ID(p.get(1), self._token_coord(p, 1))); + A.p_constant_1 = (p) => { + let uCount = 0, lCount = 0; + for (const x of p.get(1).slice(-3)) { + if (x === "l" || x === "L") lCount++; + else if (x === "u" || x === "U") uCount++; + } + if (uCount > 1) throw new PyValueError("Constant cannot have more than one u/U suffix."); + if (lCount > 2) throw new PyValueError("Constant cannot have more than two l/L suffix."); + const prefix = "unsigned ".repeat(uCount) + "long ".repeat(lCount); + p.set(0, new c_ast.Constant(prefix + "int", p.get(1), self._token_coord(p, 1))); + }; + A.p_constant_2 = (p) => { + const v = p.get(1); + const last = v[v.length - 1]; + const t = last === "f" || last === "F" ? "float" : last === "l" || last === "L" ? "long double" : "double"; + p.set(0, new c_ast.Constant(t, v, self._token_coord(p, 1))); + }; + A.p_constant_3 = (p) => p.set(0, new c_ast.Constant("char", p.get(1), self._token_coord(p, 1))); + A.p_unified_string_literal = (p) => { + if (p.length === 2) p.set(0, new c_ast.Constant("string", p.get(1), self._token_coord(p, 1))); + else { + p.get(1).value = p.get(1).value.slice(0, -1) + p.get(2).slice(1); + p.set(0, p.get(1)); + } + }; + A.p_unified_wstring_literal = (p) => { + if (p.length === 2) p.set(0, new c_ast.Constant("string", p.get(1), self._token_coord(p, 1))); + else { + p.get(1).value = pyRstrip(p.get(1).value).slice(0, -1) + p.get(2).slice(2); + p.set(0, p.get(1)); + } + }; + A.p_attrs_id_typeid = (p) => { + if (p.length === 3) p.set(0, [p.get(2), p.get(1), self._token_coord(p, 2)]); + else p.set(0, [p.get(1), [], self._token_coord(p, 1)]); + }; + A.p_brace_open = (p) => { p.set(0, p.get(1)); p.set_lineno(0, p.lineno(1)); }; + A.p_brace_close = (p) => { p.set(0, p.get(1)); p.set_lineno(0, p.lineno(1)); }; + A.p_attr_stmt = (p) => p.set(0, new c_ast.GccAttributeStatement(p.get(1), self._token_coord(p, 2))); + A.p_asm_1 = (p) => p.set(0, new c_ast.Asm(p.get(2) || [], p.get(4), [], [], [], [], self._token_coord(p, 1))); + A.p_asm_2 = (p) => p.set(0, new c_ast.Asm(p.get(2) || [], p.get(4), p.get(6) || [], [], [], [], self._token_coord(p, 1))); + A.p_asm_3 = (p) => p.set(0, new c_ast.Asm(p.get(2) || [], p.get(4), p.get(6) || [], p.get(8) || [], [], [], self._token_coord(p, 1))); + A.p_asm_4 = (p) => p.set(0, new c_ast.Asm(p.get(2) || [], p.get(4), p.get(6) || [], p.get(8) || [], p.get(10) || [], [], self._token_coord(p, 1))); + A.p_asm_5 = (p) => p.set(0, new c_ast.Asm(p.get(2) || [], p.get(4), p.get(6) || [], p.get(8) || [], p.get(10) || [], p.get(12) || [], self._token_coord(p, 1))); + A.p_asm_operands = (p) => p.set(0, p.length === 4 ? p.get(1).concat([p.get(3)]) : [p.get(1)]); + A.p_asm_operand = (p) => p.set(0, new c_ast.AsmOperand(p.get(1), p.get(2), p.get(4), self._token_coord(p, 3))); + A.p_asm_string_list = (p) => p.set(0, p.length === 4 ? p.get(1).concat([p.get(3)]) : [p.get(1)]); + A.p_asm_goto_list = (p) => p.set(0, p.length === 4 ? p.get(1).concat([p.get(3)]) : [p.get(1)]); + A.p_asm_symbolic_name = (p) => p.set(0, p.get(2)); + A.p_asm_qualifiers = (p) => p.set(0, (p.get(1) || []).concat([p.get(2)])); + A.p_asm_label = (p) => p.set(0, p.get(3)); + A.p_gcc_attributes = (p) => p.set(0, p.length === 3 ? p.get(1).concat(p.get(2)) : p.get(1)); + A.p_gcc_attribute = (p) => p.set(0, p.get(4) || []); + A.p_gcc_attribute_list = (p) => p.set(0, p.length === 4 ? p.get(1).concat(p.get(3)) : p.get(1)); + A.p_gcc_attribute_item = (p) => { + if (!p.get(1)) p.set(0, []); + else { + let name = p.get(1); + if (name.length > 4 && name.startsWith("__") && name.endsWith("__")) name = name.slice(2, -2); + let args = null; + if (p.length > 2) args = p.get(3).exprs; + p.set(0, [new c_ast.GccAttribute(name, args, self._token_coord(p, 1))]); + } + }; + A.p_empty = (p) => p.set(0, null); + return A; + } +} + +export class AssertionError extends Error { + constructor(message = "") { + super(message); + this.name = "AssertionError"; + } +} + +export class PyValueError extends Error { + constructor(message) { + super(message); + this.name = "ValueError"; + } +} + +/** Python truthiness for values the grammar produces (None, lists, strings, nodes). */ +function truthy(v) { + if (v == null || v === false) return false; + if (Array.isArray(v) || typeof v === "string") return v.length > 0; + return true; +} + +function pyRstrip(s) { return s.replace(/[\s]+$/, ""); } + +/** Python repr() of a str, as %r formats it. */ +function pyQuote(s) { + if (s == null) return "None"; + const q = s.includes("'") && !s.includes("\"") ? "\"" : "'"; + return q + s.replaceAll("\\", "\\\\").replaceAll(q, "\\" + q) + q; +} diff --git a/packages/romdev-pycparser/src/index.js b/packages/romdev-pycparser/src/index.js new file mode 100644 index 00000000..dcd1e2a6 --- /dev/null +++ b/packages/romdev-pycparser/src/index.js @@ -0,0 +1,35 @@ +// romdev-pycparser - a plain-JS port of pycparser as vendored by m2c +// (m2c_pycparser) and decomp-permuter (perm_pycparser): the same fork of +// pycparser 2.23 with GCC extensions (attributes, asm, typeof, ...). +// +// import { CParser, CGenerator, c_ast } from "romdev-pycparser"; +// const ast = new CParser().parse(text, ""); +// const back = new CGenerator().visit(ast); +import { readFileSync } from "node:fs"; +import { CParser } from "./c_parser.js"; + +export * as c_ast from "./c_ast.js"; +export { Node, NodeVisitor, nodeRepr } from "./c_ast.js"; +export { CParser, Coord, ParseError, AssertionError, PyValueError } from "./c_parser.js"; +export { CLexer, LexToken, LexError, pyRegexToJs } from "./c_lexer.js"; +export { CGenerator } from "./c_generator.js"; +export { fix_switch_cases, fix_atomic_specifiers } from "./ast_transforms.js"; + +/** + * Parse a C file (pycparser.parse_file). Upstream can shell out to `cpp`; + * this port never spawns a host tool, so preprocessing is a caller-supplied + * function: pass `preprocess(filename) -> text` together with use_cpp. + * @param {string} filename + * @param {{use_cpp?: boolean, preprocess?: (filename: string) => string, parser?: CParser, encoding?: BufferEncoding}} [opts] + */ +export function parse_file(filename, { use_cpp = false, preprocess = null, parser = null, encoding = "utf8" } = {}) { + let text; + if (use_cpp) { + if (!preprocess) throw new Error("parse_file: use_cpp needs a preprocess(filename) function (no host cpp is spawned)"); + text = preprocess(filename); + } else { + // open(filename) in text mode: universal newlines (\r\n and lone \r become \n). + text = readFileSync(filename, encoding).replace(/\r\n?/g, "\n"); + } + return (parser ?? new CParser()).parse(text, filename); +} diff --git a/packages/romdev-pycparser/src/ply_yacc.js b/packages/romdev-pycparser/src/ply_yacc.js new file mode 100644 index 00000000..60c5138f --- /dev/null +++ b/packages/romdev-pycparser/src/ply_yacc.js @@ -0,0 +1,156 @@ +// ply_yacc.js - PLY's LR parsing engine (ply/yacc.py, LRParser.parseopt_notrack), +// driven by the precomputed LALR tables in tables/yacctab.json. +// +// Upstream calls yacc.yacc(optimize=True) with a committed yacctab.py, which +// PLY loads without re-checking the grammar, so those tables ARE upstream's +// parser. This engine is a line-by-line port of the optimized parse loop, +// including "defaulted states" (a state with a single reduce action reduces +// without fetching a lookahead), which is observable: pycparser's lexer +// callbacks (scope push/pop, typedef lookup) depend on exactly when the next +// token is read. + +export class YaccSymbol { + constructor(type = null, value = null) { + this.type = type; + this.value = value; + } + + toString() { return this.type; } +} + +/** The `p` argument of a grammar action. */ +export class YaccProduction { + constructor(slice, stack) { + this.slice = slice; + this.stack = stack; + this.lexer = null; + this.parser = null; + } + + /** p[n] */ + get(n) { return n >= 0 ? this.slice[n].value : this.stack[this.stack.length + n].value; } + + /** p[n] = v */ + set(n, v) { this.slice[n].value = v; } + + /** len(p) */ + get length() { return this.slice.length; } + + lineno(n) { return this.slice[n].lineno ?? 0; } + + set_lineno(n, lineno) { this.slice[n].lineno = lineno; } + + lexpos(n) { return this.slice[n].lexpos ?? 0; } +} + +/** + * @param {{action: [number, [string, number][]][], goto: [number, [string, number][]][], productions: any[][]}} tab + * @param {Record void>} actions grammar action per function name + * @param {(tok: any) => any} errorfunc p_error + */ +export class LRParser { + constructor(tab, actions, errorfunc) { + /** @type {Map>} */ + this.action = new Map(tab.action.map(([s, items]) => [s, new Map(items)])); + /** @type {Map>} */ + this.goto = new Map(tab.goto.map(([s, items]) => [s, new Map(items)])); + this.productions = tab.productions.map(([str, name, len, func]) => { + let callable = null; + if (func) { + callable = actions[func]; + if (!callable) throw new Error(`no grammar action ${func} (${str})`); + } + return { str, name, len, func, callable }; + }); + this.errorfunc = errorfunc; + this.setDefaultedStates(); + } + + setDefaultedStates() { + /** @type {Map} */ + this.defaultedStates = new Map(); + for (const [state, actions] of this.action) { + const rules = [...actions.values()]; + if (rules.length === 1 && rules[0] < 0) this.defaultedStates.set(state, rules[0]); + } + } + + parse(input, lexer) { + let lookahead = null; + const lookaheadstack = []; + const actions = this.action; + const gotoTab = this.goto; + const prod = this.productions; + const defaulted = this.defaultedStates; + const pslice = new YaccProduction(null); + pslice.lexer = lexer; + pslice.parser = this; + if (input != null) lexer.input(input); + const getToken = () => lexer.token(); + const statestack = []; + const symstack = []; + pslice.stack = symstack; + statestack.push(0); + symstack.push(new YaccSymbol("$end")); + let state = 0; + for (;;) { + let t; + if (!defaulted.has(state)) { + if (!lookahead) { + lookahead = lookaheadstack.length ? lookaheadstack.pop() : getToken(); + if (!lookahead) lookahead = new YaccSymbol("$end"); + } + const ltype = lookahead.type; + t = actions.get(state)?.get(ltype); + } else { + t = defaulted.get(state); + } + if (t !== undefined) { + if (t > 0) { + statestack.push(t); + state = t; + symstack.push(lookahead); + lookahead = null; + continue; + } + if (t < 0) { + const p = prod[-t]; + const pname = p.name; + const plen = p.len; + const sym = new YaccSymbol(pname, null); + if (plen) { + const targ = symstack.slice(symstack.length - plen - 1); + targ[0] = sym; + pslice.slice = targ; + symstack.length -= plen; + this.state = state; + p.callable(pslice); + statestack.length -= plen; + symstack.push(sym); + state = gotoTab.get(statestack[statestack.length - 1]).get(pname); + statestack.push(state); + continue; + } + const targ = [sym]; + pslice.slice = targ; + this.state = state; + p.callable(pslice); + symstack.push(sym); + state = gotoTab.get(statestack[statestack.length - 1]).get(pname); + statestack.push(state); + continue; + } + // t === 0: accept + const n = symstack[symstack.length - 1]; + return n.value ?? null; + } + // Syntax error. pycparser's p_error always raises, so there is no + // recovery path to port: report the offending token (null at EOF). + let errtoken = lookahead; + if (errtoken.type === "$end") errtoken = null; + this.state = state; + this.errorfunc(errtoken); + throw new Error("yacc: p_error returned without raising"); + } + } +} diff --git a/packages/romdev-pycparser/src/tables/c_ast.json b/packages/romdev-pycparser/src/tables/c_ast.json new file mode 100644 index 00000000..a96534d6 --- /dev/null +++ b/packages/romdev-pycparser/src/tables/c_ast.json @@ -0,0 +1,944 @@ +[ + { + "name": "ArrayDecl", + "fields": [ + "type", + "dim", + "dim_quals" + ], + "children": [ + [ + "type", + "single" + ], + [ + "dim", + "single" + ] + ], + "attrs": [ + "dim_quals" + ] + }, + { + "name": "ArrayRef", + "fields": [ + "name", + "subscript" + ], + "children": [ + [ + "name", + "single" + ], + [ + "subscript", + "single" + ] + ], + "attrs": [] + }, + { + "name": "Asm", + "fields": [ + "quals", + "asm", + "output_operands", + "input_operands", + "clobbers", + "gotos" + ], + "children": [ + [ + "asm", + "single" + ], + [ + "output_operands", + "list" + ], + [ + "input_operands", + "list" + ], + [ + "clobbers", + "list" + ] + ], + "attrs": [ + "quals", + "gotos" + ] + }, + { + "name": "AsmOperand", + "fields": [ + "symbolic_name", + "constraint", + "expr" + ], + "children": [ + [ + "constraint", + "single" + ], + [ + "expr", + "single" + ] + ], + "attrs": [ + "symbolic_name" + ] + }, + { + "name": "Assignment", + "fields": [ + "op", + "lvalue", + "rvalue" + ], + "children": [ + [ + "lvalue", + "single" + ], + [ + "rvalue", + "single" + ] + ], + "attrs": [ + "op" + ] + }, + { + "name": "Alignas", + "fields": [ + "alignment" + ], + "children": [ + [ + "alignment", + "single" + ] + ], + "attrs": [] + }, + { + "name": "BinaryOp", + "fields": [ + "op", + "left", + "right" + ], + "children": [ + [ + "left", + "single" + ], + [ + "right", + "single" + ] + ], + "attrs": [ + "op" + ] + }, + { + "name": "Break", + "fields": [], + "children": [], + "attrs": [] + }, + { + "name": "Case", + "fields": [ + "expr", + "stmts" + ], + "children": [ + [ + "expr", + "single" + ], + [ + "stmts", + "list" + ] + ], + "attrs": [] + }, + { + "name": "Cast", + "fields": [ + "to_type", + "expr" + ], + "children": [ + [ + "to_type", + "single" + ], + [ + "expr", + "single" + ] + ], + "attrs": [] + }, + { + "name": "Compound", + "fields": [ + "block_items" + ], + "children": [ + [ + "block_items", + "list" + ] + ], + "attrs": [] + }, + { + "name": "CompoundLiteral", + "fields": [ + "type", + "init" + ], + "children": [ + [ + "type", + "single" + ], + [ + "init", + "single" + ] + ], + "attrs": [] + }, + { + "name": "Constant", + "fields": [ + "type", + "value" + ], + "children": [], + "attrs": [ + "type", + "value" + ] + }, + { + "name": "Continue", + "fields": [], + "children": [], + "attrs": [] + }, + { + "name": "Decl", + "fields": [ + "name", + "quals", + "align", + "storage", + "funcspec", + "gcc_attributes", + "type", + "init", + "bitsize", + "asmlabel" + ], + "children": [ + [ + "type", + "single" + ], + [ + "init", + "single" + ], + [ + "bitsize", + "single" + ], + [ + "asmlabel", + "single" + ], + [ + "gcc_attributes", + "list" + ] + ], + "attrs": [ + "name", + "quals", + "align", + "storage", + "funcspec" + ] + }, + { + "name": "DeclList", + "fields": [ + "decls" + ], + "children": [ + [ + "decls", + "list" + ] + ], + "attrs": [] + }, + { + "name": "Default", + "fields": [ + "stmts" + ], + "children": [ + [ + "stmts", + "list" + ] + ], + "attrs": [] + }, + { + "name": "DoWhile", + "fields": [ + "cond", + "stmt" + ], + "children": [ + [ + "cond", + "single" + ], + [ + "stmt", + "single" + ] + ], + "attrs": [] + }, + { + "name": "EllipsisParam", + "fields": [], + "children": [], + "attrs": [] + }, + { + "name": "EmptyStatement", + "fields": [], + "children": [], + "attrs": [] + }, + { + "name": "Enum", + "fields": [ + "name", + "gcc_attributes", + "values" + ], + "children": [ + [ + "values", + "single" + ], + [ + "gcc_attributes", + "list" + ] + ], + "attrs": [ + "name" + ] + }, + { + "name": "Enumerator", + "fields": [ + "name", + "gcc_attributes", + "value" + ], + "children": [ + [ + "value", + "single" + ] + ], + "attrs": [ + "name", + "gcc_attributes" + ] + }, + { + "name": "EnumeratorList", + "fields": [ + "enumerators" + ], + "children": [ + [ + "enumerators", + "list" + ] + ], + "attrs": [] + }, + { + "name": "ExprList", + "fields": [ + "exprs" + ], + "children": [ + [ + "exprs", + "list" + ] + ], + "attrs": [] + }, + { + "name": "FileAST", + "fields": [ + "ext" + ], + "children": [ + [ + "ext", + "list" + ] + ], + "attrs": [] + }, + { + "name": "For", + "fields": [ + "init", + "cond", + "next", + "stmt" + ], + "children": [ + [ + "init", + "single" + ], + [ + "cond", + "single" + ], + [ + "next", + "single" + ], + [ + "stmt", + "single" + ] + ], + "attrs": [] + }, + { + "name": "FuncCall", + "fields": [ + "name", + "args" + ], + "children": [ + [ + "name", + "single" + ], + [ + "args", + "single" + ] + ], + "attrs": [] + }, + { + "name": "FuncDecl", + "fields": [ + "args", + "type" + ], + "children": [ + [ + "args", + "single" + ], + [ + "type", + "single" + ] + ], + "attrs": [] + }, + { + "name": "FuncDef", + "fields": [ + "decl", + "param_decls", + "body" + ], + "children": [ + [ + "decl", + "single" + ], + [ + "body", + "single" + ], + [ + "param_decls", + "list" + ] + ], + "attrs": [] + }, + { + "name": "GccAttribute", + "fields": [ + "name", + "args" + ], + "children": [ + [ + "args", + "list" + ] + ], + "attrs": [ + "name" + ] + }, + { + "name": "GccAttributeStatement", + "fields": [ + "attrs" + ], + "children": [ + [ + "attrs", + "list" + ] + ], + "attrs": [] + }, + { + "name": "Goto", + "fields": [ + "name" + ], + "children": [], + "attrs": [ + "name" + ] + }, + { + "name": "ID", + "fields": [ + "name" + ], + "children": [], + "attrs": [ + "name" + ] + }, + { + "name": "IdentifierType", + "fields": [ + "names" + ], + "children": [], + "attrs": [ + "names" + ] + }, + { + "name": "If", + "fields": [ + "cond", + "iftrue", + "iffalse" + ], + "children": [ + [ + "cond", + "single" + ], + [ + "iftrue", + "single" + ], + [ + "iffalse", + "single" + ] + ], + "attrs": [] + }, + { + "name": "InitList", + "fields": [ + "exprs" + ], + "children": [ + [ + "exprs", + "list" + ] + ], + "attrs": [] + }, + { + "name": "Label", + "fields": [ + "name", + "stmt" + ], + "children": [ + [ + "stmt", + "single" + ] + ], + "attrs": [ + "name" + ] + }, + { + "name": "NamedInitializer", + "fields": [ + "name", + "expr" + ], + "children": [ + [ + "expr", + "single" + ], + [ + "name", + "list" + ] + ], + "attrs": [] + }, + { + "name": "ParamList", + "fields": [ + "params" + ], + "children": [ + [ + "params", + "list" + ] + ], + "attrs": [] + }, + { + "name": "PtrDecl", + "fields": [ + "quals", + "type" + ], + "children": [ + [ + "type", + "single" + ] + ], + "attrs": [ + "quals" + ] + }, + { + "name": "Range", + "fields": [ + "first", + "last" + ], + "children": [ + [ + "first", + "single" + ], + [ + "last", + "single" + ] + ], + "attrs": [] + }, + { + "name": "Return", + "fields": [ + "expr" + ], + "children": [ + [ + "expr", + "single" + ] + ], + "attrs": [] + }, + { + "name": "StaticAssert", + "fields": [ + "cond", + "message" + ], + "children": [ + [ + "cond", + "single" + ], + [ + "message", + "single" + ] + ], + "attrs": [] + }, + { + "name": "Struct", + "fields": [ + "name", + "gcc_attributes", + "decls" + ], + "children": [ + [ + "gcc_attributes", + "list" + ], + [ + "decls", + "list" + ] + ], + "attrs": [ + "name" + ] + }, + { + "name": "StructRef", + "fields": [ + "name", + "type", + "field" + ], + "children": [ + [ + "name", + "single" + ], + [ + "field", + "single" + ] + ], + "attrs": [ + "type" + ] + }, + { + "name": "Switch", + "fields": [ + "cond", + "stmt" + ], + "children": [ + [ + "cond", + "single" + ], + [ + "stmt", + "single" + ] + ], + "attrs": [] + }, + { + "name": "TernaryOp", + "fields": [ + "cond", + "iftrue", + "iffalse" + ], + "children": [ + [ + "cond", + "single" + ], + [ + "iftrue", + "single" + ], + [ + "iffalse", + "single" + ] + ], + "attrs": [] + }, + { + "name": "TypeDecl", + "fields": [ + "declname", + "quals", + "align", + "type" + ], + "children": [ + [ + "type", + "single" + ] + ], + "attrs": [ + "declname", + "quals", + "align" + ] + }, + { + "name": "Typedef", + "fields": [ + "name", + "quals", + "storage", + "gcc_attributes", + "type" + ], + "children": [ + [ + "type", + "single" + ], + [ + "gcc_attributes", + "list" + ] + ], + "attrs": [ + "name", + "quals", + "storage" + ] + }, + { + "name": "Typename", + "fields": [ + "name", + "quals", + "align", + "gcc_attributes", + "type" + ], + "children": [ + [ + "type", + "single" + ], + [ + "gcc_attributes", + "list" + ] + ], + "attrs": [ + "name", + "quals", + "align" + ] + }, + { + "name": "Typeof", + "fields": [ + "expr" + ], + "children": [ + [ + "expr", + "single" + ] + ], + "attrs": [] + }, + { + "name": "UnaryOp", + "fields": [ + "op", + "expr" + ], + "children": [ + [ + "expr", + "single" + ] + ], + "attrs": [ + "op" + ] + }, + { + "name": "Union", + "fields": [ + "name", + "gcc_attributes", + "decls" + ], + "children": [ + [ + "gcc_attributes", + "list" + ], + [ + "decls", + "list" + ] + ], + "attrs": [ + "name" + ] + }, + { + "name": "While", + "fields": [ + "cond", + "stmt" + ], + "children": [ + [ + "cond", + "single" + ], + [ + "stmt", + "single" + ] + ], + "attrs": [] + }, + { + "name": "Pragma", + "fields": [ + "string" + ], + "children": [], + "attrs": [ + "string" + ] + } +] diff --git a/packages/romdev-pycparser/src/tables/lextab.json b/packages/romdev-pycparser/src/tables/lextab.json new file mode 100644 index 00000000..593230bc --- /dev/null +++ b/packages/romdev-pycparser/src/tables/lextab.json @@ -0,0 +1 @@ +{"tabversion":"3.10","tokens":["AND","ANDEQUAL","ARROW","ASM","AUTO","BREAK","CASE","CHAR","CHAR_CONST","COLON","COMMA","CONDOP","CONST","CONTINUE","DEFAULT","DIVEQUAL","DIVIDE","DO","DOUBLE","ELLIPSIS","ELSE","ENUM","EQ","EQUALS","EXTERN","FLOAT","FLOAT_CONST","FOR","GE","GOTO","GT","HEX_FLOAT_CONST","ID","IF","INLINE","INT","INT_CONST_BIN","INT_CONST_CHAR","INT_CONST_DEC","INT_CONST_HEX","INT_CONST_OCT","LAND","LBRACE","LBRACKET","LE","LNOT","LONG","LOR","LPAREN","LSHIFT","LSHIFTEQUAL","LT","MINUS","MINUSEQUAL","MINUSMINUS","MOD","MODEQUAL","NE","NOT","OFFSETOF","OR","OREQUAL","PERIOD","PLUS","PLUSEQUAL","PLUSPLUS","PPHASH","PPPRAGMA","PPPRAGMASTR","RBRACE","RBRACKET","REGISTER","RESTRICT","RETURN","RPAREN","RSHIFT","RSHIFTEQUAL","SEMI","SHORT","SIGNED","SIZEOF","STATIC","STRING_LITERAL","STRUCT","SWITCH","TIMES","TIMESEQUAL","TYPEDEF","TYPEID","TYPEOF","U16CHAR_CONST","U16STRING_LITERAL","U32CHAR_CONST","U32STRING_LITERAL","U8CHAR_CONST","U8STRING_LITERAL","UNION","UNSIGNED","VOID","VOLATILE","WCHAR_CONST","WHILE","WSTRING_LITERAL","XOR","XOREQUAL","_ALIGNAS","_ALIGNOF","_ATOMIC","_BOOL","_COMPLEX","_NORETURN","_PRAGMA","_STATIC_ASSERT","_THREAD_LOCAL","__ATTRIBUTE__","__INT128"],"reflags":64,"literals":"","stateinfo":{"INITIAL":"inclusive","ppline":"exclusive","pppragma":"exclusive"},"statere":{"INITIAL":[{"pattern":"(?P[ \\t]*\\#)|(?P\\n+)|(?P\\{)|(?P\\})|(?P((((([0-9]*\\.[0-9]+)|([0-9]+\\.))([eE][-+]?[0-9]+)?)|([0-9]+([eE][-+]?[0-9]+)))[FfLl]?))|(?P(0[xX]([0-9a-fA-F]+|((([0-9a-fA-F]+)?\\.[0-9a-fA-F]+)|([0-9a-fA-F]+\\.)))([pP][+-]?[0-9]+)[FfLl]?))|(?P0[xX][0-9a-fA-F]+(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?)|(?P0[bB][01]+(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?)|(?P0[0-7]*[89])|(?P\\/\\*)|(?P\\/\\/)|(?P0[0-7]*(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?)|(?P(0(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?)|([1-9][0-9]*(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?))|(?P'([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F])))){2,4}')|(?P'([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F]))))')|(?PL'([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F]))))')|(?Pu8'([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F]))))')|(?Pu'([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F]))))')|(?PU'([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F]))))')|(?P('([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F]))))*\\n)|('([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F]))))*$))|(?P('([^'\\\\\\n]|(\\\\(([a-wyzA-Z._~!=&\\^\\-\\\\?'\"]|x(?![0-9a-fA-F]))|(\\d+)(?!\\d)|(x[0-9a-fA-F]+)(?![0-9a-fA-F]))))[^'\n]+')|('')|('([\\\\][^a-zA-Z._~^!=&\\^\\-\\\\?'\"x0-9])[^'\\n]*'))|(?PL\"([^\"\\\\\\n]|(\\\\[0-9a-zA-Z._~!=&\\^\\-\\\\?'\"]))*\")|(?Pu8\"([^\"\\\\\\n]|(\\\\[0-9a-zA-Z._~!=&\\^\\-\\\\?'\"]))*\")|(?Pu\"([^\"\\\\\\n]|(\\\\[0-9a-zA-Z._~!=&\\^\\-\\\\?'\"]))*\")|(?PU\"([^\"\\\\\\n]|(\\\\[0-9a-zA-Z._~!=&\\^\\-\\\\?'\"]))*\")|(?P\"([^\"\\\\\\n]|(\\\\[0-9a-zA-Z._~!=&\\^\\-\\\\?'\"]))*([\\\\][^a-zA-Z._~^!=&\\^\\-\\\\?'\"x0-9])([^\"\\\\\\n]|(\\\\[0-9a-zA-Z._~!=&\\^\\-\\\\?'\"]))*\")|(?P[a-zA-Z_$][0-9a-zA-Z_$]*)|(?P\"([^\"\\\\\\n]|(\\\\[0-9a-zA-Z._~!=&\\^\\-\\\\?'\"]))*\")|(?P\\.\\.\\.)|(?P\\|\\|)|(?P\\+\\+)|(?P<<=)|(?P\\|=)|(?P\\+=)|(?P>>=)|(?P\\*=)|(?P\\^=)|(?P&=)|(?P->)|(?P\\?)|(?P/=)|(?P==)|(?P>=)|(?P&&)|(?P\\[)|(?P<=)|(?P\\()|(?P<<)|(?P-=)|(?P--)|(?P%=)|(?P!=)|(?P\\|)|(?P\\.)|(?P\\+)|(?P\\])|(?P\\))|(?P>>)|(?P\\*)|(?P\\^)|(?P&)|(?P:)|(?P,)|(?P/)|(?P=)|(?P>)|(?P!)|(?P<)|(?P-)|(?P%)|(?P~)|(?P;)","names":[null,["t_PPHASH","PPHASH"],["t_NEWLINE","NEWLINE"],["t_LBRACE","LBRACE"],["t_RBRACE","RBRACE"],["t_FLOAT_CONST","FLOAT_CONST"],null,null,null,null,null,null,null,null,null,["t_HEX_FLOAT_CONST","HEX_FLOAT_CONST"],null,null,null,null,null,null,null,["t_INT_CONST_HEX","INT_CONST_HEX"],null,null,null,null,null,null,null,["t_INT_CONST_BIN","INT_CONST_BIN"],null,null,null,null,null,null,null,["t_BAD_CONST_OCT","BAD_CONST_OCT"],["t_UNSUPPORTED_C_STYLE_COMMENT","UNSUPPORTED_C_STYLE_COMMENT"],["t_UNSUPPORTED_CXX_STYLE_COMMENT","UNSUPPORTED_CXX_STYLE_COMMENT"],["t_INT_CONST_OCT","INT_CONST_OCT"],null,null,null,null,null,null,null,["t_INT_CONST_DEC","INT_CONST_DEC"],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,["t_INT_CONST_CHAR","INT_CONST_CHAR"],null,null,null,null,null,null,["t_CHAR_CONST","CHAR_CONST"],null,null,null,null,null,null,["t_WCHAR_CONST","WCHAR_CONST"],null,null,null,null,null,null,["t_U8CHAR_CONST","U8CHAR_CONST"],null,null,null,null,null,null,["t_U16CHAR_CONST","U16CHAR_CONST"],null,null,null,null,null,null,["t_U32CHAR_CONST","U32CHAR_CONST"],null,null,null,null,null,null,["t_UNMATCHED_QUOTE","UNMATCHED_QUOTE"],null,null,null,null,null,null,null,null,null,null,null,null,null,null,["t_BAD_CHAR_CONST","BAD_CHAR_CONST"],null,null,null,null,null,null,null,null,null,null,["t_WSTRING_LITERAL","WSTRING_LITERAL"],null,null,["t_U8STRING_LITERAL","U8STRING_LITERAL"],null,null,["t_U16STRING_LITERAL","U16STRING_LITERAL"],null,null,["t_U32STRING_LITERAL","U32STRING_LITERAL"],null,null,["t_BAD_STRING_LITERAL","BAD_STRING_LITERAL"],null,null,null,null,null,["t_ID","ID"],[null,"STRING_LITERAL"],null,null,[null,"ELLIPSIS"],[null,"LOR"],[null,"PLUSPLUS"],[null,"LSHIFTEQUAL"],[null,"OREQUAL"],[null,"PLUSEQUAL"],[null,"RSHIFTEQUAL"],[null,"TIMESEQUAL"],[null,"XOREQUAL"],[null,"ANDEQUAL"],[null,"ARROW"],[null,"CONDOP"],[null,"DIVEQUAL"],[null,"EQ"],[null,"GE"],[null,"LAND"],[null,"LBRACKET"],[null,"LE"],[null,"LPAREN"],[null,"LSHIFT"],[null,"MINUSEQUAL"],[null,"MINUSMINUS"],[null,"MODEQUAL"],[null,"NE"],[null,"OR"],[null,"PERIOD"],[null,"PLUS"],[null,"RBRACKET"],[null,"RPAREN"],[null,"RSHIFT"],[null,"TIMES"],[null,"XOR"],[null,"AND"],[null,"COLON"],[null,"COMMA"],[null,"DIVIDE"],[null,"EQUALS"],[null,"GT"],[null,"LNOT"],[null,"LT"],[null,"MINUS"],[null,"MOD"],[null,"NOT"],[null,"SEMI"]]}],"ppline":[{"pattern":"(?P\"([^\"\\\\\\n]|(\\\\[0-9a-zA-Z._~!=&\\^\\-\\\\?'\"]))*\")|(?P(0(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?)|([1-9][0-9]*(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?))|(?P\\n)|(?Pline)","names":[null,["t_ppline_FILENAME","FILENAME"],null,null,["t_ppline_LINE_NUMBER","LINE_NUMBER"],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,["t_ppline_NEWLINE","NEWLINE"],["t_ppline_PPLINE","PPLINE"]]}],"pppragma":[{"pattern":"(?P\\n)|(?Ppragma)|(?P.+)","names":[null,["t_pppragma_NEWLINE","NEWLINE"],["t_pppragma_PPPRAGMA","PPPRAGMA"],["t_pppragma_STR","STR"]]}]},"stateignore":{"INITIAL":" \t","ppline":" \t","pppragma":" \t"},"stateerrorf":{"INITIAL":"t_error","ppline":"t_ppline_error","pppragma":"t_pppragma_error"},"stateeoff":{}} diff --git a/packages/romdev-pycparser/src/tables/yacctab.json b/packages/romdev-pycparser/src/tables/yacctab.json new file mode 100644 index 00000000..edf70926 --- /dev/null +++ b/packages/romdev-pycparser/src/tables/yacctab.json @@ -0,0 +1 @@ +{"tabversion":"3.10","method":"LALR","signature":"translation_unit_or_emptyleftLORleftLANDleftORleftXORleftANDleftEQNEleftGTGELTLEleftRSHIFTLSHIFTleftPLUSMINUSleftTIMESDIVIDEMODAUTO BREAK CASE CHAR CONST CONTINUE DEFAULT DO DOUBLE ELSE ENUM EXTERN FLOAT FOR GOTO IF INLINE INT LONG REGISTER OFFSETOF RESTRICT RETURN SHORT SIGNED SIZEOF STATIC STRUCT SWITCH TYPEDEF UNION UNSIGNED VOID VOLATILE WHILE __INT128 TYPEOF __ATTRIBUTE__ ASM _BOOL _COMPLEX _NORETURN _THREAD_LOCAL _STATIC_ASSERT _ATOMIC _ALIGNOF _ALIGNAS _PRAGMA ID TYPEID INT_CONST_DEC INT_CONST_OCT INT_CONST_HEX INT_CONST_BIN INT_CONST_CHAR FLOAT_CONST HEX_FLOAT_CONST CHAR_CONST WCHAR_CONST U8CHAR_CONST U16CHAR_CONST U32CHAR_CONST STRING_LITERAL WSTRING_LITERAL U8STRING_LITERAL U16STRING_LITERAL U32STRING_LITERAL PLUS MINUS TIMES DIVIDE MOD OR AND NOT XOR LSHIFT RSHIFT LOR LAND LNOT LT LE GT GE EQ NE EQUALS TIMESEQUAL DIVEQUAL MODEQUAL PLUSEQUAL MINUSEQUAL LSHIFTEQUAL RSHIFTEQUAL ANDEQUAL XOREQUAL OREQUAL PLUSPLUS MINUSMINUS ARROW CONDOP LPAREN RPAREN LBRACKET RBRACKET LBRACE RBRACE COMMA PERIOD SEMI COLON ELLIPSIS PPHASH PPPRAGMA PPPRAGMASTRabstract_declarator_opt : empty\n| abstract_declaratorasm_goto_list_opt : empty\n| asm_goto_listasm_label_opt : empty\n| asm_labelasm_operands_opt : empty\n| asm_operandsasm_qualifiers_opt : empty\n| asm_qualifiersasm_string_list_opt : empty\n| asm_string_listasm_symbolic_name_opt : empty\n| asm_symbolic_nameassignment_expression_opt : empty\n| assignment_expressionblock_item_list_opt : empty\n| block_item_listdeclaration_list_opt : empty\n| declaration_listdeclaration_specifiers_no_type_opt : empty\n| declaration_specifiers_no_typedesignation_opt : empty\n| designationexpression_opt : empty\n| expressiongcc_attributes_opt : empty\n| gcc_attributesid_init_declarator_list_opt : empty\n| id_init_declarator_listidentifier_list_opt : empty\n| identifier_listinit_declarator_list_opt : empty\n| init_declarator_listinitializer_list_opt : empty\n| initializer_listparameter_type_list_opt : empty\n| parameter_type_liststruct_declarator_list_opt : empty\n| struct_declarator_listtype_qualifier_list_opt : empty\n| type_qualifier_list direct_id_declarator : ID\n direct_id_declarator : LPAREN id_declarator RPAREN\n direct_id_declarator : direct_id_declarator LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET\n direct_id_declarator : direct_id_declarator LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET\n | direct_id_declarator LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET\n direct_id_declarator : direct_id_declarator LBRACKET type_qualifier_list_opt TIMES RBRACKET\n direct_id_declarator : direct_id_declarator LPAREN parameter_type_list RPAREN\n | direct_id_declarator LPAREN identifier_list_opt RPAREN\n direct_typeid_declarator : TYPEID\n direct_typeid_declarator : LPAREN typeid_declarator RPAREN\n direct_typeid_declarator : direct_typeid_declarator LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET\n direct_typeid_declarator : direct_typeid_declarator LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET\n | direct_typeid_declarator LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET\n direct_typeid_declarator : direct_typeid_declarator LBRACKET type_qualifier_list_opt TIMES RBRACKET\n direct_typeid_declarator : direct_typeid_declarator LPAREN parameter_type_list RPAREN\n | direct_typeid_declarator LPAREN identifier_list_opt RPAREN\n direct_typeid_noparen_declarator : TYPEID\n direct_typeid_noparen_declarator : direct_typeid_noparen_declarator LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET\n direct_typeid_noparen_declarator : direct_typeid_noparen_declarator LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET\n | direct_typeid_noparen_declarator LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET\n direct_typeid_noparen_declarator : direct_typeid_noparen_declarator LBRACKET type_qualifier_list_opt TIMES RBRACKET\n direct_typeid_noparen_declarator : direct_typeid_noparen_declarator LPAREN parameter_type_list RPAREN\n | direct_typeid_noparen_declarator LPAREN identifier_list_opt RPAREN\n id_declarator : direct_id_declarator\n id_declarator : pointer direct_id_declarator\n typeid_declarator : direct_typeid_declarator\n typeid_declarator : pointer direct_typeid_declarator\n typeid_noparen_declarator : direct_typeid_noparen_declarator\n typeid_noparen_declarator : pointer direct_typeid_noparen_declarator\n translation_unit_or_empty : translation_unit\n | empty\n translation_unit : external_declaration\n translation_unit : translation_unit external_declaration\n external_declaration : function_definition\n external_declaration : declaration\n external_declaration : pp_directive\n | pppragma_directive\n external_declaration : SEMI\n external_declaration : static_assert\n external_declaration : global_asm\n global_asm : ASM LPAREN unified_string_literal RPAREN SEMI\n static_assert : _STATIC_ASSERT LPAREN constant_expression COMMA unified_string_literal RPAREN\n | _STATIC_ASSERT LPAREN constant_expression RPAREN\n pp_directive : PPHASH\n pppragma_directive : PPPRAGMA\n | PPPRAGMA PPPRAGMASTR\n | _PRAGMA LPAREN unified_string_literal RPAREN\n pppragma_directive_list : pppragma_directive\n | pppragma_directive_list pppragma_directive\n function_definition : id_declarator declaration_list_opt compound_statement\n function_definition : declaration_specifiers id_declarator declaration_list_opt compound_statement\n statement : labeled_statement\n | expression_statement\n | compound_statement\n | selection_statement\n | iteration_statement\n | jump_statement\n | pppragma_directive\n | static_assert\n | asm_statement\n | attribute_statement\n pragmacomp_or_statement : pppragma_directive_list statement\n | statement\n decl_body : declaration_specifiers init_declarator_list_opt\n | declaration_specifiers_no_type id_init_declarator_list_opt\n declaration : decl_body SEMI\n declaration_list : declaration\n | declaration_list declaration\n declaration_specifiers_no_type : type_qualifier declaration_specifiers_no_type_opt\n declaration_specifiers_no_type : storage_class_specifier declaration_specifiers_no_type_opt\n declaration_specifiers_no_type : function_specifier declaration_specifiers_no_type_opt\n declaration_specifiers_no_type : atomic_specifier declaration_specifiers_no_type_opt\n declaration_specifiers_no_type : alignment_specifier declaration_specifiers_no_type_opt\n declaration_specifiers_no_type : gcc_attribute declaration_specifiers_no_type_opt\n declaration_specifiers : declaration_specifiers type_qualifier\n declaration_specifiers : declaration_specifiers storage_class_specifier\n declaration_specifiers : declaration_specifiers function_specifier\n declaration_specifiers : declaration_specifiers type_specifier_no_typeid\n declaration_specifiers : type_specifier\n declaration_specifiers : declaration_specifiers_no_type type_specifier\n declaration_specifiers : declaration_specifiers alignment_specifier\n declaration_specifiers : declaration_specifiers gcc_attribute\n storage_class_specifier : AUTO\n | REGISTER\n | STATIC\n | EXTERN\n | TYPEDEF\n | _THREAD_LOCAL\n function_specifier : INLINE\n | _NORETURN\n type_specifier_no_typeid : VOID\n | _BOOL\n | CHAR\n | SHORT\n | INT\n | LONG\n | FLOAT\n | DOUBLE\n | _COMPLEX\n | SIGNED\n | UNSIGNED\n | __INT128\n type_specifier : typedef_name\n | enum_specifier\n | struct_or_union_specifier\n | type_specifier_no_typeid\n | atomic_specifier\n | typeof_specifier\n typeof_specifier : TYPEOF LPAREN expression RPAREN\n | TYPEOF LPAREN type_name RPAREN\n atomic_specifier : _ATOMIC LPAREN type_name RPAREN\n type_qualifier : CONST\n | RESTRICT\n | VOLATILE\n | _ATOMIC\n init_declarator_list : init_declarator\n | init_declarator_list COMMA init_declarator\n init_declarator : declarator asm_label_opt gcc_attributes_opt\n | declarator asm_label_opt gcc_attributes_opt EQUALS initializer\n | declarator asm_label_opt gcc_attributes_opt COLON constant_expression\n id_init_declarator_list : id_init_declarator\n | id_init_declarator_list COMMA init_declarator\n id_init_declarator : id_declarator asm_label_opt gcc_attributes_opt\n | id_declarator asm_label_opt gcc_attributes_opt EQUALS initializer\n specifier_qualifier_list : specifier_qualifier_list type_specifier_no_typeid\n specifier_qualifier_list : specifier_qualifier_list type_qualifier\n specifier_qualifier_list : type_specifier\n specifier_qualifier_list : qualifier_attr_list type_specifier\n specifier_qualifier_list : alignment_specifier\n specifier_qualifier_list : specifier_qualifier_list alignment_specifier\n specifier_qualifier_list : specifier_qualifier_list gcc_attribute\n struct_or_union_specifier : struct_or_union ID\n | struct_or_union TYPEID\n struct_or_union_specifier : struct_or_union gcc_attributes_opt brace_open struct_declaration_list brace_close gcc_attributes_opt\n | struct_or_union gcc_attributes_opt brace_open brace_close gcc_attributes_opt\n struct_or_union_specifier : struct_or_union attrs_id_typeid brace_open struct_declaration_list brace_close gcc_attributes_opt\n | struct_or_union attrs_id_typeid brace_open brace_close gcc_attributes_opt\n struct_or_union : STRUCT\n | UNION\n struct_declaration_list : struct_declaration\n | struct_declaration_list struct_declaration\n struct_declaration : specifier_qualifier_list struct_declarator_list_opt SEMI\n struct_declaration : SEMI\n struct_declaration : pppragma_directive\n struct_declarator_list : struct_declarator\n | struct_declarator_list COMMA struct_declarator\n struct_declarator : declarator gcc_attributes_opt\n struct_declarator : declarator gcc_attributes_opt COLON constant_expression\n | gcc_attributes_opt COLON constant_expression\n enum_specifier : ENUM ID\n | ENUM TYPEID\n enum_specifier : ENUM gcc_attributes_opt brace_open enumerator_list brace_close gcc_attributes_opt\n enum_specifier : ENUM attrs_id_typeid brace_open enumerator_list brace_close gcc_attributes_opt\n enumerator_list : enumerator\n | enumerator_list COMMA\n | enumerator_list COMMA enumerator\n alignment_specifier : _ALIGNAS LPAREN type_name RPAREN\n | _ALIGNAS LPAREN constant_expression RPAREN\n enumerator : ID gcc_attributes_opt\n | ID gcc_attributes_opt EQUALS constant_expression\n declarator : id_declarator %prec TIMES\n | typeid_declarator\n pointer : TIMES type_qualifier_list_opt\n | TIMES type_qualifier_list_opt pointer\n type_qualifier_list : type_qualifier\n | type_qualifier_list type_qualifier\n qualifier_attr_list : type_qualifier\n qualifier_attr_list : qualifier_attr_list type_qualifier\n qualifier_attr_list : gcc_attribute\n qualifier_attr_list : qualifier_attr_list gcc_attribute\n parameter_type_list : parameter_list\n | parameter_list COMMA ELLIPSIS\n parameter_list : parameter_declaration\n | parameter_list COMMA parameter_declaration\n parameter_declaration : declaration_specifiers id_declarator gcc_attributes_opt\n | declaration_specifiers typeid_noparen_declarator gcc_attributes_opt\n parameter_declaration : declaration_specifiers abstract_declarator_opt gcc_attributes_opt\n identifier_list : identifier\n | identifier_list COMMA identifier\n initializer : assignment_expression\n initializer : brace_open initializer_list_opt brace_close\n | brace_open initializer_list COMMA brace_close\n initializer_list : designation_opt initializer\n | initializer_list COMMA designation_opt initializer\n designation : designator_list EQUALS\n designator_list : designator\n | designator_list designator\n designator : LBRACKET constant_expression RBRACKET\n | PERIOD identifier\n designator : LBRACKET constant_expression ELLIPSIS constant_expression RBRACKET\n type_name : specifier_qualifier_list abstract_declarator_opt\n abstract_declarator : pointer\n abstract_declarator : pointer direct_abstract_declarator\n abstract_declarator : direct_abstract_declarator\n direct_abstract_declarator : LPAREN abstract_declarator RPAREN direct_abstract_declarator : direct_abstract_declarator LBRACKET assignment_expression_opt RBRACKET\n direct_abstract_declarator : LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET\n direct_abstract_declarator : direct_abstract_declarator LBRACKET TIMES RBRACKET\n direct_abstract_declarator : LBRACKET TIMES RBRACKET\n direct_abstract_declarator : direct_abstract_declarator LPAREN parameter_type_list_opt RPAREN\n direct_abstract_declarator : LPAREN parameter_type_list_opt RPAREN\n direct_abstract_declarator : LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET\n | LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET\n block_item : declaration\n | statement\n block_item_list : block_item\n | block_item_list block_item\n compound_statement : brace_open block_item_list_opt brace_close labeled_statement : ID COLON pragmacomp_or_statement\n | TYPEID COLON pragmacomp_or_statement\n labeled_statement : CASE constant_expression COLON pragmacomp_or_statement labeled_statement : CASE constant_expression ELLIPSIS constant_expression COLON pragmacomp_or_statement\n labeled_statement : DEFAULT COLON pragmacomp_or_statement labeled_statement : ID COLON\n | TYPEID COLON\n labeled_statement : CASE constant_expression COLON labeled_statement : CASE constant_expression ELLIPSIS constant_expression COLON\n labeled_statement : DEFAULT COLON selection_statement : IF LPAREN expression RPAREN pragmacomp_or_statement selection_statement : IF LPAREN expression RPAREN statement ELSE pragmacomp_or_statement selection_statement : SWITCH LPAREN expression RPAREN pragmacomp_or_statement iteration_statement : WHILE LPAREN expression RPAREN pragmacomp_or_statement iteration_statement : DO pragmacomp_or_statement WHILE LPAREN expression RPAREN SEMI iteration_statement : FOR LPAREN expression_opt SEMI expression_opt SEMI expression_opt RPAREN pragmacomp_or_statement iteration_statement : FOR LPAREN declaration expression_opt SEMI expression_opt RPAREN pragmacomp_or_statement jump_statement : GOTO ID SEMI\n | GOTO TYPEID SEMI\n jump_statement : BREAK SEMI jump_statement : CONTINUE SEMI jump_statement : RETURN expression SEMI\n | RETURN SEMI\n expression_statement : expression_opt SEMI expression : assignment_expression\n | expression COMMA assignment_expression\n assignment_expression : LPAREN compound_statement RPAREN typedef_name : TYPEID assignment_expression : conditional_expression\n | unary_expression assignment_operator assignment_expression\n assignment_operator : EQUALS\n | XOREQUAL\n | TIMESEQUAL\n | DIVEQUAL\n | MODEQUAL\n | PLUSEQUAL\n | MINUSEQUAL\n | LSHIFTEQUAL\n | RSHIFTEQUAL\n | ANDEQUAL\n | OREQUAL\n constant_expression : conditional_expression conditional_expression : binary_expression\n | binary_expression CONDOP expression COLON conditional_expression\n binary_expression : unary_expression\n | binary_expression TIMES binary_expression\n | binary_expression DIVIDE binary_expression\n | binary_expression MOD binary_expression\n | binary_expression PLUS binary_expression\n | binary_expression MINUS binary_expression\n | binary_expression RSHIFT binary_expression\n | binary_expression LSHIFT binary_expression\n | binary_expression LT binary_expression\n | binary_expression LE binary_expression\n | binary_expression GE binary_expression\n | binary_expression GT binary_expression\n | binary_expression EQ binary_expression\n | binary_expression NE binary_expression\n | binary_expression AND binary_expression\n | binary_expression OR binary_expression\n | binary_expression XOR binary_expression\n | binary_expression LAND binary_expression\n | binary_expression LOR binary_expression\n unary_expression : LPAREN type_name RPAREN unary_expression unary_expression : postfix_expression unary_expression : PLUSPLUS unary_expression\n | MINUSMINUS unary_expression\n | unary_operator unary_expression\n unary_expression : SIZEOF unary_expression\n | SIZEOF LPAREN type_name RPAREN\n | _ALIGNOF LPAREN type_name RPAREN\n unary_operator : AND\n | TIMES\n | PLUS\n | MINUS\n | NOT\n | LNOT\n postfix_expression : primary_expression postfix_expression : postfix_expression LBRACKET expression RBRACKET postfix_expression : postfix_expression LPAREN argument_expression_list RPAREN\n | postfix_expression LPAREN RPAREN\n postfix_expression : postfix_expression PERIOD ID\n | postfix_expression PERIOD TYPEID\n | postfix_expression ARROW ID\n | postfix_expression ARROW TYPEID\n postfix_expression : postfix_expression PLUSPLUS\n | postfix_expression MINUSMINUS\n postfix_expression : LPAREN type_name RPAREN brace_open initializer_list brace_close\n | LPAREN type_name RPAREN brace_open initializer_list COMMA brace_close\n primary_expression : identifier primary_expression : constant primary_expression : unified_string_literal\n | unified_wstring_literal\n primary_expression : LPAREN expression RPAREN primary_expression : OFFSETOF LPAREN type_name COMMA offsetof_member_designator RPAREN\n offsetof_member_designator : identifier\n | offsetof_member_designator PERIOD identifier\n | offsetof_member_designator LBRACKET expression RBRACKET\n argument_expression_list : assignment_expression\n | argument_expression_list COMMA assignment_expression\n identifier : ID constant : INT_CONST_DEC\n | INT_CONST_OCT\n | INT_CONST_HEX\n | INT_CONST_BIN\n | INT_CONST_CHAR\n constant : FLOAT_CONST\n | HEX_FLOAT_CONST\n constant : CHAR_CONST\n | WCHAR_CONST\n | U8CHAR_CONST\n | U16CHAR_CONST\n | U32CHAR_CONST\n unified_string_literal : STRING_LITERAL\n | unified_string_literal STRING_LITERAL\n unified_wstring_literal : WSTRING_LITERAL\n | U8STRING_LITERAL\n | U16STRING_LITERAL\n | U32STRING_LITERAL\n | unified_wstring_literal WSTRING_LITERAL\n | unified_wstring_literal U8STRING_LITERAL\n | unified_wstring_literal U16STRING_LITERAL\n | unified_wstring_literal U32STRING_LITERAL\n attrs_id_typeid : ID\n | TYPEID\n | gcc_attributes ID\n | gcc_attributes TYPEID\n brace_open : LBRACE\n brace_close : RBRACE\n attribute_statement : gcc_attributes SEMI\n asm_statement : ASM asm_qualifiers_opt LPAREN unified_string_literal RPAREN SEMI\n asm_statement : ASM asm_qualifiers_opt LPAREN unified_string_literal COLON asm_operands_opt RPAREN SEMI\n asm_statement : ASM asm_qualifiers_opt LPAREN unified_string_literal COLON asm_operands_opt COLON asm_operands_opt RPAREN SEMI\n asm_statement : ASM asm_qualifiers_opt LPAREN unified_string_literal COLON asm_operands_opt COLON asm_operands_opt COLON asm_string_list_opt RPAREN SEMI\n asm_statement : ASM asm_qualifiers_opt LPAREN unified_string_literal COLON asm_operands_opt COLON asm_operands_opt COLON asm_string_list_opt COLON asm_goto_list_opt RPAREN SEMI\n asm_operands : asm_operands COMMA asm_operand\n | asm_operand\n asm_operand : asm_symbolic_name_opt unified_string_literal LPAREN unary_expression RPAREN\n asm_string_list : asm_string_list COMMA unified_string_literal\n | unified_string_literal\n asm_goto_list : asm_goto_list COMMA ID\n | asm_goto_list COMMA TYPEID\n | ID\n | TYPEID\n asm_symbolic_name : LBRACKET ID RBRACKET\n | LBRACKET TYPEID RBRACKET\n asm_qualifiers : asm_qualifiers_opt VOLATILE\n | asm_qualifiers_opt INLINE\n | asm_qualifiers_opt GOTO\n asm_label : ASM LPAREN unified_string_literal RPAREN\n gcc_attributes : gcc_attribute\n | gcc_attributes gcc_attribute\n gcc_attribute : __ATTRIBUTE__ LPAREN LPAREN gcc_attribute_list RPAREN RPAREN\n gcc_attribute_list : gcc_attribute_item\n | gcc_attribute_list COMMA gcc_attribute_item\n gcc_attribute_item : empty\n | CONST\n | ID\n | TYPEID\n | ID LPAREN argument_expression_list RPAREN\n | TYPEID LPAREN argument_expression_list RPAREN\n empty : ","action":[[0,[["$end",-412],["SEMI",9],["PPHASH",15],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",20],["ID",31],["LPAREN",18],["TIMES",33],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69]]],[1,[["$end",0]]],[2,[["$end",-72],["SEMI",9],["PPHASH",15],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",20],["ID",31],["LPAREN",18],["TIMES",33],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69]]],[3,[["$end",-73]]],[4,[["$end",-74],["SEMI",-74],["PPHASH",-74],["PPPRAGMA",-74],["_PRAGMA",-74],["_STATIC_ASSERT",-74],["ASM",-74],["ID",-74],["LPAREN",-74],["TIMES",-74],["TYPEID",-74],["ENUM",-74],["VOID",-74],["_BOOL",-74],["CHAR",-74],["SHORT",-74],["INT",-74],["LONG",-74],["FLOAT",-74],["DOUBLE",-74],["_COMPLEX",-74],["SIGNED",-74],["UNSIGNED",-74],["__INT128",-74],["_ATOMIC",-74],["TYPEOF",-74],["CONST",-74],["RESTRICT",-74],["VOLATILE",-74],["AUTO",-74],["REGISTER",-74],["STATIC",-74],["EXTERN",-74],["TYPEDEF",-74],["_THREAD_LOCAL",-74],["INLINE",-74],["_NORETURN",-74],["_ALIGNAS",-74],["__ATTRIBUTE__",-74],["STRUCT",-74],["UNION",-74]]],[5,[["$end",-76],["SEMI",-76],["PPHASH",-76],["PPPRAGMA",-76],["_PRAGMA",-76],["_STATIC_ASSERT",-76],["ASM",-76],["ID",-76],["LPAREN",-76],["TIMES",-76],["TYPEID",-76],["ENUM",-76],["VOID",-76],["_BOOL",-76],["CHAR",-76],["SHORT",-76],["INT",-76],["LONG",-76],["FLOAT",-76],["DOUBLE",-76],["_COMPLEX",-76],["SIGNED",-76],["UNSIGNED",-76],["__INT128",-76],["_ATOMIC",-76],["TYPEOF",-76],["CONST",-76],["RESTRICT",-76],["VOLATILE",-76],["AUTO",-76],["REGISTER",-76],["STATIC",-76],["EXTERN",-76],["TYPEDEF",-76],["_THREAD_LOCAL",-76],["INLINE",-76],["_NORETURN",-76],["_ALIGNAS",-76],["__ATTRIBUTE__",-76],["STRUCT",-76],["UNION",-76]]],[6,[["$end",-77],["SEMI",-77],["PPHASH",-77],["PPPRAGMA",-77],["_PRAGMA",-77],["_STATIC_ASSERT",-77],["ASM",-77],["ID",-77],["LPAREN",-77],["TIMES",-77],["TYPEID",-77],["ENUM",-77],["VOID",-77],["_BOOL",-77],["CHAR",-77],["SHORT",-77],["INT",-77],["LONG",-77],["FLOAT",-77],["DOUBLE",-77],["_COMPLEX",-77],["SIGNED",-77],["UNSIGNED",-77],["__INT128",-77],["_ATOMIC",-77],["TYPEOF",-77],["CONST",-77],["RESTRICT",-77],["VOLATILE",-77],["AUTO",-77],["REGISTER",-77],["STATIC",-77],["EXTERN",-77],["TYPEDEF",-77],["_THREAD_LOCAL",-77],["INLINE",-77],["_NORETURN",-77],["_ALIGNAS",-77],["__ATTRIBUTE__",-77],["STRUCT",-77],["UNION",-77]]],[7,[["$end",-78],["SEMI",-78],["PPHASH",-78],["PPPRAGMA",-78],["_PRAGMA",-78],["_STATIC_ASSERT",-78],["ASM",-78],["ID",-78],["LPAREN",-78],["TIMES",-78],["TYPEID",-78],["ENUM",-78],["VOID",-78],["_BOOL",-78],["CHAR",-78],["SHORT",-78],["INT",-78],["LONG",-78],["FLOAT",-78],["DOUBLE",-78],["_COMPLEX",-78],["SIGNED",-78],["UNSIGNED",-78],["__INT128",-78],["_ATOMIC",-78],["TYPEOF",-78],["CONST",-78],["RESTRICT",-78],["VOLATILE",-78],["AUTO",-78],["REGISTER",-78],["STATIC",-78],["EXTERN",-78],["TYPEDEF",-78],["_THREAD_LOCAL",-78],["INLINE",-78],["_NORETURN",-78],["_ALIGNAS",-78],["__ATTRIBUTE__",-78],["STRUCT",-78],["UNION",-78]]],[8,[["$end",-79],["SEMI",-79],["PPHASH",-79],["PPPRAGMA",-79],["_PRAGMA",-79],["_STATIC_ASSERT",-79],["ASM",-79],["ID",-79],["LPAREN",-79],["TIMES",-79],["TYPEID",-79],["ENUM",-79],["VOID",-79],["_BOOL",-79],["CHAR",-79],["SHORT",-79],["INT",-79],["LONG",-79],["FLOAT",-79],["DOUBLE",-79],["_COMPLEX",-79],["SIGNED",-79],["UNSIGNED",-79],["__INT128",-79],["_ATOMIC",-79],["TYPEOF",-79],["CONST",-79],["RESTRICT",-79],["VOLATILE",-79],["AUTO",-79],["REGISTER",-79],["STATIC",-79],["EXTERN",-79],["TYPEDEF",-79],["_THREAD_LOCAL",-79],["INLINE",-79],["_NORETURN",-79],["_ALIGNAS",-79],["__ATTRIBUTE__",-79],["STRUCT",-79],["UNION",-79]]],[9,[["$end",-80],["SEMI",-80],["PPHASH",-80],["PPPRAGMA",-80],["_PRAGMA",-80],["_STATIC_ASSERT",-80],["ASM",-80],["ID",-80],["LPAREN",-80],["TIMES",-80],["TYPEID",-80],["ENUM",-80],["VOID",-80],["_BOOL",-80],["CHAR",-80],["SHORT",-80],["INT",-80],["LONG",-80],["FLOAT",-80],["DOUBLE",-80],["_COMPLEX",-80],["SIGNED",-80],["UNSIGNED",-80],["__INT128",-80],["_ATOMIC",-80],["TYPEOF",-80],["CONST",-80],["RESTRICT",-80],["VOLATILE",-80],["AUTO",-80],["REGISTER",-80],["STATIC",-80],["EXTERN",-80],["TYPEDEF",-80],["_THREAD_LOCAL",-80],["INLINE",-80],["_NORETURN",-80],["_ALIGNAS",-80],["__ATTRIBUTE__",-80],["STRUCT",-80],["UNION",-80]]],[10,[["$end",-81],["SEMI",-81],["PPHASH",-81],["PPPRAGMA",-81],["_PRAGMA",-81],["_STATIC_ASSERT",-81],["ASM",-81],["ID",-81],["LPAREN",-81],["TIMES",-81],["TYPEID",-81],["ENUM",-81],["VOID",-81],["_BOOL",-81],["CHAR",-81],["SHORT",-81],["INT",-81],["LONG",-81],["FLOAT",-81],["DOUBLE",-81],["_COMPLEX",-81],["SIGNED",-81],["UNSIGNED",-81],["__INT128",-81],["_ATOMIC",-81],["TYPEOF",-81],["CONST",-81],["RESTRICT",-81],["VOLATILE",-81],["AUTO",-81],["REGISTER",-81],["STATIC",-81],["EXTERN",-81],["TYPEDEF",-81],["_THREAD_LOCAL",-81],["INLINE",-81],["_NORETURN",-81],["_ALIGNAS",-81],["__ATTRIBUTE__",-81],["STRUCT",-81],["UNION",-81]]],[11,[["$end",-82],["SEMI",-82],["PPHASH",-82],["PPPRAGMA",-82],["_PRAGMA",-82],["_STATIC_ASSERT",-82],["ASM",-82],["ID",-82],["LPAREN",-82],["TIMES",-82],["TYPEID",-82],["ENUM",-82],["VOID",-82],["_BOOL",-82],["CHAR",-82],["SHORT",-82],["INT",-82],["LONG",-82],["FLOAT",-82],["DOUBLE",-82],["_COMPLEX",-82],["SIGNED",-82],["UNSIGNED",-82],["__INT128",-82],["_ATOMIC",-82],["TYPEOF",-82],["CONST",-82],["RESTRICT",-82],["VOLATILE",-82],["AUTO",-82],["REGISTER",-82],["STATIC",-82],["EXTERN",-82],["TYPEDEF",-82],["_THREAD_LOCAL",-82],["INLINE",-82],["_NORETURN",-82],["_ALIGNAS",-82],["__ATTRIBUTE__",-82],["STRUCT",-82],["UNION",-82]]],[15,[["$end",-86],["SEMI",-86],["PPHASH",-86],["PPPRAGMA",-86],["_PRAGMA",-86],["_STATIC_ASSERT",-86],["ASM",-86],["ID",-86],["LPAREN",-86],["TIMES",-86],["TYPEID",-86],["ENUM",-86],["VOID",-86],["_BOOL",-86],["CHAR",-86],["SHORT",-86],["INT",-86],["LONG",-86],["FLOAT",-86],["DOUBLE",-86],["_COMPLEX",-86],["SIGNED",-86],["UNSIGNED",-86],["__INT128",-86],["_ATOMIC",-86],["TYPEOF",-86],["CONST",-86],["RESTRICT",-86],["VOLATILE",-86],["AUTO",-86],["REGISTER",-86],["STATIC",-86],["EXTERN",-86],["TYPEDEF",-86],["_THREAD_LOCAL",-86],["INLINE",-86],["_NORETURN",-86],["_ALIGNAS",-86],["__ATTRIBUTE__",-86],["STRUCT",-86],["UNION",-86]]],[16,[["$end",-87],["SEMI",-87],["PPHASH",-87],["PPPRAGMA",-87],["_PRAGMA",-87],["_STATIC_ASSERT",-87],["ASM",-87],["ID",-87],["LPAREN",-87],["TIMES",-87],["TYPEID",-87],["ENUM",-87],["VOID",-87],["_BOOL",-87],["CHAR",-87],["SHORT",-87],["INT",-87],["LONG",-87],["FLOAT",-87],["DOUBLE",-87],["_COMPLEX",-87],["SIGNED",-87],["UNSIGNED",-87],["__INT128",-87],["_ATOMIC",-87],["TYPEOF",-87],["CONST",-87],["RESTRICT",-87],["VOLATILE",-87],["AUTO",-87],["REGISTER",-87],["STATIC",-87],["EXTERN",-87],["TYPEDEF",-87],["_THREAD_LOCAL",-87],["INLINE",-87],["_NORETURN",-87],["_ALIGNAS",-87],["__ATTRIBUTE__",-87],["STRUCT",-87],["UNION",-87],["LBRACE",-87],["CASE",-87],["DEFAULT",-87],["IF",-87],["SWITCH",-87],["WHILE",-87],["DO",-87],["FOR",-87],["GOTO",-87],["BREAK",-87],["CONTINUE",-87],["RETURN",-87],["PLUSPLUS",-87],["MINUSMINUS",-87],["SIZEOF",-87],["_ALIGNOF",-87],["AND",-87],["PLUS",-87],["MINUS",-87],["NOT",-87],["LNOT",-87],["OFFSETOF",-87],["INT_CONST_DEC",-87],["INT_CONST_OCT",-87],["INT_CONST_HEX",-87],["INT_CONST_BIN",-87],["INT_CONST_CHAR",-87],["FLOAT_CONST",-87],["HEX_FLOAT_CONST",-87],["CHAR_CONST",-87],["WCHAR_CONST",-87],["U8CHAR_CONST",-87],["U16CHAR_CONST",-87],["U32CHAR_CONST",-87],["STRING_LITERAL",-87],["WSTRING_LITERAL",-87],["U8STRING_LITERAL",-87],["U16STRING_LITERAL",-87],["U32STRING_LITERAL",-87],["RBRACE",-87],["ELSE",-87],["PPPRAGMASTR",98]]],[70,[["$end",-75],["SEMI",-75],["PPHASH",-75],["PPPRAGMA",-75],["_PRAGMA",-75],["_STATIC_ASSERT",-75],["ASM",-75],["ID",-75],["LPAREN",-75],["TIMES",-75],["TYPEID",-75],["ENUM",-75],["VOID",-75],["_BOOL",-75],["CHAR",-75],["SHORT",-75],["INT",-75],["LONG",-75],["FLOAT",-75],["DOUBLE",-75],["_COMPLEX",-75],["SIGNED",-75],["UNSIGNED",-75],["__INT128",-75],["_ATOMIC",-75],["TYPEOF",-75],["CONST",-75],["RESTRICT",-75],["VOLATILE",-75],["AUTO",-75],["REGISTER",-75],["STATIC",-75],["EXTERN",-75],["TYPEDEF",-75],["_THREAD_LOCAL",-75],["INLINE",-75],["_NORETURN",-75],["_ALIGNAS",-75],["__ATTRIBUTE__",-75],["STRUCT",-75],["UNION",-75]]],[97,[["$end",-108],["SEMI",-108],["PPHASH",-108],["PPPRAGMA",-108],["_PRAGMA",-108],["_STATIC_ASSERT",-108],["ASM",-108],["ID",-108],["LPAREN",-108],["TIMES",-108],["TYPEID",-108],["ENUM",-108],["VOID",-108],["_BOOL",-108],["CHAR",-108],["SHORT",-108],["INT",-108],["LONG",-108],["FLOAT",-108],["DOUBLE",-108],["_COMPLEX",-108],["SIGNED",-108],["UNSIGNED",-108],["__INT128",-108],["_ATOMIC",-108],["TYPEOF",-108],["CONST",-108],["RESTRICT",-108],["VOLATILE",-108],["AUTO",-108],["REGISTER",-108],["STATIC",-108],["EXTERN",-108],["TYPEDEF",-108],["_THREAD_LOCAL",-108],["INLINE",-108],["_NORETURN",-108],["_ALIGNAS",-108],["__ATTRIBUTE__",-108],["STRUCT",-108],["UNION",-108],["LBRACE",-108],["CASE",-108],["DEFAULT",-108],["IF",-108],["SWITCH",-108],["WHILE",-108],["DO",-108],["FOR",-108],["GOTO",-108],["BREAK",-108],["CONTINUE",-108],["RETURN",-108],["PLUSPLUS",-108],["MINUSMINUS",-108],["SIZEOF",-108],["_ALIGNOF",-108],["AND",-108],["PLUS",-108],["MINUS",-108],["NOT",-108],["LNOT",-108],["OFFSETOF",-108],["INT_CONST_DEC",-108],["INT_CONST_OCT",-108],["INT_CONST_HEX",-108],["INT_CONST_BIN",-108],["INT_CONST_CHAR",-108],["FLOAT_CONST",-108],["HEX_FLOAT_CONST",-108],["CHAR_CONST",-108],["WCHAR_CONST",-108],["U8CHAR_CONST",-108],["U16CHAR_CONST",-108],["U32CHAR_CONST",-108],["STRING_LITERAL",-108],["WSTRING_LITERAL",-108],["U8STRING_LITERAL",-108],["U16STRING_LITERAL",-108],["U32STRING_LITERAL",-108],["RBRACE",-108]]],[98,[["$end",-88],["SEMI",-88],["PPHASH",-88],["PPPRAGMA",-88],["_PRAGMA",-88],["_STATIC_ASSERT",-88],["ASM",-88],["ID",-88],["LPAREN",-88],["TIMES",-88],["TYPEID",-88],["ENUM",-88],["VOID",-88],["_BOOL",-88],["CHAR",-88],["SHORT",-88],["INT",-88],["LONG",-88],["FLOAT",-88],["DOUBLE",-88],["_COMPLEX",-88],["SIGNED",-88],["UNSIGNED",-88],["__INT128",-88],["_ATOMIC",-88],["TYPEOF",-88],["CONST",-88],["RESTRICT",-88],["VOLATILE",-88],["AUTO",-88],["REGISTER",-88],["STATIC",-88],["EXTERN",-88],["TYPEDEF",-88],["_THREAD_LOCAL",-88],["INLINE",-88],["_NORETURN",-88],["_ALIGNAS",-88],["__ATTRIBUTE__",-88],["STRUCT",-88],["UNION",-88],["LBRACE",-88],["CASE",-88],["DEFAULT",-88],["IF",-88],["SWITCH",-88],["WHILE",-88],["DO",-88],["FOR",-88],["GOTO",-88],["BREAK",-88],["CONTINUE",-88],["RETURN",-88],["PLUSPLUS",-88],["MINUSMINUS",-88],["SIZEOF",-88],["_ALIGNOF",-88],["AND",-88],["PLUS",-88],["MINUS",-88],["NOT",-88],["LNOT",-88],["OFFSETOF",-88],["INT_CONST_DEC",-88],["INT_CONST_OCT",-88],["INT_CONST_HEX",-88],["INT_CONST_BIN",-88],["INT_CONST_CHAR",-88],["FLOAT_CONST",-88],["HEX_FLOAT_CONST",-88],["CHAR_CONST",-88],["WCHAR_CONST",-88],["U8CHAR_CONST",-88],["U16CHAR_CONST",-88],["U32CHAR_CONST",-88],["STRING_LITERAL",-88],["WSTRING_LITERAL",-88],["U8STRING_LITERAL",-88],["U16STRING_LITERAL",-88],["U32STRING_LITERAL",-88],["RBRACE",-88],["ELSE",-88]]],[142,[["$end",-92],["SEMI",-92],["PPHASH",-92],["PPPRAGMA",-92],["_PRAGMA",-92],["_STATIC_ASSERT",-92],["ASM",-92],["ID",-92],["LPAREN",-92],["TIMES",-92],["TYPEID",-92],["ENUM",-92],["VOID",-92],["_BOOL",-92],["CHAR",-92],["SHORT",-92],["INT",-92],["LONG",-92],["FLOAT",-92],["DOUBLE",-92],["_COMPLEX",-92],["SIGNED",-92],["UNSIGNED",-92],["__INT128",-92],["_ATOMIC",-92],["TYPEOF",-92],["CONST",-92],["RESTRICT",-92],["VOLATILE",-92],["AUTO",-92],["REGISTER",-92],["STATIC",-92],["EXTERN",-92],["TYPEDEF",-92],["_THREAD_LOCAL",-92],["INLINE",-92],["_NORETURN",-92],["_ALIGNAS",-92],["__ATTRIBUTE__",-92],["STRUCT",-92],["UNION",-92]]],[274,[["$end",-93],["SEMI",-93],["PPHASH",-93],["PPPRAGMA",-93],["_PRAGMA",-93],["_STATIC_ASSERT",-93],["ASM",-93],["ID",-93],["LPAREN",-93],["TIMES",-93],["TYPEID",-93],["ENUM",-93],["VOID",-93],["_BOOL",-93],["CHAR",-93],["SHORT",-93],["INT",-93],["LONG",-93],["FLOAT",-93],["DOUBLE",-93],["_COMPLEX",-93],["SIGNED",-93],["UNSIGNED",-93],["__INT128",-93],["_ATOMIC",-93],["TYPEOF",-93],["CONST",-93],["RESTRICT",-93],["VOLATILE",-93],["AUTO",-93],["REGISTER",-93],["STATIC",-93],["EXTERN",-93],["TYPEDEF",-93],["_THREAD_LOCAL",-93],["INLINE",-93],["_NORETURN",-93],["_ALIGNAS",-93],["__ATTRIBUTE__",-93],["STRUCT",-93],["UNION",-93]]],[285,[["$end",-89],["SEMI",-89],["PPHASH",-89],["PPPRAGMA",-89],["_PRAGMA",-89],["_STATIC_ASSERT",-89],["ASM",-89],["ID",-89],["LPAREN",-89],["TIMES",-89],["TYPEID",-89],["ENUM",-89],["VOID",-89],["_BOOL",-89],["CHAR",-89],["SHORT",-89],["INT",-89],["LONG",-89],["FLOAT",-89],["DOUBLE",-89],["_COMPLEX",-89],["SIGNED",-89],["UNSIGNED",-89],["__INT128",-89],["_ATOMIC",-89],["TYPEOF",-89],["CONST",-89],["RESTRICT",-89],["VOLATILE",-89],["AUTO",-89],["REGISTER",-89],["STATIC",-89],["EXTERN",-89],["TYPEDEF",-89],["_THREAD_LOCAL",-89],["INLINE",-89],["_NORETURN",-89],["_ALIGNAS",-89],["__ATTRIBUTE__",-89],["STRUCT",-89],["UNION",-89],["LBRACE",-89],["CASE",-89],["DEFAULT",-89],["IF",-89],["SWITCH",-89],["WHILE",-89],["DO",-89],["FOR",-89],["GOTO",-89],["BREAK",-89],["CONTINUE",-89],["RETURN",-89],["PLUSPLUS",-89],["MINUSMINUS",-89],["SIZEOF",-89],["_ALIGNOF",-89],["AND",-89],["PLUS",-89],["MINUS",-89],["NOT",-89],["LNOT",-89],["OFFSETOF",-89],["INT_CONST_DEC",-89],["INT_CONST_OCT",-89],["INT_CONST_HEX",-89],["INT_CONST_BIN",-89],["INT_CONST_CHAR",-89],["FLOAT_CONST",-89],["HEX_FLOAT_CONST",-89],["CHAR_CONST",-89],["WCHAR_CONST",-89],["U8CHAR_CONST",-89],["U16CHAR_CONST",-89],["U32CHAR_CONST",-89],["STRING_LITERAL",-89],["WSTRING_LITERAL",-89],["U8STRING_LITERAL",-89],["U16STRING_LITERAL",-89],["U32STRING_LITERAL",-89],["RBRACE",-89],["ELSE",-89]]],[290,[["$end",-85],["SEMI",-85],["PPHASH",-85],["PPPRAGMA",-85],["_PRAGMA",-85],["_STATIC_ASSERT",-85],["ASM",-85],["ID",-85],["LPAREN",-85],["TIMES",-85],["TYPEID",-85],["ENUM",-85],["VOID",-85],["_BOOL",-85],["CHAR",-85],["SHORT",-85],["INT",-85],["LONG",-85],["FLOAT",-85],["DOUBLE",-85],["_COMPLEX",-85],["SIGNED",-85],["UNSIGNED",-85],["__INT128",-85],["_ATOMIC",-85],["TYPEOF",-85],["CONST",-85],["RESTRICT",-85],["VOLATILE",-85],["AUTO",-85],["REGISTER",-85],["STATIC",-85],["EXTERN",-85],["TYPEDEF",-85],["_THREAD_LOCAL",-85],["INLINE",-85],["_NORETURN",-85],["_ALIGNAS",-85],["__ATTRIBUTE__",-85],["STRUCT",-85],["UNION",-85],["LBRACE",-85],["CASE",-85],["DEFAULT",-85],["IF",-85],["SWITCH",-85],["WHILE",-85],["DO",-85],["FOR",-85],["GOTO",-85],["BREAK",-85],["CONTINUE",-85],["RETURN",-85],["PLUSPLUS",-85],["MINUSMINUS",-85],["SIZEOF",-85],["_ALIGNOF",-85],["AND",-85],["PLUS",-85],["MINUS",-85],["NOT",-85],["LNOT",-85],["OFFSETOF",-85],["INT_CONST_DEC",-85],["INT_CONST_OCT",-85],["INT_CONST_HEX",-85],["INT_CONST_BIN",-85],["INT_CONST_CHAR",-85],["FLOAT_CONST",-85],["HEX_FLOAT_CONST",-85],["CHAR_CONST",-85],["WCHAR_CONST",-85],["U8CHAR_CONST",-85],["U16CHAR_CONST",-85],["U32CHAR_CONST",-85],["STRING_LITERAL",-85],["WSTRING_LITERAL",-85],["U8STRING_LITERAL",-85],["U16STRING_LITERAL",-85],["U32STRING_LITERAL",-85],["RBRACE",-85],["ELSE",-85]]],[358,[["$end",-379],["SEMI",-379],["PPHASH",-379],["PPPRAGMA",-379],["_PRAGMA",-379],["_STATIC_ASSERT",-379],["ASM",-379],["ID",-379],["LPAREN",-379],["TIMES",-379],["TYPEID",-379],["ENUM",-379],["VOID",-379],["_BOOL",-379],["CHAR",-379],["SHORT",-379],["INT",-379],["LONG",-379],["FLOAT",-379],["DOUBLE",-379],["_COMPLEX",-379],["SIGNED",-379],["UNSIGNED",-379],["__INT128",-379],["_ATOMIC",-379],["TYPEOF",-379],["CONST",-379],["RESTRICT",-379],["VOLATILE",-379],["AUTO",-379],["REGISTER",-379],["STATIC",-379],["EXTERN",-379],["TYPEDEF",-379],["_THREAD_LOCAL",-379],["INLINE",-379],["_NORETURN",-379],["_ALIGNAS",-379],["__ATTRIBUTE__",-379],["STRUCT",-379],["UNION",-379],["LBRACE",-379],["CASE",-379],["DEFAULT",-379],["IF",-379],["SWITCH",-379],["WHILE",-379],["DO",-379],["FOR",-379],["GOTO",-379],["BREAK",-379],["CONTINUE",-379],["RETURN",-379],["PLUSPLUS",-379],["MINUSMINUS",-379],["SIZEOF",-379],["_ALIGNOF",-379],["AND",-379],["PLUS",-379],["MINUS",-379],["NOT",-379],["LNOT",-379],["OFFSETOF",-379],["INT_CONST_DEC",-379],["INT_CONST_OCT",-379],["INT_CONST_HEX",-379],["INT_CONST_BIN",-379],["INT_CONST_CHAR",-379],["FLOAT_CONST",-379],["HEX_FLOAT_CONST",-379],["CHAR_CONST",-379],["WCHAR_CONST",-379],["U8CHAR_CONST",-379],["U16CHAR_CONST",-379],["U32CHAR_CONST",-379],["STRING_LITERAL",-379],["WSTRING_LITERAL",-379],["U8STRING_LITERAL",-379],["U16STRING_LITERAL",-379],["U32STRING_LITERAL",-379],["RBRACE",-379],["ELSE",-379],["EQUALS",-379],["COLON",-379],["COMMA",-379],["RPAREN",-379],["LBRACKET",-379],["RBRACKET",-379],["PERIOD",-379],["ARROW",-379],["CONDOP",-379],["DIVIDE",-379],["MOD",-379],["RSHIFT",-379],["LSHIFT",-379],["LT",-379],["LE",-379],["GE",-379],["GT",-379],["EQ",-379],["NE",-379],["OR",-379],["XOR",-379],["LAND",-379],["LOR",-379],["XOREQUAL",-379],["TIMESEQUAL",-379],["DIVEQUAL",-379],["MODEQUAL",-379],["PLUSEQUAL",-379],["MINUSEQUAL",-379],["LSHIFTEQUAL",-379],["RSHIFTEQUAL",-379],["ANDEQUAL",-379],["OREQUAL",-379],["ELLIPSIS",-379]]],[399,[["$end",-250],["SEMI",-250],["PPHASH",-250],["PPPRAGMA",-250],["_PRAGMA",-250],["_STATIC_ASSERT",-250],["ASM",-250],["ID",-250],["LPAREN",-250],["TIMES",-250],["TYPEID",-250],["ENUM",-250],["VOID",-250],["_BOOL",-250],["CHAR",-250],["SHORT",-250],["INT",-250],["LONG",-250],["FLOAT",-250],["DOUBLE",-250],["_COMPLEX",-250],["SIGNED",-250],["UNSIGNED",-250],["__INT128",-250],["_ATOMIC",-250],["TYPEOF",-250],["CONST",-250],["RESTRICT",-250],["VOLATILE",-250],["AUTO",-250],["REGISTER",-250],["STATIC",-250],["EXTERN",-250],["TYPEDEF",-250],["_THREAD_LOCAL",-250],["INLINE",-250],["_NORETURN",-250],["_ALIGNAS",-250],["__ATTRIBUTE__",-250],["STRUCT",-250],["UNION",-250],["LBRACE",-250],["CASE",-250],["DEFAULT",-250],["IF",-250],["SWITCH",-250],["WHILE",-250],["DO",-250],["FOR",-250],["GOTO",-250],["BREAK",-250],["CONTINUE",-250],["RETURN",-250],["PLUSPLUS",-250],["MINUSMINUS",-250],["SIZEOF",-250],["_ALIGNOF",-250],["AND",-250],["PLUS",-250],["MINUS",-250],["NOT",-250],["LNOT",-250],["OFFSETOF",-250],["INT_CONST_DEC",-250],["INT_CONST_OCT",-250],["INT_CONST_HEX",-250],["INT_CONST_BIN",-250],["INT_CONST_CHAR",-250],["FLOAT_CONST",-250],["HEX_FLOAT_CONST",-250],["CHAR_CONST",-250],["WCHAR_CONST",-250],["U8CHAR_CONST",-250],["U16CHAR_CONST",-250],["U32CHAR_CONST",-250],["STRING_LITERAL",-250],["WSTRING_LITERAL",-250],["U8STRING_LITERAL",-250],["U16STRING_LITERAL",-250],["U32STRING_LITERAL",-250],["RBRACE",-250],["ELSE",-250],["RPAREN",-250]]],[468,[["$end",-83],["SEMI",-83],["PPHASH",-83],["PPPRAGMA",-83],["_PRAGMA",-83],["_STATIC_ASSERT",-83],["ASM",-83],["ID",-83],["LPAREN",-83],["TIMES",-83],["TYPEID",-83],["ENUM",-83],["VOID",-83],["_BOOL",-83],["CHAR",-83],["SHORT",-83],["INT",-83],["LONG",-83],["FLOAT",-83],["DOUBLE",-83],["_COMPLEX",-83],["SIGNED",-83],["UNSIGNED",-83],["__INT128",-83],["_ATOMIC",-83],["TYPEOF",-83],["CONST",-83],["RESTRICT",-83],["VOLATILE",-83],["AUTO",-83],["REGISTER",-83],["STATIC",-83],["EXTERN",-83],["TYPEDEF",-83],["_THREAD_LOCAL",-83],["INLINE",-83],["_NORETURN",-83],["_ALIGNAS",-83],["__ATTRIBUTE__",-83],["STRUCT",-83],["UNION",-83]]],[549,[["$end",-84],["SEMI",-84],["PPHASH",-84],["PPPRAGMA",-84],["_PRAGMA",-84],["_STATIC_ASSERT",-84],["ASM",-84],["ID",-84],["LPAREN",-84],["TIMES",-84],["TYPEID",-84],["ENUM",-84],["VOID",-84],["_BOOL",-84],["CHAR",-84],["SHORT",-84],["INT",-84],["LONG",-84],["FLOAT",-84],["DOUBLE",-84],["_COMPLEX",-84],["SIGNED",-84],["UNSIGNED",-84],["__INT128",-84],["_ATOMIC",-84],["TYPEOF",-84],["CONST",-84],["RESTRICT",-84],["VOLATILE",-84],["AUTO",-84],["REGISTER",-84],["STATIC",-84],["EXTERN",-84],["TYPEDEF",-84],["_THREAD_LOCAL",-84],["INLINE",-84],["_NORETURN",-84],["_ALIGNAS",-84],["__ATTRIBUTE__",-84],["STRUCT",-84],["UNION",-84],["LBRACE",-84],["CASE",-84],["DEFAULT",-84],["IF",-84],["SWITCH",-84],["WHILE",-84],["DO",-84],["FOR",-84],["GOTO",-84],["BREAK",-84],["CONTINUE",-84],["RETURN",-84],["PLUSPLUS",-84],["MINUSMINUS",-84],["SIZEOF",-84],["_ALIGNOF",-84],["AND",-84],["PLUS",-84],["MINUS",-84],["NOT",-84],["LNOT",-84],["OFFSETOF",-84],["INT_CONST_DEC",-84],["INT_CONST_OCT",-84],["INT_CONST_HEX",-84],["INT_CONST_BIN",-84],["INT_CONST_CHAR",-84],["FLOAT_CONST",-84],["HEX_FLOAT_CONST",-84],["CHAR_CONST",-84],["WCHAR_CONST",-84],["U8CHAR_CONST",-84],["U16CHAR_CONST",-84],["U32CHAR_CONST",-84],["STRING_LITERAL",-84],["WSTRING_LITERAL",-84],["U8STRING_LITERAL",-84],["U16STRING_LITERAL",-84],["U32STRING_LITERAL",-84],["RBRACE",-84],["ELSE",-84]]],[13,[["SEMI",-412],["ID",31],["LPAREN",89],["TIMES",33],["TYPEID",96],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67]]],[14,[["SEMI",97]]],[21,[["SEMI",-66],["ASM",-66],["LPAREN",104],["TYPEID",-66],["ENUM",-66],["VOID",-66],["_BOOL",-66],["CHAR",-66],["SHORT",-66],["INT",-66],["LONG",-66],["FLOAT",-66],["DOUBLE",-66],["_COMPLEX",-66],["SIGNED",-66],["UNSIGNED",-66],["__INT128",-66],["_ATOMIC",-66],["TYPEOF",-66],["CONST",-66],["RESTRICT",-66],["VOLATILE",-66],["AUTO",-66],["REGISTER",-66],["STATIC",-66],["EXTERN",-66],["TYPEDEF",-66],["_THREAD_LOCAL",-66],["INLINE",-66],["_NORETURN",-66],["_ALIGNAS",-66],["__ATTRIBUTE__",-66],["STRUCT",-66],["UNION",-66],["LBRACE",-66],["EQUALS",-66],["COLON",-66],["COMMA",-66],["RPAREN",-66],["LBRACKET",103]]],[23,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["ENUM",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412]]],[24,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["ENUM",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412]]],[25,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["ENUM",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412]]],[26,[["SEMI",-148],["ID",-148],["LPAREN",-148],["TIMES",-148],["TYPEID",-148],["VOID",-148],["_BOOL",-148],["CHAR",-148],["SHORT",-148],["INT",-148],["LONG",-148],["FLOAT",-148],["DOUBLE",-148],["_COMPLEX",-148],["SIGNED",-148],["UNSIGNED",-148],["__INT128",-148],["_ATOMIC",-148],["CONST",-148],["RESTRICT",-148],["VOLATILE",-148],["AUTO",-148],["REGISTER",-148],["STATIC",-148],["EXTERN",-148],["TYPEDEF",-148],["_THREAD_LOCAL",-148],["INLINE",-148],["_NORETURN",-148],["_ALIGNAS",-148],["__ATTRIBUTE__",-148],["COLON",-148],["COMMA",-148],["RPAREN",-148],["LBRACKET",-148]]],[27,[["SEMI",-121],["ID",-121],["LPAREN",-121],["TIMES",-121],["TYPEID",-121],["VOID",-121],["_BOOL",-121],["CHAR",-121],["SHORT",-121],["INT",-121],["LONG",-121],["FLOAT",-121],["DOUBLE",-121],["_COMPLEX",-121],["SIGNED",-121],["UNSIGNED",-121],["__INT128",-121],["_ATOMIC",-121],["CONST",-121],["RESTRICT",-121],["VOLATILE",-121],["AUTO",-121],["REGISTER",-121],["STATIC",-121],["EXTERN",-121],["TYPEDEF",-121],["_THREAD_LOCAL",-121],["INLINE",-121],["_NORETURN",-121],["_ALIGNAS",-121],["__ATTRIBUTE__",-121],["COMMA",-121],["RPAREN",-121],["LBRACKET",-121]]],[28,[["SEMI",-412],["ID",31],["LPAREN",18],["TIMES",33],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",117],["TYPEOF",55],["STRUCT",68],["UNION",69]]],[29,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["ENUM",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412]]],[30,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["ENUM",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412]]],[31,[["SEMI",-43],["ASM",-43],["LPAREN",-43],["TYPEID",-43],["ENUM",-43],["VOID",-43],["_BOOL",-43],["CHAR",-43],["SHORT",-43],["INT",-43],["LONG",-43],["FLOAT",-43],["DOUBLE",-43],["_COMPLEX",-43],["SIGNED",-43],["UNSIGNED",-43],["__INT128",-43],["_ATOMIC",-43],["TYPEOF",-43],["CONST",-43],["RESTRICT",-43],["VOLATILE",-43],["AUTO",-43],["REGISTER",-43],["STATIC",-43],["EXTERN",-43],["TYPEDEF",-43],["_THREAD_LOCAL",-43],["INLINE",-43],["_NORETURN",-43],["_ALIGNAS",-43],["__ATTRIBUTE__",-43],["STRUCT",-43],["UNION",-43],["LBRACE",-43],["EQUALS",-43],["COLON",-43],["COMMA",-43],["RPAREN",-43],["LBRACKET",-43]]],[32,[["SEMI",-127],["ID",-127],["LPAREN",-127],["TIMES",-127],["TYPEID",-127],["ENUM",-127],["VOID",-127],["_BOOL",-127],["CHAR",-127],["SHORT",-127],["INT",-127],["LONG",-127],["FLOAT",-127],["DOUBLE",-127],["_COMPLEX",-127],["SIGNED",-127],["UNSIGNED",-127],["__INT128",-127],["_ATOMIC",-127],["TYPEOF",-127],["CONST",-127],["RESTRICT",-127],["VOLATILE",-127],["AUTO",-127],["REGISTER",-127],["STATIC",-127],["EXTERN",-127],["TYPEDEF",-127],["_THREAD_LOCAL",-127],["INLINE",-127],["_NORETURN",-127],["_ALIGNAS",-127],["__ATTRIBUTE__",-127],["STRUCT",-127],["UNION",-127],["COMMA",-127],["RPAREN",-127],["LBRACKET",-127]]],[34,[["SEMI",-145],["ID",-145],["LPAREN",-145],["TIMES",-145],["TYPEID",-145],["VOID",-145],["_BOOL",-145],["CHAR",-145],["SHORT",-145],["INT",-145],["LONG",-145],["FLOAT",-145],["DOUBLE",-145],["_COMPLEX",-145],["SIGNED",-145],["UNSIGNED",-145],["__INT128",-145],["_ATOMIC",-145],["CONST",-145],["RESTRICT",-145],["VOLATILE",-145],["AUTO",-145],["REGISTER",-145],["STATIC",-145],["EXTERN",-145],["TYPEDEF",-145],["_THREAD_LOCAL",-145],["INLINE",-145],["_NORETURN",-145],["_ALIGNAS",-145],["__ATTRIBUTE__",-145],["COLON",-145],["COMMA",-145],["RPAREN",-145],["LBRACKET",-145]]],[35,[["SEMI",-146],["ID",-146],["LPAREN",-146],["TIMES",-146],["TYPEID",-146],["VOID",-146],["_BOOL",-146],["CHAR",-146],["SHORT",-146],["INT",-146],["LONG",-146],["FLOAT",-146],["DOUBLE",-146],["_COMPLEX",-146],["SIGNED",-146],["UNSIGNED",-146],["__INT128",-146],["_ATOMIC",-146],["CONST",-146],["RESTRICT",-146],["VOLATILE",-146],["AUTO",-146],["REGISTER",-146],["STATIC",-146],["EXTERN",-146],["TYPEDEF",-146],["_THREAD_LOCAL",-146],["INLINE",-146],["_NORETURN",-146],["_ALIGNAS",-146],["__ATTRIBUTE__",-146],["COLON",-146],["COMMA",-146],["RPAREN",-146],["LBRACKET",-146]]],[36,[["SEMI",-147],["ID",-147],["LPAREN",-147],["TIMES",-147],["TYPEID",-147],["VOID",-147],["_BOOL",-147],["CHAR",-147],["SHORT",-147],["INT",-147],["LONG",-147],["FLOAT",-147],["DOUBLE",-147],["_COMPLEX",-147],["SIGNED",-147],["UNSIGNED",-147],["__INT128",-147],["_ATOMIC",-147],["CONST",-147],["RESTRICT",-147],["VOLATILE",-147],["AUTO",-147],["REGISTER",-147],["STATIC",-147],["EXTERN",-147],["TYPEDEF",-147],["_THREAD_LOCAL",-147],["INLINE",-147],["_NORETURN",-147],["_ALIGNAS",-147],["__ATTRIBUTE__",-147],["COLON",-147],["COMMA",-147],["RPAREN",-147],["LBRACKET",-147]]],[37,[["SEMI",-149],["ID",-149],["LPAREN",-149],["TIMES",-149],["TYPEID",-149],["ENUM",-412],["VOID",-149],["_BOOL",-149],["CHAR",-149],["SHORT",-149],["INT",-149],["LONG",-149],["FLOAT",-149],["DOUBLE",-149],["_COMPLEX",-149],["SIGNED",-149],["UNSIGNED",-149],["__INT128",-149],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412],["COMMA",-149],["RPAREN",-149],["LBRACKET",-149]]],[38,[["SEMI",-150],["ID",-150],["LPAREN",-150],["TIMES",-150],["TYPEID",-150],["VOID",-150],["_BOOL",-150],["CHAR",-150],["SHORT",-150],["INT",-150],["LONG",-150],["FLOAT",-150],["DOUBLE",-150],["_COMPLEX",-150],["SIGNED",-150],["UNSIGNED",-150],["__INT128",-150],["_ATOMIC",-150],["CONST",-150],["RESTRICT",-150],["VOLATILE",-150],["AUTO",-150],["REGISTER",-150],["STATIC",-150],["EXTERN",-150],["TYPEDEF",-150],["_THREAD_LOCAL",-150],["INLINE",-150],["_NORETURN",-150],["_ALIGNAS",-150],["__ATTRIBUTE__",-150],["COLON",-150],["COMMA",-150],["RPAREN",-150],["LBRACKET",-150]]],[39,[["SEMI",-278],["ID",-278],["LPAREN",-278],["TIMES",-278],["TYPEID",-278],["VOID",-278],["_BOOL",-278],["CHAR",-278],["SHORT",-278],["INT",-278],["LONG",-278],["FLOAT",-278],["DOUBLE",-278],["_COMPLEX",-278],["SIGNED",-278],["UNSIGNED",-278],["__INT128",-278],["_ATOMIC",-278],["CONST",-278],["RESTRICT",-278],["VOLATILE",-278],["AUTO",-278],["REGISTER",-278],["STATIC",-278],["EXTERN",-278],["TYPEDEF",-278],["_THREAD_LOCAL",-278],["INLINE",-278],["_NORETURN",-278],["_ALIGNAS",-278],["__ATTRIBUTE__",-278],["COLON",-278],["COMMA",-278],["RPAREN",-278],["LBRACKET",-278]]],[42,[["SEMI",-133],["ID",-133],["LPAREN",-133],["TIMES",-133],["TYPEID",-133],["VOID",-133],["_BOOL",-133],["CHAR",-133],["SHORT",-133],["INT",-133],["LONG",-133],["FLOAT",-133],["DOUBLE",-133],["_COMPLEX",-133],["SIGNED",-133],["UNSIGNED",-133],["__INT128",-133],["_ATOMIC",-133],["CONST",-133],["RESTRICT",-133],["VOLATILE",-133],["AUTO",-133],["REGISTER",-133],["STATIC",-133],["EXTERN",-133],["TYPEDEF",-133],["_THREAD_LOCAL",-133],["INLINE",-133],["_NORETURN",-133],["_ALIGNAS",-133],["__ATTRIBUTE__",-133],["COLON",-133],["COMMA",-133],["RPAREN",-133],["LBRACKET",-133]]],[43,[["SEMI",-134],["ID",-134],["LPAREN",-134],["TIMES",-134],["TYPEID",-134],["VOID",-134],["_BOOL",-134],["CHAR",-134],["SHORT",-134],["INT",-134],["LONG",-134],["FLOAT",-134],["DOUBLE",-134],["_COMPLEX",-134],["SIGNED",-134],["UNSIGNED",-134],["__INT128",-134],["_ATOMIC",-134],["CONST",-134],["RESTRICT",-134],["VOLATILE",-134],["AUTO",-134],["REGISTER",-134],["STATIC",-134],["EXTERN",-134],["TYPEDEF",-134],["_THREAD_LOCAL",-134],["INLINE",-134],["_NORETURN",-134],["_ALIGNAS",-134],["__ATTRIBUTE__",-134],["COLON",-134],["COMMA",-134],["RPAREN",-134],["LBRACKET",-134]]],[44,[["SEMI",-135],["ID",-135],["LPAREN",-135],["TIMES",-135],["TYPEID",-135],["VOID",-135],["_BOOL",-135],["CHAR",-135],["SHORT",-135],["INT",-135],["LONG",-135],["FLOAT",-135],["DOUBLE",-135],["_COMPLEX",-135],["SIGNED",-135],["UNSIGNED",-135],["__INT128",-135],["_ATOMIC",-135],["CONST",-135],["RESTRICT",-135],["VOLATILE",-135],["AUTO",-135],["REGISTER",-135],["STATIC",-135],["EXTERN",-135],["TYPEDEF",-135],["_THREAD_LOCAL",-135],["INLINE",-135],["_NORETURN",-135],["_ALIGNAS",-135],["__ATTRIBUTE__",-135],["COLON",-135],["COMMA",-135],["RPAREN",-135],["LBRACKET",-135]]],[45,[["SEMI",-136],["ID",-136],["LPAREN",-136],["TIMES",-136],["TYPEID",-136],["VOID",-136],["_BOOL",-136],["CHAR",-136],["SHORT",-136],["INT",-136],["LONG",-136],["FLOAT",-136],["DOUBLE",-136],["_COMPLEX",-136],["SIGNED",-136],["UNSIGNED",-136],["__INT128",-136],["_ATOMIC",-136],["CONST",-136],["RESTRICT",-136],["VOLATILE",-136],["AUTO",-136],["REGISTER",-136],["STATIC",-136],["EXTERN",-136],["TYPEDEF",-136],["_THREAD_LOCAL",-136],["INLINE",-136],["_NORETURN",-136],["_ALIGNAS",-136],["__ATTRIBUTE__",-136],["COLON",-136],["COMMA",-136],["RPAREN",-136],["LBRACKET",-136]]],[46,[["SEMI",-137],["ID",-137],["LPAREN",-137],["TIMES",-137],["TYPEID",-137],["VOID",-137],["_BOOL",-137],["CHAR",-137],["SHORT",-137],["INT",-137],["LONG",-137],["FLOAT",-137],["DOUBLE",-137],["_COMPLEX",-137],["SIGNED",-137],["UNSIGNED",-137],["__INT128",-137],["_ATOMIC",-137],["CONST",-137],["RESTRICT",-137],["VOLATILE",-137],["AUTO",-137],["REGISTER",-137],["STATIC",-137],["EXTERN",-137],["TYPEDEF",-137],["_THREAD_LOCAL",-137],["INLINE",-137],["_NORETURN",-137],["_ALIGNAS",-137],["__ATTRIBUTE__",-137],["COLON",-137],["COMMA",-137],["RPAREN",-137],["LBRACKET",-137]]],[47,[["SEMI",-138],["ID",-138],["LPAREN",-138],["TIMES",-138],["TYPEID",-138],["VOID",-138],["_BOOL",-138],["CHAR",-138],["SHORT",-138],["INT",-138],["LONG",-138],["FLOAT",-138],["DOUBLE",-138],["_COMPLEX",-138],["SIGNED",-138],["UNSIGNED",-138],["__INT128",-138],["_ATOMIC",-138],["CONST",-138],["RESTRICT",-138],["VOLATILE",-138],["AUTO",-138],["REGISTER",-138],["STATIC",-138],["EXTERN",-138],["TYPEDEF",-138],["_THREAD_LOCAL",-138],["INLINE",-138],["_NORETURN",-138],["_ALIGNAS",-138],["__ATTRIBUTE__",-138],["COLON",-138],["COMMA",-138],["RPAREN",-138],["LBRACKET",-138]]],[48,[["SEMI",-139],["ID",-139],["LPAREN",-139],["TIMES",-139],["TYPEID",-139],["VOID",-139],["_BOOL",-139],["CHAR",-139],["SHORT",-139],["INT",-139],["LONG",-139],["FLOAT",-139],["DOUBLE",-139],["_COMPLEX",-139],["SIGNED",-139],["UNSIGNED",-139],["__INT128",-139],["_ATOMIC",-139],["CONST",-139],["RESTRICT",-139],["VOLATILE",-139],["AUTO",-139],["REGISTER",-139],["STATIC",-139],["EXTERN",-139],["TYPEDEF",-139],["_THREAD_LOCAL",-139],["INLINE",-139],["_NORETURN",-139],["_ALIGNAS",-139],["__ATTRIBUTE__",-139],["COLON",-139],["COMMA",-139],["RPAREN",-139],["LBRACKET",-139]]],[49,[["SEMI",-140],["ID",-140],["LPAREN",-140],["TIMES",-140],["TYPEID",-140],["VOID",-140],["_BOOL",-140],["CHAR",-140],["SHORT",-140],["INT",-140],["LONG",-140],["FLOAT",-140],["DOUBLE",-140],["_COMPLEX",-140],["SIGNED",-140],["UNSIGNED",-140],["__INT128",-140],["_ATOMIC",-140],["CONST",-140],["RESTRICT",-140],["VOLATILE",-140],["AUTO",-140],["REGISTER",-140],["STATIC",-140],["EXTERN",-140],["TYPEDEF",-140],["_THREAD_LOCAL",-140],["INLINE",-140],["_NORETURN",-140],["_ALIGNAS",-140],["__ATTRIBUTE__",-140],["COLON",-140],["COMMA",-140],["RPAREN",-140],["LBRACKET",-140]]],[50,[["SEMI",-141],["ID",-141],["LPAREN",-141],["TIMES",-141],["TYPEID",-141],["VOID",-141],["_BOOL",-141],["CHAR",-141],["SHORT",-141],["INT",-141],["LONG",-141],["FLOAT",-141],["DOUBLE",-141],["_COMPLEX",-141],["SIGNED",-141],["UNSIGNED",-141],["__INT128",-141],["_ATOMIC",-141],["CONST",-141],["RESTRICT",-141],["VOLATILE",-141],["AUTO",-141],["REGISTER",-141],["STATIC",-141],["EXTERN",-141],["TYPEDEF",-141],["_THREAD_LOCAL",-141],["INLINE",-141],["_NORETURN",-141],["_ALIGNAS",-141],["__ATTRIBUTE__",-141],["COLON",-141],["COMMA",-141],["RPAREN",-141],["LBRACKET",-141]]],[51,[["SEMI",-142],["ID",-142],["LPAREN",-142],["TIMES",-142],["TYPEID",-142],["VOID",-142],["_BOOL",-142],["CHAR",-142],["SHORT",-142],["INT",-142],["LONG",-142],["FLOAT",-142],["DOUBLE",-142],["_COMPLEX",-142],["SIGNED",-142],["UNSIGNED",-142],["__INT128",-142],["_ATOMIC",-142],["CONST",-142],["RESTRICT",-142],["VOLATILE",-142],["AUTO",-142],["REGISTER",-142],["STATIC",-142],["EXTERN",-142],["TYPEDEF",-142],["_THREAD_LOCAL",-142],["INLINE",-142],["_NORETURN",-142],["_ALIGNAS",-142],["__ATTRIBUTE__",-142],["COLON",-142],["COMMA",-142],["RPAREN",-142],["LBRACKET",-142]]],[52,[["SEMI",-143],["ID",-143],["LPAREN",-143],["TIMES",-143],["TYPEID",-143],["VOID",-143],["_BOOL",-143],["CHAR",-143],["SHORT",-143],["INT",-143],["LONG",-143],["FLOAT",-143],["DOUBLE",-143],["_COMPLEX",-143],["SIGNED",-143],["UNSIGNED",-143],["__INT128",-143],["_ATOMIC",-143],["CONST",-143],["RESTRICT",-143],["VOLATILE",-143],["AUTO",-143],["REGISTER",-143],["STATIC",-143],["EXTERN",-143],["TYPEDEF",-143],["_THREAD_LOCAL",-143],["INLINE",-143],["_NORETURN",-143],["_ALIGNAS",-143],["__ATTRIBUTE__",-143],["COLON",-143],["COMMA",-143],["RPAREN",-143],["LBRACKET",-143]]],[53,[["SEMI",-144],["ID",-144],["LPAREN",-144],["TIMES",-144],["TYPEID",-144],["VOID",-144],["_BOOL",-144],["CHAR",-144],["SHORT",-144],["INT",-144],["LONG",-144],["FLOAT",-144],["DOUBLE",-144],["_COMPLEX",-144],["SIGNED",-144],["UNSIGNED",-144],["__INT128",-144],["_ATOMIC",-144],["CONST",-144],["RESTRICT",-144],["VOLATILE",-144],["AUTO",-144],["REGISTER",-144],["STATIC",-144],["EXTERN",-144],["TYPEDEF",-144],["_THREAD_LOCAL",-144],["INLINE",-144],["_NORETURN",-144],["_ALIGNAS",-144],["__ATTRIBUTE__",-144],["COLON",-144],["COMMA",-144],["RPAREN",-144],["LBRACKET",-144]]],[54,[["SEMI",-157],["ID",-157],["LPAREN",138],["TIMES",-157],["TYPEID",-157],["ENUM",-157],["VOID",-157],["_BOOL",-157],["CHAR",-157],["SHORT",-157],["INT",-157],["LONG",-157],["FLOAT",-157],["DOUBLE",-157],["_COMPLEX",-157],["SIGNED",-157],["UNSIGNED",-157],["__INT128",-157],["_ATOMIC",-157],["TYPEOF",-157],["CONST",-157],["RESTRICT",-157],["VOLATILE",-157],["AUTO",-157],["REGISTER",-157],["STATIC",-157],["EXTERN",-157],["TYPEDEF",-157],["_THREAD_LOCAL",-157],["INLINE",-157],["_NORETURN",-157],["_ALIGNAS",-157],["__ATTRIBUTE__",-157],["STRUCT",-157],["UNION",-157]]],[56,[["SEMI",-154],["ID",-154],["LPAREN",-154],["TIMES",-154],["TYPEID",-154],["ENUM",-154],["VOID",-154],["_BOOL",-154],["CHAR",-154],["SHORT",-154],["INT",-154],["LONG",-154],["FLOAT",-154],["DOUBLE",-154],["_COMPLEX",-154],["SIGNED",-154],["UNSIGNED",-154],["__INT128",-154],["_ATOMIC",-154],["TYPEOF",-154],["CONST",-154],["RESTRICT",-154],["VOLATILE",-154],["AUTO",-154],["REGISTER",-154],["STATIC",-154],["EXTERN",-154],["TYPEDEF",-154],["_THREAD_LOCAL",-154],["INLINE",-154],["_NORETURN",-154],["_ALIGNAS",-154],["__ATTRIBUTE__",-154],["STRUCT",-154],["UNION",-154],["PLUSPLUS",-154],["MINUSMINUS",-154],["SIZEOF",-154],["_ALIGNOF",-154],["AND",-154],["PLUS",-154],["MINUS",-154],["NOT",-154],["LNOT",-154],["OFFSETOF",-154],["INT_CONST_DEC",-154],["INT_CONST_OCT",-154],["INT_CONST_HEX",-154],["INT_CONST_BIN",-154],["INT_CONST_CHAR",-154],["FLOAT_CONST",-154],["HEX_FLOAT_CONST",-154],["CHAR_CONST",-154],["WCHAR_CONST",-154],["U8CHAR_CONST",-154],["U16CHAR_CONST",-154],["U32CHAR_CONST",-154],["STRING_LITERAL",-154],["WSTRING_LITERAL",-154],["U8STRING_LITERAL",-154],["U16STRING_LITERAL",-154],["U32STRING_LITERAL",-154],["COLON",-154],["COMMA",-154],["RPAREN",-154],["LBRACKET",-154],["RBRACKET",-154]]],[57,[["SEMI",-155],["ID",-155],["LPAREN",-155],["TIMES",-155],["TYPEID",-155],["ENUM",-155],["VOID",-155],["_BOOL",-155],["CHAR",-155],["SHORT",-155],["INT",-155],["LONG",-155],["FLOAT",-155],["DOUBLE",-155],["_COMPLEX",-155],["SIGNED",-155],["UNSIGNED",-155],["__INT128",-155],["_ATOMIC",-155],["TYPEOF",-155],["CONST",-155],["RESTRICT",-155],["VOLATILE",-155],["AUTO",-155],["REGISTER",-155],["STATIC",-155],["EXTERN",-155],["TYPEDEF",-155],["_THREAD_LOCAL",-155],["INLINE",-155],["_NORETURN",-155],["_ALIGNAS",-155],["__ATTRIBUTE__",-155],["STRUCT",-155],["UNION",-155],["PLUSPLUS",-155],["MINUSMINUS",-155],["SIZEOF",-155],["_ALIGNOF",-155],["AND",-155],["PLUS",-155],["MINUS",-155],["NOT",-155],["LNOT",-155],["OFFSETOF",-155],["INT_CONST_DEC",-155],["INT_CONST_OCT",-155],["INT_CONST_HEX",-155],["INT_CONST_BIN",-155],["INT_CONST_CHAR",-155],["FLOAT_CONST",-155],["HEX_FLOAT_CONST",-155],["CHAR_CONST",-155],["WCHAR_CONST",-155],["U8CHAR_CONST",-155],["U16CHAR_CONST",-155],["U32CHAR_CONST",-155],["STRING_LITERAL",-155],["WSTRING_LITERAL",-155],["U8STRING_LITERAL",-155],["U16STRING_LITERAL",-155],["U32STRING_LITERAL",-155],["COLON",-155],["COMMA",-155],["RPAREN",-155],["LBRACKET",-155],["RBRACKET",-155]]],[58,[["SEMI",-156],["ID",-156],["LPAREN",-156],["TIMES",-156],["TYPEID",-156],["ENUM",-156],["VOID",-156],["_BOOL",-156],["CHAR",-156],["SHORT",-156],["INT",-156],["LONG",-156],["FLOAT",-156],["DOUBLE",-156],["_COMPLEX",-156],["SIGNED",-156],["UNSIGNED",-156],["__INT128",-156],["_ATOMIC",-156],["TYPEOF",-156],["CONST",-156],["RESTRICT",-156],["VOLATILE",-156],["AUTO",-156],["REGISTER",-156],["STATIC",-156],["EXTERN",-156],["TYPEDEF",-156],["_THREAD_LOCAL",-156],["INLINE",-156],["_NORETURN",-156],["_ALIGNAS",-156],["__ATTRIBUTE__",-156],["STRUCT",-156],["UNION",-156],["PLUSPLUS",-156],["MINUSMINUS",-156],["SIZEOF",-156],["_ALIGNOF",-156],["AND",-156],["PLUS",-156],["MINUS",-156],["NOT",-156],["LNOT",-156],["OFFSETOF",-156],["INT_CONST_DEC",-156],["INT_CONST_OCT",-156],["INT_CONST_HEX",-156],["INT_CONST_BIN",-156],["INT_CONST_CHAR",-156],["FLOAT_CONST",-156],["HEX_FLOAT_CONST",-156],["CHAR_CONST",-156],["WCHAR_CONST",-156],["U8CHAR_CONST",-156],["U16CHAR_CONST",-156],["U32CHAR_CONST",-156],["STRING_LITERAL",-156],["WSTRING_LITERAL",-156],["U8STRING_LITERAL",-156],["U16STRING_LITERAL",-156],["U32STRING_LITERAL",-156],["COLON",-156],["COMMA",-156],["RPAREN",-156],["LBRACKET",-156],["RBRACKET",-156]]],[59,[["SEMI",-125],["ID",-125],["LPAREN",-125],["TIMES",-125],["TYPEID",-125],["ENUM",-125],["VOID",-125],["_BOOL",-125],["CHAR",-125],["SHORT",-125],["INT",-125],["LONG",-125],["FLOAT",-125],["DOUBLE",-125],["_COMPLEX",-125],["SIGNED",-125],["UNSIGNED",-125],["__INT128",-125],["_ATOMIC",-125],["TYPEOF",-125],["CONST",-125],["RESTRICT",-125],["VOLATILE",-125],["AUTO",-125],["REGISTER",-125],["STATIC",-125],["EXTERN",-125],["TYPEDEF",-125],["_THREAD_LOCAL",-125],["INLINE",-125],["_NORETURN",-125],["_ALIGNAS",-125],["__ATTRIBUTE__",-125],["STRUCT",-125],["UNION",-125],["COMMA",-125],["RPAREN",-125],["LBRACKET",-125]]],[60,[["SEMI",-126],["ID",-126],["LPAREN",-126],["TIMES",-126],["TYPEID",-126],["ENUM",-126],["VOID",-126],["_BOOL",-126],["CHAR",-126],["SHORT",-126],["INT",-126],["LONG",-126],["FLOAT",-126],["DOUBLE",-126],["_COMPLEX",-126],["SIGNED",-126],["UNSIGNED",-126],["__INT128",-126],["_ATOMIC",-126],["TYPEOF",-126],["CONST",-126],["RESTRICT",-126],["VOLATILE",-126],["AUTO",-126],["REGISTER",-126],["STATIC",-126],["EXTERN",-126],["TYPEDEF",-126],["_THREAD_LOCAL",-126],["INLINE",-126],["_NORETURN",-126],["_ALIGNAS",-126],["__ATTRIBUTE__",-126],["STRUCT",-126],["UNION",-126],["COMMA",-126],["RPAREN",-126],["LBRACKET",-126]]],[61,[["SEMI",-128],["ID",-128],["LPAREN",-128],["TIMES",-128],["TYPEID",-128],["ENUM",-128],["VOID",-128],["_BOOL",-128],["CHAR",-128],["SHORT",-128],["INT",-128],["LONG",-128],["FLOAT",-128],["DOUBLE",-128],["_COMPLEX",-128],["SIGNED",-128],["UNSIGNED",-128],["__INT128",-128],["_ATOMIC",-128],["TYPEOF",-128],["CONST",-128],["RESTRICT",-128],["VOLATILE",-128],["AUTO",-128],["REGISTER",-128],["STATIC",-128],["EXTERN",-128],["TYPEDEF",-128],["_THREAD_LOCAL",-128],["INLINE",-128],["_NORETURN",-128],["_ALIGNAS",-128],["__ATTRIBUTE__",-128],["STRUCT",-128],["UNION",-128],["COMMA",-128],["RPAREN",-128],["LBRACKET",-128]]],[62,[["SEMI",-129],["ID",-129],["LPAREN",-129],["TIMES",-129],["TYPEID",-129],["ENUM",-129],["VOID",-129],["_BOOL",-129],["CHAR",-129],["SHORT",-129],["INT",-129],["LONG",-129],["FLOAT",-129],["DOUBLE",-129],["_COMPLEX",-129],["SIGNED",-129],["UNSIGNED",-129],["__INT128",-129],["_ATOMIC",-129],["TYPEOF",-129],["CONST",-129],["RESTRICT",-129],["VOLATILE",-129],["AUTO",-129],["REGISTER",-129],["STATIC",-129],["EXTERN",-129],["TYPEDEF",-129],["_THREAD_LOCAL",-129],["INLINE",-129],["_NORETURN",-129],["_ALIGNAS",-129],["__ATTRIBUTE__",-129],["STRUCT",-129],["UNION",-129],["COMMA",-129],["RPAREN",-129],["LBRACKET",-129]]],[63,[["SEMI",-130],["ID",-130],["LPAREN",-130],["TIMES",-130],["TYPEID",-130],["ENUM",-130],["VOID",-130],["_BOOL",-130],["CHAR",-130],["SHORT",-130],["INT",-130],["LONG",-130],["FLOAT",-130],["DOUBLE",-130],["_COMPLEX",-130],["SIGNED",-130],["UNSIGNED",-130],["__INT128",-130],["_ATOMIC",-130],["TYPEOF",-130],["CONST",-130],["RESTRICT",-130],["VOLATILE",-130],["AUTO",-130],["REGISTER",-130],["STATIC",-130],["EXTERN",-130],["TYPEDEF",-130],["_THREAD_LOCAL",-130],["INLINE",-130],["_NORETURN",-130],["_ALIGNAS",-130],["__ATTRIBUTE__",-130],["STRUCT",-130],["UNION",-130],["COMMA",-130],["RPAREN",-130],["LBRACKET",-130]]],[64,[["SEMI",-131],["ID",-131],["LPAREN",-131],["TIMES",-131],["TYPEID",-131],["ENUM",-131],["VOID",-131],["_BOOL",-131],["CHAR",-131],["SHORT",-131],["INT",-131],["LONG",-131],["FLOAT",-131],["DOUBLE",-131],["_COMPLEX",-131],["SIGNED",-131],["UNSIGNED",-131],["__INT128",-131],["_ATOMIC",-131],["TYPEOF",-131],["CONST",-131],["RESTRICT",-131],["VOLATILE",-131],["AUTO",-131],["REGISTER",-131],["STATIC",-131],["EXTERN",-131],["TYPEDEF",-131],["_THREAD_LOCAL",-131],["INLINE",-131],["_NORETURN",-131],["_ALIGNAS",-131],["__ATTRIBUTE__",-131],["STRUCT",-131],["UNION",-131],["COMMA",-131],["RPAREN",-131],["LBRACKET",-131]]],[65,[["SEMI",-132],["ID",-132],["LPAREN",-132],["TIMES",-132],["TYPEID",-132],["ENUM",-132],["VOID",-132],["_BOOL",-132],["CHAR",-132],["SHORT",-132],["INT",-132],["LONG",-132],["FLOAT",-132],["DOUBLE",-132],["_COMPLEX",-132],["SIGNED",-132],["UNSIGNED",-132],["__INT128",-132],["_ATOMIC",-132],["TYPEOF",-132],["CONST",-132],["RESTRICT",-132],["VOLATILE",-132],["AUTO",-132],["REGISTER",-132],["STATIC",-132],["EXTERN",-132],["TYPEDEF",-132],["_THREAD_LOCAL",-132],["INLINE",-132],["_NORETURN",-132],["_ALIGNAS",-132],["__ATTRIBUTE__",-132],["STRUCT",-132],["UNION",-132],["COMMA",-132],["RPAREN",-132],["LBRACKET",-132]]],[75,[["SEMI",-412],["ID",31],["LPAREN",89],["TIMES",33],["TYPEID",96],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67]]],[76,[["SEMI",-412],["ID",31],["LPAREN",18],["TIMES",33],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",117],["TYPEOF",55],["STRUCT",68],["UNION",69]]],[77,[["SEMI",-149],["ID",-149],["LPAREN",-149],["TIMES",-149],["TYPEID",-149],["ENUM",-412],["VOID",-149],["_BOOL",-149],["CHAR",-149],["SHORT",-149],["INT",-149],["LONG",-149],["FLOAT",-149],["DOUBLE",-149],["_COMPLEX",-149],["SIGNED",-149],["UNSIGNED",-149],["__INT128",-149],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412]]],[78,[["SEMI",-157],["ID",-157],["LPAREN",138],["TIMES",-157],["TYPEID",-157],["ENUM",-157],["VOID",-157],["_BOOL",-157],["CHAR",-157],["SHORT",-157],["INT",-157],["LONG",-157],["FLOAT",-157],["DOUBLE",-157],["_COMPLEX",-157],["SIGNED",-157],["UNSIGNED",-157],["__INT128",-157],["_ATOMIC",-157],["TYPEOF",-157],["CONST",-157],["RESTRICT",-157],["VOLATILE",-157],["AUTO",-157],["REGISTER",-157],["STATIC",-157],["EXTERN",-157],["TYPEDEF",-157],["_THREAD_LOCAL",-157],["INLINE",-157],["_NORETURN",-157],["_ALIGNAS",-157],["__ATTRIBUTE__",-157],["STRUCT",-157],["UNION",-157]]],[79,[["SEMI",-203],["ASM",-203],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",78],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",-203],["STRUCT",68],["UNION",69],["LBRACE",-412],["EQUALS",-203],["COLON",-203],["COMMA",-203]]],[80,[["SEMI",-117],["ID",-117],["LPAREN",-117],["TIMES",-117],["TYPEID",-117],["VOID",-117],["_BOOL",-117],["CHAR",-117],["SHORT",-117],["INT",-117],["LONG",-117],["FLOAT",-117],["DOUBLE",-117],["_COMPLEX",-117],["SIGNED",-117],["UNSIGNED",-117],["__INT128",-117],["_ATOMIC",-117],["CONST",-117],["RESTRICT",-117],["VOLATILE",-117],["AUTO",-117],["REGISTER",-117],["STATIC",-117],["EXTERN",-117],["TYPEDEF",-117],["_THREAD_LOCAL",-117],["INLINE",-117],["_NORETURN",-117],["_ALIGNAS",-117],["__ATTRIBUTE__",-117],["COMMA",-117],["RPAREN",-117],["LBRACKET",-117]]],[81,[["SEMI",-118],["ID",-118],["LPAREN",-118],["TIMES",-118],["TYPEID",-118],["VOID",-118],["_BOOL",-118],["CHAR",-118],["SHORT",-118],["INT",-118],["LONG",-118],["FLOAT",-118],["DOUBLE",-118],["_COMPLEX",-118],["SIGNED",-118],["UNSIGNED",-118],["__INT128",-118],["_ATOMIC",-118],["CONST",-118],["RESTRICT",-118],["VOLATILE",-118],["AUTO",-118],["REGISTER",-118],["STATIC",-118],["EXTERN",-118],["TYPEDEF",-118],["_THREAD_LOCAL",-118],["INLINE",-118],["_NORETURN",-118],["_ALIGNAS",-118],["__ATTRIBUTE__",-118],["COMMA",-118],["RPAREN",-118],["LBRACKET",-118]]],[82,[["SEMI",-119],["ID",-119],["LPAREN",-119],["TIMES",-119],["TYPEID",-119],["VOID",-119],["_BOOL",-119],["CHAR",-119],["SHORT",-119],["INT",-119],["LONG",-119],["FLOAT",-119],["DOUBLE",-119],["_COMPLEX",-119],["SIGNED",-119],["UNSIGNED",-119],["__INT128",-119],["_ATOMIC",-119],["CONST",-119],["RESTRICT",-119],["VOLATILE",-119],["AUTO",-119],["REGISTER",-119],["STATIC",-119],["EXTERN",-119],["TYPEDEF",-119],["_THREAD_LOCAL",-119],["INLINE",-119],["_NORETURN",-119],["_ALIGNAS",-119],["__ATTRIBUTE__",-119],["COMMA",-119],["RPAREN",-119],["LBRACKET",-119]]],[83,[["SEMI",-120],["ID",-120],["LPAREN",-120],["TIMES",-120],["TYPEID",-120],["VOID",-120],["_BOOL",-120],["CHAR",-120],["SHORT",-120],["INT",-120],["LONG",-120],["FLOAT",-120],["DOUBLE",-120],["_COMPLEX",-120],["SIGNED",-120],["UNSIGNED",-120],["__INT128",-120],["_ATOMIC",-120],["CONST",-120],["RESTRICT",-120],["VOLATILE",-120],["AUTO",-120],["REGISTER",-120],["STATIC",-120],["EXTERN",-120],["TYPEDEF",-120],["_THREAD_LOCAL",-120],["INLINE",-120],["_NORETURN",-120],["_ALIGNAS",-120],["__ATTRIBUTE__",-120],["COMMA",-120],["RPAREN",-120],["LBRACKET",-120]]],[84,[["SEMI",-123],["ID",-123],["LPAREN",-123],["TIMES",-123],["TYPEID",-123],["VOID",-123],["_BOOL",-123],["CHAR",-123],["SHORT",-123],["INT",-123],["LONG",-123],["FLOAT",-123],["DOUBLE",-123],["_COMPLEX",-123],["SIGNED",-123],["UNSIGNED",-123],["__INT128",-123],["_ATOMIC",-123],["CONST",-123],["RESTRICT",-123],["VOLATILE",-123],["AUTO",-123],["REGISTER",-123],["STATIC",-123],["EXTERN",-123],["TYPEDEF",-123],["_THREAD_LOCAL",-123],["INLINE",-123],["_NORETURN",-123],["_ALIGNAS",-123],["__ATTRIBUTE__",-123],["COMMA",-123],["RPAREN",-123],["LBRACKET",-123]]],[85,[["SEMI",-124],["ID",-124],["LPAREN",-124],["TIMES",-124],["TYPEID",-124],["VOID",-124],["_BOOL",-124],["CHAR",-124],["SHORT",-124],["INT",-124],["LONG",-124],["FLOAT",-124],["DOUBLE",-124],["_COMPLEX",-124],["SIGNED",-124],["UNSIGNED",-124],["__INT128",-124],["_ATOMIC",-124],["CONST",-124],["RESTRICT",-124],["VOLATILE",-124],["AUTO",-124],["REGISTER",-124],["STATIC",-124],["EXTERN",-124],["TYPEDEF",-124],["_THREAD_LOCAL",-124],["INLINE",-124],["_NORETURN",-124],["_ALIGNAS",-124],["__ATTRIBUTE__",-124],["COMMA",-124],["RPAREN",-124],["LBRACKET",-124]]],[86,[["SEMI",-106]]],[88,[["SEMI",-157],["ID",-157],["LPAREN",-157],["TIMES",-157],["TYPEID",-157],["VOID",-157],["_BOOL",-157],["CHAR",-157],["SHORT",-157],["INT",-157],["LONG",-157],["FLOAT",-157],["DOUBLE",-157],["_COMPLEX",-157],["SIGNED",-157],["UNSIGNED",-157],["__INT128",-157],["_ATOMIC",-157],["CONST",-157],["RESTRICT",-157],["VOLATILE",-157],["AUTO",-157],["REGISTER",-157],["STATIC",-157],["EXTERN",-157],["TYPEDEF",-157],["_THREAD_LOCAL",-157],["INLINE",-157],["_NORETURN",-157],["_ALIGNAS",-157],["__ATTRIBUTE__",-157],["PLUSPLUS",-157],["MINUSMINUS",-157],["SIZEOF",-157],["_ALIGNOF",-157],["AND",-157],["PLUS",-157],["MINUS",-157],["NOT",-157],["LNOT",-157],["OFFSETOF",-157],["INT_CONST_DEC",-157],["INT_CONST_OCT",-157],["INT_CONST_HEX",-157],["INT_CONST_BIN",-157],["INT_CONST_CHAR",-157],["FLOAT_CONST",-157],["HEX_FLOAT_CONST",-157],["CHAR_CONST",-157],["WCHAR_CONST",-157],["U8CHAR_CONST",-157],["U16CHAR_CONST",-157],["U32CHAR_CONST",-157],["STRING_LITERAL",-157],["WSTRING_LITERAL",-157],["U8STRING_LITERAL",-157],["U16STRING_LITERAL",-157],["U32STRING_LITERAL",-157],["COLON",-157],["COMMA",-157],["RPAREN",-157],["LBRACKET",-157],["RBRACKET",-157]]],[90,[["SEMI",-33]]],[91,[["SEMI",-34],["COMMA",150]]],[92,[["SEMI",-158],["COMMA",-158]]],[93,[["SEMI",-412],["ASM",154],["__ATTRIBUTE__",-412],["EQUALS",-412],["COLON",-412],["COMMA",-412]]],[94,[["SEMI",-204],["ASM",-204],["__ATTRIBUTE__",-204],["EQUALS",-204],["COLON",-204],["COMMA",-204]]],[95,[["SEMI",-68],["ASM",-68],["LPAREN",156],["__ATTRIBUTE__",-68],["EQUALS",-68],["COLON",-68],["COMMA",-68],["RPAREN",-68],["LBRACKET",155]]],[96,[["SEMI",-51],["ASM",-51],["LPAREN",-51],["__ATTRIBUTE__",-51],["EQUALS",-51],["COLON",-51],["COMMA",-51],["RPAREN",-51],["LBRACKET",-51]]],[105,[["SEMI",-67],["ASM",-67],["LPAREN",104],["TYPEID",-67],["ENUM",-67],["VOID",-67],["_BOOL",-67],["CHAR",-67],["SHORT",-67],["INT",-67],["LONG",-67],["FLOAT",-67],["DOUBLE",-67],["_COMPLEX",-67],["SIGNED",-67],["UNSIGNED",-67],["__INT128",-67],["_ATOMIC",-67],["TYPEOF",-67],["CONST",-67],["RESTRICT",-67],["VOLATILE",-67],["AUTO",-67],["REGISTER",-67],["STATIC",-67],["EXTERN",-67],["TYPEDEF",-67],["_THREAD_LOCAL",-67],["INLINE",-67],["_NORETURN",-67],["_ALIGNAS",-67],["__ATTRIBUTE__",-67],["STRUCT",-67],["UNION",-67],["LBRACE",-67],["EQUALS",-67],["COLON",-67],["COMMA",-67],["RPAREN",-67],["LBRACKET",103]]],[106,[["SEMI",-111],["ID",-111],["LPAREN",-111],["TIMES",-111],["TYPEID",-111],["ENUM",-111],["VOID",-111],["_BOOL",-111],["CHAR",-111],["SHORT",-111],["INT",-111],["LONG",-111],["FLOAT",-111],["DOUBLE",-111],["_COMPLEX",-111],["SIGNED",-111],["UNSIGNED",-111],["__INT128",-111],["_ATOMIC",-111],["TYPEOF",-111],["STRUCT",-111],["UNION",-111]]],[107,[["SEMI",-21],["ID",-21],["LPAREN",-21],["TIMES",-21],["TYPEID",-21],["ENUM",-21],["VOID",-21],["_BOOL",-21],["CHAR",-21],["SHORT",-21],["INT",-21],["LONG",-21],["FLOAT",-21],["DOUBLE",-21],["_COMPLEX",-21],["SIGNED",-21],["UNSIGNED",-21],["__INT128",-21],["_ATOMIC",-21],["TYPEOF",-21],["STRUCT",-21],["UNION",-21]]],[108,[["SEMI",-22],["ID",-22],["LPAREN",-22],["TIMES",-22],["TYPEID",-22],["ENUM",-22],["VOID",-22],["_BOOL",-22],["CHAR",-22],["SHORT",-22],["INT",-22],["LONG",-22],["FLOAT",-22],["DOUBLE",-22],["_COMPLEX",-22],["SIGNED",-22],["UNSIGNED",-22],["__INT128",-22],["_ATOMIC",-22],["TYPEOF",-22],["STRUCT",-22],["UNION",-22]]],[109,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["ENUM",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412]]],[110,[["SEMI",-112],["ID",-112],["LPAREN",-112],["TIMES",-112],["TYPEID",-112],["ENUM",-112],["VOID",-112],["_BOOL",-112],["CHAR",-112],["SHORT",-112],["INT",-112],["LONG",-112],["FLOAT",-112],["DOUBLE",-112],["_COMPLEX",-112],["SIGNED",-112],["UNSIGNED",-112],["__INT128",-112],["_ATOMIC",-112],["TYPEOF",-112],["STRUCT",-112],["UNION",-112]]],[111,[["SEMI",-113],["ID",-113],["LPAREN",-113],["TIMES",-113],["TYPEID",-113],["ENUM",-113],["VOID",-113],["_BOOL",-113],["CHAR",-113],["SHORT",-113],["INT",-113],["LONG",-113],["FLOAT",-113],["DOUBLE",-113],["_COMPLEX",-113],["SIGNED",-113],["UNSIGNED",-113],["__INT128",-113],["_ATOMIC",-113],["TYPEOF",-113],["STRUCT",-113],["UNION",-113]]],[112,[["SEMI",-122],["ID",-122],["LPAREN",-122],["TIMES",-122],["TYPEID",-122],["VOID",-122],["_BOOL",-122],["CHAR",-122],["SHORT",-122],["INT",-122],["LONG",-122],["FLOAT",-122],["DOUBLE",-122],["_COMPLEX",-122],["SIGNED",-122],["UNSIGNED",-122],["__INT128",-122],["_ATOMIC",-122],["CONST",-122],["RESTRICT",-122],["VOLATILE",-122],["AUTO",-122],["REGISTER",-122],["STATIC",-122],["EXTERN",-122],["TYPEDEF",-122],["_THREAD_LOCAL",-122],["INLINE",-122],["_NORETURN",-122],["_ALIGNAS",-122],["__ATTRIBUTE__",-122],["COMMA",-122],["RPAREN",-122],["LBRACKET",-122]]],[113,[["SEMI",-107]]],[114,[["SEMI",-149],["ID",-149],["LPAREN",-149],["TIMES",-149],["TYPEID",-149],["VOID",-149],["_BOOL",-149],["CHAR",-149],["SHORT",-149],["INT",-149],["LONG",-149],["FLOAT",-149],["DOUBLE",-149],["_COMPLEX",-149],["SIGNED",-149],["UNSIGNED",-149],["__INT128",-149],["_ATOMIC",-149],["CONST",-149],["RESTRICT",-149],["VOLATILE",-149],["AUTO",-149],["REGISTER",-149],["STATIC",-149],["EXTERN",-149],["TYPEDEF",-149],["_THREAD_LOCAL",-149],["INLINE",-149],["_NORETURN",-149],["_ALIGNAS",-149],["__ATTRIBUTE__",-149],["COLON",-149],["COMMA",-149],["RPAREN",-149],["LBRACKET",-149]]],[115,[["SEMI",-29]]],[116,[["SEMI",-30],["COMMA",213]]],[118,[["SEMI",-163],["COMMA",-163]]],[119,[["SEMI",-412],["ASM",154],["__ATTRIBUTE__",-412],["EQUALS",-412],["COMMA",-412]]],[120,[["SEMI",-115],["ID",-115],["LPAREN",-115],["TIMES",-115],["TYPEID",-115],["ENUM",-115],["VOID",-115],["_BOOL",-115],["CHAR",-115],["SHORT",-115],["INT",-115],["LONG",-115],["FLOAT",-115],["DOUBLE",-115],["_COMPLEX",-115],["SIGNED",-115],["UNSIGNED",-115],["__INT128",-115],["_ATOMIC",-115],["TYPEOF",-115],["STRUCT",-115],["UNION",-115]]],[121,[["SEMI",-116],["ID",-116],["LPAREN",-116],["TIMES",-116],["TYPEID",-116],["ENUM",-116],["VOID",-116],["_BOOL",-116],["CHAR",-116],["SHORT",-116],["INT",-116],["LONG",-116],["FLOAT",-116],["DOUBLE",-116],["_COMPLEX",-116],["SIGNED",-116],["UNSIGNED",-116],["__INT128",-116],["_ATOMIC",-116],["TYPEOF",-116],["STRUCT",-116],["UNION",-116]]],[126,[["SEMI",-114],["ID",-114],["LPAREN",-114],["TIMES",-114],["TYPEID",-114],["ENUM",-114],["VOID",-114],["_BOOL",-114],["CHAR",-114],["SHORT",-114],["INT",-114],["LONG",-114],["FLOAT",-114],["DOUBLE",-114],["_COMPLEX",-114],["SIGNED",-114],["UNSIGNED",-114],["__INT128",-114],["_ATOMIC",-114],["TYPEOF",-114],["STRUCT",-114],["UNION",-114]]],[127,[["SEMI",-192],["ID",-192],["LPAREN",-192],["TIMES",-192],["TYPEID",-192],["VOID",-192],["_BOOL",-192],["CHAR",-192],["SHORT",-192],["INT",-192],["LONG",-192],["FLOAT",-192],["DOUBLE",-192],["_COMPLEX",-192],["SIGNED",-192],["UNSIGNED",-192],["__INT128",-192],["_ATOMIC",-192],["CONST",-192],["RESTRICT",-192],["VOLATILE",-192],["AUTO",-192],["REGISTER",-192],["STATIC",-192],["EXTERN",-192],["TYPEDEF",-192],["_THREAD_LOCAL",-192],["INLINE",-192],["_NORETURN",-192],["_ALIGNAS",-192],["__ATTRIBUTE__",-192],["LBRACE",-374],["COLON",-192],["COMMA",-192],["RPAREN",-192],["LBRACKET",-192]]],[128,[["SEMI",-193],["ID",-193],["LPAREN",-193],["TIMES",-193],["TYPEID",-193],["VOID",-193],["_BOOL",-193],["CHAR",-193],["SHORT",-193],["INT",-193],["LONG",-193],["FLOAT",-193],["DOUBLE",-193],["_COMPLEX",-193],["SIGNED",-193],["UNSIGNED",-193],["__INT128",-193],["_ATOMIC",-193],["CONST",-193],["RESTRICT",-193],["VOLATILE",-193],["AUTO",-193],["REGISTER",-193],["STATIC",-193],["EXTERN",-193],["TYPEDEF",-193],["_THREAD_LOCAL",-193],["INLINE",-193],["_NORETURN",-193],["_ALIGNAS",-193],["__ATTRIBUTE__",-193],["LBRACE",-375],["COLON",-193],["COMMA",-193],["RPAREN",-193],["LBRACKET",-193]]],[131,[["SEMI",-27],["ID",-27],["LPAREN",-27],["TIMES",-27],["TYPEID",-27],["VOID",-27],["_BOOL",-27],["CHAR",-27],["SHORT",-27],["INT",-27],["LONG",-27],["FLOAT",-27],["DOUBLE",-27],["_COMPLEX",-27],["SIGNED",-27],["UNSIGNED",-27],["__INT128",-27],["_ATOMIC",-27],["CONST",-27],["RESTRICT",-27],["VOLATILE",-27],["AUTO",-27],["REGISTER",-27],["STATIC",-27],["EXTERN",-27],["TYPEDEF",-27],["_THREAD_LOCAL",-27],["INLINE",-27],["_NORETURN",-27],["_ALIGNAS",-27],["__ATTRIBUTE__",-27],["LBRACE",-27],["RBRACE",-27],["EQUALS",-27],["COLON",-27],["COMMA",-27],["RPAREN",-27],["LBRACKET",-27]]],[133,[["SEMI",-401],["ID",-401],["LPAREN",-401],["TIMES",-401],["TYPEID",-401],["VOID",-401],["_BOOL",-401],["CHAR",-401],["SHORT",-401],["INT",-401],["LONG",-401],["FLOAT",-401],["DOUBLE",-401],["_COMPLEX",-401],["SIGNED",-401],["UNSIGNED",-401],["__INT128",-401],["_ATOMIC",-401],["CONST",-401],["RESTRICT",-401],["VOLATILE",-401],["AUTO",-401],["REGISTER",-401],["STATIC",-401],["EXTERN",-401],["TYPEDEF",-401],["_THREAD_LOCAL",-401],["INLINE",-401],["_NORETURN",-401],["_ALIGNAS",-401],["__ATTRIBUTE__",-401],["LBRACE",-401],["RBRACE",-401],["EQUALS",-401],["COLON",-401],["COMMA",-401],["RPAREN",-401],["LBRACKET",-401]]],[134,[["SEMI",-174],["ID",-174],["LPAREN",-174],["TIMES",-174],["TYPEID",-174],["VOID",-174],["_BOOL",-174],["CHAR",-174],["SHORT",-174],["INT",-174],["LONG",-174],["FLOAT",-174],["DOUBLE",-174],["_COMPLEX",-174],["SIGNED",-174],["UNSIGNED",-174],["__INT128",-174],["_ATOMIC",-174],["CONST",-174],["RESTRICT",-174],["VOLATILE",-174],["AUTO",-174],["REGISTER",-174],["STATIC",-174],["EXTERN",-174],["TYPEDEF",-174],["_THREAD_LOCAL",-174],["INLINE",-174],["_NORETURN",-174],["_ALIGNAS",-174],["__ATTRIBUTE__",-174],["LBRACE",-374],["COLON",-174],["COMMA",-174],["RPAREN",-174],["LBRACKET",-174]]],[135,[["SEMI",-175],["ID",-175],["LPAREN",-175],["TIMES",-175],["TYPEID",-175],["VOID",-175],["_BOOL",-175],["CHAR",-175],["SHORT",-175],["INT",-175],["LONG",-175],["FLOAT",-175],["DOUBLE",-175],["_COMPLEX",-175],["SIGNED",-175],["UNSIGNED",-175],["__INT128",-175],["_ATOMIC",-175],["CONST",-175],["RESTRICT",-175],["VOLATILE",-175],["AUTO",-175],["REGISTER",-175],["STATIC",-175],["EXTERN",-175],["TYPEDEF",-175],["_THREAD_LOCAL",-175],["INLINE",-175],["_NORETURN",-175],["_ALIGNAS",-175],["__ATTRIBUTE__",-175],["LBRACE",-375],["COLON",-175],["COMMA",-175],["RPAREN",-175],["LBRACKET",-175]]],[143,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",257],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",78],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACE",-412]]],[144,[["SEMI",-378],["PPPRAGMA",-378],["_PRAGMA",-378],["_STATIC_ASSERT",-378],["ASM",-378],["ID",-378],["LPAREN",-378],["TIMES",-378],["TYPEID",-378],["ENUM",-378],["VOID",-378],["_BOOL",-378],["CHAR",-378],["SHORT",-378],["INT",-378],["LONG",-378],["FLOAT",-378],["DOUBLE",-378],["_COMPLEX",-378],["SIGNED",-378],["UNSIGNED",-378],["__INT128",-378],["_ATOMIC",-378],["TYPEOF",-378],["CONST",-378],["RESTRICT",-378],["VOLATILE",-378],["AUTO",-378],["REGISTER",-378],["STATIC",-378],["EXTERN",-378],["TYPEDEF",-378],["_THREAD_LOCAL",-378],["INLINE",-378],["_NORETURN",-378],["_ALIGNAS",-378],["__ATTRIBUTE__",-378],["STRUCT",-378],["UNION",-378],["LBRACE",-378],["CASE",-378],["DEFAULT",-378],["IF",-378],["SWITCH",-378],["WHILE",-378],["DO",-378],["FOR",-378],["GOTO",-378],["BREAK",-378],["CONTINUE",-378],["RETURN",-378],["PLUSPLUS",-378],["MINUSMINUS",-378],["SIZEOF",-378],["_ALIGNOF",-378],["AND",-378],["PLUS",-378],["MINUS",-378],["NOT",-378],["LNOT",-378],["OFFSETOF",-378],["INT_CONST_DEC",-378],["INT_CONST_OCT",-378],["INT_CONST_HEX",-378],["INT_CONST_BIN",-378],["INT_CONST_CHAR",-378],["FLOAT_CONST",-378],["HEX_FLOAT_CONST",-378],["CHAR_CONST",-378],["WCHAR_CONST",-378],["U8CHAR_CONST",-378],["U16CHAR_CONST",-378],["U32CHAR_CONST",-378],["STRING_LITERAL",-378],["WSTRING_LITERAL",-378],["U8STRING_LITERAL",-378],["U16STRING_LITERAL",-378],["U32STRING_LITERAL",-378],["RBRACE",-378],["LBRACKET",-378],["PERIOD",-378]]],[146,[["SEMI",-203],["ASM",-203],["__ATTRIBUTE__",-203],["EQUALS",-203],["COLON",-203],["COMMA",-203]]],[148,[["SEMI",-69],["ASM",-69],["LPAREN",156],["__ATTRIBUTE__",-69],["EQUALS",-69],["COLON",-69],["COMMA",-69],["RPAREN",-69],["LBRACKET",155]]],[151,[["SEMI",-412],["__ATTRIBUTE__",67],["EQUALS",-412],["COLON",-412],["COMMA",-412]]],[152,[["SEMI",-5],["__ATTRIBUTE__",-5],["EQUALS",-5],["COLON",-5],["COMMA",-5]]],[153,[["SEMI",-6],["__ATTRIBUTE__",-6],["EQUALS",-6],["COLON",-6],["COMMA",-6]]],[158,[["SEMI",-364],["LPAREN",-364],["TIMES",-364],["PLUSPLUS",-364],["MINUSMINUS",-364],["AND",-364],["PLUS",-364],["MINUS",-364],["STRING_LITERAL",-364],["RBRACE",-364],["EQUALS",-364],["COLON",-364],["COMMA",-364],["RPAREN",-364],["LBRACKET",-364],["RBRACKET",-364],["PERIOD",-364],["ARROW",-364],["CONDOP",-364],["DIVIDE",-364],["MOD",-364],["RSHIFT",-364],["LSHIFT",-364],["LT",-364],["LE",-364],["GE",-364],["GT",-364],["EQ",-364],["NE",-364],["OR",-364],["XOR",-364],["LAND",-364],["LOR",-364],["XOREQUAL",-364],["TIMESEQUAL",-364],["DIVEQUAL",-364],["MODEQUAL",-364],["PLUSEQUAL",-364],["MINUSEQUAL",-364],["LSHIFTEQUAL",-364],["RSHIFTEQUAL",-364],["ANDEQUAL",-364],["OREQUAL",-364],["ELLIPSIS",-364]]],[159,[["SEMI",-44],["ASM",-44],["LPAREN",-44],["TYPEID",-44],["ENUM",-44],["VOID",-44],["_BOOL",-44],["CHAR",-44],["SHORT",-44],["INT",-44],["LONG",-44],["FLOAT",-44],["DOUBLE",-44],["_COMPLEX",-44],["SIGNED",-44],["UNSIGNED",-44],["__INT128",-44],["_ATOMIC",-44],["TYPEOF",-44],["CONST",-44],["RESTRICT",-44],["VOLATILE",-44],["AUTO",-44],["REGISTER",-44],["STATIC",-44],["EXTERN",-44],["TYPEDEF",-44],["_THREAD_LOCAL",-44],["INLINE",-44],["_NORETURN",-44],["_ALIGNAS",-44],["__ATTRIBUTE__",-44],["STRUCT",-44],["UNION",-44],["LBRACE",-44],["EQUALS",-44],["COLON",-44],["COMMA",-44],["RPAREN",-44],["LBRACKET",-44]]],[162,[["SEMI",-342],["LPAREN",-342],["TIMES",-342],["PLUSPLUS",-342],["MINUSMINUS",-342],["AND",-342],["PLUS",-342],["MINUS",-342],["STRING_LITERAL",286],["RBRACE",-342],["EQUALS",-342],["COLON",-342],["COMMA",-342],["RPAREN",-342],["LBRACKET",-342],["RBRACKET",-342],["PERIOD",-342],["ARROW",-342],["CONDOP",-342],["DIVIDE",-342],["MOD",-342],["RSHIFT",-342],["LSHIFT",-342],["LT",-342],["LE",-342],["GE",-342],["GT",-342],["EQ",-342],["NE",-342],["OR",-342],["XOR",-342],["LAND",-342],["LOR",-342],["XOREQUAL",-342],["TIMESEQUAL",-342],["DIVEQUAL",-342],["MODEQUAL",-342],["PLUSEQUAL",-342],["MINUSEQUAL",-342],["LSHIFTEQUAL",-342],["RSHIFTEQUAL",-342],["ANDEQUAL",-342],["OREQUAL",-342],["ELLIPSIS",-342]]],[163,[["SEMI",-292],["RBRACE",-292],["COLON",-292],["COMMA",-292],["RPAREN",-292],["RBRACKET",-292],["ELLIPSIS",-292]]],[164,[["SEMI",-293],["TIMES",292],["AND",305],["PLUS",295],["MINUS",296],["RBRACE",-293],["COLON",-293],["COMMA",-293],["RPAREN",-293],["RBRACKET",-293],["CONDOP",291],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",299],["LE",300],["GE",301],["GT",302],["EQ",303],["NE",304],["OR",306],["XOR",307],["LAND",308],["LOR",309],["ELLIPSIS",-293]]],[165,[["SEMI",-295],["TIMES",-295],["AND",-295],["PLUS",-295],["MINUS",-295],["RBRACE",-295],["COLON",-295],["COMMA",-295],["RPAREN",-295],["RBRACKET",-295],["CONDOP",-295],["DIVIDE",-295],["MOD",-295],["RSHIFT",-295],["LSHIFT",-295],["LT",-295],["LE",-295],["GE",-295],["GT",-295],["EQ",-295],["NE",-295],["OR",-295],["XOR",-295],["LAND",-295],["LOR",-295],["ELLIPSIS",-295]]],[170,[["SEMI",-315],["LPAREN",311],["TIMES",-315],["PLUSPLUS",314],["MINUSMINUS",315],["AND",-315],["PLUS",-315],["MINUS",-315],["RBRACE",-315],["EQUALS",-315],["COLON",-315],["COMMA",-315],["RPAREN",-315],["LBRACKET",310],["RBRACKET",-315],["PERIOD",312],["ARROW",313],["CONDOP",-315],["DIVIDE",-315],["MOD",-315],["RSHIFT",-315],["LSHIFT",-315],["LT",-315],["LE",-315],["GE",-315],["GT",-315],["EQ",-315],["NE",-315],["OR",-315],["XOR",-315],["LAND",-315],["LOR",-315],["XOREQUAL",-315],["TIMESEQUAL",-315],["DIVEQUAL",-315],["MODEQUAL",-315],["PLUSEQUAL",-315],["MINUSEQUAL",-315],["LSHIFTEQUAL",-315],["RSHIFTEQUAL",-315],["ANDEQUAL",-315],["OREQUAL",-315],["ELLIPSIS",-315]]],[176,[["SEMI",-328],["LPAREN",-328],["TIMES",-328],["PLUSPLUS",-328],["MINUSMINUS",-328],["AND",-328],["PLUS",-328],["MINUS",-328],["RBRACE",-328],["EQUALS",-328],["COLON",-328],["COMMA",-328],["RPAREN",-328],["LBRACKET",-328],["RBRACKET",-328],["PERIOD",-328],["ARROW",-328],["CONDOP",-328],["DIVIDE",-328],["MOD",-328],["RSHIFT",-328],["LSHIFT",-328],["LT",-328],["LE",-328],["GE",-328],["GT",-328],["EQ",-328],["NE",-328],["OR",-328],["XOR",-328],["LAND",-328],["LOR",-328],["XOREQUAL",-328],["TIMESEQUAL",-328],["DIVEQUAL",-328],["MODEQUAL",-328],["PLUSEQUAL",-328],["MINUSEQUAL",-328],["LSHIFTEQUAL",-328],["RSHIFTEQUAL",-328],["ANDEQUAL",-328],["OREQUAL",-328],["ELLIPSIS",-328]]],[177,[["SEMI",-351],["LPAREN",-351],["TIMES",-351],["PLUSPLUS",-351],["MINUSMINUS",-351],["AND",-351],["PLUS",-351],["MINUS",-351],["RBRACE",-351],["EQUALS",-351],["COLON",-351],["COMMA",-351],["RPAREN",-351],["LBRACKET",-351],["RBRACKET",-351],["PERIOD",-351],["ARROW",-351],["CONDOP",-351],["DIVIDE",-351],["MOD",-351],["RSHIFT",-351],["LSHIFT",-351],["LT",-351],["LE",-351],["GE",-351],["GT",-351],["EQ",-351],["NE",-351],["OR",-351],["XOR",-351],["LAND",-351],["LOR",-351],["XOREQUAL",-351],["TIMESEQUAL",-351],["DIVEQUAL",-351],["MODEQUAL",-351],["PLUSEQUAL",-351],["MINUSEQUAL",-351],["LSHIFTEQUAL",-351],["RSHIFTEQUAL",-351],["ANDEQUAL",-351],["OREQUAL",-351],["ELLIPSIS",-351]]],[180,[["SEMI",-340],["LPAREN",-340],["TIMES",-340],["PLUSPLUS",-340],["MINUSMINUS",-340],["AND",-340],["PLUS",-340],["MINUS",-340],["RBRACE",-340],["EQUALS",-340],["COLON",-340],["COMMA",-340],["RPAREN",-340],["LBRACKET",-340],["RBRACKET",-340],["PERIOD",-340],["ARROW",-340],["CONDOP",-340],["DIVIDE",-340],["MOD",-340],["RSHIFT",-340],["LSHIFT",-340],["LT",-340],["LE",-340],["GE",-340],["GT",-340],["EQ",-340],["NE",-340],["OR",-340],["XOR",-340],["LAND",-340],["LOR",-340],["XOREQUAL",-340],["TIMESEQUAL",-340],["DIVEQUAL",-340],["MODEQUAL",-340],["PLUSEQUAL",-340],["MINUSEQUAL",-340],["LSHIFTEQUAL",-340],["RSHIFTEQUAL",-340],["ANDEQUAL",-340],["OREQUAL",-340],["ELLIPSIS",-340]]],[181,[["SEMI",-341],["LPAREN",-341],["TIMES",-341],["PLUSPLUS",-341],["MINUSMINUS",-341],["AND",-341],["PLUS",-341],["MINUS",-341],["RBRACE",-341],["EQUALS",-341],["COLON",-341],["COMMA",-341],["RPAREN",-341],["LBRACKET",-341],["RBRACKET",-341],["PERIOD",-341],["ARROW",-341],["CONDOP",-341],["DIVIDE",-341],["MOD",-341],["RSHIFT",-341],["LSHIFT",-341],["LT",-341],["LE",-341],["GE",-341],["GT",-341],["EQ",-341],["NE",-341],["OR",-341],["XOR",-341],["LAND",-341],["LOR",-341],["XOREQUAL",-341],["TIMESEQUAL",-341],["DIVEQUAL",-341],["MODEQUAL",-341],["PLUSEQUAL",-341],["MINUSEQUAL",-341],["LSHIFTEQUAL",-341],["RSHIFTEQUAL",-341],["ANDEQUAL",-341],["OREQUAL",-341],["ELLIPSIS",-341]]],[182,[["SEMI",-343],["LPAREN",-343],["TIMES",-343],["PLUSPLUS",-343],["MINUSMINUS",-343],["AND",-343],["PLUS",-343],["MINUS",-343],["WSTRING_LITERAL",322],["U8STRING_LITERAL",323],["U16STRING_LITERAL",324],["U32STRING_LITERAL",325],["RBRACE",-343],["EQUALS",-343],["COLON",-343],["COMMA",-343],["RPAREN",-343],["LBRACKET",-343],["RBRACKET",-343],["PERIOD",-343],["ARROW",-343],["CONDOP",-343],["DIVIDE",-343],["MOD",-343],["RSHIFT",-343],["LSHIFT",-343],["LT",-343],["LE",-343],["GE",-343],["GT",-343],["EQ",-343],["NE",-343],["OR",-343],["XOR",-343],["LAND",-343],["LOR",-343],["XOREQUAL",-343],["TIMESEQUAL",-343],["DIVEQUAL",-343],["MODEQUAL",-343],["PLUSEQUAL",-343],["MINUSEQUAL",-343],["LSHIFTEQUAL",-343],["RSHIFTEQUAL",-343],["ANDEQUAL",-343],["OREQUAL",-343],["ELLIPSIS",-343]]],[184,[["SEMI",-352],["LPAREN",-352],["TIMES",-352],["PLUSPLUS",-352],["MINUSMINUS",-352],["AND",-352],["PLUS",-352],["MINUS",-352],["RBRACE",-352],["EQUALS",-352],["COLON",-352],["COMMA",-352],["RPAREN",-352],["LBRACKET",-352],["RBRACKET",-352],["PERIOD",-352],["ARROW",-352],["CONDOP",-352],["DIVIDE",-352],["MOD",-352],["RSHIFT",-352],["LSHIFT",-352],["LT",-352],["LE",-352],["GE",-352],["GT",-352],["EQ",-352],["NE",-352],["OR",-352],["XOR",-352],["LAND",-352],["LOR",-352],["XOREQUAL",-352],["TIMESEQUAL",-352],["DIVEQUAL",-352],["MODEQUAL",-352],["PLUSEQUAL",-352],["MINUSEQUAL",-352],["LSHIFTEQUAL",-352],["RSHIFTEQUAL",-352],["ANDEQUAL",-352],["OREQUAL",-352],["ELLIPSIS",-352]]],[185,[["SEMI",-353],["LPAREN",-353],["TIMES",-353],["PLUSPLUS",-353],["MINUSMINUS",-353],["AND",-353],["PLUS",-353],["MINUS",-353],["RBRACE",-353],["EQUALS",-353],["COLON",-353],["COMMA",-353],["RPAREN",-353],["LBRACKET",-353],["RBRACKET",-353],["PERIOD",-353],["ARROW",-353],["CONDOP",-353],["DIVIDE",-353],["MOD",-353],["RSHIFT",-353],["LSHIFT",-353],["LT",-353],["LE",-353],["GE",-353],["GT",-353],["EQ",-353],["NE",-353],["OR",-353],["XOR",-353],["LAND",-353],["LOR",-353],["XOREQUAL",-353],["TIMESEQUAL",-353],["DIVEQUAL",-353],["MODEQUAL",-353],["PLUSEQUAL",-353],["MINUSEQUAL",-353],["LSHIFTEQUAL",-353],["RSHIFTEQUAL",-353],["ANDEQUAL",-353],["OREQUAL",-353],["ELLIPSIS",-353]]],[186,[["SEMI",-354],["LPAREN",-354],["TIMES",-354],["PLUSPLUS",-354],["MINUSMINUS",-354],["AND",-354],["PLUS",-354],["MINUS",-354],["RBRACE",-354],["EQUALS",-354],["COLON",-354],["COMMA",-354],["RPAREN",-354],["LBRACKET",-354],["RBRACKET",-354],["PERIOD",-354],["ARROW",-354],["CONDOP",-354],["DIVIDE",-354],["MOD",-354],["RSHIFT",-354],["LSHIFT",-354],["LT",-354],["LE",-354],["GE",-354],["GT",-354],["EQ",-354],["NE",-354],["OR",-354],["XOR",-354],["LAND",-354],["LOR",-354],["XOREQUAL",-354],["TIMESEQUAL",-354],["DIVEQUAL",-354],["MODEQUAL",-354],["PLUSEQUAL",-354],["MINUSEQUAL",-354],["LSHIFTEQUAL",-354],["RSHIFTEQUAL",-354],["ANDEQUAL",-354],["OREQUAL",-354],["ELLIPSIS",-354]]],[187,[["SEMI",-355],["LPAREN",-355],["TIMES",-355],["PLUSPLUS",-355],["MINUSMINUS",-355],["AND",-355],["PLUS",-355],["MINUS",-355],["RBRACE",-355],["EQUALS",-355],["COLON",-355],["COMMA",-355],["RPAREN",-355],["LBRACKET",-355],["RBRACKET",-355],["PERIOD",-355],["ARROW",-355],["CONDOP",-355],["DIVIDE",-355],["MOD",-355],["RSHIFT",-355],["LSHIFT",-355],["LT",-355],["LE",-355],["GE",-355],["GT",-355],["EQ",-355],["NE",-355],["OR",-355],["XOR",-355],["LAND",-355],["LOR",-355],["XOREQUAL",-355],["TIMESEQUAL",-355],["DIVEQUAL",-355],["MODEQUAL",-355],["PLUSEQUAL",-355],["MINUSEQUAL",-355],["LSHIFTEQUAL",-355],["RSHIFTEQUAL",-355],["ANDEQUAL",-355],["OREQUAL",-355],["ELLIPSIS",-355]]],[188,[["SEMI",-356],["LPAREN",-356],["TIMES",-356],["PLUSPLUS",-356],["MINUSMINUS",-356],["AND",-356],["PLUS",-356],["MINUS",-356],["RBRACE",-356],["EQUALS",-356],["COLON",-356],["COMMA",-356],["RPAREN",-356],["LBRACKET",-356],["RBRACKET",-356],["PERIOD",-356],["ARROW",-356],["CONDOP",-356],["DIVIDE",-356],["MOD",-356],["RSHIFT",-356],["LSHIFT",-356],["LT",-356],["LE",-356],["GE",-356],["GT",-356],["EQ",-356],["NE",-356],["OR",-356],["XOR",-356],["LAND",-356],["LOR",-356],["XOREQUAL",-356],["TIMESEQUAL",-356],["DIVEQUAL",-356],["MODEQUAL",-356],["PLUSEQUAL",-356],["MINUSEQUAL",-356],["LSHIFTEQUAL",-356],["RSHIFTEQUAL",-356],["ANDEQUAL",-356],["OREQUAL",-356],["ELLIPSIS",-356]]],[189,[["SEMI",-357],["LPAREN",-357],["TIMES",-357],["PLUSPLUS",-357],["MINUSMINUS",-357],["AND",-357],["PLUS",-357],["MINUS",-357],["RBRACE",-357],["EQUALS",-357],["COLON",-357],["COMMA",-357],["RPAREN",-357],["LBRACKET",-357],["RBRACKET",-357],["PERIOD",-357],["ARROW",-357],["CONDOP",-357],["DIVIDE",-357],["MOD",-357],["RSHIFT",-357],["LSHIFT",-357],["LT",-357],["LE",-357],["GE",-357],["GT",-357],["EQ",-357],["NE",-357],["OR",-357],["XOR",-357],["LAND",-357],["LOR",-357],["XOREQUAL",-357],["TIMESEQUAL",-357],["DIVEQUAL",-357],["MODEQUAL",-357],["PLUSEQUAL",-357],["MINUSEQUAL",-357],["LSHIFTEQUAL",-357],["RSHIFTEQUAL",-357],["ANDEQUAL",-357],["OREQUAL",-357],["ELLIPSIS",-357]]],[190,[["SEMI",-358],["LPAREN",-358],["TIMES",-358],["PLUSPLUS",-358],["MINUSMINUS",-358],["AND",-358],["PLUS",-358],["MINUS",-358],["RBRACE",-358],["EQUALS",-358],["COLON",-358],["COMMA",-358],["RPAREN",-358],["LBRACKET",-358],["RBRACKET",-358],["PERIOD",-358],["ARROW",-358],["CONDOP",-358],["DIVIDE",-358],["MOD",-358],["RSHIFT",-358],["LSHIFT",-358],["LT",-358],["LE",-358],["GE",-358],["GT",-358],["EQ",-358],["NE",-358],["OR",-358],["XOR",-358],["LAND",-358],["LOR",-358],["XOREQUAL",-358],["TIMESEQUAL",-358],["DIVEQUAL",-358],["MODEQUAL",-358],["PLUSEQUAL",-358],["MINUSEQUAL",-358],["LSHIFTEQUAL",-358],["RSHIFTEQUAL",-358],["ANDEQUAL",-358],["OREQUAL",-358],["ELLIPSIS",-358]]],[191,[["SEMI",-359],["LPAREN",-359],["TIMES",-359],["PLUSPLUS",-359],["MINUSMINUS",-359],["AND",-359],["PLUS",-359],["MINUS",-359],["RBRACE",-359],["EQUALS",-359],["COLON",-359],["COMMA",-359],["RPAREN",-359],["LBRACKET",-359],["RBRACKET",-359],["PERIOD",-359],["ARROW",-359],["CONDOP",-359],["DIVIDE",-359],["MOD",-359],["RSHIFT",-359],["LSHIFT",-359],["LT",-359],["LE",-359],["GE",-359],["GT",-359],["EQ",-359],["NE",-359],["OR",-359],["XOR",-359],["LAND",-359],["LOR",-359],["XOREQUAL",-359],["TIMESEQUAL",-359],["DIVEQUAL",-359],["MODEQUAL",-359],["PLUSEQUAL",-359],["MINUSEQUAL",-359],["LSHIFTEQUAL",-359],["RSHIFTEQUAL",-359],["ANDEQUAL",-359],["OREQUAL",-359],["ELLIPSIS",-359]]],[192,[["SEMI",-360],["LPAREN",-360],["TIMES",-360],["PLUSPLUS",-360],["MINUSMINUS",-360],["AND",-360],["PLUS",-360],["MINUS",-360],["RBRACE",-360],["EQUALS",-360],["COLON",-360],["COMMA",-360],["RPAREN",-360],["LBRACKET",-360],["RBRACKET",-360],["PERIOD",-360],["ARROW",-360],["CONDOP",-360],["DIVIDE",-360],["MOD",-360],["RSHIFT",-360],["LSHIFT",-360],["LT",-360],["LE",-360],["GE",-360],["GT",-360],["EQ",-360],["NE",-360],["OR",-360],["XOR",-360],["LAND",-360],["LOR",-360],["XOREQUAL",-360],["TIMESEQUAL",-360],["DIVEQUAL",-360],["MODEQUAL",-360],["PLUSEQUAL",-360],["MINUSEQUAL",-360],["LSHIFTEQUAL",-360],["RSHIFTEQUAL",-360],["ANDEQUAL",-360],["OREQUAL",-360],["ELLIPSIS",-360]]],[193,[["SEMI",-361],["LPAREN",-361],["TIMES",-361],["PLUSPLUS",-361],["MINUSMINUS",-361],["AND",-361],["PLUS",-361],["MINUS",-361],["RBRACE",-361],["EQUALS",-361],["COLON",-361],["COMMA",-361],["RPAREN",-361],["LBRACKET",-361],["RBRACKET",-361],["PERIOD",-361],["ARROW",-361],["CONDOP",-361],["DIVIDE",-361],["MOD",-361],["RSHIFT",-361],["LSHIFT",-361],["LT",-361],["LE",-361],["GE",-361],["GT",-361],["EQ",-361],["NE",-361],["OR",-361],["XOR",-361],["LAND",-361],["LOR",-361],["XOREQUAL",-361],["TIMESEQUAL",-361],["DIVEQUAL",-361],["MODEQUAL",-361],["PLUSEQUAL",-361],["MINUSEQUAL",-361],["LSHIFTEQUAL",-361],["RSHIFTEQUAL",-361],["ANDEQUAL",-361],["OREQUAL",-361],["ELLIPSIS",-361]]],[194,[["SEMI",-362],["LPAREN",-362],["TIMES",-362],["PLUSPLUS",-362],["MINUSMINUS",-362],["AND",-362],["PLUS",-362],["MINUS",-362],["RBRACE",-362],["EQUALS",-362],["COLON",-362],["COMMA",-362],["RPAREN",-362],["LBRACKET",-362],["RBRACKET",-362],["PERIOD",-362],["ARROW",-362],["CONDOP",-362],["DIVIDE",-362],["MOD",-362],["RSHIFT",-362],["LSHIFT",-362],["LT",-362],["LE",-362],["GE",-362],["GT",-362],["EQ",-362],["NE",-362],["OR",-362],["XOR",-362],["LAND",-362],["LOR",-362],["XOREQUAL",-362],["TIMESEQUAL",-362],["DIVEQUAL",-362],["MODEQUAL",-362],["PLUSEQUAL",-362],["MINUSEQUAL",-362],["LSHIFTEQUAL",-362],["RSHIFTEQUAL",-362],["ANDEQUAL",-362],["OREQUAL",-362],["ELLIPSIS",-362]]],[195,[["SEMI",-363],["LPAREN",-363],["TIMES",-363],["PLUSPLUS",-363],["MINUSMINUS",-363],["AND",-363],["PLUS",-363],["MINUS",-363],["RBRACE",-363],["EQUALS",-363],["COLON",-363],["COMMA",-363],["RPAREN",-363],["LBRACKET",-363],["RBRACKET",-363],["PERIOD",-363],["ARROW",-363],["CONDOP",-363],["DIVIDE",-363],["MOD",-363],["RSHIFT",-363],["LSHIFT",-363],["LT",-363],["LE",-363],["GE",-363],["GT",-363],["EQ",-363],["NE",-363],["OR",-363],["XOR",-363],["LAND",-363],["LOR",-363],["XOREQUAL",-363],["TIMESEQUAL",-363],["DIVEQUAL",-363],["MODEQUAL",-363],["PLUSEQUAL",-363],["MINUSEQUAL",-363],["LSHIFTEQUAL",-363],["RSHIFTEQUAL",-363],["ANDEQUAL",-363],["OREQUAL",-363],["ELLIPSIS",-363]]],[196,[["SEMI",-366],["LPAREN",-366],["TIMES",-366],["PLUSPLUS",-366],["MINUSMINUS",-366],["AND",-366],["PLUS",-366],["MINUS",-366],["WSTRING_LITERAL",-366],["U8STRING_LITERAL",-366],["U16STRING_LITERAL",-366],["U32STRING_LITERAL",-366],["RBRACE",-366],["EQUALS",-366],["COLON",-366],["COMMA",-366],["RPAREN",-366],["LBRACKET",-366],["RBRACKET",-366],["PERIOD",-366],["ARROW",-366],["CONDOP",-366],["DIVIDE",-366],["MOD",-366],["RSHIFT",-366],["LSHIFT",-366],["LT",-366],["LE",-366],["GE",-366],["GT",-366],["EQ",-366],["NE",-366],["OR",-366],["XOR",-366],["LAND",-366],["LOR",-366],["XOREQUAL",-366],["TIMESEQUAL",-366],["DIVEQUAL",-366],["MODEQUAL",-366],["PLUSEQUAL",-366],["MINUSEQUAL",-366],["LSHIFTEQUAL",-366],["RSHIFTEQUAL",-366],["ANDEQUAL",-366],["OREQUAL",-366],["ELLIPSIS",-366]]],[197,[["SEMI",-367],["LPAREN",-367],["TIMES",-367],["PLUSPLUS",-367],["MINUSMINUS",-367],["AND",-367],["PLUS",-367],["MINUS",-367],["WSTRING_LITERAL",-367],["U8STRING_LITERAL",-367],["U16STRING_LITERAL",-367],["U32STRING_LITERAL",-367],["RBRACE",-367],["EQUALS",-367],["COLON",-367],["COMMA",-367],["RPAREN",-367],["LBRACKET",-367],["RBRACKET",-367],["PERIOD",-367],["ARROW",-367],["CONDOP",-367],["DIVIDE",-367],["MOD",-367],["RSHIFT",-367],["LSHIFT",-367],["LT",-367],["LE",-367],["GE",-367],["GT",-367],["EQ",-367],["NE",-367],["OR",-367],["XOR",-367],["LAND",-367],["LOR",-367],["XOREQUAL",-367],["TIMESEQUAL",-367],["DIVEQUAL",-367],["MODEQUAL",-367],["PLUSEQUAL",-367],["MINUSEQUAL",-367],["LSHIFTEQUAL",-367],["RSHIFTEQUAL",-367],["ANDEQUAL",-367],["OREQUAL",-367],["ELLIPSIS",-367]]],[198,[["SEMI",-368],["LPAREN",-368],["TIMES",-368],["PLUSPLUS",-368],["MINUSMINUS",-368],["AND",-368],["PLUS",-368],["MINUS",-368],["WSTRING_LITERAL",-368],["U8STRING_LITERAL",-368],["U16STRING_LITERAL",-368],["U32STRING_LITERAL",-368],["RBRACE",-368],["EQUALS",-368],["COLON",-368],["COMMA",-368],["RPAREN",-368],["LBRACKET",-368],["RBRACKET",-368],["PERIOD",-368],["ARROW",-368],["CONDOP",-368],["DIVIDE",-368],["MOD",-368],["RSHIFT",-368],["LSHIFT",-368],["LT",-368],["LE",-368],["GE",-368],["GT",-368],["EQ",-368],["NE",-368],["OR",-368],["XOR",-368],["LAND",-368],["LOR",-368],["XOREQUAL",-368],["TIMESEQUAL",-368],["DIVEQUAL",-368],["MODEQUAL",-368],["PLUSEQUAL",-368],["MINUSEQUAL",-368],["LSHIFTEQUAL",-368],["RSHIFTEQUAL",-368],["ANDEQUAL",-368],["OREQUAL",-368],["ELLIPSIS",-368]]],[199,[["SEMI",-369],["LPAREN",-369],["TIMES",-369],["PLUSPLUS",-369],["MINUSMINUS",-369],["AND",-369],["PLUS",-369],["MINUS",-369],["WSTRING_LITERAL",-369],["U8STRING_LITERAL",-369],["U16STRING_LITERAL",-369],["U32STRING_LITERAL",-369],["RBRACE",-369],["EQUALS",-369],["COLON",-369],["COMMA",-369],["RPAREN",-369],["LBRACKET",-369],["RBRACKET",-369],["PERIOD",-369],["ARROW",-369],["CONDOP",-369],["DIVIDE",-369],["MOD",-369],["RSHIFT",-369],["LSHIFT",-369],["LT",-369],["LE",-369],["GE",-369],["GT",-369],["EQ",-369],["NE",-369],["OR",-369],["XOR",-369],["LAND",-369],["LOR",-369],["XOREQUAL",-369],["TIMESEQUAL",-369],["DIVEQUAL",-369],["MODEQUAL",-369],["PLUSEQUAL",-369],["MINUSEQUAL",-369],["LSHIFTEQUAL",-369],["RSHIFTEQUAL",-369],["ANDEQUAL",-369],["OREQUAL",-369],["ELLIPSIS",-369]]],[214,[["SEMI",-412],["__ATTRIBUTE__",67],["EQUALS",-412],["COMMA",-412]]],[221,[["SEMI",-402],["ID",-402],["LPAREN",-402],["TIMES",-402],["TYPEID",-402],["VOID",-402],["_BOOL",-402],["CHAR",-402],["SHORT",-402],["INT",-402],["LONG",-402],["FLOAT",-402],["DOUBLE",-402],["_COMPLEX",-402],["SIGNED",-402],["UNSIGNED",-402],["__INT128",-402],["_ATOMIC",-402],["CONST",-402],["RESTRICT",-402],["VOLATILE",-402],["AUTO",-402],["REGISTER",-402],["STATIC",-402],["EXTERN",-402],["TYPEDEF",-402],["_THREAD_LOCAL",-402],["INLINE",-402],["_NORETURN",-402],["_ALIGNAS",-402],["__ATTRIBUTE__",-402],["LBRACE",-402],["RBRACE",-402],["EQUALS",-402],["COLON",-402],["COMMA",-402],["RPAREN",-402],["LBRACKET",-402]]],[222,[["SEMI",360],["PPPRAGMA",16],["_PRAGMA",17],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RBRACE",358]]],[223,[["SEMI",360],["PPPRAGMA",16],["_PRAGMA",17],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RBRACE",358]]],[227,[["SEMI",-169],["ID",-169],["LPAREN",-169],["TIMES",-169],["TYPEID",-169],["VOID",-169],["_BOOL",-169],["CHAR",-169],["SHORT",-169],["INT",-169],["LONG",-169],["FLOAT",-169],["DOUBLE",-169],["_COMPLEX",-169],["SIGNED",-169],["UNSIGNED",-169],["__INT128",-169],["_ATOMIC",-169],["CONST",-169],["RESTRICT",-169],["VOLATILE",-169],["_ALIGNAS",-169],["__ATTRIBUTE__",-169],["COLON",-169],["COMMA",-169],["RPAREN",-169],["LBRACKET",-169]]],[229,[["SEMI",-171],["ID",-171],["LPAREN",-171],["TIMES",-171],["TYPEID",-171],["VOID",-171],["_BOOL",-171],["CHAR",-171],["SHORT",-171],["INT",-171],["LONG",-171],["FLOAT",-171],["DOUBLE",-171],["_COMPLEX",-171],["SIGNED",-171],["UNSIGNED",-171],["__INT128",-171],["_ATOMIC",-171],["CONST",-171],["RESTRICT",-171],["VOLATILE",-171],["_ALIGNAS",-171],["__ATTRIBUTE__",-171],["COLON",-171],["COMMA",-171],["RPAREN",-171],["LBRACKET",-171]]],[234,[["SEMI",-275],["COLON",-275],["COMMA",-275],["RPAREN",-275],["RBRACKET",-275]]],[235,[["SEMI",-279],["RBRACE",-279],["COLON",-279],["COMMA",-279],["RPAREN",-279],["RBRACKET",-279]]],[236,[["SEMI",-295],["TIMES",-295],["AND",-295],["PLUS",-295],["MINUS",-295],["RBRACE",-295],["EQUALS",380],["COLON",-295],["COMMA",-295],["RPAREN",-295],["RBRACKET",-295],["CONDOP",-295],["DIVIDE",-295],["MOD",-295],["RSHIFT",-295],["LSHIFT",-295],["LT",-295],["LE",-295],["GE",-295],["GT",-295],["EQ",-295],["NE",-295],["OR",-295],["XOR",-295],["LAND",-295],["LOR",-295],["XOREQUAL",381],["TIMESEQUAL",382],["DIVEQUAL",383],["MODEQUAL",384],["PLUSEQUAL",385],["MINUSEQUAL",386],["LSHIFTEQUAL",387],["RSHIFTEQUAL",388],["ANDEQUAL",389],["OREQUAL",390]]],[241,[["SEMI",-25],["RBRACE",-17]]],[242,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",257],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",78],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACE",-18]]],[243,[["SEMI",-248],["PPPRAGMA",-248],["_PRAGMA",-248],["_STATIC_ASSERT",-248],["ASM",-248],["ID",-248],["LPAREN",-248],["TIMES",-248],["TYPEID",-248],["ENUM",-248],["VOID",-248],["_BOOL",-248],["CHAR",-248],["SHORT",-248],["INT",-248],["LONG",-248],["FLOAT",-248],["DOUBLE",-248],["_COMPLEX",-248],["SIGNED",-248],["UNSIGNED",-248],["__INT128",-248],["_ATOMIC",-248],["TYPEOF",-248],["CONST",-248],["RESTRICT",-248],["VOLATILE",-248],["AUTO",-248],["REGISTER",-248],["STATIC",-248],["EXTERN",-248],["TYPEDEF",-248],["_THREAD_LOCAL",-248],["INLINE",-248],["_NORETURN",-248],["_ALIGNAS",-248],["__ATTRIBUTE__",-248],["STRUCT",-248],["UNION",-248],["LBRACE",-248],["CASE",-248],["DEFAULT",-248],["IF",-248],["SWITCH",-248],["WHILE",-248],["DO",-248],["FOR",-248],["GOTO",-248],["BREAK",-248],["CONTINUE",-248],["RETURN",-248],["PLUSPLUS",-248],["MINUSMINUS",-248],["SIZEOF",-248],["_ALIGNOF",-248],["AND",-248],["PLUS",-248],["MINUS",-248],["NOT",-248],["LNOT",-248],["OFFSETOF",-248],["INT_CONST_DEC",-248],["INT_CONST_OCT",-248],["INT_CONST_HEX",-248],["INT_CONST_BIN",-248],["INT_CONST_CHAR",-248],["FLOAT_CONST",-248],["HEX_FLOAT_CONST",-248],["CHAR_CONST",-248],["WCHAR_CONST",-248],["U8CHAR_CONST",-248],["U16CHAR_CONST",-248],["U32CHAR_CONST",-248],["STRING_LITERAL",-248],["WSTRING_LITERAL",-248],["U8STRING_LITERAL",-248],["U16STRING_LITERAL",-248],["U32STRING_LITERAL",-248],["RBRACE",-248]]],[244,[["SEMI",-246],["PPPRAGMA",-246],["_PRAGMA",-246],["_STATIC_ASSERT",-246],["ASM",-246],["ID",-246],["LPAREN",-246],["TIMES",-246],["TYPEID",-246],["ENUM",-246],["VOID",-246],["_BOOL",-246],["CHAR",-246],["SHORT",-246],["INT",-246],["LONG",-246],["FLOAT",-246],["DOUBLE",-246],["_COMPLEX",-246],["SIGNED",-246],["UNSIGNED",-246],["__INT128",-246],["_ATOMIC",-246],["TYPEOF",-246],["CONST",-246],["RESTRICT",-246],["VOLATILE",-246],["AUTO",-246],["REGISTER",-246],["STATIC",-246],["EXTERN",-246],["TYPEDEF",-246],["_THREAD_LOCAL",-246],["INLINE",-246],["_NORETURN",-246],["_ALIGNAS",-246],["__ATTRIBUTE__",-246],["STRUCT",-246],["UNION",-246],["LBRACE",-246],["CASE",-246],["DEFAULT",-246],["IF",-246],["SWITCH",-246],["WHILE",-246],["DO",-246],["FOR",-246],["GOTO",-246],["BREAK",-246],["CONTINUE",-246],["RETURN",-246],["PLUSPLUS",-246],["MINUSMINUS",-246],["SIZEOF",-246],["_ALIGNOF",-246],["AND",-246],["PLUS",-246],["MINUS",-246],["NOT",-246],["LNOT",-246],["OFFSETOF",-246],["INT_CONST_DEC",-246],["INT_CONST_OCT",-246],["INT_CONST_HEX",-246],["INT_CONST_BIN",-246],["INT_CONST_CHAR",-246],["FLOAT_CONST",-246],["HEX_FLOAT_CONST",-246],["CHAR_CONST",-246],["WCHAR_CONST",-246],["U8CHAR_CONST",-246],["U16CHAR_CONST",-246],["U32CHAR_CONST",-246],["STRING_LITERAL",-246],["WSTRING_LITERAL",-246],["U8STRING_LITERAL",-246],["U16STRING_LITERAL",-246],["U32STRING_LITERAL",-246],["RBRACE",-246]]],[245,[["SEMI",-247],["PPPRAGMA",-247],["_PRAGMA",-247],["_STATIC_ASSERT",-247],["ASM",-247],["ID",-247],["LPAREN",-247],["TIMES",-247],["TYPEID",-247],["ENUM",-247],["VOID",-247],["_BOOL",-247],["CHAR",-247],["SHORT",-247],["INT",-247],["LONG",-247],["FLOAT",-247],["DOUBLE",-247],["_COMPLEX",-247],["SIGNED",-247],["UNSIGNED",-247],["__INT128",-247],["_ATOMIC",-247],["TYPEOF",-247],["CONST",-247],["RESTRICT",-247],["VOLATILE",-247],["AUTO",-247],["REGISTER",-247],["STATIC",-247],["EXTERN",-247],["TYPEDEF",-247],["_THREAD_LOCAL",-247],["INLINE",-247],["_NORETURN",-247],["_ALIGNAS",-247],["__ATTRIBUTE__",-247],["STRUCT",-247],["UNION",-247],["LBRACE",-247],["CASE",-247],["DEFAULT",-247],["IF",-247],["SWITCH",-247],["WHILE",-247],["DO",-247],["FOR",-247],["GOTO",-247],["BREAK",-247],["CONTINUE",-247],["RETURN",-247],["PLUSPLUS",-247],["MINUSMINUS",-247],["SIZEOF",-247],["_ALIGNOF",-247],["AND",-247],["PLUS",-247],["MINUS",-247],["NOT",-247],["LNOT",-247],["OFFSETOF",-247],["INT_CONST_DEC",-247],["INT_CONST_OCT",-247],["INT_CONST_HEX",-247],["INT_CONST_BIN",-247],["INT_CONST_CHAR",-247],["FLOAT_CONST",-247],["HEX_FLOAT_CONST",-247],["CHAR_CONST",-247],["WCHAR_CONST",-247],["U8CHAR_CONST",-247],["U16CHAR_CONST",-247],["U32CHAR_CONST",-247],["STRING_LITERAL",-247],["WSTRING_LITERAL",-247],["U8STRING_LITERAL",-247],["U16STRING_LITERAL",-247],["U32STRING_LITERAL",-247],["RBRACE",-247]]],[246,[["SEMI",-94],["PPPRAGMA",-94],["_PRAGMA",-94],["_STATIC_ASSERT",-94],["ASM",-94],["ID",-94],["LPAREN",-94],["TIMES",-94],["TYPEID",-94],["ENUM",-94],["VOID",-94],["_BOOL",-94],["CHAR",-94],["SHORT",-94],["INT",-94],["LONG",-94],["FLOAT",-94],["DOUBLE",-94],["_COMPLEX",-94],["SIGNED",-94],["UNSIGNED",-94],["__INT128",-94],["_ATOMIC",-94],["TYPEOF",-94],["CONST",-94],["RESTRICT",-94],["VOLATILE",-94],["AUTO",-94],["REGISTER",-94],["STATIC",-94],["EXTERN",-94],["TYPEDEF",-94],["_THREAD_LOCAL",-94],["INLINE",-94],["_NORETURN",-94],["_ALIGNAS",-94],["__ATTRIBUTE__",-94],["STRUCT",-94],["UNION",-94],["LBRACE",-94],["CASE",-94],["DEFAULT",-94],["IF",-94],["SWITCH",-94],["WHILE",-94],["DO",-94],["FOR",-94],["GOTO",-94],["BREAK",-94],["CONTINUE",-94],["RETURN",-94],["PLUSPLUS",-94],["MINUSMINUS",-94],["SIZEOF",-94],["_ALIGNOF",-94],["AND",-94],["PLUS",-94],["MINUS",-94],["NOT",-94],["LNOT",-94],["OFFSETOF",-94],["INT_CONST_DEC",-94],["INT_CONST_OCT",-94],["INT_CONST_HEX",-94],["INT_CONST_BIN",-94],["INT_CONST_CHAR",-94],["FLOAT_CONST",-94],["HEX_FLOAT_CONST",-94],["CHAR_CONST",-94],["WCHAR_CONST",-94],["U8CHAR_CONST",-94],["U16CHAR_CONST",-94],["U32CHAR_CONST",-94],["STRING_LITERAL",-94],["WSTRING_LITERAL",-94],["U8STRING_LITERAL",-94],["U16STRING_LITERAL",-94],["U32STRING_LITERAL",-94],["RBRACE",-94],["ELSE",-94]]],[247,[["SEMI",-95],["PPPRAGMA",-95],["_PRAGMA",-95],["_STATIC_ASSERT",-95],["ASM",-95],["ID",-95],["LPAREN",-95],["TIMES",-95],["TYPEID",-95],["ENUM",-95],["VOID",-95],["_BOOL",-95],["CHAR",-95],["SHORT",-95],["INT",-95],["LONG",-95],["FLOAT",-95],["DOUBLE",-95],["_COMPLEX",-95],["SIGNED",-95],["UNSIGNED",-95],["__INT128",-95],["_ATOMIC",-95],["TYPEOF",-95],["CONST",-95],["RESTRICT",-95],["VOLATILE",-95],["AUTO",-95],["REGISTER",-95],["STATIC",-95],["EXTERN",-95],["TYPEDEF",-95],["_THREAD_LOCAL",-95],["INLINE",-95],["_NORETURN",-95],["_ALIGNAS",-95],["__ATTRIBUTE__",-95],["STRUCT",-95],["UNION",-95],["LBRACE",-95],["CASE",-95],["DEFAULT",-95],["IF",-95],["SWITCH",-95],["WHILE",-95],["DO",-95],["FOR",-95],["GOTO",-95],["BREAK",-95],["CONTINUE",-95],["RETURN",-95],["PLUSPLUS",-95],["MINUSMINUS",-95],["SIZEOF",-95],["_ALIGNOF",-95],["AND",-95],["PLUS",-95],["MINUS",-95],["NOT",-95],["LNOT",-95],["OFFSETOF",-95],["INT_CONST_DEC",-95],["INT_CONST_OCT",-95],["INT_CONST_HEX",-95],["INT_CONST_BIN",-95],["INT_CONST_CHAR",-95],["FLOAT_CONST",-95],["HEX_FLOAT_CONST",-95],["CHAR_CONST",-95],["WCHAR_CONST",-95],["U8CHAR_CONST",-95],["U16CHAR_CONST",-95],["U32CHAR_CONST",-95],["STRING_LITERAL",-95],["WSTRING_LITERAL",-95],["U8STRING_LITERAL",-95],["U16STRING_LITERAL",-95],["U32STRING_LITERAL",-95],["RBRACE",-95],["ELSE",-95]]],[248,[["SEMI",-96],["PPPRAGMA",-96],["_PRAGMA",-96],["_STATIC_ASSERT",-96],["ASM",-96],["ID",-96],["LPAREN",-96],["TIMES",-96],["TYPEID",-96],["ENUM",-96],["VOID",-96],["_BOOL",-96],["CHAR",-96],["SHORT",-96],["INT",-96],["LONG",-96],["FLOAT",-96],["DOUBLE",-96],["_COMPLEX",-96],["SIGNED",-96],["UNSIGNED",-96],["__INT128",-96],["_ATOMIC",-96],["TYPEOF",-96],["CONST",-96],["RESTRICT",-96],["VOLATILE",-96],["AUTO",-96],["REGISTER",-96],["STATIC",-96],["EXTERN",-96],["TYPEDEF",-96],["_THREAD_LOCAL",-96],["INLINE",-96],["_NORETURN",-96],["_ALIGNAS",-96],["__ATTRIBUTE__",-96],["STRUCT",-96],["UNION",-96],["LBRACE",-96],["CASE",-96],["DEFAULT",-96],["IF",-96],["SWITCH",-96],["WHILE",-96],["DO",-96],["FOR",-96],["GOTO",-96],["BREAK",-96],["CONTINUE",-96],["RETURN",-96],["PLUSPLUS",-96],["MINUSMINUS",-96],["SIZEOF",-96],["_ALIGNOF",-96],["AND",-96],["PLUS",-96],["MINUS",-96],["NOT",-96],["LNOT",-96],["OFFSETOF",-96],["INT_CONST_DEC",-96],["INT_CONST_OCT",-96],["INT_CONST_HEX",-96],["INT_CONST_BIN",-96],["INT_CONST_CHAR",-96],["FLOAT_CONST",-96],["HEX_FLOAT_CONST",-96],["CHAR_CONST",-96],["WCHAR_CONST",-96],["U8CHAR_CONST",-96],["U16CHAR_CONST",-96],["U32CHAR_CONST",-96],["STRING_LITERAL",-96],["WSTRING_LITERAL",-96],["U8STRING_LITERAL",-96],["U16STRING_LITERAL",-96],["U32STRING_LITERAL",-96],["RBRACE",-96],["ELSE",-96]]],[249,[["SEMI",-97],["PPPRAGMA",-97],["_PRAGMA",-97],["_STATIC_ASSERT",-97],["ASM",-97],["ID",-97],["LPAREN",-97],["TIMES",-97],["TYPEID",-97],["ENUM",-97],["VOID",-97],["_BOOL",-97],["CHAR",-97],["SHORT",-97],["INT",-97],["LONG",-97],["FLOAT",-97],["DOUBLE",-97],["_COMPLEX",-97],["SIGNED",-97],["UNSIGNED",-97],["__INT128",-97],["_ATOMIC",-97],["TYPEOF",-97],["CONST",-97],["RESTRICT",-97],["VOLATILE",-97],["AUTO",-97],["REGISTER",-97],["STATIC",-97],["EXTERN",-97],["TYPEDEF",-97],["_THREAD_LOCAL",-97],["INLINE",-97],["_NORETURN",-97],["_ALIGNAS",-97],["__ATTRIBUTE__",-97],["STRUCT",-97],["UNION",-97],["LBRACE",-97],["CASE",-97],["DEFAULT",-97],["IF",-97],["SWITCH",-97],["WHILE",-97],["DO",-97],["FOR",-97],["GOTO",-97],["BREAK",-97],["CONTINUE",-97],["RETURN",-97],["PLUSPLUS",-97],["MINUSMINUS",-97],["SIZEOF",-97],["_ALIGNOF",-97],["AND",-97],["PLUS",-97],["MINUS",-97],["NOT",-97],["LNOT",-97],["OFFSETOF",-97],["INT_CONST_DEC",-97],["INT_CONST_OCT",-97],["INT_CONST_HEX",-97],["INT_CONST_BIN",-97],["INT_CONST_CHAR",-97],["FLOAT_CONST",-97],["HEX_FLOAT_CONST",-97],["CHAR_CONST",-97],["WCHAR_CONST",-97],["U8CHAR_CONST",-97],["U16CHAR_CONST",-97],["U32CHAR_CONST",-97],["STRING_LITERAL",-97],["WSTRING_LITERAL",-97],["U8STRING_LITERAL",-97],["U16STRING_LITERAL",-97],["U32STRING_LITERAL",-97],["RBRACE",-97],["ELSE",-97]]],[250,[["SEMI",-98],["PPPRAGMA",-98],["_PRAGMA",-98],["_STATIC_ASSERT",-98],["ASM",-98],["ID",-98],["LPAREN",-98],["TIMES",-98],["TYPEID",-98],["ENUM",-98],["VOID",-98],["_BOOL",-98],["CHAR",-98],["SHORT",-98],["INT",-98],["LONG",-98],["FLOAT",-98],["DOUBLE",-98],["_COMPLEX",-98],["SIGNED",-98],["UNSIGNED",-98],["__INT128",-98],["_ATOMIC",-98],["TYPEOF",-98],["CONST",-98],["RESTRICT",-98],["VOLATILE",-98],["AUTO",-98],["REGISTER",-98],["STATIC",-98],["EXTERN",-98],["TYPEDEF",-98],["_THREAD_LOCAL",-98],["INLINE",-98],["_NORETURN",-98],["_ALIGNAS",-98],["__ATTRIBUTE__",-98],["STRUCT",-98],["UNION",-98],["LBRACE",-98],["CASE",-98],["DEFAULT",-98],["IF",-98],["SWITCH",-98],["WHILE",-98],["DO",-98],["FOR",-98],["GOTO",-98],["BREAK",-98],["CONTINUE",-98],["RETURN",-98],["PLUSPLUS",-98],["MINUSMINUS",-98],["SIZEOF",-98],["_ALIGNOF",-98],["AND",-98],["PLUS",-98],["MINUS",-98],["NOT",-98],["LNOT",-98],["OFFSETOF",-98],["INT_CONST_DEC",-98],["INT_CONST_OCT",-98],["INT_CONST_HEX",-98],["INT_CONST_BIN",-98],["INT_CONST_CHAR",-98],["FLOAT_CONST",-98],["HEX_FLOAT_CONST",-98],["CHAR_CONST",-98],["WCHAR_CONST",-98],["U8CHAR_CONST",-98],["U16CHAR_CONST",-98],["U32CHAR_CONST",-98],["STRING_LITERAL",-98],["WSTRING_LITERAL",-98],["U8STRING_LITERAL",-98],["U16STRING_LITERAL",-98],["U32STRING_LITERAL",-98],["RBRACE",-98],["ELSE",-98]]],[251,[["SEMI",-99],["PPPRAGMA",-99],["_PRAGMA",-99],["_STATIC_ASSERT",-99],["ASM",-99],["ID",-99],["LPAREN",-99],["TIMES",-99],["TYPEID",-99],["ENUM",-99],["VOID",-99],["_BOOL",-99],["CHAR",-99],["SHORT",-99],["INT",-99],["LONG",-99],["FLOAT",-99],["DOUBLE",-99],["_COMPLEX",-99],["SIGNED",-99],["UNSIGNED",-99],["__INT128",-99],["_ATOMIC",-99],["TYPEOF",-99],["CONST",-99],["RESTRICT",-99],["VOLATILE",-99],["AUTO",-99],["REGISTER",-99],["STATIC",-99],["EXTERN",-99],["TYPEDEF",-99],["_THREAD_LOCAL",-99],["INLINE",-99],["_NORETURN",-99],["_ALIGNAS",-99],["__ATTRIBUTE__",-99],["STRUCT",-99],["UNION",-99],["LBRACE",-99],["CASE",-99],["DEFAULT",-99],["IF",-99],["SWITCH",-99],["WHILE",-99],["DO",-99],["FOR",-99],["GOTO",-99],["BREAK",-99],["CONTINUE",-99],["RETURN",-99],["PLUSPLUS",-99],["MINUSMINUS",-99],["SIZEOF",-99],["_ALIGNOF",-99],["AND",-99],["PLUS",-99],["MINUS",-99],["NOT",-99],["LNOT",-99],["OFFSETOF",-99],["INT_CONST_DEC",-99],["INT_CONST_OCT",-99],["INT_CONST_HEX",-99],["INT_CONST_BIN",-99],["INT_CONST_CHAR",-99],["FLOAT_CONST",-99],["HEX_FLOAT_CONST",-99],["CHAR_CONST",-99],["WCHAR_CONST",-99],["U8CHAR_CONST",-99],["U16CHAR_CONST",-99],["U32CHAR_CONST",-99],["STRING_LITERAL",-99],["WSTRING_LITERAL",-99],["U8STRING_LITERAL",-99],["U16STRING_LITERAL",-99],["U32STRING_LITERAL",-99],["RBRACE",-99],["ELSE",-99]]],[252,[["SEMI",-100],["PPPRAGMA",-100],["_PRAGMA",-100],["_STATIC_ASSERT",-100],["ASM",-100],["ID",-100],["LPAREN",-100],["TIMES",-100],["TYPEID",-100],["ENUM",-100],["VOID",-100],["_BOOL",-100],["CHAR",-100],["SHORT",-100],["INT",-100],["LONG",-100],["FLOAT",-100],["DOUBLE",-100],["_COMPLEX",-100],["SIGNED",-100],["UNSIGNED",-100],["__INT128",-100],["_ATOMIC",-100],["TYPEOF",-100],["CONST",-100],["RESTRICT",-100],["VOLATILE",-100],["AUTO",-100],["REGISTER",-100],["STATIC",-100],["EXTERN",-100],["TYPEDEF",-100],["_THREAD_LOCAL",-100],["INLINE",-100],["_NORETURN",-100],["_ALIGNAS",-100],["__ATTRIBUTE__",-100],["STRUCT",-100],["UNION",-100],["LBRACE",-100],["CASE",-100],["DEFAULT",-100],["IF",-100],["SWITCH",-100],["WHILE",-100],["DO",-100],["FOR",-100],["GOTO",-100],["BREAK",-100],["CONTINUE",-100],["RETURN",-100],["PLUSPLUS",-100],["MINUSMINUS",-100],["SIZEOF",-100],["_ALIGNOF",-100],["AND",-100],["PLUS",-100],["MINUS",-100],["NOT",-100],["LNOT",-100],["OFFSETOF",-100],["INT_CONST_DEC",-100],["INT_CONST_OCT",-100],["INT_CONST_HEX",-100],["INT_CONST_BIN",-100],["INT_CONST_CHAR",-100],["FLOAT_CONST",-100],["HEX_FLOAT_CONST",-100],["CHAR_CONST",-100],["WCHAR_CONST",-100],["U8CHAR_CONST",-100],["U16CHAR_CONST",-100],["U32CHAR_CONST",-100],["STRING_LITERAL",-100],["WSTRING_LITERAL",-100],["U8STRING_LITERAL",-100],["U16STRING_LITERAL",-100],["U32STRING_LITERAL",-100],["RBRACE",-100]]],[253,[["SEMI",-101],["PPPRAGMA",-101],["_PRAGMA",-101],["_STATIC_ASSERT",-101],["ASM",-101],["ID",-101],["LPAREN",-101],["TIMES",-101],["TYPEID",-101],["ENUM",-101],["VOID",-101],["_BOOL",-101],["CHAR",-101],["SHORT",-101],["INT",-101],["LONG",-101],["FLOAT",-101],["DOUBLE",-101],["_COMPLEX",-101],["SIGNED",-101],["UNSIGNED",-101],["__INT128",-101],["_ATOMIC",-101],["TYPEOF",-101],["CONST",-101],["RESTRICT",-101],["VOLATILE",-101],["AUTO",-101],["REGISTER",-101],["STATIC",-101],["EXTERN",-101],["TYPEDEF",-101],["_THREAD_LOCAL",-101],["INLINE",-101],["_NORETURN",-101],["_ALIGNAS",-101],["__ATTRIBUTE__",-101],["STRUCT",-101],["UNION",-101],["LBRACE",-101],["CASE",-101],["DEFAULT",-101],["IF",-101],["SWITCH",-101],["WHILE",-101],["DO",-101],["FOR",-101],["GOTO",-101],["BREAK",-101],["CONTINUE",-101],["RETURN",-101],["PLUSPLUS",-101],["MINUSMINUS",-101],["SIZEOF",-101],["_ALIGNOF",-101],["AND",-101],["PLUS",-101],["MINUS",-101],["NOT",-101],["LNOT",-101],["OFFSETOF",-101],["INT_CONST_DEC",-101],["INT_CONST_OCT",-101],["INT_CONST_HEX",-101],["INT_CONST_BIN",-101],["INT_CONST_CHAR",-101],["FLOAT_CONST",-101],["HEX_FLOAT_CONST",-101],["CHAR_CONST",-101],["WCHAR_CONST",-101],["U8CHAR_CONST",-101],["U16CHAR_CONST",-101],["U32CHAR_CONST",-101],["STRING_LITERAL",-101],["WSTRING_LITERAL",-101],["U8STRING_LITERAL",-101],["U16STRING_LITERAL",-101],["U32STRING_LITERAL",-101],["RBRACE",-101],["ELSE",-101]]],[254,[["SEMI",-102],["PPPRAGMA",-102],["_PRAGMA",-102],["_STATIC_ASSERT",-102],["ASM",-102],["ID",-102],["LPAREN",-102],["TIMES",-102],["TYPEID",-102],["ENUM",-102],["VOID",-102],["_BOOL",-102],["CHAR",-102],["SHORT",-102],["INT",-102],["LONG",-102],["FLOAT",-102],["DOUBLE",-102],["_COMPLEX",-102],["SIGNED",-102],["UNSIGNED",-102],["__INT128",-102],["_ATOMIC",-102],["TYPEOF",-102],["CONST",-102],["RESTRICT",-102],["VOLATILE",-102],["AUTO",-102],["REGISTER",-102],["STATIC",-102],["EXTERN",-102],["TYPEDEF",-102],["_THREAD_LOCAL",-102],["INLINE",-102],["_NORETURN",-102],["_ALIGNAS",-102],["__ATTRIBUTE__",-102],["STRUCT",-102],["UNION",-102],["LBRACE",-102],["CASE",-102],["DEFAULT",-102],["IF",-102],["SWITCH",-102],["WHILE",-102],["DO",-102],["FOR",-102],["GOTO",-102],["BREAK",-102],["CONTINUE",-102],["RETURN",-102],["PLUSPLUS",-102],["MINUSMINUS",-102],["SIZEOF",-102],["_ALIGNOF",-102],["AND",-102],["PLUS",-102],["MINUS",-102],["NOT",-102],["LNOT",-102],["OFFSETOF",-102],["INT_CONST_DEC",-102],["INT_CONST_OCT",-102],["INT_CONST_HEX",-102],["INT_CONST_BIN",-102],["INT_CONST_CHAR",-102],["FLOAT_CONST",-102],["HEX_FLOAT_CONST",-102],["CHAR_CONST",-102],["WCHAR_CONST",-102],["U8CHAR_CONST",-102],["U16CHAR_CONST",-102],["U32CHAR_CONST",-102],["STRING_LITERAL",-102],["WSTRING_LITERAL",-102],["U8STRING_LITERAL",-102],["U16STRING_LITERAL",-102],["U32STRING_LITERAL",-102],["RBRACE",-102],["ELSE",-102]]],[255,[["SEMI",-103],["PPPRAGMA",-103],["_PRAGMA",-103],["_STATIC_ASSERT",-103],["ASM",-103],["ID",-103],["LPAREN",-103],["TIMES",-103],["TYPEID",-103],["ENUM",-103],["VOID",-103],["_BOOL",-103],["CHAR",-103],["SHORT",-103],["INT",-103],["LONG",-103],["FLOAT",-103],["DOUBLE",-103],["_COMPLEX",-103],["SIGNED",-103],["UNSIGNED",-103],["__INT128",-103],["_ATOMIC",-103],["TYPEOF",-103],["CONST",-103],["RESTRICT",-103],["VOLATILE",-103],["AUTO",-103],["REGISTER",-103],["STATIC",-103],["EXTERN",-103],["TYPEDEF",-103],["_THREAD_LOCAL",-103],["INLINE",-103],["_NORETURN",-103],["_ALIGNAS",-103],["__ATTRIBUTE__",-103],["STRUCT",-103],["UNION",-103],["LBRACE",-103],["CASE",-103],["DEFAULT",-103],["IF",-103],["SWITCH",-103],["WHILE",-103],["DO",-103],["FOR",-103],["GOTO",-103],["BREAK",-103],["CONTINUE",-103],["RETURN",-103],["PLUSPLUS",-103],["MINUSMINUS",-103],["SIZEOF",-103],["_ALIGNOF",-103],["AND",-103],["PLUS",-103],["MINUS",-103],["NOT",-103],["LNOT",-103],["OFFSETOF",-103],["INT_CONST_DEC",-103],["INT_CONST_OCT",-103],["INT_CONST_HEX",-103],["INT_CONST_BIN",-103],["INT_CONST_CHAR",-103],["FLOAT_CONST",-103],["HEX_FLOAT_CONST",-103],["CHAR_CONST",-103],["WCHAR_CONST",-103],["U8CHAR_CONST",-103],["U16CHAR_CONST",-103],["U32CHAR_CONST",-103],["STRING_LITERAL",-103],["WSTRING_LITERAL",-103],["U8STRING_LITERAL",-103],["U16STRING_LITERAL",-103],["U32STRING_LITERAL",-103],["RBRACE",-103],["ELSE",-103]]],[256,[["SEMI",-351],["LPAREN",-351],["TIMES",-351],["PLUSPLUS",-351],["MINUSMINUS",-351],["AND",-351],["PLUS",-351],["MINUS",-351],["EQUALS",-351],["COLON",402],["COMMA",-351],["LBRACKET",-351],["PERIOD",-351],["ARROW",-351],["CONDOP",-351],["DIVIDE",-351],["MOD",-351],["RSHIFT",-351],["LSHIFT",-351],["LT",-351],["LE",-351],["GE",-351],["GT",-351],["EQ",-351],["NE",-351],["OR",-351],["XOR",-351],["LAND",-351],["LOR",-351],["XOREQUAL",-351],["TIMESEQUAL",-351],["DIVEQUAL",-351],["MODEQUAL",-351],["PLUSEQUAL",-351],["MINUSEQUAL",-351],["LSHIFTEQUAL",-351],["RSHIFTEQUAL",-351],["ANDEQUAL",-351],["OREQUAL",-351]]],[257,[["SEMI",-278],["ID",-278],["LPAREN",-278],["TIMES",-278],["TYPEID",-278],["VOID",-278],["_BOOL",-278],["CHAR",-278],["SHORT",-278],["INT",-278],["LONG",-278],["FLOAT",-278],["DOUBLE",-278],["_COMPLEX",-278],["SIGNED",-278],["UNSIGNED",-278],["__INT128",-278],["_ATOMIC",-278],["CONST",-278],["RESTRICT",-278],["VOLATILE",-278],["AUTO",-278],["REGISTER",-278],["STATIC",-278],["EXTERN",-278],["TYPEDEF",-278],["_THREAD_LOCAL",-278],["INLINE",-278],["_NORETURN",-278],["_ALIGNAS",-278],["__ATTRIBUTE__",-278],["COLON",403]]],[260,[["SEMI",406]]],[262,[["SEMI",-26],["COMMA",377],["RPAREN",-26]]],[265,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["__ATTRIBUTE__",67],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[268,[["SEMI",418]]],[269,[["SEMI",419]]],[270,[["SEMI",421],["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[272,[["SEMI",425],["__ATTRIBUTE__",67]]],[273,[["SEMI",-401],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["ENUM",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",78],["TYPEOF",-412],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",-412],["UNION",-412]]],[275,[["SEMI",-52],["ASM",-52],["LPAREN",-52],["__ATTRIBUTE__",-52],["EQUALS",-52],["COLON",-52],["COMMA",-52],["RPAREN",-52],["LBRACKET",-52]]],[276,[["SEMI",-159],["COMMA",-159]]],[277,[["SEMI",-160],["EQUALS",426],["COLON",427],["COMMA",-160]]],[278,[["SEMI",-28],["ID",-28],["LPAREN",-28],["TIMES",-28],["TYPEID",-28],["VOID",-28],["_BOOL",-28],["CHAR",-28],["SHORT",-28],["INT",-28],["LONG",-28],["FLOAT",-28],["DOUBLE",-28],["_COMPLEX",-28],["SIGNED",-28],["UNSIGNED",-28],["__INT128",-28],["_ATOMIC",-28],["CONST",-28],["RESTRICT",-28],["VOLATILE",-28],["AUTO",-28],["REGISTER",-28],["STATIC",-28],["EXTERN",-28],["TYPEDEF",-28],["_THREAD_LOCAL",-28],["INLINE",-28],["_NORETURN",-28],["_ALIGNAS",-28],["__ATTRIBUTE__",67],["RBRACE",-28],["EQUALS",-28],["COLON",-28],["COMMA",-28],["RPAREN",-28],["LBRACKET",-28]]],[286,[["SEMI",-365],["LPAREN",-365],["TIMES",-365],["PLUSPLUS",-365],["MINUSMINUS",-365],["AND",-365],["PLUS",-365],["MINUS",-365],["STRING_LITERAL",-365],["RBRACE",-365],["EQUALS",-365],["COLON",-365],["COMMA",-365],["RPAREN",-365],["LBRACKET",-365],["RBRACKET",-365],["PERIOD",-365],["ARROW",-365],["CONDOP",-365],["DIVIDE",-365],["MOD",-365],["RSHIFT",-365],["LSHIFT",-365],["LT",-365],["LE",-365],["GE",-365],["GT",-365],["EQ",-365],["NE",-365],["OR",-365],["XOR",-365],["LAND",-365],["LOR",-365],["XOREQUAL",-365],["TIMESEQUAL",-365],["DIVEQUAL",-365],["MODEQUAL",-365],["PLUSEQUAL",-365],["MINUSEQUAL",-365],["LSHIFTEQUAL",-365],["RSHIFTEQUAL",-365],["ANDEQUAL",-365],["OREQUAL",-365],["ELLIPSIS",-365]]],[314,[["SEMI",-336],["LPAREN",-336],["TIMES",-336],["PLUSPLUS",-336],["MINUSMINUS",-336],["AND",-336],["PLUS",-336],["MINUS",-336],["RBRACE",-336],["EQUALS",-336],["COLON",-336],["COMMA",-336],["RPAREN",-336],["LBRACKET",-336],["RBRACKET",-336],["PERIOD",-336],["ARROW",-336],["CONDOP",-336],["DIVIDE",-336],["MOD",-336],["RSHIFT",-336],["LSHIFT",-336],["LT",-336],["LE",-336],["GE",-336],["GT",-336],["EQ",-336],["NE",-336],["OR",-336],["XOR",-336],["LAND",-336],["LOR",-336],["XOREQUAL",-336],["TIMESEQUAL",-336],["DIVEQUAL",-336],["MODEQUAL",-336],["PLUSEQUAL",-336],["MINUSEQUAL",-336],["LSHIFTEQUAL",-336],["RSHIFTEQUAL",-336],["ANDEQUAL",-336],["OREQUAL",-336],["ELLIPSIS",-336]]],[315,[["SEMI",-337],["LPAREN",-337],["TIMES",-337],["PLUSPLUS",-337],["MINUSMINUS",-337],["AND",-337],["PLUS",-337],["MINUS",-337],["RBRACE",-337],["EQUALS",-337],["COLON",-337],["COMMA",-337],["RPAREN",-337],["LBRACKET",-337],["RBRACKET",-337],["PERIOD",-337],["ARROW",-337],["CONDOP",-337],["DIVIDE",-337],["MOD",-337],["RSHIFT",-337],["LSHIFT",-337],["LT",-337],["LE",-337],["GE",-337],["GT",-337],["EQ",-337],["NE",-337],["OR",-337],["XOR",-337],["LAND",-337],["LOR",-337],["XOREQUAL",-337],["TIMESEQUAL",-337],["DIVEQUAL",-337],["MODEQUAL",-337],["PLUSEQUAL",-337],["MINUSEQUAL",-337],["LSHIFTEQUAL",-337],["RSHIFTEQUAL",-337],["ANDEQUAL",-337],["OREQUAL",-337],["ELLIPSIS",-337]]],[316,[["SEMI",-316],["TIMES",-316],["AND",-316],["PLUS",-316],["MINUS",-316],["RBRACE",-316],["EQUALS",-316],["COLON",-316],["COMMA",-316],["RPAREN",-316],["RBRACKET",-316],["CONDOP",-316],["DIVIDE",-316],["MOD",-316],["RSHIFT",-316],["LSHIFT",-316],["LT",-316],["LE",-316],["GE",-316],["GT",-316],["EQ",-316],["NE",-316],["OR",-316],["XOR",-316],["LAND",-316],["LOR",-316],["XOREQUAL",-316],["TIMESEQUAL",-316],["DIVEQUAL",-316],["MODEQUAL",-316],["PLUSEQUAL",-316],["MINUSEQUAL",-316],["LSHIFTEQUAL",-316],["RSHIFTEQUAL",-316],["ANDEQUAL",-316],["OREQUAL",-316],["ELLIPSIS",-316]]],[317,[["SEMI",-317],["TIMES",-317],["AND",-317],["PLUS",-317],["MINUS",-317],["RBRACE",-317],["EQUALS",-317],["COLON",-317],["COMMA",-317],["RPAREN",-317],["RBRACKET",-317],["CONDOP",-317],["DIVIDE",-317],["MOD",-317],["RSHIFT",-317],["LSHIFT",-317],["LT",-317],["LE",-317],["GE",-317],["GT",-317],["EQ",-317],["NE",-317],["OR",-317],["XOR",-317],["LAND",-317],["LOR",-317],["XOREQUAL",-317],["TIMESEQUAL",-317],["DIVEQUAL",-317],["MODEQUAL",-317],["PLUSEQUAL",-317],["MINUSEQUAL",-317],["LSHIFTEQUAL",-317],["RSHIFTEQUAL",-317],["ANDEQUAL",-317],["OREQUAL",-317],["ELLIPSIS",-317]]],[318,[["SEMI",-318],["TIMES",-318],["AND",-318],["PLUS",-318],["MINUS",-318],["RBRACE",-318],["EQUALS",-318],["COLON",-318],["COMMA",-318],["RPAREN",-318],["RBRACKET",-318],["CONDOP",-318],["DIVIDE",-318],["MOD",-318],["RSHIFT",-318],["LSHIFT",-318],["LT",-318],["LE",-318],["GE",-318],["GT",-318],["EQ",-318],["NE",-318],["OR",-318],["XOR",-318],["LAND",-318],["LOR",-318],["XOREQUAL",-318],["TIMESEQUAL",-318],["DIVEQUAL",-318],["MODEQUAL",-318],["PLUSEQUAL",-318],["MINUSEQUAL",-318],["LSHIFTEQUAL",-318],["RSHIFTEQUAL",-318],["ANDEQUAL",-318],["OREQUAL",-318],["ELLIPSIS",-318]]],[319,[["SEMI",-319],["TIMES",-319],["AND",-319],["PLUS",-319],["MINUS",-319],["RBRACE",-319],["EQUALS",-319],["COLON",-319],["COMMA",-319],["RPAREN",-319],["RBRACKET",-319],["CONDOP",-319],["DIVIDE",-319],["MOD",-319],["RSHIFT",-319],["LSHIFT",-319],["LT",-319],["LE",-319],["GE",-319],["GT",-319],["EQ",-319],["NE",-319],["OR",-319],["XOR",-319],["LAND",-319],["LOR",-319],["XOREQUAL",-319],["TIMESEQUAL",-319],["DIVEQUAL",-319],["MODEQUAL",-319],["PLUSEQUAL",-319],["MINUSEQUAL",-319],["LSHIFTEQUAL",-319],["RSHIFTEQUAL",-319],["ANDEQUAL",-319],["OREQUAL",-319],["ELLIPSIS",-319]]],[322,[["SEMI",-370],["LPAREN",-370],["TIMES",-370],["PLUSPLUS",-370],["MINUSMINUS",-370],["AND",-370],["PLUS",-370],["MINUS",-370],["WSTRING_LITERAL",-370],["U8STRING_LITERAL",-370],["U16STRING_LITERAL",-370],["U32STRING_LITERAL",-370],["RBRACE",-370],["EQUALS",-370],["COLON",-370],["COMMA",-370],["RPAREN",-370],["LBRACKET",-370],["RBRACKET",-370],["PERIOD",-370],["ARROW",-370],["CONDOP",-370],["DIVIDE",-370],["MOD",-370],["RSHIFT",-370],["LSHIFT",-370],["LT",-370],["LE",-370],["GE",-370],["GT",-370],["EQ",-370],["NE",-370],["OR",-370],["XOR",-370],["LAND",-370],["LOR",-370],["XOREQUAL",-370],["TIMESEQUAL",-370],["DIVEQUAL",-370],["MODEQUAL",-370],["PLUSEQUAL",-370],["MINUSEQUAL",-370],["LSHIFTEQUAL",-370],["RSHIFTEQUAL",-370],["ANDEQUAL",-370],["OREQUAL",-370],["ELLIPSIS",-370]]],[323,[["SEMI",-371],["LPAREN",-371],["TIMES",-371],["PLUSPLUS",-371],["MINUSMINUS",-371],["AND",-371],["PLUS",-371],["MINUS",-371],["WSTRING_LITERAL",-371],["U8STRING_LITERAL",-371],["U16STRING_LITERAL",-371],["U32STRING_LITERAL",-371],["RBRACE",-371],["EQUALS",-371],["COLON",-371],["COMMA",-371],["RPAREN",-371],["LBRACKET",-371],["RBRACKET",-371],["PERIOD",-371],["ARROW",-371],["CONDOP",-371],["DIVIDE",-371],["MOD",-371],["RSHIFT",-371],["LSHIFT",-371],["LT",-371],["LE",-371],["GE",-371],["GT",-371],["EQ",-371],["NE",-371],["OR",-371],["XOR",-371],["LAND",-371],["LOR",-371],["XOREQUAL",-371],["TIMESEQUAL",-371],["DIVEQUAL",-371],["MODEQUAL",-371],["PLUSEQUAL",-371],["MINUSEQUAL",-371],["LSHIFTEQUAL",-371],["RSHIFTEQUAL",-371],["ANDEQUAL",-371],["OREQUAL",-371],["ELLIPSIS",-371]]],[324,[["SEMI",-372],["LPAREN",-372],["TIMES",-372],["PLUSPLUS",-372],["MINUSMINUS",-372],["AND",-372],["PLUS",-372],["MINUS",-372],["WSTRING_LITERAL",-372],["U8STRING_LITERAL",-372],["U16STRING_LITERAL",-372],["U32STRING_LITERAL",-372],["RBRACE",-372],["EQUALS",-372],["COLON",-372],["COMMA",-372],["RPAREN",-372],["LBRACKET",-372],["RBRACKET",-372],["PERIOD",-372],["ARROW",-372],["CONDOP",-372],["DIVIDE",-372],["MOD",-372],["RSHIFT",-372],["LSHIFT",-372],["LT",-372],["LE",-372],["GE",-372],["GT",-372],["EQ",-372],["NE",-372],["OR",-372],["XOR",-372],["LAND",-372],["LOR",-372],["XOREQUAL",-372],["TIMESEQUAL",-372],["DIVEQUAL",-372],["MODEQUAL",-372],["PLUSEQUAL",-372],["MINUSEQUAL",-372],["LSHIFTEQUAL",-372],["RSHIFTEQUAL",-372],["ANDEQUAL",-372],["OREQUAL",-372],["ELLIPSIS",-372]]],[325,[["SEMI",-373],["LPAREN",-373],["TIMES",-373],["PLUSPLUS",-373],["MINUSMINUS",-373],["AND",-373],["PLUS",-373],["MINUS",-373],["WSTRING_LITERAL",-373],["U8STRING_LITERAL",-373],["U16STRING_LITERAL",-373],["U32STRING_LITERAL",-373],["RBRACE",-373],["EQUALS",-373],["COLON",-373],["COMMA",-373],["RPAREN",-373],["LBRACKET",-373],["RBRACKET",-373],["PERIOD",-373],["ARROW",-373],["CONDOP",-373],["DIVIDE",-373],["MOD",-373],["RSHIFT",-373],["LSHIFT",-373],["LT",-373],["LE",-373],["GE",-373],["GT",-373],["EQ",-373],["NE",-373],["OR",-373],["XOR",-373],["LAND",-373],["LOR",-373],["XOREQUAL",-373],["TIMESEQUAL",-373],["DIVEQUAL",-373],["MODEQUAL",-373],["PLUSEQUAL",-373],["MINUSEQUAL",-373],["LSHIFTEQUAL",-373],["RSHIFTEQUAL",-373],["ANDEQUAL",-373],["OREQUAL",-373],["ELLIPSIS",-373]]],[327,[["SEMI",468]]],[334,[["SEMI",-49],["ASM",-49],["LPAREN",-49],["TYPEID",-49],["ENUM",-49],["VOID",-49],["_BOOL",-49],["CHAR",-49],["SHORT",-49],["INT",-49],["LONG",-49],["FLOAT",-49],["DOUBLE",-49],["_COMPLEX",-49],["SIGNED",-49],["UNSIGNED",-49],["__INT128",-49],["_ATOMIC",-49],["TYPEOF",-49],["CONST",-49],["RESTRICT",-49],["VOLATILE",-49],["AUTO",-49],["REGISTER",-49],["STATIC",-49],["EXTERN",-49],["TYPEDEF",-49],["_THREAD_LOCAL",-49],["INLINE",-49],["_NORETURN",-49],["_ALIGNAS",-49],["__ATTRIBUTE__",-49],["STRUCT",-49],["UNION",-49],["LBRACE",-49],["EQUALS",-49],["COLON",-49],["COMMA",-49],["RPAREN",-49],["LBRACKET",-49]]],[335,[["SEMI",-50],["ASM",-50],["LPAREN",-50],["TYPEID",-50],["ENUM",-50],["VOID",-50],["_BOOL",-50],["CHAR",-50],["SHORT",-50],["INT",-50],["LONG",-50],["FLOAT",-50],["DOUBLE",-50],["_COMPLEX",-50],["SIGNED",-50],["UNSIGNED",-50],["__INT128",-50],["_ATOMIC",-50],["TYPEOF",-50],["CONST",-50],["RESTRICT",-50],["VOLATILE",-50],["AUTO",-50],["REGISTER",-50],["STATIC",-50],["EXTERN",-50],["TYPEDEF",-50],["_THREAD_LOCAL",-50],["INLINE",-50],["_NORETURN",-50],["_ALIGNAS",-50],["__ATTRIBUTE__",-50],["STRUCT",-50],["UNION",-50],["LBRACE",-50],["EQUALS",-50],["COLON",-50],["COMMA",-50],["RPAREN",-50],["LBRACKET",-50]]],[349,[["SEMI",-164],["COMMA",-164]]],[350,[["SEMI",-165],["EQUALS",494],["COMMA",-165]]],[355,[["SEMI",360],["PPPRAGMA",16],["_PRAGMA",17],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RBRACE",358]]],[356,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",-412],["CONST",-412],["RESTRICT",-412],["VOLATILE",-412],["AUTO",-412],["REGISTER",-412],["STATIC",-412],["EXTERN",-412],["TYPEDEF",-412],["_THREAD_LOCAL",-412],["INLINE",-412],["_NORETURN",-412],["_ALIGNAS",-412],["__ATTRIBUTE__",67],["COLON",-412],["COMMA",-412],["RPAREN",-412],["LBRACKET",-412]]],[357,[["SEMI",-182],["PPPRAGMA",-182],["_PRAGMA",-182],["TYPEID",-182],["ENUM",-182],["VOID",-182],["_BOOL",-182],["CHAR",-182],["SHORT",-182],["INT",-182],["LONG",-182],["FLOAT",-182],["DOUBLE",-182],["_COMPLEX",-182],["SIGNED",-182],["UNSIGNED",-182],["__INT128",-182],["_ATOMIC",-182],["TYPEOF",-182],["CONST",-182],["RESTRICT",-182],["VOLATILE",-182],["_ALIGNAS",-182],["__ATTRIBUTE__",-182],["STRUCT",-182],["UNION",-182],["RBRACE",-182]]],[359,[["SEMI",-412],["ID",31],["LPAREN",89],["TIMES",33],["TYPEID",96],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["COLON",-412]]],[360,[["SEMI",-185],["PPPRAGMA",-185],["_PRAGMA",-185],["TYPEID",-185],["ENUM",-185],["VOID",-185],["_BOOL",-185],["CHAR",-185],["SHORT",-185],["INT",-185],["LONG",-185],["FLOAT",-185],["DOUBLE",-185],["_COMPLEX",-185],["SIGNED",-185],["UNSIGNED",-185],["__INT128",-185],["_ATOMIC",-185],["TYPEOF",-185],["CONST",-185],["RESTRICT",-185],["VOLATILE",-185],["_ALIGNAS",-185],["__ATTRIBUTE__",-185],["STRUCT",-185],["UNION",-185],["RBRACE",-185]]],[361,[["SEMI",-186],["PPPRAGMA",-186],["_PRAGMA",-186],["TYPEID",-186],["ENUM",-186],["VOID",-186],["_BOOL",-186],["CHAR",-186],["SHORT",-186],["INT",-186],["LONG",-186],["FLOAT",-186],["DOUBLE",-186],["_COMPLEX",-186],["SIGNED",-186],["UNSIGNED",-186],["__INT128",-186],["_ATOMIC",-186],["TYPEOF",-186],["CONST",-186],["RESTRICT",-186],["VOLATILE",-186],["_ALIGNAS",-186],["__ATTRIBUTE__",-186],["STRUCT",-186],["UNION",-186],["RBRACE",-186]]],[362,[["SEMI",360],["PPPRAGMA",16],["_PRAGMA",17],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RBRACE",358]]],[363,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",-412],["CONST",-412],["RESTRICT",-412],["VOLATILE",-412],["AUTO",-412],["REGISTER",-412],["STATIC",-412],["EXTERN",-412],["TYPEDEF",-412],["_THREAD_LOCAL",-412],["INLINE",-412],["_NORETURN",-412],["_ALIGNAS",-412],["__ATTRIBUTE__",67],["COLON",-412],["COMMA",-412],["RPAREN",-412],["LBRACKET",-412]]],[364,[["SEMI",-153],["ID",-153],["LPAREN",-153],["TIMES",-153],["TYPEID",-153],["ENUM",-153],["VOID",-153],["_BOOL",-153],["CHAR",-153],["SHORT",-153],["INT",-153],["LONG",-153],["FLOAT",-153],["DOUBLE",-153],["_COMPLEX",-153],["SIGNED",-153],["UNSIGNED",-153],["__INT128",-153],["_ATOMIC",-153],["TYPEOF",-153],["CONST",-153],["RESTRICT",-153],["VOLATILE",-153],["AUTO",-153],["REGISTER",-153],["STATIC",-153],["EXTERN",-153],["TYPEDEF",-153],["_THREAD_LOCAL",-153],["INLINE",-153],["_NORETURN",-153],["_ALIGNAS",-153],["__ATTRIBUTE__",-153],["STRUCT",-153],["UNION",-153],["COLON",-153],["COMMA",-153],["RPAREN",-153],["LBRACKET",-153]]],[366,[["SEMI",-167],["ID",-167],["LPAREN",-167],["TIMES",-167],["TYPEID",-167],["VOID",-167],["_BOOL",-167],["CHAR",-167],["SHORT",-167],["INT",-167],["LONG",-167],["FLOAT",-167],["DOUBLE",-167],["_COMPLEX",-167],["SIGNED",-167],["UNSIGNED",-167],["__INT128",-167],["_ATOMIC",-167],["CONST",-167],["RESTRICT",-167],["VOLATILE",-167],["_ALIGNAS",-167],["__ATTRIBUTE__",-167],["COLON",-167],["COMMA",-167],["RPAREN",-167],["LBRACKET",-167]]],[367,[["SEMI",-168],["ID",-168],["LPAREN",-168],["TIMES",-168],["TYPEID",-168],["VOID",-168],["_BOOL",-168],["CHAR",-168],["SHORT",-168],["INT",-168],["LONG",-168],["FLOAT",-168],["DOUBLE",-168],["_COMPLEX",-168],["SIGNED",-168],["UNSIGNED",-168],["__INT128",-168],["_ATOMIC",-168],["CONST",-168],["RESTRICT",-168],["VOLATILE",-168],["_ALIGNAS",-168],["__ATTRIBUTE__",-168],["COLON",-168],["COMMA",-168],["RPAREN",-168],["LBRACKET",-168]]],[368,[["SEMI",-172],["ID",-172],["LPAREN",-172],["TIMES",-172],["TYPEID",-172],["VOID",-172],["_BOOL",-172],["CHAR",-172],["SHORT",-172],["INT",-172],["LONG",-172],["FLOAT",-172],["DOUBLE",-172],["_COMPLEX",-172],["SIGNED",-172],["UNSIGNED",-172],["__INT128",-172],["_ATOMIC",-172],["CONST",-172],["RESTRICT",-172],["VOLATILE",-172],["_ALIGNAS",-172],["__ATTRIBUTE__",-172],["COLON",-172],["COMMA",-172],["RPAREN",-172],["LBRACKET",-172]]],[372,[["SEMI",-170],["ID",-170],["LPAREN",-170],["TIMES",-170],["TYPEID",-170],["VOID",-170],["_BOOL",-170],["CHAR",-170],["SHORT",-170],["INT",-170],["LONG",-170],["FLOAT",-170],["DOUBLE",-170],["_COMPLEX",-170],["SIGNED",-170],["UNSIGNED",-170],["__INT128",-170],["_ATOMIC",-170],["CONST",-170],["RESTRICT",-170],["VOLATILE",-170],["_ALIGNAS",-170],["__ATTRIBUTE__",-170],["COLON",-170],["COMMA",-170],["RPAREN",-170],["LBRACKET",-170]]],[376,[["SEMI",-151],["ID",-151],["LPAREN",-151],["TIMES",-151],["TYPEID",-151],["VOID",-151],["_BOOL",-151],["CHAR",-151],["SHORT",-151],["INT",-151],["LONG",-151],["FLOAT",-151],["DOUBLE",-151],["_COMPLEX",-151],["SIGNED",-151],["UNSIGNED",-151],["__INT128",-151],["_ATOMIC",-151],["CONST",-151],["RESTRICT",-151],["VOLATILE",-151],["AUTO",-151],["REGISTER",-151],["STATIC",-151],["EXTERN",-151],["TYPEDEF",-151],["_THREAD_LOCAL",-151],["INLINE",-151],["_NORETURN",-151],["_ALIGNAS",-151],["__ATTRIBUTE__",-151],["COLON",-151],["COMMA",-151],["RPAREN",-151],["LBRACKET",-151]]],[378,[["SEMI",-152],["ID",-152],["LPAREN",-152],["TIMES",-152],["TYPEID",-152],["VOID",-152],["_BOOL",-152],["CHAR",-152],["SHORT",-152],["INT",-152],["LONG",-152],["FLOAT",-152],["DOUBLE",-152],["_COMPLEX",-152],["SIGNED",-152],["UNSIGNED",-152],["__INT128",-152],["_ATOMIC",-152],["CONST",-152],["RESTRICT",-152],["VOLATILE",-152],["AUTO",-152],["REGISTER",-152],["STATIC",-152],["EXTERN",-152],["TYPEDEF",-152],["_THREAD_LOCAL",-152],["INLINE",-152],["_NORETURN",-152],["_ALIGNAS",-152],["__ATTRIBUTE__",-152],["COLON",-152],["COMMA",-152],["RPAREN",-152],["LBRACKET",-152]]],[391,[["SEMI",-199],["ID",-199],["LPAREN",-199],["TIMES",-199],["TYPEID",-199],["ENUM",-199],["VOID",-199],["_BOOL",-199],["CHAR",-199],["SHORT",-199],["INT",-199],["LONG",-199],["FLOAT",-199],["DOUBLE",-199],["_COMPLEX",-199],["SIGNED",-199],["UNSIGNED",-199],["__INT128",-199],["_ATOMIC",-199],["TYPEOF",-199],["CONST",-199],["RESTRICT",-199],["VOLATILE",-199],["AUTO",-199],["REGISTER",-199],["STATIC",-199],["EXTERN",-199],["TYPEDEF",-199],["_THREAD_LOCAL",-199],["INLINE",-199],["_NORETURN",-199],["_ALIGNAS",-199],["__ATTRIBUTE__",-199],["STRUCT",-199],["UNION",-199],["COLON",-199],["COMMA",-199],["RPAREN",-199],["LBRACKET",-199]]],[392,[["SEMI",-200],["ID",-200],["LPAREN",-200],["TIMES",-200],["TYPEID",-200],["ENUM",-200],["VOID",-200],["_BOOL",-200],["CHAR",-200],["SHORT",-200],["INT",-200],["LONG",-200],["FLOAT",-200],["DOUBLE",-200],["_COMPLEX",-200],["SIGNED",-200],["UNSIGNED",-200],["__INT128",-200],["_ATOMIC",-200],["TYPEOF",-200],["CONST",-200],["RESTRICT",-200],["VOLATILE",-200],["AUTO",-200],["REGISTER",-200],["STATIC",-200],["EXTERN",-200],["TYPEDEF",-200],["_THREAD_LOCAL",-200],["INLINE",-200],["_NORETURN",-200],["_ALIGNAS",-200],["__ATTRIBUTE__",-200],["STRUCT",-200],["UNION",-200],["COLON",-200],["COMMA",-200],["RPAREN",-200],["LBRACKET",-200]]],[400,[["SEMI",-249],["PPPRAGMA",-249],["_PRAGMA",-249],["_STATIC_ASSERT",-249],["ASM",-249],["ID",-249],["LPAREN",-249],["TIMES",-249],["TYPEID",-249],["ENUM",-249],["VOID",-249],["_BOOL",-249],["CHAR",-249],["SHORT",-249],["INT",-249],["LONG",-249],["FLOAT",-249],["DOUBLE",-249],["_COMPLEX",-249],["SIGNED",-249],["UNSIGNED",-249],["__INT128",-249],["_ATOMIC",-249],["TYPEOF",-249],["CONST",-249],["RESTRICT",-249],["VOLATILE",-249],["AUTO",-249],["REGISTER",-249],["STATIC",-249],["EXTERN",-249],["TYPEDEF",-249],["_THREAD_LOCAL",-249],["INLINE",-249],["_NORETURN",-249],["_ALIGNAS",-249],["__ATTRIBUTE__",-249],["STRUCT",-249],["UNION",-249],["LBRACE",-249],["CASE",-249],["DEFAULT",-249],["IF",-249],["SWITCH",-249],["WHILE",-249],["DO",-249],["FOR",-249],["GOTO",-249],["BREAK",-249],["CONTINUE",-249],["RETURN",-249],["PLUSPLUS",-249],["MINUSMINUS",-249],["SIZEOF",-249],["_ALIGNOF",-249],["AND",-249],["PLUS",-249],["MINUS",-249],["NOT",-249],["LNOT",-249],["OFFSETOF",-249],["INT_CONST_DEC",-249],["INT_CONST_OCT",-249],["INT_CONST_HEX",-249],["INT_CONST_BIN",-249],["INT_CONST_CHAR",-249],["FLOAT_CONST",-249],["HEX_FLOAT_CONST",-249],["CHAR_CONST",-249],["WCHAR_CONST",-249],["U8CHAR_CONST",-249],["U16CHAR_CONST",-249],["U32CHAR_CONST",-249],["STRING_LITERAL",-249],["WSTRING_LITERAL",-249],["U8STRING_LITERAL",-249],["U16STRING_LITERAL",-249],["U32STRING_LITERAL",-249],["RBRACE",-249]]],[401,[["SEMI",-25],["RPAREN",-25]]],[402,[["SEMI",-256],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["ENUM",-256],["VOID",-256],["_BOOL",-256],["CHAR",-256],["SHORT",-256],["INT",-256],["LONG",-256],["FLOAT",-256],["DOUBLE",-256],["_COMPLEX",-256],["SIGNED",-256],["UNSIGNED",-256],["__INT128",-256],["_ATOMIC",-256],["TYPEOF",-256],["CONST",-256],["RESTRICT",-256],["VOLATILE",-256],["AUTO",-256],["REGISTER",-256],["STATIC",-256],["EXTERN",-256],["TYPEDEF",-256],["_THREAD_LOCAL",-256],["INLINE",-256],["_NORETURN",-256],["_ALIGNAS",-256],["__ATTRIBUTE__",67],["STRUCT",-256],["UNION",-256],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACE",-256],["ELSE",-256]]],[403,[["SEMI",-257],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["ENUM",-257],["VOID",-257],["_BOOL",-257],["CHAR",-257],["SHORT",-257],["INT",-257],["LONG",-257],["FLOAT",-257],["DOUBLE",-257],["_COMPLEX",-257],["SIGNED",-257],["UNSIGNED",-257],["__INT128",-257],["_ATOMIC",-257],["TYPEOF",-257],["CONST",-257],["RESTRICT",-257],["VOLATILE",-257],["AUTO",-257],["REGISTER",-257],["STATIC",-257],["EXTERN",-257],["TYPEDEF",-257],["_THREAD_LOCAL",-257],["INLINE",-257],["_NORETURN",-257],["_ALIGNAS",-257],["__ATTRIBUTE__",67],["STRUCT",-257],["UNION",-257],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACE",-257],["ELSE",-257]]],[405,[["SEMI",-260],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["ENUM",-260],["VOID",-260],["_BOOL",-260],["CHAR",-260],["SHORT",-260],["INT",-260],["LONG",-260],["FLOAT",-260],["DOUBLE",-260],["_COMPLEX",-260],["SIGNED",-260],["UNSIGNED",-260],["__INT128",-260],["_ATOMIC",-260],["TYPEOF",-260],["CONST",-260],["RESTRICT",-260],["VOLATILE",-260],["AUTO",-260],["REGISTER",-260],["STATIC",-260],["EXTERN",-260],["TYPEDEF",-260],["_THREAD_LOCAL",-260],["INLINE",-260],["_NORETURN",-260],["_ALIGNAS",-260],["__ATTRIBUTE__",67],["STRUCT",-260],["UNION",-260],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACE",-260],["ELSE",-260]]],[406,[["SEMI",-274],["PPPRAGMA",-274],["_PRAGMA",-274],["_STATIC_ASSERT",-274],["ASM",-274],["ID",-274],["LPAREN",-274],["TIMES",-274],["TYPEID",-274],["ENUM",-274],["VOID",-274],["_BOOL",-274],["CHAR",-274],["SHORT",-274],["INT",-274],["LONG",-274],["FLOAT",-274],["DOUBLE",-274],["_COMPLEX",-274],["SIGNED",-274],["UNSIGNED",-274],["__INT128",-274],["_ATOMIC",-274],["TYPEOF",-274],["CONST",-274],["RESTRICT",-274],["VOLATILE",-274],["AUTO",-274],["REGISTER",-274],["STATIC",-274],["EXTERN",-274],["TYPEDEF",-274],["_THREAD_LOCAL",-274],["INLINE",-274],["_NORETURN",-274],["_ALIGNAS",-274],["__ATTRIBUTE__",-274],["STRUCT",-274],["UNION",-274],["LBRACE",-274],["CASE",-274],["DEFAULT",-274],["IF",-274],["SWITCH",-274],["WHILE",-274],["DO",-274],["FOR",-274],["GOTO",-274],["BREAK",-274],["CONTINUE",-274],["RETURN",-274],["PLUSPLUS",-274],["MINUSMINUS",-274],["SIZEOF",-274],["_ALIGNOF",-274],["AND",-274],["PLUS",-274],["MINUS",-274],["NOT",-274],["LNOT",-274],["OFFSETOF",-274],["INT_CONST_DEC",-274],["INT_CONST_OCT",-274],["INT_CONST_HEX",-274],["INT_CONST_BIN",-274],["INT_CONST_CHAR",-274],["FLOAT_CONST",-274],["HEX_FLOAT_CONST",-274],["CHAR_CONST",-274],["WCHAR_CONST",-274],["U8CHAR_CONST",-274],["U16CHAR_CONST",-274],["U32CHAR_CONST",-274],["STRING_LITERAL",-274],["WSTRING_LITERAL",-274],["U8STRING_LITERAL",-274],["U16STRING_LITERAL",-274],["U32STRING_LITERAL",-274],["RBRACE",-274],["ELSE",-274]]],[411,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["__ATTRIBUTE__",67],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[412,[["SEMI",-105],["PPPRAGMA",-105],["_PRAGMA",-105],["_STATIC_ASSERT",-105],["ASM",-105],["ID",-105],["LPAREN",-105],["TIMES",-105],["TYPEID",-105],["ENUM",-105],["VOID",-105],["_BOOL",-105],["CHAR",-105],["SHORT",-105],["INT",-105],["LONG",-105],["FLOAT",-105],["DOUBLE",-105],["_COMPLEX",-105],["SIGNED",-105],["UNSIGNED",-105],["__INT128",-105],["_ATOMIC",-105],["TYPEOF",-105],["CONST",-105],["RESTRICT",-105],["VOLATILE",-105],["AUTO",-105],["REGISTER",-105],["STATIC",-105],["EXTERN",-105],["TYPEDEF",-105],["_THREAD_LOCAL",-105],["INLINE",-105],["_NORETURN",-105],["_ALIGNAS",-105],["__ATTRIBUTE__",-105],["STRUCT",-105],["UNION",-105],["LBRACE",-105],["CASE",-105],["DEFAULT",-105],["IF",-105],["SWITCH",-105],["WHILE",-105],["DO",-105],["FOR",-105],["GOTO",-105],["BREAK",-105],["CONTINUE",-105],["RETURN",-105],["PLUSPLUS",-105],["MINUSMINUS",-105],["SIZEOF",-105],["_ALIGNOF",-105],["AND",-105],["PLUS",-105],["MINUS",-105],["NOT",-105],["LNOT",-105],["OFFSETOF",-105],["INT_CONST_DEC",-105],["INT_CONST_OCT",-105],["INT_CONST_HEX",-105],["INT_CONST_BIN",-105],["INT_CONST_CHAR",-105],["FLOAT_CONST",-105],["HEX_FLOAT_CONST",-105],["CHAR_CONST",-105],["WCHAR_CONST",-105],["U8CHAR_CONST",-105],["U16CHAR_CONST",-105],["U32CHAR_CONST",-105],["STRING_LITERAL",-105],["WSTRING_LITERAL",-105],["U8STRING_LITERAL",-105],["U16STRING_LITERAL",-105],["U32STRING_LITERAL",-105],["RBRACE",-105],["ELSE",-105]]],[413,[["SEMI",-90],["PPPRAGMA",-90],["_PRAGMA",-90],["_STATIC_ASSERT",-90],["ASM",-90],["ID",-90],["LPAREN",-90],["TIMES",-90],["TYPEID",-90],["ENUM",-100],["VOID",-100],["_BOOL",-100],["CHAR",-100],["SHORT",-100],["INT",-100],["LONG",-100],["FLOAT",-100],["DOUBLE",-100],["_COMPLEX",-100],["SIGNED",-100],["UNSIGNED",-100],["__INT128",-100],["_ATOMIC",-100],["TYPEOF",-100],["CONST",-100],["RESTRICT",-100],["VOLATILE",-100],["AUTO",-100],["REGISTER",-100],["STATIC",-100],["EXTERN",-100],["TYPEDEF",-100],["_THREAD_LOCAL",-100],["INLINE",-100],["_NORETURN",-100],["_ALIGNAS",-100],["__ATTRIBUTE__",-90],["STRUCT",-100],["UNION",-100],["LBRACE",-90],["CASE",-90],["DEFAULT",-90],["IF",-90],["SWITCH",-90],["WHILE",-90],["DO",-90],["FOR",-90],["GOTO",-90],["BREAK",-90],["CONTINUE",-90],["RETURN",-90],["PLUSPLUS",-90],["MINUSMINUS",-90],["SIZEOF",-90],["_ALIGNOF",-90],["AND",-90],["PLUS",-90],["MINUS",-90],["NOT",-90],["LNOT",-90],["OFFSETOF",-90],["INT_CONST_DEC",-90],["INT_CONST_OCT",-90],["INT_CONST_HEX",-90],["INT_CONST_BIN",-90],["INT_CONST_CHAR",-90],["FLOAT_CONST",-90],["HEX_FLOAT_CONST",-90],["CHAR_CONST",-90],["WCHAR_CONST",-90],["U8CHAR_CONST",-90],["U16CHAR_CONST",-90],["U32CHAR_CONST",-90],["STRING_LITERAL",-90],["WSTRING_LITERAL",-90],["U8STRING_LITERAL",-90],["U16STRING_LITERAL",-90],["U32STRING_LITERAL",-90],["RBRACE",-100],["ELSE",-100]]],[415,[["SEMI",-412],["ID",177],["LPAREN",231],["TIMES",166],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",78],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[416,[["SEMI",531]]],[417,[["SEMI",532]]],[418,[["SEMI",-270],["PPPRAGMA",-270],["_PRAGMA",-270],["_STATIC_ASSERT",-270],["ASM",-270],["ID",-270],["LPAREN",-270],["TIMES",-270],["TYPEID",-270],["ENUM",-270],["VOID",-270],["_BOOL",-270],["CHAR",-270],["SHORT",-270],["INT",-270],["LONG",-270],["FLOAT",-270],["DOUBLE",-270],["_COMPLEX",-270],["SIGNED",-270],["UNSIGNED",-270],["__INT128",-270],["_ATOMIC",-270],["TYPEOF",-270],["CONST",-270],["RESTRICT",-270],["VOLATILE",-270],["AUTO",-270],["REGISTER",-270],["STATIC",-270],["EXTERN",-270],["TYPEDEF",-270],["_THREAD_LOCAL",-270],["INLINE",-270],["_NORETURN",-270],["_ALIGNAS",-270],["__ATTRIBUTE__",-270],["STRUCT",-270],["UNION",-270],["LBRACE",-270],["CASE",-270],["DEFAULT",-270],["IF",-270],["SWITCH",-270],["WHILE",-270],["DO",-270],["FOR",-270],["GOTO",-270],["BREAK",-270],["CONTINUE",-270],["RETURN",-270],["PLUSPLUS",-270],["MINUSMINUS",-270],["SIZEOF",-270],["_ALIGNOF",-270],["AND",-270],["PLUS",-270],["MINUS",-270],["NOT",-270],["LNOT",-270],["OFFSETOF",-270],["INT_CONST_DEC",-270],["INT_CONST_OCT",-270],["INT_CONST_HEX",-270],["INT_CONST_BIN",-270],["INT_CONST_CHAR",-270],["FLOAT_CONST",-270],["HEX_FLOAT_CONST",-270],["CHAR_CONST",-270],["WCHAR_CONST",-270],["U8CHAR_CONST",-270],["U16CHAR_CONST",-270],["U32CHAR_CONST",-270],["STRING_LITERAL",-270],["WSTRING_LITERAL",-270],["U8STRING_LITERAL",-270],["U16STRING_LITERAL",-270],["U32STRING_LITERAL",-270],["RBRACE",-270],["ELSE",-270]]],[419,[["SEMI",-271],["PPPRAGMA",-271],["_PRAGMA",-271],["_STATIC_ASSERT",-271],["ASM",-271],["ID",-271],["LPAREN",-271],["TIMES",-271],["TYPEID",-271],["ENUM",-271],["VOID",-271],["_BOOL",-271],["CHAR",-271],["SHORT",-271],["INT",-271],["LONG",-271],["FLOAT",-271],["DOUBLE",-271],["_COMPLEX",-271],["SIGNED",-271],["UNSIGNED",-271],["__INT128",-271],["_ATOMIC",-271],["TYPEOF",-271],["CONST",-271],["RESTRICT",-271],["VOLATILE",-271],["AUTO",-271],["REGISTER",-271],["STATIC",-271],["EXTERN",-271],["TYPEDEF",-271],["_THREAD_LOCAL",-271],["INLINE",-271],["_NORETURN",-271],["_ALIGNAS",-271],["__ATTRIBUTE__",-271],["STRUCT",-271],["UNION",-271],["LBRACE",-271],["CASE",-271],["DEFAULT",-271],["IF",-271],["SWITCH",-271],["WHILE",-271],["DO",-271],["FOR",-271],["GOTO",-271],["BREAK",-271],["CONTINUE",-271],["RETURN",-271],["PLUSPLUS",-271],["MINUSMINUS",-271],["SIZEOF",-271],["_ALIGNOF",-271],["AND",-271],["PLUS",-271],["MINUS",-271],["NOT",-271],["LNOT",-271],["OFFSETOF",-271],["INT_CONST_DEC",-271],["INT_CONST_OCT",-271],["INT_CONST_HEX",-271],["INT_CONST_BIN",-271],["INT_CONST_CHAR",-271],["FLOAT_CONST",-271],["HEX_FLOAT_CONST",-271],["CHAR_CONST",-271],["WCHAR_CONST",-271],["U8CHAR_CONST",-271],["U16CHAR_CONST",-271],["U32CHAR_CONST",-271],["STRING_LITERAL",-271],["WSTRING_LITERAL",-271],["U8STRING_LITERAL",-271],["U16STRING_LITERAL",-271],["U32STRING_LITERAL",-271],["RBRACE",-271],["ELSE",-271]]],[420,[["SEMI",533],["COMMA",377]]],[421,[["SEMI",-273],["PPPRAGMA",-273],["_PRAGMA",-273],["_STATIC_ASSERT",-273],["ASM",-273],["ID",-273],["LPAREN",-273],["TIMES",-273],["TYPEID",-273],["ENUM",-273],["VOID",-273],["_BOOL",-273],["CHAR",-273],["SHORT",-273],["INT",-273],["LONG",-273],["FLOAT",-273],["DOUBLE",-273],["_COMPLEX",-273],["SIGNED",-273],["UNSIGNED",-273],["__INT128",-273],["_ATOMIC",-273],["TYPEOF",-273],["CONST",-273],["RESTRICT",-273],["VOLATILE",-273],["AUTO",-273],["REGISTER",-273],["STATIC",-273],["EXTERN",-273],["TYPEDEF",-273],["_THREAD_LOCAL",-273],["INLINE",-273],["_NORETURN",-273],["_ALIGNAS",-273],["__ATTRIBUTE__",-273],["STRUCT",-273],["UNION",-273],["LBRACE",-273],["CASE",-273],["DEFAULT",-273],["IF",-273],["SWITCH",-273],["WHILE",-273],["DO",-273],["FOR",-273],["GOTO",-273],["BREAK",-273],["CONTINUE",-273],["RETURN",-273],["PLUSPLUS",-273],["MINUSMINUS",-273],["SIZEOF",-273],["_ALIGNOF",-273],["AND",-273],["PLUS",-273],["MINUS",-273],["NOT",-273],["LNOT",-273],["OFFSETOF",-273],["INT_CONST_DEC",-273],["INT_CONST_OCT",-273],["INT_CONST_HEX",-273],["INT_CONST_BIN",-273],["INT_CONST_CHAR",-273],["FLOAT_CONST",-273],["HEX_FLOAT_CONST",-273],["CHAR_CONST",-273],["WCHAR_CONST",-273],["U8CHAR_CONST",-273],["U16CHAR_CONST",-273],["U32CHAR_CONST",-273],["STRING_LITERAL",-273],["WSTRING_LITERAL",-273],["U8STRING_LITERAL",-273],["U16STRING_LITERAL",-273],["U32STRING_LITERAL",-273],["RBRACE",-273],["ELSE",-273]]],[425,[["SEMI",-380],["PPPRAGMA",-380],["_PRAGMA",-380],["_STATIC_ASSERT",-380],["ASM",-380],["ID",-380],["LPAREN",-380],["TIMES",-380],["TYPEID",-380],["ENUM",-380],["VOID",-380],["_BOOL",-380],["CHAR",-380],["SHORT",-380],["INT",-380],["LONG",-380],["FLOAT",-380],["DOUBLE",-380],["_COMPLEX",-380],["SIGNED",-380],["UNSIGNED",-380],["__INT128",-380],["_ATOMIC",-380],["TYPEOF",-380],["CONST",-380],["RESTRICT",-380],["VOLATILE",-380],["AUTO",-380],["REGISTER",-380],["STATIC",-380],["EXTERN",-380],["TYPEDEF",-380],["_THREAD_LOCAL",-380],["INLINE",-380],["_NORETURN",-380],["_ALIGNAS",-380],["__ATTRIBUTE__",-380],["STRUCT",-380],["UNION",-380],["LBRACE",-380],["CASE",-380],["DEFAULT",-380],["IF",-380],["SWITCH",-380],["WHILE",-380],["DO",-380],["FOR",-380],["GOTO",-380],["BREAK",-380],["CONTINUE",-380],["RETURN",-380],["PLUSPLUS",-380],["MINUSMINUS",-380],["SIZEOF",-380],["_ALIGNOF",-380],["AND",-380],["PLUS",-380],["MINUS",-380],["NOT",-380],["LNOT",-380],["OFFSETOF",-380],["INT_CONST_DEC",-380],["INT_CONST_OCT",-380],["INT_CONST_HEX",-380],["INT_CONST_BIN",-380],["INT_CONST_CHAR",-380],["FLOAT_CONST",-380],["HEX_FLOAT_CONST",-380],["CHAR_CONST",-380],["WCHAR_CONST",-380],["U8CHAR_CONST",-380],["U16CHAR_CONST",-380],["U32CHAR_CONST",-380],["STRING_LITERAL",-380],["WSTRING_LITERAL",-380],["U8STRING_LITERAL",-380],["U16STRING_LITERAL",-380],["U32STRING_LITERAL",-380],["RBRACE",-380],["ELSE",-380]]],[433,[["SEMI",-57],["ASM",-57],["LPAREN",-57],["__ATTRIBUTE__",-57],["EQUALS",-57],["COLON",-57],["COMMA",-57],["RPAREN",-57],["LBRACKET",-57]]],[434,[["SEMI",-58],["ASM",-58],["LPAREN",-58],["__ATTRIBUTE__",-58],["EQUALS",-58],["COLON",-58],["COMMA",-58],["RPAREN",-58],["LBRACKET",-58]]],[436,[["SEMI",-344],["LPAREN",-344],["TIMES",-344],["PLUSPLUS",-344],["MINUSMINUS",-344],["AND",-344],["PLUS",-344],["MINUS",-344],["RBRACE",-344],["EQUALS",-344],["COLON",-344],["COMMA",-344],["RPAREN",-344],["LBRACKET",-344],["RBRACKET",-344],["PERIOD",-344],["ARROW",-344],["CONDOP",-344],["DIVIDE",-344],["MOD",-344],["RSHIFT",-344],["LSHIFT",-344],["LT",-344],["LE",-344],["GE",-344],["GT",-344],["EQ",-344],["NE",-344],["OR",-344],["XOR",-344],["LAND",-344],["LOR",-344],["XOREQUAL",-344],["TIMESEQUAL",-344],["DIVEQUAL",-344],["MODEQUAL",-344],["PLUSEQUAL",-344],["MINUSEQUAL",-344],["LSHIFTEQUAL",-344],["RSHIFTEQUAL",-344],["ANDEQUAL",-344],["OREQUAL",-344],["ELLIPSIS",-344]]],[439,[["SEMI",-296],["TIMES",-296],["AND",-296],["PLUS",-296],["MINUS",-296],["RBRACE",-296],["COLON",-296],["COMMA",-296],["RPAREN",-296],["RBRACKET",-296],["CONDOP",-296],["DIVIDE",-296],["MOD",-296],["RSHIFT",-296],["LSHIFT",-296],["LT",-296],["LE",-296],["GE",-296],["GT",-296],["EQ",-296],["NE",-296],["OR",-296],["XOR",-296],["LAND",-296],["LOR",-296],["ELLIPSIS",-296]]],[440,[["SEMI",-297],["TIMES",-297],["AND",-297],["PLUS",-297],["MINUS",-297],["RBRACE",-297],["COLON",-297],["COMMA",-297],["RPAREN",-297],["RBRACKET",-297],["CONDOP",-297],["DIVIDE",-297],["MOD",-297],["RSHIFT",-297],["LSHIFT",-297],["LT",-297],["LE",-297],["GE",-297],["GT",-297],["EQ",-297],["NE",-297],["OR",-297],["XOR",-297],["LAND",-297],["LOR",-297],["ELLIPSIS",-297]]],[441,[["SEMI",-298],["TIMES",-298],["AND",-298],["PLUS",-298],["MINUS",-298],["RBRACE",-298],["COLON",-298],["COMMA",-298],["RPAREN",-298],["RBRACKET",-298],["CONDOP",-298],["DIVIDE",-298],["MOD",-298],["RSHIFT",-298],["LSHIFT",-298],["LT",-298],["LE",-298],["GE",-298],["GT",-298],["EQ",-298],["NE",-298],["OR",-298],["XOR",-298],["LAND",-298],["LOR",-298],["ELLIPSIS",-298]]],[442,[["SEMI",-299],["TIMES",292],["AND",-299],["PLUS",-299],["MINUS",-299],["RBRACE",-299],["COLON",-299],["COMMA",-299],["RPAREN",-299],["RBRACKET",-299],["CONDOP",-299],["DIVIDE",293],["MOD",294],["RSHIFT",-299],["LSHIFT",-299],["LT",-299],["LE",-299],["GE",-299],["GT",-299],["EQ",-299],["NE",-299],["OR",-299],["XOR",-299],["LAND",-299],["LOR",-299],["ELLIPSIS",-299]]],[443,[["SEMI",-300],["TIMES",292],["AND",-300],["PLUS",-300],["MINUS",-300],["RBRACE",-300],["COLON",-300],["COMMA",-300],["RPAREN",-300],["RBRACKET",-300],["CONDOP",-300],["DIVIDE",293],["MOD",294],["RSHIFT",-300],["LSHIFT",-300],["LT",-300],["LE",-300],["GE",-300],["GT",-300],["EQ",-300],["NE",-300],["OR",-300],["XOR",-300],["LAND",-300],["LOR",-300],["ELLIPSIS",-300]]],[444,[["SEMI",-301],["TIMES",292],["AND",-301],["PLUS",295],["MINUS",296],["RBRACE",-301],["COLON",-301],["COMMA",-301],["RPAREN",-301],["RBRACKET",-301],["CONDOP",-301],["DIVIDE",293],["MOD",294],["RSHIFT",-301],["LSHIFT",-301],["LT",-301],["LE",-301],["GE",-301],["GT",-301],["EQ",-301],["NE",-301],["OR",-301],["XOR",-301],["LAND",-301],["LOR",-301],["ELLIPSIS",-301]]],[445,[["SEMI",-302],["TIMES",292],["AND",-302],["PLUS",295],["MINUS",296],["RBRACE",-302],["COLON",-302],["COMMA",-302],["RPAREN",-302],["RBRACKET",-302],["CONDOP",-302],["DIVIDE",293],["MOD",294],["RSHIFT",-302],["LSHIFT",-302],["LT",-302],["LE",-302],["GE",-302],["GT",-302],["EQ",-302],["NE",-302],["OR",-302],["XOR",-302],["LAND",-302],["LOR",-302],["ELLIPSIS",-302]]],[446,[["SEMI",-303],["TIMES",292],["AND",-303],["PLUS",295],["MINUS",296],["RBRACE",-303],["COLON",-303],["COMMA",-303],["RPAREN",-303],["RBRACKET",-303],["CONDOP",-303],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",-303],["LE",-303],["GE",-303],["GT",-303],["EQ",-303],["NE",-303],["OR",-303],["XOR",-303],["LAND",-303],["LOR",-303],["ELLIPSIS",-303]]],[447,[["SEMI",-304],["TIMES",292],["AND",-304],["PLUS",295],["MINUS",296],["RBRACE",-304],["COLON",-304],["COMMA",-304],["RPAREN",-304],["RBRACKET",-304],["CONDOP",-304],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",-304],["LE",-304],["GE",-304],["GT",-304],["EQ",-304],["NE",-304],["OR",-304],["XOR",-304],["LAND",-304],["LOR",-304],["ELLIPSIS",-304]]],[448,[["SEMI",-305],["TIMES",292],["AND",-305],["PLUS",295],["MINUS",296],["RBRACE",-305],["COLON",-305],["COMMA",-305],["RPAREN",-305],["RBRACKET",-305],["CONDOP",-305],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",-305],["LE",-305],["GE",-305],["GT",-305],["EQ",-305],["NE",-305],["OR",-305],["XOR",-305],["LAND",-305],["LOR",-305],["ELLIPSIS",-305]]],[449,[["SEMI",-306],["TIMES",292],["AND",-306],["PLUS",295],["MINUS",296],["RBRACE",-306],["COLON",-306],["COMMA",-306],["RPAREN",-306],["RBRACKET",-306],["CONDOP",-306],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",-306],["LE",-306],["GE",-306],["GT",-306],["EQ",-306],["NE",-306],["OR",-306],["XOR",-306],["LAND",-306],["LOR",-306],["ELLIPSIS",-306]]],[450,[["SEMI",-307],["TIMES",292],["AND",-307],["PLUS",295],["MINUS",296],["RBRACE",-307],["COLON",-307],["COMMA",-307],["RPAREN",-307],["RBRACKET",-307],["CONDOP",-307],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",299],["LE",300],["GE",301],["GT",302],["EQ",-307],["NE",-307],["OR",-307],["XOR",-307],["LAND",-307],["LOR",-307],["ELLIPSIS",-307]]],[451,[["SEMI",-308],["TIMES",292],["AND",-308],["PLUS",295],["MINUS",296],["RBRACE",-308],["COLON",-308],["COMMA",-308],["RPAREN",-308],["RBRACKET",-308],["CONDOP",-308],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",299],["LE",300],["GE",301],["GT",302],["EQ",-308],["NE",-308],["OR",-308],["XOR",-308],["LAND",-308],["LOR",-308],["ELLIPSIS",-308]]],[452,[["SEMI",-309],["TIMES",292],["AND",-309],["PLUS",295],["MINUS",296],["RBRACE",-309],["COLON",-309],["COMMA",-309],["RPAREN",-309],["RBRACKET",-309],["CONDOP",-309],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",299],["LE",300],["GE",301],["GT",302],["EQ",303],["NE",304],["OR",-309],["XOR",-309],["LAND",-309],["LOR",-309],["ELLIPSIS",-309]]],[453,[["SEMI",-310],["TIMES",292],["AND",305],["PLUS",295],["MINUS",296],["RBRACE",-310],["COLON",-310],["COMMA",-310],["RPAREN",-310],["RBRACKET",-310],["CONDOP",-310],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",299],["LE",300],["GE",301],["GT",302],["EQ",303],["NE",304],["OR",-310],["XOR",307],["LAND",-310],["LOR",-310],["ELLIPSIS",-310]]],[454,[["SEMI",-311],["TIMES",292],["AND",305],["PLUS",295],["MINUS",296],["RBRACE",-311],["COLON",-311],["COMMA",-311],["RPAREN",-311],["RBRACKET",-311],["CONDOP",-311],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",299],["LE",300],["GE",301],["GT",302],["EQ",303],["NE",304],["OR",-311],["XOR",-311],["LAND",-311],["LOR",-311],["ELLIPSIS",-311]]],[455,[["SEMI",-312],["TIMES",292],["AND",305],["PLUS",295],["MINUS",296],["RBRACE",-312],["COLON",-312],["COMMA",-312],["RPAREN",-312],["RBRACKET",-312],["CONDOP",-312],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",299],["LE",300],["GE",301],["GT",302],["EQ",303],["NE",304],["OR",306],["XOR",307],["LAND",-312],["LOR",-312],["ELLIPSIS",-312]]],[456,[["SEMI",-313],["TIMES",292],["AND",305],["PLUS",295],["MINUS",296],["RBRACE",-313],["COLON",-313],["COMMA",-313],["RPAREN",-313],["RBRACKET",-313],["CONDOP",-313],["DIVIDE",293],["MOD",294],["RSHIFT",297],["LSHIFT",298],["LT",299],["LE",300],["GE",301],["GT",302],["EQ",303],["NE",304],["OR",306],["XOR",307],["LAND",308],["LOR",-313],["ELLIPSIS",-313]]],[459,[["SEMI",-331],["LPAREN",-331],["TIMES",-331],["PLUSPLUS",-331],["MINUSMINUS",-331],["AND",-331],["PLUS",-331],["MINUS",-331],["RBRACE",-331],["EQUALS",-331],["COLON",-331],["COMMA",-331],["RPAREN",-331],["LBRACKET",-331],["RBRACKET",-331],["PERIOD",-331],["ARROW",-331],["CONDOP",-331],["DIVIDE",-331],["MOD",-331],["RSHIFT",-331],["LSHIFT",-331],["LT",-331],["LE",-331],["GE",-331],["GT",-331],["EQ",-331],["NE",-331],["OR",-331],["XOR",-331],["LAND",-331],["LOR",-331],["XOREQUAL",-331],["TIMESEQUAL",-331],["DIVEQUAL",-331],["MODEQUAL",-331],["PLUSEQUAL",-331],["MINUSEQUAL",-331],["LSHIFTEQUAL",-331],["RSHIFTEQUAL",-331],["ANDEQUAL",-331],["OREQUAL",-331],["ELLIPSIS",-331]]],[461,[["SEMI",-332],["LPAREN",-332],["TIMES",-332],["PLUSPLUS",-332],["MINUSMINUS",-332],["AND",-332],["PLUS",-332],["MINUS",-332],["RBRACE",-332],["EQUALS",-332],["COLON",-332],["COMMA",-332],["RPAREN",-332],["LBRACKET",-332],["RBRACKET",-332],["PERIOD",-332],["ARROW",-332],["CONDOP",-332],["DIVIDE",-332],["MOD",-332],["RSHIFT",-332],["LSHIFT",-332],["LT",-332],["LE",-332],["GE",-332],["GT",-332],["EQ",-332],["NE",-332],["OR",-332],["XOR",-332],["LAND",-332],["LOR",-332],["XOREQUAL",-332],["TIMESEQUAL",-332],["DIVEQUAL",-332],["MODEQUAL",-332],["PLUSEQUAL",-332],["MINUSEQUAL",-332],["LSHIFTEQUAL",-332],["RSHIFTEQUAL",-332],["ANDEQUAL",-332],["OREQUAL",-332],["ELLIPSIS",-332]]],[462,[["SEMI",-333],["LPAREN",-333],["TIMES",-333],["PLUSPLUS",-333],["MINUSMINUS",-333],["AND",-333],["PLUS",-333],["MINUS",-333],["RBRACE",-333],["EQUALS",-333],["COLON",-333],["COMMA",-333],["RPAREN",-333],["LBRACKET",-333],["RBRACKET",-333],["PERIOD",-333],["ARROW",-333],["CONDOP",-333],["DIVIDE",-333],["MOD",-333],["RSHIFT",-333],["LSHIFT",-333],["LT",-333],["LE",-333],["GE",-333],["GT",-333],["EQ",-333],["NE",-333],["OR",-333],["XOR",-333],["LAND",-333],["LOR",-333],["XOREQUAL",-333],["TIMESEQUAL",-333],["DIVEQUAL",-333],["MODEQUAL",-333],["PLUSEQUAL",-333],["MINUSEQUAL",-333],["LSHIFTEQUAL",-333],["RSHIFTEQUAL",-333],["ANDEQUAL",-333],["OREQUAL",-333],["ELLIPSIS",-333]]],[463,[["SEMI",-334],["LPAREN",-334],["TIMES",-334],["PLUSPLUS",-334],["MINUSMINUS",-334],["AND",-334],["PLUS",-334],["MINUS",-334],["RBRACE",-334],["EQUALS",-334],["COLON",-334],["COMMA",-334],["RPAREN",-334],["LBRACKET",-334],["RBRACKET",-334],["PERIOD",-334],["ARROW",-334],["CONDOP",-334],["DIVIDE",-334],["MOD",-334],["RSHIFT",-334],["LSHIFT",-334],["LT",-334],["LE",-334],["GE",-334],["GT",-334],["EQ",-334],["NE",-334],["OR",-334],["XOR",-334],["LAND",-334],["LOR",-334],["XOREQUAL",-334],["TIMESEQUAL",-334],["DIVEQUAL",-334],["MODEQUAL",-334],["PLUSEQUAL",-334],["MINUSEQUAL",-334],["LSHIFTEQUAL",-334],["RSHIFTEQUAL",-334],["ANDEQUAL",-334],["OREQUAL",-334],["ELLIPSIS",-334]]],[464,[["SEMI",-335],["LPAREN",-335],["TIMES",-335],["PLUSPLUS",-335],["MINUSMINUS",-335],["AND",-335],["PLUS",-335],["MINUS",-335],["RBRACE",-335],["EQUALS",-335],["COLON",-335],["COMMA",-335],["RPAREN",-335],["LBRACKET",-335],["RBRACKET",-335],["PERIOD",-335],["ARROW",-335],["CONDOP",-335],["DIVIDE",-335],["MOD",-335],["RSHIFT",-335],["LSHIFT",-335],["LT",-335],["LE",-335],["GE",-335],["GT",-335],["EQ",-335],["NE",-335],["OR",-335],["XOR",-335],["LAND",-335],["LOR",-335],["XOREQUAL",-335],["TIMESEQUAL",-335],["DIVEQUAL",-335],["MODEQUAL",-335],["PLUSEQUAL",-335],["MINUSEQUAL",-335],["LSHIFTEQUAL",-335],["RSHIFTEQUAL",-335],["ANDEQUAL",-335],["OREQUAL",-335],["ELLIPSIS",-335]]],[469,[["SEMI",-45],["ASM",-45],["LPAREN",-45],["TYPEID",-45],["ENUM",-45],["VOID",-45],["_BOOL",-45],["CHAR",-45],["SHORT",-45],["INT",-45],["LONG",-45],["FLOAT",-45],["DOUBLE",-45],["_COMPLEX",-45],["SIGNED",-45],["UNSIGNED",-45],["__INT128",-45],["_ATOMIC",-45],["TYPEOF",-45],["CONST",-45],["RESTRICT",-45],["VOLATILE",-45],["AUTO",-45],["REGISTER",-45],["STATIC",-45],["EXTERN",-45],["TYPEDEF",-45],["_THREAD_LOCAL",-45],["INLINE",-45],["_NORETURN",-45],["_ALIGNAS",-45],["__ATTRIBUTE__",-45],["STRUCT",-45],["UNION",-45],["LBRACE",-45],["EQUALS",-45],["COLON",-45],["COMMA",-45],["RPAREN",-45],["LBRACKET",-45]]],[470,[["SEMI",-48],["ASM",-48],["LPAREN",-48],["TYPEID",-48],["ENUM",-48],["VOID",-48],["_BOOL",-48],["CHAR",-48],["SHORT",-48],["INT",-48],["LONG",-48],["FLOAT",-48],["DOUBLE",-48],["_COMPLEX",-48],["SIGNED",-48],["UNSIGNED",-48],["__INT128",-48],["_ATOMIC",-48],["TYPEOF",-48],["CONST",-48],["RESTRICT",-48],["VOLATILE",-48],["AUTO",-48],["REGISTER",-48],["STATIC",-48],["EXTERN",-48],["TYPEDEF",-48],["_THREAD_LOCAL",-48],["INLINE",-48],["_NORETURN",-48],["_ALIGNAS",-48],["__ATTRIBUTE__",-48],["STRUCT",-48],["UNION",-48],["LBRACE",-48],["EQUALS",-48],["COLON",-48],["COMMA",-48],["RPAREN",-48],["LBRACKET",-48]]],[495,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",-412],["CONST",-412],["RESTRICT",-412],["VOLATILE",-412],["AUTO",-412],["REGISTER",-412],["STATIC",-412],["EXTERN",-412],["TYPEDEF",-412],["_THREAD_LOCAL",-412],["INLINE",-412],["_NORETURN",-412],["_ALIGNAS",-412],["__ATTRIBUTE__",67],["COLON",-412],["COMMA",-412],["RPAREN",-412],["LBRACKET",-412]]],[498,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",-412],["CONST",-412],["RESTRICT",-412],["VOLATILE",-412],["AUTO",-412],["REGISTER",-412],["STATIC",-412],["EXTERN",-412],["TYPEDEF",-412],["_THREAD_LOCAL",-412],["INLINE",-412],["_NORETURN",-412],["_ALIGNAS",-412],["__ATTRIBUTE__",67],["COLON",-412],["COMMA",-412],["RPAREN",-412],["LBRACKET",-412]]],[499,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",-412],["CONST",-412],["RESTRICT",-412],["VOLATILE",-412],["AUTO",-412],["REGISTER",-412],["STATIC",-412],["EXTERN",-412],["TYPEDEF",-412],["_THREAD_LOCAL",-412],["INLINE",-412],["_NORETURN",-412],["_ALIGNAS",-412],["__ATTRIBUTE__",67],["COLON",-412],["COMMA",-412],["RPAREN",-412],["LBRACKET",-412]]],[500,[["SEMI",-183],["PPPRAGMA",-183],["_PRAGMA",-183],["TYPEID",-183],["ENUM",-183],["VOID",-183],["_BOOL",-183],["CHAR",-183],["SHORT",-183],["INT",-183],["LONG",-183],["FLOAT",-183],["DOUBLE",-183],["_COMPLEX",-183],["SIGNED",-183],["UNSIGNED",-183],["__INT128",-183],["_ATOMIC",-183],["TYPEOF",-183],["CONST",-183],["RESTRICT",-183],["VOLATILE",-183],["_ALIGNAS",-183],["__ATTRIBUTE__",-183],["STRUCT",-183],["UNION",-183],["RBRACE",-183]]],[501,[["SEMI",-177],["ID",-177],["LPAREN",-177],["TIMES",-177],["TYPEID",-177],["VOID",-177],["_BOOL",-177],["CHAR",-177],["SHORT",-177],["INT",-177],["LONG",-177],["FLOAT",-177],["DOUBLE",-177],["_COMPLEX",-177],["SIGNED",-177],["UNSIGNED",-177],["__INT128",-177],["_ATOMIC",-177],["CONST",-177],["RESTRICT",-177],["VOLATILE",-177],["AUTO",-177],["REGISTER",-177],["STATIC",-177],["EXTERN",-177],["TYPEDEF",-177],["_THREAD_LOCAL",-177],["INLINE",-177],["_NORETURN",-177],["_ALIGNAS",-177],["__ATTRIBUTE__",-177],["COLON",-177],["COMMA",-177],["RPAREN",-177],["LBRACKET",-177]]],[502,[["SEMI",579]]],[503,[["SEMI",-173],["ID",-173],["LPAREN",-173],["TIMES",-173],["TYPEID",-173],["VOID",-173],["_BOOL",-173],["CHAR",-173],["SHORT",-173],["INT",-173],["LONG",-173],["FLOAT",-173],["DOUBLE",-173],["_COMPLEX",-173],["SIGNED",-173],["UNSIGNED",-173],["__INT128",-173],["_ATOMIC",-173],["CONST",-173],["RESTRICT",-173],["VOLATILE",-173],["_ALIGNAS",-173],["__ATTRIBUTE__",-173],["COLON",-173]]],[504,[["SEMI",-39],["COLON",-27]]],[505,[["SEMI",-40],["COMMA",580]]],[506,[["SEMI",-187],["COMMA",-187]]],[507,[["SEMI",-412],["__ATTRIBUTE__",67],["COLON",-412],["COMMA",-412]]],[509,[["SEMI",-412],["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["VOID",-412],["_BOOL",-412],["CHAR",-412],["SHORT",-412],["INT",-412],["LONG",-412],["FLOAT",-412],["DOUBLE",-412],["_COMPLEX",-412],["SIGNED",-412],["UNSIGNED",-412],["__INT128",-412],["_ATOMIC",-412],["CONST",-412],["RESTRICT",-412],["VOLATILE",-412],["AUTO",-412],["REGISTER",-412],["STATIC",-412],["EXTERN",-412],["TYPEDEF",-412],["_THREAD_LOCAL",-412],["INLINE",-412],["_NORETURN",-412],["_ALIGNAS",-412],["__ATTRIBUTE__",67],["COLON",-412],["COMMA",-412],["RPAREN",-412],["LBRACKET",-412]]],[510,[["SEMI",-179],["ID",-179],["LPAREN",-179],["TIMES",-179],["TYPEID",-179],["VOID",-179],["_BOOL",-179],["CHAR",-179],["SHORT",-179],["INT",-179],["LONG",-179],["FLOAT",-179],["DOUBLE",-179],["_COMPLEX",-179],["SIGNED",-179],["UNSIGNED",-179],["__INT128",-179],["_ATOMIC",-179],["CONST",-179],["RESTRICT",-179],["VOLATILE",-179],["AUTO",-179],["REGISTER",-179],["STATIC",-179],["EXTERN",-179],["TYPEDEF",-179],["_THREAD_LOCAL",-179],["INLINE",-179],["_NORETURN",-179],["_ALIGNAS",-179],["__ATTRIBUTE__",-179],["COLON",-179],["COMMA",-179],["RPAREN",-179],["LBRACKET",-179]]],[511,[["SEMI",-277],["RBRACE",-277],["COLON",-277],["COMMA",-277],["RPAREN",-277],["RBRACKET",-277]]],[512,[["SEMI",-276],["COLON",-276],["COMMA",-276],["RPAREN",-276],["RBRACKET",-276]]],[513,[["SEMI",-280],["RBRACE",-280],["COLON",-280],["COMMA",-280],["RPAREN",-280],["RBRACKET",-280]]],[518,[["SEMI",-251],["PPPRAGMA",-251],["_PRAGMA",-251],["_STATIC_ASSERT",-251],["ASM",-251],["ID",-251],["LPAREN",-251],["TIMES",-251],["TYPEID",-251],["ENUM",-251],["VOID",-251],["_BOOL",-251],["CHAR",-251],["SHORT",-251],["INT",-251],["LONG",-251],["FLOAT",-251],["DOUBLE",-251],["_COMPLEX",-251],["SIGNED",-251],["UNSIGNED",-251],["__INT128",-251],["_ATOMIC",-251],["TYPEOF",-251],["CONST",-251],["RESTRICT",-251],["VOLATILE",-251],["AUTO",-251],["REGISTER",-251],["STATIC",-251],["EXTERN",-251],["TYPEDEF",-251],["_THREAD_LOCAL",-251],["INLINE",-251],["_NORETURN",-251],["_ALIGNAS",-251],["__ATTRIBUTE__",-251],["STRUCT",-251],["UNION",-251],["LBRACE",-251],["CASE",-251],["DEFAULT",-251],["IF",-251],["SWITCH",-251],["WHILE",-251],["DO",-251],["FOR",-251],["GOTO",-251],["BREAK",-251],["CONTINUE",-251],["RETURN",-251],["PLUSPLUS",-251],["MINUSMINUS",-251],["SIZEOF",-251],["_ALIGNOF",-251],["AND",-251],["PLUS",-251],["MINUS",-251],["NOT",-251],["LNOT",-251],["OFFSETOF",-251],["INT_CONST_DEC",-251],["INT_CONST_OCT",-251],["INT_CONST_HEX",-251],["INT_CONST_BIN",-251],["INT_CONST_CHAR",-251],["FLOAT_CONST",-251],["HEX_FLOAT_CONST",-251],["CHAR_CONST",-251],["WCHAR_CONST",-251],["U8CHAR_CONST",-251],["U16CHAR_CONST",-251],["U32CHAR_CONST",-251],["STRING_LITERAL",-251],["WSTRING_LITERAL",-251],["U8STRING_LITERAL",-251],["U16STRING_LITERAL",-251],["U32STRING_LITERAL",-251],["RBRACE",-251],["ELSE",-251]]],[519,[["SEMI",-252],["PPPRAGMA",-252],["_PRAGMA",-252],["_STATIC_ASSERT",-252],["ASM",-252],["ID",-252],["LPAREN",-252],["TIMES",-252],["TYPEID",-252],["ENUM",-252],["VOID",-252],["_BOOL",-252],["CHAR",-252],["SHORT",-252],["INT",-252],["LONG",-252],["FLOAT",-252],["DOUBLE",-252],["_COMPLEX",-252],["SIGNED",-252],["UNSIGNED",-252],["__INT128",-252],["_ATOMIC",-252],["TYPEOF",-252],["CONST",-252],["RESTRICT",-252],["VOLATILE",-252],["AUTO",-252],["REGISTER",-252],["STATIC",-252],["EXTERN",-252],["TYPEDEF",-252],["_THREAD_LOCAL",-252],["INLINE",-252],["_NORETURN",-252],["_ALIGNAS",-252],["__ATTRIBUTE__",-252],["STRUCT",-252],["UNION",-252],["LBRACE",-252],["CASE",-252],["DEFAULT",-252],["IF",-252],["SWITCH",-252],["WHILE",-252],["DO",-252],["FOR",-252],["GOTO",-252],["BREAK",-252],["CONTINUE",-252],["RETURN",-252],["PLUSPLUS",-252],["MINUSMINUS",-252],["SIZEOF",-252],["_ALIGNOF",-252],["AND",-252],["PLUS",-252],["MINUS",-252],["NOT",-252],["LNOT",-252],["OFFSETOF",-252],["INT_CONST_DEC",-252],["INT_CONST_OCT",-252],["INT_CONST_HEX",-252],["INT_CONST_BIN",-252],["INT_CONST_CHAR",-252],["FLOAT_CONST",-252],["HEX_FLOAT_CONST",-252],["CHAR_CONST",-252],["WCHAR_CONST",-252],["U8CHAR_CONST",-252],["U16CHAR_CONST",-252],["U32CHAR_CONST",-252],["STRING_LITERAL",-252],["WSTRING_LITERAL",-252],["U8STRING_LITERAL",-252],["U16STRING_LITERAL",-252],["U32STRING_LITERAL",-252],["RBRACE",-252],["ELSE",-252]]],[520,[["SEMI",-258],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["ENUM",-258],["VOID",-258],["_BOOL",-258],["CHAR",-258],["SHORT",-258],["INT",-258],["LONG",-258],["FLOAT",-258],["DOUBLE",-258],["_COMPLEX",-258],["SIGNED",-258],["UNSIGNED",-258],["__INT128",-258],["_ATOMIC",-258],["TYPEOF",-258],["CONST",-258],["RESTRICT",-258],["VOLATILE",-258],["AUTO",-258],["REGISTER",-258],["STATIC",-258],["EXTERN",-258],["TYPEDEF",-258],["_THREAD_LOCAL",-258],["INLINE",-258],["_NORETURN",-258],["_ALIGNAS",-258],["__ATTRIBUTE__",67],["STRUCT",-258],["UNION",-258],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACE",-258],["ELSE",-258]]],[522,[["SEMI",-255],["PPPRAGMA",-255],["_PRAGMA",-255],["_STATIC_ASSERT",-255],["ASM",-255],["ID",-255],["LPAREN",-255],["TIMES",-255],["TYPEID",-255],["ENUM",-255],["VOID",-255],["_BOOL",-255],["CHAR",-255],["SHORT",-255],["INT",-255],["LONG",-255],["FLOAT",-255],["DOUBLE",-255],["_COMPLEX",-255],["SIGNED",-255],["UNSIGNED",-255],["__INT128",-255],["_ATOMIC",-255],["TYPEOF",-255],["CONST",-255],["RESTRICT",-255],["VOLATILE",-255],["AUTO",-255],["REGISTER",-255],["STATIC",-255],["EXTERN",-255],["TYPEDEF",-255],["_THREAD_LOCAL",-255],["INLINE",-255],["_NORETURN",-255],["_ALIGNAS",-255],["__ATTRIBUTE__",-255],["STRUCT",-255],["UNION",-255],["LBRACE",-255],["CASE",-255],["DEFAULT",-255],["IF",-255],["SWITCH",-255],["WHILE",-255],["DO",-255],["FOR",-255],["GOTO",-255],["BREAK",-255],["CONTINUE",-255],["RETURN",-255],["PLUSPLUS",-255],["MINUSMINUS",-255],["SIZEOF",-255],["_ALIGNOF",-255],["AND",-255],["PLUS",-255],["MINUS",-255],["NOT",-255],["LNOT",-255],["OFFSETOF",-255],["INT_CONST_DEC",-255],["INT_CONST_OCT",-255],["INT_CONST_HEX",-255],["INT_CONST_BIN",-255],["INT_CONST_CHAR",-255],["FLOAT_CONST",-255],["HEX_FLOAT_CONST",-255],["CHAR_CONST",-255],["WCHAR_CONST",-255],["U8CHAR_CONST",-255],["U16CHAR_CONST",-255],["U32CHAR_CONST",-255],["STRING_LITERAL",-255],["WSTRING_LITERAL",-255],["U8STRING_LITERAL",-255],["U16STRING_LITERAL",-255],["U32STRING_LITERAL",-255],["RBRACE",-255],["ELSE",-255]]],[527,[["SEMI",-104],["PPPRAGMA",-104],["_PRAGMA",-104],["_STATIC_ASSERT",-104],["ASM",-104],["ID",-104],["LPAREN",-104],["TIMES",-104],["TYPEID",-104],["ENUM",-104],["VOID",-104],["_BOOL",-104],["CHAR",-104],["SHORT",-104],["INT",-104],["LONG",-104],["FLOAT",-104],["DOUBLE",-104],["_COMPLEX",-104],["SIGNED",-104],["UNSIGNED",-104],["__INT128",-104],["_ATOMIC",-104],["TYPEOF",-104],["CONST",-104],["RESTRICT",-104],["VOLATILE",-104],["AUTO",-104],["REGISTER",-104],["STATIC",-104],["EXTERN",-104],["TYPEDEF",-104],["_THREAD_LOCAL",-104],["INLINE",-104],["_NORETURN",-104],["_ALIGNAS",-104],["__ATTRIBUTE__",-104],["STRUCT",-104],["UNION",-104],["LBRACE",-104],["CASE",-104],["DEFAULT",-104],["IF",-104],["SWITCH",-104],["WHILE",-104],["DO",-104],["FOR",-104],["GOTO",-104],["BREAK",-104],["CONTINUE",-104],["RETURN",-104],["PLUSPLUS",-104],["MINUSMINUS",-104],["SIZEOF",-104],["_ALIGNOF",-104],["AND",-104],["PLUS",-104],["MINUS",-104],["NOT",-104],["LNOT",-104],["OFFSETOF",-104],["INT_CONST_DEC",-104],["INT_CONST_OCT",-104],["INT_CONST_HEX",-104],["INT_CONST_BIN",-104],["INT_CONST_CHAR",-104],["FLOAT_CONST",-104],["HEX_FLOAT_CONST",-104],["CHAR_CONST",-104],["WCHAR_CONST",-104],["U8CHAR_CONST",-104],["U16CHAR_CONST",-104],["U32CHAR_CONST",-104],["STRING_LITERAL",-104],["WSTRING_LITERAL",-104],["U8STRING_LITERAL",-104],["U16STRING_LITERAL",-104],["U32STRING_LITERAL",-104],["RBRACE",-104],["ELSE",-104]]],[528,[["SEMI",-91],["PPPRAGMA",-91],["_PRAGMA",-91],["_STATIC_ASSERT",-91],["ASM",-91],["ID",-91],["LPAREN",-91],["TIMES",-91],["TYPEID",-91],["ENUM",-100],["VOID",-100],["_BOOL",-100],["CHAR",-100],["SHORT",-100],["INT",-100],["LONG",-100],["FLOAT",-100],["DOUBLE",-100],["_COMPLEX",-100],["SIGNED",-100],["UNSIGNED",-100],["__INT128",-100],["_ATOMIC",-100],["TYPEOF",-100],["CONST",-100],["RESTRICT",-100],["VOLATILE",-100],["AUTO",-100],["REGISTER",-100],["STATIC",-100],["EXTERN",-100],["TYPEDEF",-100],["_THREAD_LOCAL",-100],["INLINE",-100],["_NORETURN",-100],["_ALIGNAS",-100],["__ATTRIBUTE__",-91],["STRUCT",-100],["UNION",-100],["LBRACE",-91],["CASE",-91],["DEFAULT",-91],["IF",-91],["SWITCH",-91],["WHILE",-91],["DO",-91],["FOR",-91],["GOTO",-91],["BREAK",-91],["CONTINUE",-91],["RETURN",-91],["PLUSPLUS",-91],["MINUSMINUS",-91],["SIZEOF",-91],["_ALIGNOF",-91],["AND",-91],["PLUS",-91],["MINUS",-91],["NOT",-91],["LNOT",-91],["OFFSETOF",-91],["INT_CONST_DEC",-91],["INT_CONST_OCT",-91],["INT_CONST_HEX",-91],["INT_CONST_BIN",-91],["INT_CONST_CHAR",-91],["FLOAT_CONST",-91],["HEX_FLOAT_CONST",-91],["CHAR_CONST",-91],["WCHAR_CONST",-91],["U8CHAR_CONST",-91],["U16CHAR_CONST",-91],["U32CHAR_CONST",-91],["STRING_LITERAL",-91],["WSTRING_LITERAL",-91],["U8STRING_LITERAL",-91],["U16STRING_LITERAL",-91],["U32STRING_LITERAL",-91],["RBRACE",-100],["ELSE",-100]]],[529,[["SEMI",594]]],[530,[["SEMI",-412],["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[531,[["SEMI",-268],["PPPRAGMA",-268],["_PRAGMA",-268],["_STATIC_ASSERT",-268],["ASM",-268],["ID",-268],["LPAREN",-268],["TIMES",-268],["TYPEID",-268],["ENUM",-268],["VOID",-268],["_BOOL",-268],["CHAR",-268],["SHORT",-268],["INT",-268],["LONG",-268],["FLOAT",-268],["DOUBLE",-268],["_COMPLEX",-268],["SIGNED",-268],["UNSIGNED",-268],["__INT128",-268],["_ATOMIC",-268],["TYPEOF",-268],["CONST",-268],["RESTRICT",-268],["VOLATILE",-268],["AUTO",-268],["REGISTER",-268],["STATIC",-268],["EXTERN",-268],["TYPEDEF",-268],["_THREAD_LOCAL",-268],["INLINE",-268],["_NORETURN",-268],["_ALIGNAS",-268],["__ATTRIBUTE__",-268],["STRUCT",-268],["UNION",-268],["LBRACE",-268],["CASE",-268],["DEFAULT",-268],["IF",-268],["SWITCH",-268],["WHILE",-268],["DO",-268],["FOR",-268],["GOTO",-268],["BREAK",-268],["CONTINUE",-268],["RETURN",-268],["PLUSPLUS",-268],["MINUSMINUS",-268],["SIZEOF",-268],["_ALIGNOF",-268],["AND",-268],["PLUS",-268],["MINUS",-268],["NOT",-268],["LNOT",-268],["OFFSETOF",-268],["INT_CONST_DEC",-268],["INT_CONST_OCT",-268],["INT_CONST_HEX",-268],["INT_CONST_BIN",-268],["INT_CONST_CHAR",-268],["FLOAT_CONST",-268],["HEX_FLOAT_CONST",-268],["CHAR_CONST",-268],["WCHAR_CONST",-268],["U8CHAR_CONST",-268],["U16CHAR_CONST",-268],["U32CHAR_CONST",-268],["STRING_LITERAL",-268],["WSTRING_LITERAL",-268],["U8STRING_LITERAL",-268],["U16STRING_LITERAL",-268],["U32STRING_LITERAL",-268],["RBRACE",-268],["ELSE",-268]]],[532,[["SEMI",-269],["PPPRAGMA",-269],["_PRAGMA",-269],["_STATIC_ASSERT",-269],["ASM",-269],["ID",-269],["LPAREN",-269],["TIMES",-269],["TYPEID",-269],["ENUM",-269],["VOID",-269],["_BOOL",-269],["CHAR",-269],["SHORT",-269],["INT",-269],["LONG",-269],["FLOAT",-269],["DOUBLE",-269],["_COMPLEX",-269],["SIGNED",-269],["UNSIGNED",-269],["__INT128",-269],["_ATOMIC",-269],["TYPEOF",-269],["CONST",-269],["RESTRICT",-269],["VOLATILE",-269],["AUTO",-269],["REGISTER",-269],["STATIC",-269],["EXTERN",-269],["TYPEDEF",-269],["_THREAD_LOCAL",-269],["INLINE",-269],["_NORETURN",-269],["_ALIGNAS",-269],["__ATTRIBUTE__",-269],["STRUCT",-269],["UNION",-269],["LBRACE",-269],["CASE",-269],["DEFAULT",-269],["IF",-269],["SWITCH",-269],["WHILE",-269],["DO",-269],["FOR",-269],["GOTO",-269],["BREAK",-269],["CONTINUE",-269],["RETURN",-269],["PLUSPLUS",-269],["MINUSMINUS",-269],["SIZEOF",-269],["_ALIGNOF",-269],["AND",-269],["PLUS",-269],["MINUS",-269],["NOT",-269],["LNOT",-269],["OFFSETOF",-269],["INT_CONST_DEC",-269],["INT_CONST_OCT",-269],["INT_CONST_HEX",-269],["INT_CONST_BIN",-269],["INT_CONST_CHAR",-269],["FLOAT_CONST",-269],["HEX_FLOAT_CONST",-269],["CHAR_CONST",-269],["WCHAR_CONST",-269],["U8CHAR_CONST",-269],["U16CHAR_CONST",-269],["U32CHAR_CONST",-269],["STRING_LITERAL",-269],["WSTRING_LITERAL",-269],["U8STRING_LITERAL",-269],["U16STRING_LITERAL",-269],["U32STRING_LITERAL",-269],["RBRACE",-269],["ELSE",-269]]],[533,[["SEMI",-272],["PPPRAGMA",-272],["_PRAGMA",-272],["_STATIC_ASSERT",-272],["ASM",-272],["ID",-272],["LPAREN",-272],["TIMES",-272],["TYPEID",-272],["ENUM",-272],["VOID",-272],["_BOOL",-272],["CHAR",-272],["SHORT",-272],["INT",-272],["LONG",-272],["FLOAT",-272],["DOUBLE",-272],["_COMPLEX",-272],["SIGNED",-272],["UNSIGNED",-272],["__INT128",-272],["_ATOMIC",-272],["TYPEOF",-272],["CONST",-272],["RESTRICT",-272],["VOLATILE",-272],["AUTO",-272],["REGISTER",-272],["STATIC",-272],["EXTERN",-272],["TYPEDEF",-272],["_THREAD_LOCAL",-272],["INLINE",-272],["_NORETURN",-272],["_ALIGNAS",-272],["__ATTRIBUTE__",-272],["STRUCT",-272],["UNION",-272],["LBRACE",-272],["CASE",-272],["DEFAULT",-272],["IF",-272],["SWITCH",-272],["WHILE",-272],["DO",-272],["FOR",-272],["GOTO",-272],["BREAK",-272],["CONTINUE",-272],["RETURN",-272],["PLUSPLUS",-272],["MINUSMINUS",-272],["SIZEOF",-272],["_ALIGNOF",-272],["AND",-272],["PLUS",-272],["MINUS",-272],["NOT",-272],["LNOT",-272],["OFFSETOF",-272],["INT_CONST_DEC",-272],["INT_CONST_OCT",-272],["INT_CONST_HEX",-272],["INT_CONST_BIN",-272],["INT_CONST_CHAR",-272],["FLOAT_CONST",-272],["HEX_FLOAT_CONST",-272],["CHAR_CONST",-272],["WCHAR_CONST",-272],["U8CHAR_CONST",-272],["U16CHAR_CONST",-272],["U32CHAR_CONST",-272],["STRING_LITERAL",-272],["WSTRING_LITERAL",-272],["U8STRING_LITERAL",-272],["U16STRING_LITERAL",-272],["U32STRING_LITERAL",-272],["RBRACE",-272],["ELSE",-272]]],[538,[["SEMI",-161],["COMMA",-161]]],[539,[["SEMI",-222],["RBRACE",-222],["COMMA",-222]]],[541,[["SEMI",-162],["COMMA",-162]]],[542,[["SEMI",-400],["__ATTRIBUTE__",-400],["EQUALS",-400],["COLON",-400],["COMMA",-400]]],[543,[["SEMI",-53],["ASM",-53],["LPAREN",-53],["__ATTRIBUTE__",-53],["EQUALS",-53],["COLON",-53],["COMMA",-53],["RPAREN",-53],["LBRACKET",-53]]],[544,[["SEMI",-56],["ASM",-56],["LPAREN",-56],["__ATTRIBUTE__",-56],["EQUALS",-56],["COLON",-56],["COMMA",-56],["RPAREN",-56],["LBRACKET",-56]]],[547,[["SEMI",-314],["TIMES",-314],["AND",-314],["PLUS",-314],["MINUS",-314],["RBRACE",-314],["EQUALS",-314],["COLON",-314],["COMMA",-314],["RPAREN",-314],["RBRACKET",-314],["CONDOP",-314],["DIVIDE",-314],["MOD",-314],["RSHIFT",-314],["LSHIFT",-314],["LT",-314],["LE",-314],["GE",-314],["GT",-314],["EQ",-314],["NE",-314],["OR",-314],["XOR",-314],["LAND",-314],["LOR",-314],["XOREQUAL",-314],["TIMESEQUAL",-314],["DIVEQUAL",-314],["MODEQUAL",-314],["PLUSEQUAL",-314],["MINUSEQUAL",-314],["LSHIFTEQUAL",-314],["RSHIFTEQUAL",-314],["ANDEQUAL",-314],["OREQUAL",-314],["ELLIPSIS",-314]]],[551,[["SEMI",-329],["LPAREN",-329],["TIMES",-329],["PLUSPLUS",-329],["MINUSMINUS",-329],["AND",-329],["PLUS",-329],["MINUS",-329],["RBRACE",-329],["EQUALS",-329],["COLON",-329],["COMMA",-329],["RPAREN",-329],["LBRACKET",-329],["RBRACKET",-329],["PERIOD",-329],["ARROW",-329],["CONDOP",-329],["DIVIDE",-329],["MOD",-329],["RSHIFT",-329],["LSHIFT",-329],["LT",-329],["LE",-329],["GE",-329],["GT",-329],["EQ",-329],["NE",-329],["OR",-329],["XOR",-329],["LAND",-329],["LOR",-329],["XOREQUAL",-329],["TIMESEQUAL",-329],["DIVEQUAL",-329],["MODEQUAL",-329],["PLUSEQUAL",-329],["MINUSEQUAL",-329],["LSHIFTEQUAL",-329],["RSHIFTEQUAL",-329],["ANDEQUAL",-329],["OREQUAL",-329],["ELLIPSIS",-329]]],[552,[["SEMI",-330],["LPAREN",-330],["TIMES",-330],["PLUSPLUS",-330],["MINUSMINUS",-330],["AND",-330],["PLUS",-330],["MINUS",-330],["RBRACE",-330],["EQUALS",-330],["COLON",-330],["COMMA",-330],["RPAREN",-330],["LBRACKET",-330],["RBRACKET",-330],["PERIOD",-330],["ARROW",-330],["CONDOP",-330],["DIVIDE",-330],["MOD",-330],["RSHIFT",-330],["LSHIFT",-330],["LT",-330],["LE",-330],["GE",-330],["GT",-330],["EQ",-330],["NE",-330],["OR",-330],["XOR",-330],["LAND",-330],["LOR",-330],["XOREQUAL",-330],["TIMESEQUAL",-330],["DIVEQUAL",-330],["MODEQUAL",-330],["PLUSEQUAL",-330],["MINUSEQUAL",-330],["LSHIFTEQUAL",-330],["RSHIFTEQUAL",-330],["ANDEQUAL",-330],["OREQUAL",-330],["ELLIPSIS",-330]]],[554,[["SEMI",-320],["ID",177],["LPAREN",160],["TIMES",166],["LBRACE",144],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACE",-320],["EQUALS",-320],["COLON",-320],["COMMA",-320],["RPAREN",-320],["RBRACKET",-320],["CONDOP",-320],["DIVIDE",-320],["MOD",-320],["RSHIFT",-320],["LSHIFT",-320],["LT",-320],["LE",-320],["GE",-320],["GT",-320],["EQ",-320],["NE",-320],["OR",-320],["XOR",-320],["LAND",-320],["LOR",-320],["XOREQUAL",-320],["TIMESEQUAL",-320],["DIVEQUAL",-320],["MODEQUAL",-320],["PLUSEQUAL",-320],["MINUSEQUAL",-320],["LSHIFTEQUAL",-320],["RSHIFTEQUAL",-320],["ANDEQUAL",-320],["OREQUAL",-320],["ELLIPSIS",-320]]],[555,[["SEMI",-321],["TIMES",-321],["AND",-321],["PLUS",-321],["MINUS",-321],["RBRACE",-321],["EQUALS",-321],["COLON",-321],["COMMA",-321],["RPAREN",-321],["RBRACKET",-321],["CONDOP",-321],["DIVIDE",-321],["MOD",-321],["RSHIFT",-321],["LSHIFT",-321],["LT",-321],["LE",-321],["GE",-321],["GT",-321],["EQ",-321],["NE",-321],["OR",-321],["XOR",-321],["LAND",-321],["LOR",-321],["XOREQUAL",-321],["TIMESEQUAL",-321],["DIVEQUAL",-321],["MODEQUAL",-321],["PLUSEQUAL",-321],["MINUSEQUAL",-321],["LSHIFTEQUAL",-321],["RSHIFTEQUAL",-321],["ANDEQUAL",-321],["OREQUAL",-321],["ELLIPSIS",-321]]],[557,[["SEMI",-46],["ASM",-46],["LPAREN",-46],["TYPEID",-46],["ENUM",-46],["VOID",-46],["_BOOL",-46],["CHAR",-46],["SHORT",-46],["INT",-46],["LONG",-46],["FLOAT",-46],["DOUBLE",-46],["_COMPLEX",-46],["SIGNED",-46],["UNSIGNED",-46],["__INT128",-46],["_ATOMIC",-46],["TYPEOF",-46],["CONST",-46],["RESTRICT",-46],["VOLATILE",-46],["AUTO",-46],["REGISTER",-46],["STATIC",-46],["EXTERN",-46],["TYPEDEF",-46],["_THREAD_LOCAL",-46],["INLINE",-46],["_NORETURN",-46],["_ALIGNAS",-46],["__ATTRIBUTE__",-46],["STRUCT",-46],["UNION",-46],["LBRACE",-46],["EQUALS",-46],["COLON",-46],["COMMA",-46],["RPAREN",-46],["LBRACKET",-46]]],[558,[["SEMI",-47],["ASM",-47],["LPAREN",-47],["TYPEID",-47],["ENUM",-47],["VOID",-47],["_BOOL",-47],["CHAR",-47],["SHORT",-47],["INT",-47],["LONG",-47],["FLOAT",-47],["DOUBLE",-47],["_COMPLEX",-47],["SIGNED",-47],["UNSIGNED",-47],["__INT128",-47],["_ATOMIC",-47],["TYPEOF",-47],["CONST",-47],["RESTRICT",-47],["VOLATILE",-47],["AUTO",-47],["REGISTER",-47],["STATIC",-47],["EXTERN",-47],["TYPEDEF",-47],["_THREAD_LOCAL",-47],["INLINE",-47],["_NORETURN",-47],["_ALIGNAS",-47],["__ATTRIBUTE__",-47],["STRUCT",-47],["UNION",-47],["LBRACE",-47],["EQUALS",-47],["COLON",-47],["COMMA",-47],["RPAREN",-47],["LBRACKET",-47]]],[573,[["SEMI",-166],["COMMA",-166]]],[574,[["SEMI",-194],["ID",-194],["LPAREN",-194],["TIMES",-194],["TYPEID",-194],["VOID",-194],["_BOOL",-194],["CHAR",-194],["SHORT",-194],["INT",-194],["LONG",-194],["FLOAT",-194],["DOUBLE",-194],["_COMPLEX",-194],["SIGNED",-194],["UNSIGNED",-194],["__INT128",-194],["_ATOMIC",-194],["CONST",-194],["RESTRICT",-194],["VOLATILE",-194],["AUTO",-194],["REGISTER",-194],["STATIC",-194],["EXTERN",-194],["TYPEDEF",-194],["_THREAD_LOCAL",-194],["INLINE",-194],["_NORETURN",-194],["_ALIGNAS",-194],["__ATTRIBUTE__",-194],["COLON",-194],["COMMA",-194],["RPAREN",-194],["LBRACKET",-194]]],[577,[["SEMI",-195],["ID",-195],["LPAREN",-195],["TIMES",-195],["TYPEID",-195],["VOID",-195],["_BOOL",-195],["CHAR",-195],["SHORT",-195],["INT",-195],["LONG",-195],["FLOAT",-195],["DOUBLE",-195],["_COMPLEX",-195],["SIGNED",-195],["UNSIGNED",-195],["__INT128",-195],["_ATOMIC",-195],["CONST",-195],["RESTRICT",-195],["VOLATILE",-195],["AUTO",-195],["REGISTER",-195],["STATIC",-195],["EXTERN",-195],["TYPEDEF",-195],["_THREAD_LOCAL",-195],["INLINE",-195],["_NORETURN",-195],["_ALIGNAS",-195],["__ATTRIBUTE__",-195],["COLON",-195],["COMMA",-195],["RPAREN",-195],["LBRACKET",-195]]],[578,[["SEMI",-176],["ID",-176],["LPAREN",-176],["TIMES",-176],["TYPEID",-176],["VOID",-176],["_BOOL",-176],["CHAR",-176],["SHORT",-176],["INT",-176],["LONG",-176],["FLOAT",-176],["DOUBLE",-176],["_COMPLEX",-176],["SIGNED",-176],["UNSIGNED",-176],["__INT128",-176],["_ATOMIC",-176],["CONST",-176],["RESTRICT",-176],["VOLATILE",-176],["AUTO",-176],["REGISTER",-176],["STATIC",-176],["EXTERN",-176],["TYPEDEF",-176],["_THREAD_LOCAL",-176],["INLINE",-176],["_NORETURN",-176],["_ALIGNAS",-176],["__ATTRIBUTE__",-176],["COLON",-176],["COMMA",-176],["RPAREN",-176],["LBRACKET",-176]]],[579,[["SEMI",-184],["PPPRAGMA",-184],["_PRAGMA",-184],["TYPEID",-184],["ENUM",-184],["VOID",-184],["_BOOL",-184],["CHAR",-184],["SHORT",-184],["INT",-184],["LONG",-184],["FLOAT",-184],["DOUBLE",-184],["_COMPLEX",-184],["SIGNED",-184],["UNSIGNED",-184],["__INT128",-184],["_ATOMIC",-184],["TYPEOF",-184],["CONST",-184],["RESTRICT",-184],["VOLATILE",-184],["_ALIGNAS",-184],["__ATTRIBUTE__",-184],["STRUCT",-184],["UNION",-184],["RBRACE",-184]]],[581,[["SEMI",-189],["COLON",628],["COMMA",-189]]],[583,[["SEMI",-178],["ID",-178],["LPAREN",-178],["TIMES",-178],["TYPEID",-178],["VOID",-178],["_BOOL",-178],["CHAR",-178],["SHORT",-178],["INT",-178],["LONG",-178],["FLOAT",-178],["DOUBLE",-178],["_COMPLEX",-178],["SIGNED",-178],["UNSIGNED",-178],["__INT128",-178],["_ATOMIC",-178],["CONST",-178],["RESTRICT",-178],["VOLATILE",-178],["AUTO",-178],["REGISTER",-178],["STATIC",-178],["EXTERN",-178],["TYPEDEF",-178],["_THREAD_LOCAL",-178],["INLINE",-178],["_NORETURN",-178],["_ALIGNAS",-178],["__ATTRIBUTE__",-178],["COLON",-178],["COMMA",-178],["RPAREN",-178],["LBRACKET",-178]]],[584,[["SEMI",-403],["ID",-403],["LPAREN",-403],["TIMES",-403],["TYPEID",-403],["ENUM",-403],["VOID",-403],["_BOOL",-403],["CHAR",-403],["SHORT",-403],["INT",-403],["LONG",-403],["FLOAT",-403],["DOUBLE",-403],["_COMPLEX",-403],["SIGNED",-403],["UNSIGNED",-403],["__INT128",-403],["_ATOMIC",-403],["TYPEOF",-403],["CONST",-403],["RESTRICT",-403],["VOLATILE",-403],["AUTO",-403],["REGISTER",-403],["STATIC",-403],["EXTERN",-403],["TYPEDEF",-403],["_THREAD_LOCAL",-403],["INLINE",-403],["_NORETURN",-403],["_ALIGNAS",-403],["__ATTRIBUTE__",-403],["STRUCT",-403],["UNION",-403],["LBRACE",-403],["RBRACE",-403],["EQUALS",-403],["COLON",-403],["COMMA",-403],["RPAREN",-403],["LBRACKET",-403]]],[588,[["SEMI",-253],["PPPRAGMA",-253],["_PRAGMA",-253],["_STATIC_ASSERT",-253],["ASM",-253],["ID",-253],["LPAREN",-253],["TIMES",-253],["TYPEID",-253],["ENUM",-253],["VOID",-253],["_BOOL",-253],["CHAR",-253],["SHORT",-253],["INT",-253],["LONG",-253],["FLOAT",-253],["DOUBLE",-253],["_COMPLEX",-253],["SIGNED",-253],["UNSIGNED",-253],["__INT128",-253],["_ATOMIC",-253],["TYPEOF",-253],["CONST",-253],["RESTRICT",-253],["VOLATILE",-253],["AUTO",-253],["REGISTER",-253],["STATIC",-253],["EXTERN",-253],["TYPEDEF",-253],["_THREAD_LOCAL",-253],["INLINE",-253],["_NORETURN",-253],["_ALIGNAS",-253],["__ATTRIBUTE__",-253],["STRUCT",-253],["UNION",-253],["LBRACE",-253],["CASE",-253],["DEFAULT",-253],["IF",-253],["SWITCH",-253],["WHILE",-253],["DO",-253],["FOR",-253],["GOTO",-253],["BREAK",-253],["CONTINUE",-253],["RETURN",-253],["PLUSPLUS",-253],["MINUSMINUS",-253],["SIZEOF",-253],["_ALIGNOF",-253],["AND",-253],["PLUS",-253],["MINUS",-253],["NOT",-253],["LNOT",-253],["OFFSETOF",-253],["INT_CONST_DEC",-253],["INT_CONST_OCT",-253],["INT_CONST_HEX",-253],["INT_CONST_BIN",-253],["INT_CONST_CHAR",-253],["FLOAT_CONST",-253],["HEX_FLOAT_CONST",-253],["CHAR_CONST",-253],["WCHAR_CONST",-253],["U8CHAR_CONST",-253],["U16CHAR_CONST",-253],["U32CHAR_CONST",-253],["STRING_LITERAL",-253],["WSTRING_LITERAL",-253],["U8STRING_LITERAL",-253],["U16STRING_LITERAL",-253],["U32STRING_LITERAL",-253],["RBRACE",-253],["ELSE",-253]]],[590,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["__ATTRIBUTE__",67],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[591,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["__ATTRIBUTE__",67],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[592,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["__ATTRIBUTE__",67],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[594,[["SEMI",-412],["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[595,[["SEMI",640]]],[606,[["SEMI",-54],["ASM",-54],["LPAREN",-54],["__ATTRIBUTE__",-54],["EQUALS",-54],["COLON",-54],["COMMA",-54],["RPAREN",-54],["LBRACKET",-54]]],[607,[["SEMI",-55],["ASM",-55],["LPAREN",-55],["__ATTRIBUTE__",-55],["EQUALS",-55],["COLON",-55],["COMMA",-55],["RPAREN",-55],["LBRACKET",-55]]],[610,[["SEMI",-294],["RBRACE",-294],["COLON",-294],["COMMA",-294],["RPAREN",-294],["RBRACKET",-294],["ELLIPSIS",-294]]],[627,[["SEMI",-188],["COMMA",-188]]],[629,[["SEMI",-191],["COMMA",-191]]],[632,[["SEMI",-259],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["ENUM",-259],["VOID",-259],["_BOOL",-259],["CHAR",-259],["SHORT",-259],["INT",-259],["LONG",-259],["FLOAT",-259],["DOUBLE",-259],["_COMPLEX",-259],["SIGNED",-259],["UNSIGNED",-259],["__INT128",-259],["_ATOMIC",-259],["TYPEOF",-259],["CONST",-259],["RESTRICT",-259],["VOLATILE",-259],["AUTO",-259],["REGISTER",-259],["STATIC",-259],["EXTERN",-259],["TYPEDEF",-259],["_THREAD_LOCAL",-259],["INLINE",-259],["_NORETURN",-259],["_ALIGNAS",-259],["__ATTRIBUTE__",67],["STRUCT",-259],["UNION",-259],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACE",-259],["ELSE",-259]]],[633,[["SEMI",-261],["PPPRAGMA",-261],["_PRAGMA",-261],["_STATIC_ASSERT",-261],["ASM",-261],["ID",-261],["LPAREN",-261],["TIMES",-261],["TYPEID",-261],["ENUM",-261],["VOID",-261],["_BOOL",-261],["CHAR",-261],["SHORT",-261],["INT",-261],["LONG",-261],["FLOAT",-261],["DOUBLE",-261],["_COMPLEX",-261],["SIGNED",-261],["UNSIGNED",-261],["__INT128",-261],["_ATOMIC",-261],["TYPEOF",-261],["CONST",-261],["RESTRICT",-261],["VOLATILE",-261],["AUTO",-261],["REGISTER",-261],["STATIC",-261],["EXTERN",-261],["TYPEDEF",-261],["_THREAD_LOCAL",-261],["INLINE",-261],["_NORETURN",-261],["_ALIGNAS",-261],["__ATTRIBUTE__",-261],["STRUCT",-261],["UNION",-261],["LBRACE",-261],["CASE",-261],["DEFAULT",-261],["IF",-261],["SWITCH",-261],["WHILE",-261],["DO",-261],["FOR",-261],["GOTO",-261],["BREAK",-261],["CONTINUE",-261],["RETURN",-261],["PLUSPLUS",-261],["MINUSMINUS",-261],["SIZEOF",-261],["_ALIGNOF",-261],["AND",-261],["PLUS",-261],["MINUS",-261],["NOT",-261],["LNOT",-261],["OFFSETOF",-261],["INT_CONST_DEC",-261],["INT_CONST_OCT",-261],["INT_CONST_HEX",-261],["INT_CONST_BIN",-261],["INT_CONST_CHAR",-261],["FLOAT_CONST",-261],["HEX_FLOAT_CONST",-261],["CHAR_CONST",-261],["WCHAR_CONST",-261],["U8CHAR_CONST",-261],["U16CHAR_CONST",-261],["U32CHAR_CONST",-261],["STRING_LITERAL",-261],["WSTRING_LITERAL",-261],["U8STRING_LITERAL",-261],["U16STRING_LITERAL",-261],["U32STRING_LITERAL",-261],["RBRACE",-261],["ELSE",-261]]],[634,[["SEMI",-105],["PPPRAGMA",-105],["_PRAGMA",-105],["_STATIC_ASSERT",-105],["ASM",-105],["ID",-105],["LPAREN",-105],["TIMES",-105],["TYPEID",-105],["ENUM",-105],["VOID",-105],["_BOOL",-105],["CHAR",-105],["SHORT",-105],["INT",-105],["LONG",-105],["FLOAT",-105],["DOUBLE",-105],["_COMPLEX",-105],["SIGNED",-105],["UNSIGNED",-105],["__INT128",-105],["_ATOMIC",-105],["TYPEOF",-105],["CONST",-105],["RESTRICT",-105],["VOLATILE",-105],["AUTO",-105],["REGISTER",-105],["STATIC",-105],["EXTERN",-105],["TYPEDEF",-105],["_THREAD_LOCAL",-105],["INLINE",-105],["_NORETURN",-105],["_ALIGNAS",-105],["__ATTRIBUTE__",-105],["STRUCT",-105],["UNION",-105],["LBRACE",-105],["CASE",-105],["DEFAULT",-105],["IF",-105],["SWITCH",-105],["WHILE",-105],["DO",-105],["FOR",-105],["GOTO",-105],["BREAK",-105],["CONTINUE",-105],["RETURN",-105],["PLUSPLUS",-105],["MINUSMINUS",-105],["SIZEOF",-105],["_ALIGNOF",-105],["AND",-105],["PLUS",-105],["MINUS",-105],["NOT",-105],["LNOT",-105],["OFFSETOF",-105],["INT_CONST_DEC",-105],["INT_CONST_OCT",-105],["INT_CONST_HEX",-105],["INT_CONST_BIN",-105],["INT_CONST_CHAR",-105],["FLOAT_CONST",-105],["HEX_FLOAT_CONST",-105],["CHAR_CONST",-105],["WCHAR_CONST",-105],["U8CHAR_CONST",-105],["U16CHAR_CONST",-105],["U32CHAR_CONST",-105],["STRING_LITERAL",-105],["WSTRING_LITERAL",-105],["U8STRING_LITERAL",-105],["U16STRING_LITERAL",-105],["U32STRING_LITERAL",-105],["RBRACE",-105],["ELSE",663]]],[635,[["SEMI",-90],["PPPRAGMA",-90],["_PRAGMA",-90],["_STATIC_ASSERT",-90],["ASM",-90],["ID",-90],["LPAREN",-90],["TIMES",-90],["TYPEID",-90],["ENUM",-100],["VOID",-100],["_BOOL",-100],["CHAR",-100],["SHORT",-100],["INT",-100],["LONG",-100],["FLOAT",-100],["DOUBLE",-100],["_COMPLEX",-100],["SIGNED",-100],["UNSIGNED",-100],["__INT128",-100],["_ATOMIC",-100],["TYPEOF",-100],["CONST",-100],["RESTRICT",-100],["VOLATILE",-100],["AUTO",-100],["REGISTER",-100],["STATIC",-100],["EXTERN",-100],["TYPEDEF",-100],["_THREAD_LOCAL",-100],["INLINE",-100],["_NORETURN",-100],["_ALIGNAS",-100],["__ATTRIBUTE__",-90],["STRUCT",-100],["UNION",-100],["LBRACE",-90],["CASE",-90],["DEFAULT",-90],["IF",-90],["SWITCH",-90],["WHILE",-90],["DO",-90],["FOR",-90],["GOTO",-90],["BREAK",-90],["CONTINUE",-90],["RETURN",-90],["PLUSPLUS",-90],["MINUSMINUS",-90],["SIZEOF",-90],["_ALIGNOF",-90],["AND",-90],["PLUS",-90],["MINUS",-90],["NOT",-90],["LNOT",-90],["OFFSETOF",-90],["INT_CONST_DEC",-90],["INT_CONST_OCT",-90],["INT_CONST_HEX",-90],["INT_CONST_BIN",-90],["INT_CONST_CHAR",-90],["FLOAT_CONST",-90],["HEX_FLOAT_CONST",-90],["CHAR_CONST",-90],["WCHAR_CONST",-90],["U8CHAR_CONST",-90],["U16CHAR_CONST",-90],["U32CHAR_CONST",-90],["STRING_LITERAL",-90],["WSTRING_LITERAL",-90],["U8STRING_LITERAL",-90],["U16STRING_LITERAL",-90],["U32STRING_LITERAL",-90],["RBRACE",-100],["ELSE",-100]]],[636,[["SEMI",-263],["PPPRAGMA",-263],["_PRAGMA",-263],["_STATIC_ASSERT",-263],["ASM",-263],["ID",-263],["LPAREN",-263],["TIMES",-263],["TYPEID",-263],["ENUM",-263],["VOID",-263],["_BOOL",-263],["CHAR",-263],["SHORT",-263],["INT",-263],["LONG",-263],["FLOAT",-263],["DOUBLE",-263],["_COMPLEX",-263],["SIGNED",-263],["UNSIGNED",-263],["__INT128",-263],["_ATOMIC",-263],["TYPEOF",-263],["CONST",-263],["RESTRICT",-263],["VOLATILE",-263],["AUTO",-263],["REGISTER",-263],["STATIC",-263],["EXTERN",-263],["TYPEDEF",-263],["_THREAD_LOCAL",-263],["INLINE",-263],["_NORETURN",-263],["_ALIGNAS",-263],["__ATTRIBUTE__",-263],["STRUCT",-263],["UNION",-263],["LBRACE",-263],["CASE",-263],["DEFAULT",-263],["IF",-263],["SWITCH",-263],["WHILE",-263],["DO",-263],["FOR",-263],["GOTO",-263],["BREAK",-263],["CONTINUE",-263],["RETURN",-263],["PLUSPLUS",-263],["MINUSMINUS",-263],["SIZEOF",-263],["_ALIGNOF",-263],["AND",-263],["PLUS",-263],["MINUS",-263],["NOT",-263],["LNOT",-263],["OFFSETOF",-263],["INT_CONST_DEC",-263],["INT_CONST_OCT",-263],["INT_CONST_HEX",-263],["INT_CONST_BIN",-263],["INT_CONST_CHAR",-263],["FLOAT_CONST",-263],["HEX_FLOAT_CONST",-263],["CHAR_CONST",-263],["WCHAR_CONST",-263],["U8CHAR_CONST",-263],["U16CHAR_CONST",-263],["U32CHAR_CONST",-263],["STRING_LITERAL",-263],["WSTRING_LITERAL",-263],["U8STRING_LITERAL",-263],["U16STRING_LITERAL",-263],["U32STRING_LITERAL",-263],["RBRACE",-263],["ELSE",-263]]],[637,[["SEMI",-264],["PPPRAGMA",-264],["_PRAGMA",-264],["_STATIC_ASSERT",-264],["ASM",-264],["ID",-264],["LPAREN",-264],["TIMES",-264],["TYPEID",-264],["ENUM",-264],["VOID",-264],["_BOOL",-264],["CHAR",-264],["SHORT",-264],["INT",-264],["LONG",-264],["FLOAT",-264],["DOUBLE",-264],["_COMPLEX",-264],["SIGNED",-264],["UNSIGNED",-264],["__INT128",-264],["_ATOMIC",-264],["TYPEOF",-264],["CONST",-264],["RESTRICT",-264],["VOLATILE",-264],["AUTO",-264],["REGISTER",-264],["STATIC",-264],["EXTERN",-264],["TYPEDEF",-264],["_THREAD_LOCAL",-264],["INLINE",-264],["_NORETURN",-264],["_ALIGNAS",-264],["__ATTRIBUTE__",-264],["STRUCT",-264],["UNION",-264],["LBRACE",-264],["CASE",-264],["DEFAULT",-264],["IF",-264],["SWITCH",-264],["WHILE",-264],["DO",-264],["FOR",-264],["GOTO",-264],["BREAK",-264],["CONTINUE",-264],["RETURN",-264],["PLUSPLUS",-264],["MINUSMINUS",-264],["SIZEOF",-264],["_ALIGNOF",-264],["AND",-264],["PLUS",-264],["MINUS",-264],["NOT",-264],["LNOT",-264],["OFFSETOF",-264],["INT_CONST_DEC",-264],["INT_CONST_OCT",-264],["INT_CONST_HEX",-264],["INT_CONST_BIN",-264],["INT_CONST_CHAR",-264],["FLOAT_CONST",-264],["HEX_FLOAT_CONST",-264],["CHAR_CONST",-264],["WCHAR_CONST",-264],["U8CHAR_CONST",-264],["U16CHAR_CONST",-264],["U32CHAR_CONST",-264],["STRING_LITERAL",-264],["WSTRING_LITERAL",-264],["U8STRING_LITERAL",-264],["U16STRING_LITERAL",-264],["U32STRING_LITERAL",-264],["RBRACE",-264],["ELSE",-264]]],[639,[["SEMI",665]]],[641,[["SEMI",667]]],[643,[["SEMI",-223],["RBRACE",-223],["COMMA",-223]]],[650,[["SEMI",-338],["LPAREN",-338],["TIMES",-338],["PLUSPLUS",-338],["MINUSMINUS",-338],["AND",-338],["PLUS",-338],["MINUS",-338],["RBRACE",-338],["EQUALS",-338],["COLON",-338],["COMMA",-338],["RPAREN",-338],["LBRACKET",-338],["RBRACKET",-338],["PERIOD",-338],["ARROW",-338],["CONDOP",-338],["DIVIDE",-338],["MOD",-338],["RSHIFT",-338],["LSHIFT",-338],["LT",-338],["LE",-338],["GE",-338],["GT",-338],["EQ",-338],["NE",-338],["OR",-338],["XOR",-338],["LAND",-338],["LOR",-338],["XOREQUAL",-338],["TIMESEQUAL",-338],["DIVEQUAL",-338],["MODEQUAL",-338],["PLUSEQUAL",-338],["MINUSEQUAL",-338],["LSHIFTEQUAL",-338],["RSHIFTEQUAL",-338],["ANDEQUAL",-338],["OREQUAL",-338],["ELLIPSIS",-338]]],[652,[["SEMI",-345],["LPAREN",-345],["TIMES",-345],["PLUSPLUS",-345],["MINUSMINUS",-345],["AND",-345],["PLUS",-345],["MINUS",-345],["RBRACE",-345],["EQUALS",-345],["COLON",-345],["COMMA",-345],["RPAREN",-345],["LBRACKET",-345],["RBRACKET",-345],["PERIOD",-345],["ARROW",-345],["CONDOP",-345],["DIVIDE",-345],["MOD",-345],["RSHIFT",-345],["LSHIFT",-345],["LT",-345],["LE",-345],["GE",-345],["GT",-345],["EQ",-345],["NE",-345],["OR",-345],["XOR",-345],["LAND",-345],["LOR",-345],["XOREQUAL",-345],["TIMESEQUAL",-345],["DIVEQUAL",-345],["MODEQUAL",-345],["PLUSEQUAL",-345],["MINUSEQUAL",-345],["LSHIFTEQUAL",-345],["RSHIFTEQUAL",-345],["ANDEQUAL",-345],["OREQUAL",-345],["ELLIPSIS",-345]]],[661,[["SEMI",-190],["COMMA",-190]]],[662,[["SEMI",-254],["PPPRAGMA",-254],["_PRAGMA",-254],["_STATIC_ASSERT",-254],["ASM",-254],["ID",-254],["LPAREN",-254],["TIMES",-254],["TYPEID",-254],["ENUM",-254],["VOID",-254],["_BOOL",-254],["CHAR",-254],["SHORT",-254],["INT",-254],["LONG",-254],["FLOAT",-254],["DOUBLE",-254],["_COMPLEX",-254],["SIGNED",-254],["UNSIGNED",-254],["__INT128",-254],["_ATOMIC",-254],["TYPEOF",-254],["CONST",-254],["RESTRICT",-254],["VOLATILE",-254],["AUTO",-254],["REGISTER",-254],["STATIC",-254],["EXTERN",-254],["TYPEDEF",-254],["_THREAD_LOCAL",-254],["INLINE",-254],["_NORETURN",-254],["_ALIGNAS",-254],["__ATTRIBUTE__",-254],["STRUCT",-254],["UNION",-254],["LBRACE",-254],["CASE",-254],["DEFAULT",-254],["IF",-254],["SWITCH",-254],["WHILE",-254],["DO",-254],["FOR",-254],["GOTO",-254],["BREAK",-254],["CONTINUE",-254],["RETURN",-254],["PLUSPLUS",-254],["MINUSMINUS",-254],["SIZEOF",-254],["_ALIGNOF",-254],["AND",-254],["PLUS",-254],["MINUS",-254],["NOT",-254],["LNOT",-254],["OFFSETOF",-254],["INT_CONST_DEC",-254],["INT_CONST_OCT",-254],["INT_CONST_HEX",-254],["INT_CONST_BIN",-254],["INT_CONST_CHAR",-254],["FLOAT_CONST",-254],["HEX_FLOAT_CONST",-254],["CHAR_CONST",-254],["WCHAR_CONST",-254],["U8CHAR_CONST",-254],["U16CHAR_CONST",-254],["U32CHAR_CONST",-254],["STRING_LITERAL",-254],["WSTRING_LITERAL",-254],["U8STRING_LITERAL",-254],["U16STRING_LITERAL",-254],["U32STRING_LITERAL",-254],["RBRACE",-254],["ELSE",-254]]],[663,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["__ATTRIBUTE__",67],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[664,[["SEMI",685]]],[667,[["SEMI",-381],["PPPRAGMA",-381],["_PRAGMA",-381],["_STATIC_ASSERT",-381],["ASM",-381],["ID",-381],["LPAREN",-381],["TIMES",-381],["TYPEID",-381],["ENUM",-381],["VOID",-381],["_BOOL",-381],["CHAR",-381],["SHORT",-381],["INT",-381],["LONG",-381],["FLOAT",-381],["DOUBLE",-381],["_COMPLEX",-381],["SIGNED",-381],["UNSIGNED",-381],["__INT128",-381],["_ATOMIC",-381],["TYPEOF",-381],["CONST",-381],["RESTRICT",-381],["VOLATILE",-381],["AUTO",-381],["REGISTER",-381],["STATIC",-381],["EXTERN",-381],["TYPEDEF",-381],["_THREAD_LOCAL",-381],["INLINE",-381],["_NORETURN",-381],["_ALIGNAS",-381],["__ATTRIBUTE__",-381],["STRUCT",-381],["UNION",-381],["LBRACE",-381],["CASE",-381],["DEFAULT",-381],["IF",-381],["SWITCH",-381],["WHILE",-381],["DO",-381],["FOR",-381],["GOTO",-381],["BREAK",-381],["CONTINUE",-381],["RETURN",-381],["PLUSPLUS",-381],["MINUSMINUS",-381],["SIZEOF",-381],["_ALIGNOF",-381],["AND",-381],["PLUS",-381],["MINUS",-381],["NOT",-381],["LNOT",-381],["OFFSETOF",-381],["INT_CONST_DEC",-381],["INT_CONST_OCT",-381],["INT_CONST_HEX",-381],["INT_CONST_BIN",-381],["INT_CONST_CHAR",-381],["FLOAT_CONST",-381],["HEX_FLOAT_CONST",-381],["CHAR_CONST",-381],["WCHAR_CONST",-381],["U8CHAR_CONST",-381],["U16CHAR_CONST",-381],["U32CHAR_CONST",-381],["STRING_LITERAL",-381],["WSTRING_LITERAL",-381],["U8STRING_LITERAL",-381],["U16STRING_LITERAL",-381],["U32STRING_LITERAL",-381],["RBRACE",-381],["ELSE",-381]]],[675,[["SEMI",-224],["RBRACE",-224],["COMMA",-224]]],[679,[["SEMI",-339],["LPAREN",-339],["TIMES",-339],["PLUSPLUS",-339],["MINUSMINUS",-339],["AND",-339],["PLUS",-339],["MINUS",-339],["RBRACE",-339],["EQUALS",-339],["COLON",-339],["COMMA",-339],["RPAREN",-339],["LBRACKET",-339],["RBRACKET",-339],["PERIOD",-339],["ARROW",-339],["CONDOP",-339],["DIVIDE",-339],["MOD",-339],["RSHIFT",-339],["LSHIFT",-339],["LT",-339],["LE",-339],["GE",-339],["GT",-339],["EQ",-339],["NE",-339],["OR",-339],["XOR",-339],["LAND",-339],["LOR",-339],["XOREQUAL",-339],["TIMESEQUAL",-339],["DIVEQUAL",-339],["MODEQUAL",-339],["PLUSEQUAL",-339],["MINUSEQUAL",-339],["LSHIFTEQUAL",-339],["RSHIFTEQUAL",-339],["ANDEQUAL",-339],["OREQUAL",-339],["ELLIPSIS",-339]]],[684,[["SEMI",-262],["PPPRAGMA",-262],["_PRAGMA",-262],["_STATIC_ASSERT",-262],["ASM",-262],["ID",-262],["LPAREN",-262],["TIMES",-262],["TYPEID",-262],["ENUM",-262],["VOID",-262],["_BOOL",-262],["CHAR",-262],["SHORT",-262],["INT",-262],["LONG",-262],["FLOAT",-262],["DOUBLE",-262],["_COMPLEX",-262],["SIGNED",-262],["UNSIGNED",-262],["__INT128",-262],["_ATOMIC",-262],["TYPEOF",-262],["CONST",-262],["RESTRICT",-262],["VOLATILE",-262],["AUTO",-262],["REGISTER",-262],["STATIC",-262],["EXTERN",-262],["TYPEDEF",-262],["_THREAD_LOCAL",-262],["INLINE",-262],["_NORETURN",-262],["_ALIGNAS",-262],["__ATTRIBUTE__",-262],["STRUCT",-262],["UNION",-262],["LBRACE",-262],["CASE",-262],["DEFAULT",-262],["IF",-262],["SWITCH",-262],["WHILE",-262],["DO",-262],["FOR",-262],["GOTO",-262],["BREAK",-262],["CONTINUE",-262],["RETURN",-262],["PLUSPLUS",-262],["MINUSMINUS",-262],["SIZEOF",-262],["_ALIGNOF",-262],["AND",-262],["PLUS",-262],["MINUS",-262],["NOT",-262],["LNOT",-262],["OFFSETOF",-262],["INT_CONST_DEC",-262],["INT_CONST_OCT",-262],["INT_CONST_HEX",-262],["INT_CONST_BIN",-262],["INT_CONST_CHAR",-262],["FLOAT_CONST",-262],["HEX_FLOAT_CONST",-262],["CHAR_CONST",-262],["WCHAR_CONST",-262],["U8CHAR_CONST",-262],["U16CHAR_CONST",-262],["U32CHAR_CONST",-262],["STRING_LITERAL",-262],["WSTRING_LITERAL",-262],["U8STRING_LITERAL",-262],["U16STRING_LITERAL",-262],["U32STRING_LITERAL",-262],["RBRACE",-262],["ELSE",-262]]],[685,[["SEMI",-265],["PPPRAGMA",-265],["_PRAGMA",-265],["_STATIC_ASSERT",-265],["ASM",-265],["ID",-265],["LPAREN",-265],["TIMES",-265],["TYPEID",-265],["ENUM",-265],["VOID",-265],["_BOOL",-265],["CHAR",-265],["SHORT",-265],["INT",-265],["LONG",-265],["FLOAT",-265],["DOUBLE",-265],["_COMPLEX",-265],["SIGNED",-265],["UNSIGNED",-265],["__INT128",-265],["_ATOMIC",-265],["TYPEOF",-265],["CONST",-265],["RESTRICT",-265],["VOLATILE",-265],["AUTO",-265],["REGISTER",-265],["STATIC",-265],["EXTERN",-265],["TYPEDEF",-265],["_THREAD_LOCAL",-265],["INLINE",-265],["_NORETURN",-265],["_ALIGNAS",-265],["__ATTRIBUTE__",-265],["STRUCT",-265],["UNION",-265],["LBRACE",-265],["CASE",-265],["DEFAULT",-265],["IF",-265],["SWITCH",-265],["WHILE",-265],["DO",-265],["FOR",-265],["GOTO",-265],["BREAK",-265],["CONTINUE",-265],["RETURN",-265],["PLUSPLUS",-265],["MINUSMINUS",-265],["SIZEOF",-265],["_ALIGNOF",-265],["AND",-265],["PLUS",-265],["MINUS",-265],["NOT",-265],["LNOT",-265],["OFFSETOF",-265],["INT_CONST_DEC",-265],["INT_CONST_OCT",-265],["INT_CONST_HEX",-265],["INT_CONST_BIN",-265],["INT_CONST_CHAR",-265],["FLOAT_CONST",-265],["HEX_FLOAT_CONST",-265],["CHAR_CONST",-265],["WCHAR_CONST",-265],["U8CHAR_CONST",-265],["U16CHAR_CONST",-265],["U32CHAR_CONST",-265],["STRING_LITERAL",-265],["WSTRING_LITERAL",-265],["U8STRING_LITERAL",-265],["U16STRING_LITERAL",-265],["U32STRING_LITERAL",-265],["RBRACE",-265],["ELSE",-265]]],[687,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["__ATTRIBUTE__",67],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[689,[["SEMI",700]]],[697,[["SEMI",-412],["PPPRAGMA",16],["_PRAGMA",17],["_STATIC_ASSERT",19],["ASM",271],["ID",256],["LPAREN",231],["TIMES",166],["TYPEID",414],["__ATTRIBUTE__",67],["LBRACE",144],["CASE",258],["DEFAULT",259],["IF",261],["SWITCH",263],["WHILE",264],["DO",265],["FOR",266],["GOTO",267],["BREAK",268],["CONTINUE",269],["RETURN",270],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[698,[["SEMI",-267],["PPPRAGMA",-267],["_PRAGMA",-267],["_STATIC_ASSERT",-267],["ASM",-267],["ID",-267],["LPAREN",-267],["TIMES",-267],["TYPEID",-267],["ENUM",-267],["VOID",-267],["_BOOL",-267],["CHAR",-267],["SHORT",-267],["INT",-267],["LONG",-267],["FLOAT",-267],["DOUBLE",-267],["_COMPLEX",-267],["SIGNED",-267],["UNSIGNED",-267],["__INT128",-267],["_ATOMIC",-267],["TYPEOF",-267],["CONST",-267],["RESTRICT",-267],["VOLATILE",-267],["AUTO",-267],["REGISTER",-267],["STATIC",-267],["EXTERN",-267],["TYPEDEF",-267],["_THREAD_LOCAL",-267],["INLINE",-267],["_NORETURN",-267],["_ALIGNAS",-267],["__ATTRIBUTE__",-267],["STRUCT",-267],["UNION",-267],["LBRACE",-267],["CASE",-267],["DEFAULT",-267],["IF",-267],["SWITCH",-267],["WHILE",-267],["DO",-267],["FOR",-267],["GOTO",-267],["BREAK",-267],["CONTINUE",-267],["RETURN",-267],["PLUSPLUS",-267],["MINUSMINUS",-267],["SIZEOF",-267],["_ALIGNOF",-267],["AND",-267],["PLUS",-267],["MINUS",-267],["NOT",-267],["LNOT",-267],["OFFSETOF",-267],["INT_CONST_DEC",-267],["INT_CONST_OCT",-267],["INT_CONST_HEX",-267],["INT_CONST_BIN",-267],["INT_CONST_CHAR",-267],["FLOAT_CONST",-267],["HEX_FLOAT_CONST",-267],["CHAR_CONST",-267],["WCHAR_CONST",-267],["U8CHAR_CONST",-267],["U16CHAR_CONST",-267],["U32CHAR_CONST",-267],["STRING_LITERAL",-267],["WSTRING_LITERAL",-267],["U8STRING_LITERAL",-267],["U16STRING_LITERAL",-267],["U32STRING_LITERAL",-267],["RBRACE",-267],["ELSE",-267]]],[700,[["SEMI",-382],["PPPRAGMA",-382],["_PRAGMA",-382],["_STATIC_ASSERT",-382],["ASM",-382],["ID",-382],["LPAREN",-382],["TIMES",-382],["TYPEID",-382],["ENUM",-382],["VOID",-382],["_BOOL",-382],["CHAR",-382],["SHORT",-382],["INT",-382],["LONG",-382],["FLOAT",-382],["DOUBLE",-382],["_COMPLEX",-382],["SIGNED",-382],["UNSIGNED",-382],["__INT128",-382],["_ATOMIC",-382],["TYPEOF",-382],["CONST",-382],["RESTRICT",-382],["VOLATILE",-382],["AUTO",-382],["REGISTER",-382],["STATIC",-382],["EXTERN",-382],["TYPEDEF",-382],["_THREAD_LOCAL",-382],["INLINE",-382],["_NORETURN",-382],["_ALIGNAS",-382],["__ATTRIBUTE__",-382],["STRUCT",-382],["UNION",-382],["LBRACE",-382],["CASE",-382],["DEFAULT",-382],["IF",-382],["SWITCH",-382],["WHILE",-382],["DO",-382],["FOR",-382],["GOTO",-382],["BREAK",-382],["CONTINUE",-382],["RETURN",-382],["PLUSPLUS",-382],["MINUSMINUS",-382],["SIZEOF",-382],["_ALIGNOF",-382],["AND",-382],["PLUS",-382],["MINUS",-382],["NOT",-382],["LNOT",-382],["OFFSETOF",-382],["INT_CONST_DEC",-382],["INT_CONST_OCT",-382],["INT_CONST_HEX",-382],["INT_CONST_BIN",-382],["INT_CONST_CHAR",-382],["FLOAT_CONST",-382],["HEX_FLOAT_CONST",-382],["CHAR_CONST",-382],["WCHAR_CONST",-382],["U8CHAR_CONST",-382],["U16CHAR_CONST",-382],["U32CHAR_CONST",-382],["STRING_LITERAL",-382],["WSTRING_LITERAL",-382],["U8STRING_LITERAL",-382],["U16STRING_LITERAL",-382],["U32STRING_LITERAL",-382],["RBRACE",-382],["ELSE",-382]]],[707,[["SEMI",-266],["PPPRAGMA",-266],["_PRAGMA",-266],["_STATIC_ASSERT",-266],["ASM",-266],["ID",-266],["LPAREN",-266],["TIMES",-266],["TYPEID",-266],["ENUM",-266],["VOID",-266],["_BOOL",-266],["CHAR",-266],["SHORT",-266],["INT",-266],["LONG",-266],["FLOAT",-266],["DOUBLE",-266],["_COMPLEX",-266],["SIGNED",-266],["UNSIGNED",-266],["__INT128",-266],["_ATOMIC",-266],["TYPEOF",-266],["CONST",-266],["RESTRICT",-266],["VOLATILE",-266],["AUTO",-266],["REGISTER",-266],["STATIC",-266],["EXTERN",-266],["TYPEDEF",-266],["_THREAD_LOCAL",-266],["INLINE",-266],["_NORETURN",-266],["_ALIGNAS",-266],["__ATTRIBUTE__",-266],["STRUCT",-266],["UNION",-266],["LBRACE",-266],["CASE",-266],["DEFAULT",-266],["IF",-266],["SWITCH",-266],["WHILE",-266],["DO",-266],["FOR",-266],["GOTO",-266],["BREAK",-266],["CONTINUE",-266],["RETURN",-266],["PLUSPLUS",-266],["MINUSMINUS",-266],["SIZEOF",-266],["_ALIGNOF",-266],["AND",-266],["PLUS",-266],["MINUS",-266],["NOT",-266],["LNOT",-266],["OFFSETOF",-266],["INT_CONST_DEC",-266],["INT_CONST_OCT",-266],["INT_CONST_HEX",-266],["INT_CONST_BIN",-266],["INT_CONST_CHAR",-266],["FLOAT_CONST",-266],["HEX_FLOAT_CONST",-266],["CHAR_CONST",-266],["WCHAR_CONST",-266],["U8CHAR_CONST",-266],["U16CHAR_CONST",-266],["U32CHAR_CONST",-266],["STRING_LITERAL",-266],["WSTRING_LITERAL",-266],["U8STRING_LITERAL",-266],["U16STRING_LITERAL",-266],["U32STRING_LITERAL",-266],["RBRACE",-266],["ELSE",-266]]],[709,[["SEMI",715]]],[715,[["SEMI",-383],["PPPRAGMA",-383],["_PRAGMA",-383],["_STATIC_ASSERT",-383],["ASM",-383],["ID",-383],["LPAREN",-383],["TIMES",-383],["TYPEID",-383],["ENUM",-383],["VOID",-383],["_BOOL",-383],["CHAR",-383],["SHORT",-383],["INT",-383],["LONG",-383],["FLOAT",-383],["DOUBLE",-383],["_COMPLEX",-383],["SIGNED",-383],["UNSIGNED",-383],["__INT128",-383],["_ATOMIC",-383],["TYPEOF",-383],["CONST",-383],["RESTRICT",-383],["VOLATILE",-383],["AUTO",-383],["REGISTER",-383],["STATIC",-383],["EXTERN",-383],["TYPEDEF",-383],["_THREAD_LOCAL",-383],["INLINE",-383],["_NORETURN",-383],["_ALIGNAS",-383],["__ATTRIBUTE__",-383],["STRUCT",-383],["UNION",-383],["LBRACE",-383],["CASE",-383],["DEFAULT",-383],["IF",-383],["SWITCH",-383],["WHILE",-383],["DO",-383],["FOR",-383],["GOTO",-383],["BREAK",-383],["CONTINUE",-383],["RETURN",-383],["PLUSPLUS",-383],["MINUSMINUS",-383],["SIZEOF",-383],["_ALIGNOF",-383],["AND",-383],["PLUS",-383],["MINUS",-383],["NOT",-383],["LNOT",-383],["OFFSETOF",-383],["INT_CONST_DEC",-383],["INT_CONST_OCT",-383],["INT_CONST_HEX",-383],["INT_CONST_BIN",-383],["INT_CONST_CHAR",-383],["FLOAT_CONST",-383],["HEX_FLOAT_CONST",-383],["CHAR_CONST",-383],["WCHAR_CONST",-383],["U8CHAR_CONST",-383],["U16CHAR_CONST",-383],["U32CHAR_CONST",-383],["STRING_LITERAL",-383],["WSTRING_LITERAL",-383],["U8STRING_LITERAL",-383],["U16STRING_LITERAL",-383],["U32STRING_LITERAL",-383],["RBRACE",-383],["ELSE",-383]]],[718,[["SEMI",725]]],[725,[["SEMI",-384],["PPPRAGMA",-384],["_PRAGMA",-384],["_STATIC_ASSERT",-384],["ASM",-384],["ID",-384],["LPAREN",-384],["TIMES",-384],["TYPEID",-384],["ENUM",-384],["VOID",-384],["_BOOL",-384],["CHAR",-384],["SHORT",-384],["INT",-384],["LONG",-384],["FLOAT",-384],["DOUBLE",-384],["_COMPLEX",-384],["SIGNED",-384],["UNSIGNED",-384],["__INT128",-384],["_ATOMIC",-384],["TYPEOF",-384],["CONST",-384],["RESTRICT",-384],["VOLATILE",-384],["AUTO",-384],["REGISTER",-384],["STATIC",-384],["EXTERN",-384],["TYPEDEF",-384],["_THREAD_LOCAL",-384],["INLINE",-384],["_NORETURN",-384],["_ALIGNAS",-384],["__ATTRIBUTE__",-384],["STRUCT",-384],["UNION",-384],["LBRACE",-384],["CASE",-384],["DEFAULT",-384],["IF",-384],["SWITCH",-384],["WHILE",-384],["DO",-384],["FOR",-384],["GOTO",-384],["BREAK",-384],["CONTINUE",-384],["RETURN",-384],["PLUSPLUS",-384],["MINUSMINUS",-384],["SIZEOF",-384],["_ALIGNOF",-384],["AND",-384],["PLUS",-384],["MINUS",-384],["NOT",-384],["LNOT",-384],["OFFSETOF",-384],["INT_CONST_DEC",-384],["INT_CONST_OCT",-384],["INT_CONST_HEX",-384],["INT_CONST_BIN",-384],["INT_CONST_CHAR",-384],["FLOAT_CONST",-384],["HEX_FLOAT_CONST",-384],["CHAR_CONST",-384],["WCHAR_CONST",-384],["U8CHAR_CONST",-384],["U16CHAR_CONST",-384],["U32CHAR_CONST",-384],["STRING_LITERAL",-384],["WSTRING_LITERAL",-384],["U8STRING_LITERAL",-384],["U16STRING_LITERAL",-384],["U32STRING_LITERAL",-384],["RBRACE",-384],["ELSE",-384]]],[727,[["SEMI",729]]],[729,[["SEMI",-385],["PPPRAGMA",-385],["_PRAGMA",-385],["_STATIC_ASSERT",-385],["ASM",-385],["ID",-385],["LPAREN",-385],["TIMES",-385],["TYPEID",-385],["ENUM",-385],["VOID",-385],["_BOOL",-385],["CHAR",-385],["SHORT",-385],["INT",-385],["LONG",-385],["FLOAT",-385],["DOUBLE",-385],["_COMPLEX",-385],["SIGNED",-385],["UNSIGNED",-385],["__INT128",-385],["_ATOMIC",-385],["TYPEOF",-385],["CONST",-385],["RESTRICT",-385],["VOLATILE",-385],["AUTO",-385],["REGISTER",-385],["STATIC",-385],["EXTERN",-385],["TYPEDEF",-385],["_THREAD_LOCAL",-385],["INLINE",-385],["_NORETURN",-385],["_ALIGNAS",-385],["__ATTRIBUTE__",-385],["STRUCT",-385],["UNION",-385],["LBRACE",-385],["CASE",-385],["DEFAULT",-385],["IF",-385],["SWITCH",-385],["WHILE",-385],["DO",-385],["FOR",-385],["GOTO",-385],["BREAK",-385],["CONTINUE",-385],["RETURN",-385],["PLUSPLUS",-385],["MINUSMINUS",-385],["SIZEOF",-385],["_ALIGNOF",-385],["AND",-385],["PLUS",-385],["MINUS",-385],["NOT",-385],["LNOT",-385],["OFFSETOF",-385],["INT_CONST_DEC",-385],["INT_CONST_OCT",-385],["INT_CONST_HEX",-385],["INT_CONST_BIN",-385],["INT_CONST_CHAR",-385],["FLOAT_CONST",-385],["HEX_FLOAT_CONST",-385],["CHAR_CONST",-385],["WCHAR_CONST",-385],["U8CHAR_CONST",-385],["U16CHAR_CONST",-385],["U32CHAR_CONST",-385],["STRING_LITERAL",-385],["WSTRING_LITERAL",-385],["U8STRING_LITERAL",-385],["U16STRING_LITERAL",-385],["U32STRING_LITERAL",-385],["RBRACE",-385],["ELSE",-385]]],[18,[["ID",31],["LPAREN",18],["TIMES",33]]],[22,[["ID",31],["LPAREN",18]]],[33,[["ID",-412],["LPAREN",-412],["TIMES",-412],["TYPEID",-412],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["__ATTRIBUTE__",-412],["COMMA",-412],["RPAREN",-412],["LBRACKET",-412]]],[40,[["ID",127],["TYPEID",128],["__ATTRIBUTE__",67],["LBRACE",-412]]],[41,[["ID",134],["TYPEID",135],["__ATTRIBUTE__",67],["LBRACE",-412]]],[68,[["ID",-180],["TYPEID",-180],["__ATTRIBUTE__",-180],["LBRACE",-180]]],[69,[["ID",-181],["TYPEID",-181],["__ATTRIBUTE__",-181],["LBRACE",-181]]],[87,[["ID",31],["LPAREN",89],["TYPEID",96]]],[89,[["ID",31],["LPAREN",89],["TIMES",33],["TYPEID",96]]],[101,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[103,[["ID",-412],["LPAREN",-412],["TIMES",-412],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["STATIC",202],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412],["RBRACKET",-412]]],[104,[["ID",177],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RPAREN",-412]]],[122,[["ID",-205],["LPAREN",-205],["TIMES",33],["TYPEID",-205],["__ATTRIBUTE__",-205],["COMMA",-205],["RPAREN",-205],["LBRACKET",-205]]],[123,[["ID",-41],["LPAREN",-41],["TIMES",-41],["TYPEID",-41],["__ATTRIBUTE__",-41],["PLUSPLUS",-41],["MINUSMINUS",-41],["SIZEOF",-41],["_ALIGNOF",-41],["AND",-41],["PLUS",-41],["MINUS",-41],["NOT",-41],["LNOT",-41],["OFFSETOF",-41],["INT_CONST_DEC",-41],["INT_CONST_OCT",-41],["INT_CONST_HEX",-41],["INT_CONST_BIN",-41],["INT_CONST_CHAR",-41],["FLOAT_CONST",-41],["HEX_FLOAT_CONST",-41],["CHAR_CONST",-41],["WCHAR_CONST",-41],["U8CHAR_CONST",-41],["U16CHAR_CONST",-41],["U32CHAR_CONST",-41],["STRING_LITERAL",-41],["WSTRING_LITERAL",-41],["U8STRING_LITERAL",-41],["U16STRING_LITERAL",-41],["U32STRING_LITERAL",-41],["COMMA",-41],["RPAREN",-41],["LBRACKET",-41],["RBRACKET",-41]]],[124,[["ID",-42],["LPAREN",-42],["TIMES",-42],["TYPEID",-42],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["__ATTRIBUTE__",-42],["PLUSPLUS",-42],["MINUSMINUS",-42],["SIZEOF",-42],["_ALIGNOF",-42],["AND",-42],["PLUS",-42],["MINUS",-42],["NOT",-42],["LNOT",-42],["OFFSETOF",-42],["INT_CONST_DEC",-42],["INT_CONST_OCT",-42],["INT_CONST_HEX",-42],["INT_CONST_BIN",-42],["INT_CONST_CHAR",-42],["FLOAT_CONST",-42],["HEX_FLOAT_CONST",-42],["CHAR_CONST",-42],["WCHAR_CONST",-42],["U8CHAR_CONST",-42],["U16CHAR_CONST",-42],["U32CHAR_CONST",-42],["STRING_LITERAL",-42],["WSTRING_LITERAL",-42],["U8STRING_LITERAL",-42],["U16STRING_LITERAL",-42],["U32STRING_LITERAL",-42],["COMMA",-42],["RPAREN",-42],["LBRACKET",-42]]],[125,[["ID",-207],["LPAREN",-207],["TIMES",-207],["TYPEID",-207],["_ATOMIC",-207],["CONST",-207],["RESTRICT",-207],["VOLATILE",-207],["STATIC",-207],["__ATTRIBUTE__",-207],["PLUSPLUS",-207],["MINUSMINUS",-207],["SIZEOF",-207],["_ALIGNOF",-207],["AND",-207],["PLUS",-207],["MINUS",-207],["NOT",-207],["LNOT",-207],["OFFSETOF",-207],["INT_CONST_DEC",-207],["INT_CONST_OCT",-207],["INT_CONST_HEX",-207],["INT_CONST_BIN",-207],["INT_CONST_CHAR",-207],["FLOAT_CONST",-207],["HEX_FLOAT_CONST",-207],["CHAR_CONST",-207],["WCHAR_CONST",-207],["U8CHAR_CONST",-207],["U16CHAR_CONST",-207],["U32CHAR_CONST",-207],["STRING_LITERAL",-207],["WSTRING_LITERAL",-207],["U8STRING_LITERAL",-207],["U16STRING_LITERAL",-207],["U32STRING_LITERAL",-207],["COMMA",-207],["RPAREN",-207],["LBRACKET",-207],["RBRACKET",-207]]],[132,[["ID",219],["TYPEID",220],["__ATTRIBUTE__",67],["LBRACE",-28]]],[139,[["ID",177],["LPAREN",231],["TIMES",166],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[140,[["ID",177],["LPAREN",160],["TIMES",166],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[150,[["ID",31],["LPAREN",89],["TIMES",33],["TYPEID",96]]],[155,[["ID",-412],["LPAREN",-412],["TIMES",-412],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["STATIC",281],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412],["RBRACKET",-412]]],[156,[["ID",177],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RPAREN",-412]]],[160,[["ID",177],["LPAREN",231],["TIMES",166],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[166,[["ID",-323],["LPAREN",-323],["TIMES",-323],["PLUSPLUS",-323],["MINUSMINUS",-323],["SIZEOF",-323],["_ALIGNOF",-323],["AND",-323],["PLUS",-323],["MINUS",-323],["NOT",-323],["LNOT",-323],["OFFSETOF",-323],["INT_CONST_DEC",-323],["INT_CONST_OCT",-323],["INT_CONST_HEX",-323],["INT_CONST_BIN",-323],["INT_CONST_CHAR",-323],["FLOAT_CONST",-323],["HEX_FLOAT_CONST",-323],["CHAR_CONST",-323],["WCHAR_CONST",-323],["U8CHAR_CONST",-323],["U16CHAR_CONST",-323],["U32CHAR_CONST",-323],["STRING_LITERAL",-323],["WSTRING_LITERAL",-323],["U8STRING_LITERAL",-323],["U16STRING_LITERAL",-323],["U32STRING_LITERAL",-323]]],[167,[["ID",-324],["LPAREN",-324],["TIMES",-324],["PLUSPLUS",-324],["MINUSMINUS",-324],["SIZEOF",-324],["_ALIGNOF",-324],["AND",-324],["PLUS",-324],["MINUS",-324],["NOT",-324],["LNOT",-324],["OFFSETOF",-324],["INT_CONST_DEC",-324],["INT_CONST_OCT",-324],["INT_CONST_HEX",-324],["INT_CONST_BIN",-324],["INT_CONST_CHAR",-324],["FLOAT_CONST",-324],["HEX_FLOAT_CONST",-324],["CHAR_CONST",-324],["WCHAR_CONST",-324],["U8CHAR_CONST",-324],["U16CHAR_CONST",-324],["U32CHAR_CONST",-324],["STRING_LITERAL",-324],["WSTRING_LITERAL",-324],["U8STRING_LITERAL",-324],["U16STRING_LITERAL",-324],["U32STRING_LITERAL",-324]]],[168,[["ID",-325],["LPAREN",-325],["TIMES",-325],["PLUSPLUS",-325],["MINUSMINUS",-325],["SIZEOF",-325],["_ALIGNOF",-325],["AND",-325],["PLUS",-325],["MINUS",-325],["NOT",-325],["LNOT",-325],["OFFSETOF",-325],["INT_CONST_DEC",-325],["INT_CONST_OCT",-325],["INT_CONST_HEX",-325],["INT_CONST_BIN",-325],["INT_CONST_CHAR",-325],["FLOAT_CONST",-325],["HEX_FLOAT_CONST",-325],["CHAR_CONST",-325],["WCHAR_CONST",-325],["U8CHAR_CONST",-325],["U16CHAR_CONST",-325],["U32CHAR_CONST",-325],["STRING_LITERAL",-325],["WSTRING_LITERAL",-325],["U8STRING_LITERAL",-325],["U16STRING_LITERAL",-325],["U32STRING_LITERAL",-325]]],[169,[["ID",-322],["LPAREN",-322],["TIMES",-322],["PLUSPLUS",-322],["MINUSMINUS",-322],["SIZEOF",-322],["_ALIGNOF",-322],["AND",-322],["PLUS",-322],["MINUS",-322],["NOT",-322],["LNOT",-322],["OFFSETOF",-322],["INT_CONST_DEC",-322],["INT_CONST_OCT",-322],["INT_CONST_HEX",-322],["INT_CONST_BIN",-322],["INT_CONST_CHAR",-322],["FLOAT_CONST",-322],["HEX_FLOAT_CONST",-322],["CHAR_CONST",-322],["WCHAR_CONST",-322],["U8CHAR_CONST",-322],["U16CHAR_CONST",-322],["U32CHAR_CONST",-322],["STRING_LITERAL",-322],["WSTRING_LITERAL",-322],["U8STRING_LITERAL",-322],["U16STRING_LITERAL",-322],["U32STRING_LITERAL",-322]]],[171,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[172,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[173,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[174,[["ID",177],["LPAREN",320],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[178,[["ID",-326],["LPAREN",-326],["TIMES",-326],["PLUSPLUS",-326],["MINUSMINUS",-326],["SIZEOF",-326],["_ALIGNOF",-326],["AND",-326],["PLUS",-326],["MINUS",-326],["NOT",-326],["LNOT",-326],["OFFSETOF",-326],["INT_CONST_DEC",-326],["INT_CONST_OCT",-326],["INT_CONST_HEX",-326],["INT_CONST_BIN",-326],["INT_CONST_CHAR",-326],["FLOAT_CONST",-326],["HEX_FLOAT_CONST",-326],["CHAR_CONST",-326],["WCHAR_CONST",-326],["U8CHAR_CONST",-326],["U16CHAR_CONST",-326],["U32CHAR_CONST",-326],["STRING_LITERAL",-326],["WSTRING_LITERAL",-326],["U8STRING_LITERAL",-326],["U16STRING_LITERAL",-326],["U32STRING_LITERAL",-326]]],[179,[["ID",-327],["LPAREN",-327],["TIMES",-327],["PLUSPLUS",-327],["MINUSMINUS",-327],["SIZEOF",-327],["_ALIGNOF",-327],["AND",-327],["PLUS",-327],["MINUS",-327],["NOT",-327],["LNOT",-327],["OFFSETOF",-327],["INT_CONST_DEC",-327],["INT_CONST_OCT",-327],["INT_CONST_HEX",-327],["INT_CONST_BIN",-327],["INT_CONST_CHAR",-327],["FLOAT_CONST",-327],["HEX_FLOAT_CONST",-327],["CHAR_CONST",-327],["WCHAR_CONST",-327],["U8CHAR_CONST",-327],["U16CHAR_CONST",-327],["U32CHAR_CONST",-327],["STRING_LITERAL",-327],["WSTRING_LITERAL",-327],["U8STRING_LITERAL",-327],["U16STRING_LITERAL",-327],["U32STRING_LITERAL",-327]]],[201,[["ID",177],["LPAREN",231],["TIMES",329],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACKET",-412]]],[202,[["ID",-412],["LPAREN",-412],["TIMES",-412],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412]]],[203,[["ID",-42],["LPAREN",-42],["TIMES",-42],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["STATIC",333],["PLUSPLUS",-42],["MINUSMINUS",-42],["SIZEOF",-42],["_ALIGNOF",-42],["AND",-42],["PLUS",-42],["MINUS",-42],["NOT",-42],["LNOT",-42],["OFFSETOF",-42],["INT_CONST_DEC",-42],["INT_CONST_OCT",-42],["INT_CONST_HEX",-42],["INT_CONST_BIN",-42],["INT_CONST_CHAR",-42],["FLOAT_CONST",-42],["HEX_FLOAT_CONST",-42],["CHAR_CONST",-42],["WCHAR_CONST",-42],["U8CHAR_CONST",-42],["U16CHAR_CONST",-42],["U32CHAR_CONST",-42],["STRING_LITERAL",-42],["WSTRING_LITERAL",-42],["U8STRING_LITERAL",-42],["U16STRING_LITERAL",-42],["U32STRING_LITERAL",-42],["RBRACKET",-42]]],[211,[["ID",31],["LPAREN",345],["TIMES",33],["TYPEID",347],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["COMMA",-412],["RPAREN",-412],["LBRACKET",346]]],[213,[["ID",31],["LPAREN",89],["TIMES",33],["TYPEID",96]]],[215,[["ID",-206],["LPAREN",-206],["TYPEID",-206],["__ATTRIBUTE__",-206],["COMMA",-206],["RPAREN",-206],["LBRACKET",-206]]],[216,[["ID",-208],["LPAREN",-208],["TIMES",-208],["TYPEID",-208],["_ATOMIC",-208],["CONST",-208],["RESTRICT",-208],["VOLATILE",-208],["STATIC",-208],["__ATTRIBUTE__",-208],["PLUSPLUS",-208],["MINUSMINUS",-208],["SIZEOF",-208],["_ALIGNOF",-208],["AND",-208],["PLUS",-208],["MINUS",-208],["NOT",-208],["LNOT",-208],["OFFSETOF",-208],["INT_CONST_DEC",-208],["INT_CONST_OCT",-208],["INT_CONST_HEX",-208],["INT_CONST_BIN",-208],["INT_CONST_CHAR",-208],["FLOAT_CONST",-208],["HEX_FLOAT_CONST",-208],["CHAR_CONST",-208],["WCHAR_CONST",-208],["U8CHAR_CONST",-208],["U16CHAR_CONST",-208],["U32CHAR_CONST",-208],["STRING_LITERAL",-208],["WSTRING_LITERAL",-208],["U8STRING_LITERAL",-208],["U16STRING_LITERAL",-208],["U32STRING_LITERAL",-208],["COMMA",-208],["RPAREN",-208],["LBRACKET",-208],["RBRACKET",-208]]],[217,[["ID",353]]],[218,[["ID",353]]],[231,[["ID",177],["LPAREN",231],["TIMES",166],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["LBRACE",144],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[239,[["ID",397],["TYPEID",398],["CONST",396],["COMMA",-412],["RPAREN",-412]]],[258,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[267,[["ID",416],["TYPEID",417]]],[280,[["ID",177],["LPAREN",231],["TIMES",430],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACKET",-412]]],[281,[["ID",-412],["LPAREN",-412],["TIMES",-412],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412]]],[282,[["ID",-42],["LPAREN",-42],["TIMES",-42],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["STATIC",432],["PLUSPLUS",-42],["MINUSMINUS",-42],["SIZEOF",-42],["_ALIGNOF",-42],["AND",-42],["PLUS",-42],["MINUS",-42],["NOT",-42],["LNOT",-42],["OFFSETOF",-42],["INT_CONST_DEC",-42],["INT_CONST_OCT",-42],["INT_CONST_HEX",-42],["INT_CONST_BIN",-42],["INT_CONST_CHAR",-42],["FLOAT_CONST",-42],["HEX_FLOAT_CONST",-42],["CHAR_CONST",-42],["WCHAR_CONST",-42],["U8CHAR_CONST",-42],["U16CHAR_CONST",-42],["U32CHAR_CONST",-42],["STRING_LITERAL",-42],["WSTRING_LITERAL",-42],["U8STRING_LITERAL",-42],["U16STRING_LITERAL",-42],["U32STRING_LITERAL",-42],["RBRACKET",-42]]],[291,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[292,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[293,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[294,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[295,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[296,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[297,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[298,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[299,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[300,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[301,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[302,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[303,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[304,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[305,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[306,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[307,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[308,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[309,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[310,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[311,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RPAREN",459]]],[312,[["ID",461],["TYPEID",462]]],[313,[["ID",463],["TYPEID",464]]],[320,[["ID",177],["LPAREN",231],["TIMES",166],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[329,[["ID",-323],["LPAREN",-323],["TIMES",-323],["PLUSPLUS",-323],["MINUSMINUS",-323],["SIZEOF",-323],["_ALIGNOF",-323],["AND",-323],["PLUS",-323],["MINUS",-323],["NOT",-323],["LNOT",-323],["OFFSETOF",-323],["INT_CONST_DEC",-323],["INT_CONST_OCT",-323],["INT_CONST_HEX",-323],["INT_CONST_BIN",-323],["INT_CONST_CHAR",-323],["FLOAT_CONST",-323],["HEX_FLOAT_CONST",-323],["CHAR_CONST",-323],["WCHAR_CONST",-323],["U8CHAR_CONST",-323],["U16CHAR_CONST",-323],["U32CHAR_CONST",-323],["STRING_LITERAL",-323],["WSTRING_LITERAL",-323],["U8STRING_LITERAL",-323],["U16STRING_LITERAL",-323],["U32STRING_LITERAL",-323],["RBRACKET",470]]],[332,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[333,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[337,[["ID",177]]],[341,[["ID",31],["LPAREN",345],["TYPEID",347],["__ATTRIBUTE__",-234],["COMMA",-234],["RPAREN",-234],["LBRACKET",346]]],[345,[["ID",31],["LPAREN",345],["TIMES",33],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RPAREN",-412],["LBRACKET",346]]],[346,[["ID",-412],["LPAREN",-412],["TIMES",489],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["STATIC",490],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412],["RBRACKET",-412]]],[377,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[379,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[380,[["ID",-281],["LPAREN",-281],["TIMES",-281],["PLUSPLUS",-281],["MINUSMINUS",-281],["SIZEOF",-281],["_ALIGNOF",-281],["AND",-281],["PLUS",-281],["MINUS",-281],["NOT",-281],["LNOT",-281],["OFFSETOF",-281],["INT_CONST_DEC",-281],["INT_CONST_OCT",-281],["INT_CONST_HEX",-281],["INT_CONST_BIN",-281],["INT_CONST_CHAR",-281],["FLOAT_CONST",-281],["HEX_FLOAT_CONST",-281],["CHAR_CONST",-281],["WCHAR_CONST",-281],["U8CHAR_CONST",-281],["U16CHAR_CONST",-281],["U32CHAR_CONST",-281],["STRING_LITERAL",-281],["WSTRING_LITERAL",-281],["U8STRING_LITERAL",-281],["U16STRING_LITERAL",-281],["U32STRING_LITERAL",-281]]],[381,[["ID",-282],["LPAREN",-282],["TIMES",-282],["PLUSPLUS",-282],["MINUSMINUS",-282],["SIZEOF",-282],["_ALIGNOF",-282],["AND",-282],["PLUS",-282],["MINUS",-282],["NOT",-282],["LNOT",-282],["OFFSETOF",-282],["INT_CONST_DEC",-282],["INT_CONST_OCT",-282],["INT_CONST_HEX",-282],["INT_CONST_BIN",-282],["INT_CONST_CHAR",-282],["FLOAT_CONST",-282],["HEX_FLOAT_CONST",-282],["CHAR_CONST",-282],["WCHAR_CONST",-282],["U8CHAR_CONST",-282],["U16CHAR_CONST",-282],["U32CHAR_CONST",-282],["STRING_LITERAL",-282],["WSTRING_LITERAL",-282],["U8STRING_LITERAL",-282],["U16STRING_LITERAL",-282],["U32STRING_LITERAL",-282]]],[382,[["ID",-283],["LPAREN",-283],["TIMES",-283],["PLUSPLUS",-283],["MINUSMINUS",-283],["SIZEOF",-283],["_ALIGNOF",-283],["AND",-283],["PLUS",-283],["MINUS",-283],["NOT",-283],["LNOT",-283],["OFFSETOF",-283],["INT_CONST_DEC",-283],["INT_CONST_OCT",-283],["INT_CONST_HEX",-283],["INT_CONST_BIN",-283],["INT_CONST_CHAR",-283],["FLOAT_CONST",-283],["HEX_FLOAT_CONST",-283],["CHAR_CONST",-283],["WCHAR_CONST",-283],["U8CHAR_CONST",-283],["U16CHAR_CONST",-283],["U32CHAR_CONST",-283],["STRING_LITERAL",-283],["WSTRING_LITERAL",-283],["U8STRING_LITERAL",-283],["U16STRING_LITERAL",-283],["U32STRING_LITERAL",-283]]],[383,[["ID",-284],["LPAREN",-284],["TIMES",-284],["PLUSPLUS",-284],["MINUSMINUS",-284],["SIZEOF",-284],["_ALIGNOF",-284],["AND",-284],["PLUS",-284],["MINUS",-284],["NOT",-284],["LNOT",-284],["OFFSETOF",-284],["INT_CONST_DEC",-284],["INT_CONST_OCT",-284],["INT_CONST_HEX",-284],["INT_CONST_BIN",-284],["INT_CONST_CHAR",-284],["FLOAT_CONST",-284],["HEX_FLOAT_CONST",-284],["CHAR_CONST",-284],["WCHAR_CONST",-284],["U8CHAR_CONST",-284],["U16CHAR_CONST",-284],["U32CHAR_CONST",-284],["STRING_LITERAL",-284],["WSTRING_LITERAL",-284],["U8STRING_LITERAL",-284],["U16STRING_LITERAL",-284],["U32STRING_LITERAL",-284]]],[384,[["ID",-285],["LPAREN",-285],["TIMES",-285],["PLUSPLUS",-285],["MINUSMINUS",-285],["SIZEOF",-285],["_ALIGNOF",-285],["AND",-285],["PLUS",-285],["MINUS",-285],["NOT",-285],["LNOT",-285],["OFFSETOF",-285],["INT_CONST_DEC",-285],["INT_CONST_OCT",-285],["INT_CONST_HEX",-285],["INT_CONST_BIN",-285],["INT_CONST_CHAR",-285],["FLOAT_CONST",-285],["HEX_FLOAT_CONST",-285],["CHAR_CONST",-285],["WCHAR_CONST",-285],["U8CHAR_CONST",-285],["U16CHAR_CONST",-285],["U32CHAR_CONST",-285],["STRING_LITERAL",-285],["WSTRING_LITERAL",-285],["U8STRING_LITERAL",-285],["U16STRING_LITERAL",-285],["U32STRING_LITERAL",-285]]],[385,[["ID",-286],["LPAREN",-286],["TIMES",-286],["PLUSPLUS",-286],["MINUSMINUS",-286],["SIZEOF",-286],["_ALIGNOF",-286],["AND",-286],["PLUS",-286],["MINUS",-286],["NOT",-286],["LNOT",-286],["OFFSETOF",-286],["INT_CONST_DEC",-286],["INT_CONST_OCT",-286],["INT_CONST_HEX",-286],["INT_CONST_BIN",-286],["INT_CONST_CHAR",-286],["FLOAT_CONST",-286],["HEX_FLOAT_CONST",-286],["CHAR_CONST",-286],["WCHAR_CONST",-286],["U8CHAR_CONST",-286],["U16CHAR_CONST",-286],["U32CHAR_CONST",-286],["STRING_LITERAL",-286],["WSTRING_LITERAL",-286],["U8STRING_LITERAL",-286],["U16STRING_LITERAL",-286],["U32STRING_LITERAL",-286]]],[386,[["ID",-287],["LPAREN",-287],["TIMES",-287],["PLUSPLUS",-287],["MINUSMINUS",-287],["SIZEOF",-287],["_ALIGNOF",-287],["AND",-287],["PLUS",-287],["MINUS",-287],["NOT",-287],["LNOT",-287],["OFFSETOF",-287],["INT_CONST_DEC",-287],["INT_CONST_OCT",-287],["INT_CONST_HEX",-287],["INT_CONST_BIN",-287],["INT_CONST_CHAR",-287],["FLOAT_CONST",-287],["HEX_FLOAT_CONST",-287],["CHAR_CONST",-287],["WCHAR_CONST",-287],["U8CHAR_CONST",-287],["U16CHAR_CONST",-287],["U32CHAR_CONST",-287],["STRING_LITERAL",-287],["WSTRING_LITERAL",-287],["U8STRING_LITERAL",-287],["U16STRING_LITERAL",-287],["U32STRING_LITERAL",-287]]],[387,[["ID",-288],["LPAREN",-288],["TIMES",-288],["PLUSPLUS",-288],["MINUSMINUS",-288],["SIZEOF",-288],["_ALIGNOF",-288],["AND",-288],["PLUS",-288],["MINUS",-288],["NOT",-288],["LNOT",-288],["OFFSETOF",-288],["INT_CONST_DEC",-288],["INT_CONST_OCT",-288],["INT_CONST_HEX",-288],["INT_CONST_BIN",-288],["INT_CONST_CHAR",-288],["FLOAT_CONST",-288],["HEX_FLOAT_CONST",-288],["CHAR_CONST",-288],["WCHAR_CONST",-288],["U8CHAR_CONST",-288],["U16CHAR_CONST",-288],["U32CHAR_CONST",-288],["STRING_LITERAL",-288],["WSTRING_LITERAL",-288],["U8STRING_LITERAL",-288],["U16STRING_LITERAL",-288],["U32STRING_LITERAL",-288]]],[388,[["ID",-289],["LPAREN",-289],["TIMES",-289],["PLUSPLUS",-289],["MINUSMINUS",-289],["SIZEOF",-289],["_ALIGNOF",-289],["AND",-289],["PLUS",-289],["MINUS",-289],["NOT",-289],["LNOT",-289],["OFFSETOF",-289],["INT_CONST_DEC",-289],["INT_CONST_OCT",-289],["INT_CONST_HEX",-289],["INT_CONST_BIN",-289],["INT_CONST_CHAR",-289],["FLOAT_CONST",-289],["HEX_FLOAT_CONST",-289],["CHAR_CONST",-289],["WCHAR_CONST",-289],["U8CHAR_CONST",-289],["U16CHAR_CONST",-289],["U32CHAR_CONST",-289],["STRING_LITERAL",-289],["WSTRING_LITERAL",-289],["U8STRING_LITERAL",-289],["U16STRING_LITERAL",-289],["U32STRING_LITERAL",-289]]],[389,[["ID",-290],["LPAREN",-290],["TIMES",-290],["PLUSPLUS",-290],["MINUSMINUS",-290],["SIZEOF",-290],["_ALIGNOF",-290],["AND",-290],["PLUS",-290],["MINUS",-290],["NOT",-290],["LNOT",-290],["OFFSETOF",-290],["INT_CONST_DEC",-290],["INT_CONST_OCT",-290],["INT_CONST_HEX",-290],["INT_CONST_BIN",-290],["INT_CONST_CHAR",-290],["FLOAT_CONST",-290],["HEX_FLOAT_CONST",-290],["CHAR_CONST",-290],["WCHAR_CONST",-290],["U8CHAR_CONST",-290],["U16CHAR_CONST",-290],["U32CHAR_CONST",-290],["STRING_LITERAL",-290],["WSTRING_LITERAL",-290],["U8STRING_LITERAL",-290],["U16STRING_LITERAL",-290],["U32STRING_LITERAL",-290]]],[390,[["ID",-291],["LPAREN",-291],["TIMES",-291],["PLUSPLUS",-291],["MINUSMINUS",-291],["SIZEOF",-291],["_ALIGNOF",-291],["AND",-291],["PLUS",-291],["MINUS",-291],["NOT",-291],["LNOT",-291],["OFFSETOF",-291],["INT_CONST_DEC",-291],["INT_CONST_OCT",-291],["INT_CONST_HEX",-291],["INT_CONST_BIN",-291],["INT_CONST_CHAR",-291],["FLOAT_CONST",-291],["HEX_FLOAT_CONST",-291],["CHAR_CONST",-291],["WCHAR_CONST",-291],["U8CHAR_CONST",-291],["U16CHAR_CONST",-291],["U32CHAR_CONST",-291],["STRING_LITERAL",-291],["WSTRING_LITERAL",-291],["U8STRING_LITERAL",-291],["U16STRING_LITERAL",-291],["U32STRING_LITERAL",-291]]],[407,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[408,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[409,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[426,[["ID",177],["LPAREN",231],["TIMES",166],["LBRACE",144],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[427,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[430,[["ID",-323],["LPAREN",-323],["TIMES",-323],["PLUSPLUS",-323],["MINUSMINUS",-323],["SIZEOF",-323],["_ALIGNOF",-323],["AND",-323],["PLUS",-323],["MINUS",-323],["NOT",-323],["LNOT",-323],["OFFSETOF",-323],["INT_CONST_DEC",-323],["INT_CONST_OCT",-323],["INT_CONST_HEX",-323],["INT_CONST_BIN",-323],["INT_CONST_CHAR",-323],["FLOAT_CONST",-323],["HEX_FLOAT_CONST",-323],["CHAR_CONST",-323],["WCHAR_CONST",-323],["U8CHAR_CONST",-323],["U16CHAR_CONST",-323],["U32CHAR_CONST",-323],["STRING_LITERAL",-323],["WSTRING_LITERAL",-323],["U8STRING_LITERAL",-323],["U16STRING_LITERAL",-323],["U32STRING_LITERAL",-323],["RBRACKET",544]]],[431,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[432,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[435,[["ID",177],["LPAREN",160],["TIMES",166],["LBRACE",144],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[481,[["ID",-412],["LPAREN",-412],["TIMES",-412],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["STATIC",560],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412],["RBRACKET",-412]]],[482,[["ID",177],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RPAREN",-412]]],[485,[["ID",31],["LPAREN",345],["RPAREN",-234],["LBRACKET",346]]],[488,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACKET",-412]]],[490,[["ID",-412],["LPAREN",-412],["TIMES",-412],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412]]],[491,[["ID",-42],["LPAREN",-42],["TIMES",-42],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["STATIC",569],["PLUSPLUS",-42],["MINUSMINUS",-42],["SIZEOF",-42],["_ALIGNOF",-42],["AND",-42],["PLUS",-42],["MINUS",-42],["NOT",-42],["LNOT",-42],["OFFSETOF",-42],["INT_CONST_DEC",-42],["INT_CONST_OCT",-42],["INT_CONST_HEX",-42],["INT_CONST_BIN",-42],["INT_CONST_CHAR",-42],["FLOAT_CONST",-42],["HEX_FLOAT_CONST",-42],["CHAR_CONST",-42],["WCHAR_CONST",-42],["U8CHAR_CONST",-42],["U16CHAR_CONST",-42],["U32CHAR_CONST",-42],["STRING_LITERAL",-42],["WSTRING_LITERAL",-42],["U8STRING_LITERAL",-42],["U16STRING_LITERAL",-42],["U32STRING_LITERAL",-42],["RBRACKET",-42]]],[492,[["ID",177],["LPAREN",231],["TIMES",571],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACKET",-412]]],[494,[["ID",177],["LPAREN",231],["TIMES",166],["LBRACE",144],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[496,[["ID",353],["RBRACE",-197],["COMMA",-197]]],[515,[["ID",397],["TYPEID",398],["CONST",396],["COMMA",-412],["RPAREN",-412]]],[516,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[517,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[521,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[540,[["ID",-412],["LPAREN",-412],["TIMES",-412],["LBRACE",-412],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412],["RBRACE",-412],["LBRACKET",604],["PERIOD",605]]],[548,[["ID",-412],["LPAREN",-412],["TIMES",-412],["LBRACE",-412],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412],["LBRACKET",604],["PERIOD",605]]],[550,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[553,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[556,[["ID",177]]],[559,[["ID",177],["LPAREN",231],["TIMES",615],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RBRACKET",-412]]],[560,[["ID",-412],["LPAREN",-412],["TIMES",-412],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412]]],[561,[["ID",-42],["LPAREN",-42],["TIMES",-42],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["STATIC",617],["PLUSPLUS",-42],["MINUSMINUS",-42],["SIZEOF",-42],["_ALIGNOF",-42],["AND",-42],["PLUS",-42],["MINUS",-42],["NOT",-42],["LNOT",-42],["OFFSETOF",-42],["INT_CONST_DEC",-42],["INT_CONST_OCT",-42],["INT_CONST_HEX",-42],["INT_CONST_BIN",-42],["INT_CONST_CHAR",-42],["FLOAT_CONST",-42],["HEX_FLOAT_CONST",-42],["CHAR_CONST",-42],["WCHAR_CONST",-42],["U8CHAR_CONST",-42],["U16CHAR_CONST",-42],["U32CHAR_CONST",-42],["STRING_LITERAL",-42],["WSTRING_LITERAL",-42],["U8STRING_LITERAL",-42],["U16STRING_LITERAL",-42],["U32STRING_LITERAL",-42],["RBRACKET",-42]]],[568,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[569,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[571,[["ID",-323],["LPAREN",-323],["TIMES",-323],["PLUSPLUS",-323],["MINUSMINUS",-323],["SIZEOF",-323],["_ALIGNOF",-323],["AND",-323],["PLUS",-323],["MINUS",-323],["NOT",-323],["LNOT",-323],["OFFSETOF",-323],["INT_CONST_DEC",-323],["INT_CONST_OCT",-323],["INT_CONST_HEX",-323],["INT_CONST_BIN",-323],["INT_CONST_CHAR",-323],["FLOAT_CONST",-323],["HEX_FLOAT_CONST",-323],["CHAR_CONST",-323],["WCHAR_CONST",-323],["U8CHAR_CONST",-323],["U16CHAR_CONST",-323],["U32CHAR_CONST",-323],["STRING_LITERAL",-323],["WSTRING_LITERAL",-323],["U8STRING_LITERAL",-323],["U16STRING_LITERAL",-323],["U32STRING_LITERAL",-323],["RBRACKET",624]]],[576,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[580,[["ID",31],["LPAREN",89],["TIMES",33],["TYPEID",96],["__ATTRIBUTE__",67],["COLON",-412]]],[582,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[593,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[599,[["ID",-23],["LPAREN",-23],["TIMES",-23],["LBRACE",-23],["PLUSPLUS",-23],["MINUSMINUS",-23],["SIZEOF",-23],["_ALIGNOF",-23],["AND",-23],["PLUS",-23],["MINUS",-23],["NOT",-23],["LNOT",-23],["OFFSETOF",-23],["INT_CONST_DEC",-23],["INT_CONST_OCT",-23],["INT_CONST_HEX",-23],["INT_CONST_BIN",-23],["INT_CONST_CHAR",-23],["FLOAT_CONST",-23],["HEX_FLOAT_CONST",-23],["CHAR_CONST",-23],["WCHAR_CONST",-23],["U8CHAR_CONST",-23],["U16CHAR_CONST",-23],["U32CHAR_CONST",-23],["STRING_LITERAL",-23],["WSTRING_LITERAL",-23],["U8STRING_LITERAL",-23],["U16STRING_LITERAL",-23],["U32STRING_LITERAL",-23],["RBRACE",-35]]],[600,[["ID",177],["LPAREN",231],["TIMES",166],["LBRACE",144],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[601,[["ID",-24],["LPAREN",-24],["TIMES",-24],["LBRACE",-24],["PLUSPLUS",-24],["MINUSMINUS",-24],["SIZEOF",-24],["_ALIGNOF",-24],["AND",-24],["PLUS",-24],["MINUS",-24],["NOT",-24],["LNOT",-24],["OFFSETOF",-24],["INT_CONST_DEC",-24],["INT_CONST_OCT",-24],["INT_CONST_HEX",-24],["INT_CONST_BIN",-24],["INT_CONST_CHAR",-24],["FLOAT_CONST",-24],["HEX_FLOAT_CONST",-24],["CHAR_CONST",-24],["WCHAR_CONST",-24],["U8CHAR_CONST",-24],["U16CHAR_CONST",-24],["U32CHAR_CONST",-24],["STRING_LITERAL",-24],["WSTRING_LITERAL",-24],["U8STRING_LITERAL",-24],["U16STRING_LITERAL",-24],["U32STRING_LITERAL",-24]]],[604,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[605,[["ID",177]]],[609,[["ID",-23],["LPAREN",-23],["TIMES",-23],["LBRACE",-23],["PLUSPLUS",-23],["MINUSMINUS",-23],["SIZEOF",-23],["_ALIGNOF",-23],["AND",-23],["PLUS",-23],["MINUS",-23],["NOT",-23],["LNOT",-23],["OFFSETOF",-23],["INT_CONST_DEC",-23],["INT_CONST_OCT",-23],["INT_CONST_HEX",-23],["INT_CONST_BIN",-23],["INT_CONST_CHAR",-23],["FLOAT_CONST",-23],["HEX_FLOAT_CONST",-23],["CHAR_CONST",-23],["WCHAR_CONST",-23],["U8CHAR_CONST",-23],["U16CHAR_CONST",-23],["U32CHAR_CONST",-23],["STRING_LITERAL",-23],["WSTRING_LITERAL",-23],["U8STRING_LITERAL",-23],["U16STRING_LITERAL",-23],["U32STRING_LITERAL",-23]]],[615,[["ID",-323],["LPAREN",-323],["TIMES",-323],["PLUSPLUS",-323],["MINUSMINUS",-323],["SIZEOF",-323],["_ALIGNOF",-323],["AND",-323],["PLUS",-323],["MINUS",-323],["NOT",-323],["LNOT",-323],["OFFSETOF",-323],["INT_CONST_DEC",-323],["INT_CONST_OCT",-323],["INT_CONST_HEX",-323],["INT_CONST_BIN",-323],["INT_CONST_CHAR",-323],["FLOAT_CONST",-323],["HEX_FLOAT_CONST",-323],["CHAR_CONST",-323],["WCHAR_CONST",-323],["U8CHAR_CONST",-323],["U16CHAR_CONST",-323],["U32CHAR_CONST",-323],["STRING_LITERAL",-323],["WSTRING_LITERAL",-323],["U8STRING_LITERAL",-323],["U16STRING_LITERAL",-323],["U32STRING_LITERAL",-323],["RBRACKET",656]]],[616,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[617,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[628,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[640,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RPAREN",-412]]],[644,[["ID",-412],["LPAREN",-412],["TIMES",-412],["LBRACE",-412],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412],["RBRACE",358],["LBRACKET",604],["PERIOD",605]]],[646,[["ID",-227],["LPAREN",-227],["TIMES",-227],["LBRACE",-227],["PLUSPLUS",-227],["MINUSMINUS",-227],["SIZEOF",-227],["_ALIGNOF",-227],["AND",-227],["PLUS",-227],["MINUS",-227],["NOT",-227],["LNOT",-227],["OFFSETOF",-227],["INT_CONST_DEC",-227],["INT_CONST_OCT",-227],["INT_CONST_HEX",-227],["INT_CONST_BIN",-227],["INT_CONST_CHAR",-227],["FLOAT_CONST",-227],["HEX_FLOAT_CONST",-227],["CHAR_CONST",-227],["WCHAR_CONST",-227],["U8CHAR_CONST",-227],["U16CHAR_CONST",-227],["U32CHAR_CONST",-227],["STRING_LITERAL",-227],["WSTRING_LITERAL",-227],["U8STRING_LITERAL",-227],["U16STRING_LITERAL",-227],["U32STRING_LITERAL",-227]]],[651,[["ID",-412],["LPAREN",-412],["TIMES",-412],["LBRACE",-412],["PLUSPLUS",-412],["MINUSMINUS",-412],["SIZEOF",-412],["_ALIGNOF",-412],["AND",-412],["PLUS",-412],["MINUS",-412],["NOT",-412],["LNOT",-412],["OFFSETOF",-412],["INT_CONST_DEC",-412],["INT_CONST_OCT",-412],["INT_CONST_HEX",-412],["INT_CONST_BIN",-412],["INT_CONST_CHAR",-412],["FLOAT_CONST",-412],["HEX_FLOAT_CONST",-412],["CHAR_CONST",-412],["WCHAR_CONST",-412],["U8CHAR_CONST",-412],["U16CHAR_CONST",-412],["U32CHAR_CONST",-412],["STRING_LITERAL",-412],["WSTRING_LITERAL",-412],["U8STRING_LITERAL",-412],["U16STRING_LITERAL",-412],["U32STRING_LITERAL",-412],["RBRACE",358],["LBRACKET",604],["PERIOD",605]]],[653,[["ID",177]]],[654,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[665,[["ID",177],["LPAREN",231],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199],["RPAREN",-412]]],[674,[["ID",692],["TYPEID",693]]],[676,[["ID",177],["LPAREN",231],["TIMES",166],["LBRACE",144],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[678,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[703,[["ID",177],["LPAREN",160],["TIMES",166],["PLUSPLUS",171],["MINUSMINUS",172],["SIZEOF",174],["_ALIGNOF",175],["AND",169],["PLUS",167],["MINUS",168],["NOT",178],["LNOT",179],["OFFSETOF",183],["INT_CONST_DEC",184],["INT_CONST_OCT",185],["INT_CONST_HEX",186],["INT_CONST_BIN",187],["INT_CONST_CHAR",188],["FLOAT_CONST",189],["HEX_FLOAT_CONST",190],["CHAR_CONST",191],["WCHAR_CONST",192],["U8CHAR_CONST",193],["U16CHAR_CONST",194],["U32CHAR_CONST",195],["STRING_LITERAL",158],["WSTRING_LITERAL",196],["U8STRING_LITERAL",197],["U16STRING_LITERAL",198],["U32STRING_LITERAL",199]]],[717,[["ID",723],["TYPEID",724],["RPAREN",-412]]],[728,[["ID",730],["TYPEID",731]]],[17,[["LPAREN",99]]],[19,[["LPAREN",101]]],[20,[["LPAREN",102]]],[55,[["LPAREN",139]]],[66,[["LPAREN",140]]],[67,[["LPAREN",141]]],[117,[["LPAREN",138]]],[141,[["LPAREN",239]]],[154,[["LPAREN",279]]],[175,[["LPAREN",321]]],[183,[["LPAREN",326]]],[225,[["LPAREN",370],["TIMES",33],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",88],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["COMMA",-412],["RPAREN",-412],["LBRACKET",346]]],[261,[["LPAREN",407]]],[263,[["LPAREN",408]]],[264,[["LPAREN",409]]],[266,[["LPAREN",415]]],[271,[["LPAREN",-412],["VOLATILE",-412],["INLINE",-412],["GOTO",-412]]],[342,[["LPAREN",482],["__ATTRIBUTE__",-70],["COMMA",-70],["RPAREN",-70],["LBRACKET",481]]],[347,[["LPAREN",-59],["__ATTRIBUTE__",-59],["COMMA",-59],["RPAREN",-59],["LBRACKET",-59]]],[348,[["LPAREN",493],["__ATTRIBUTE__",-236],["COMMA",-236],["RPAREN",-236],["LBRACKET",492]]],[369,[["LPAREN",-173],["TIMES",-173],["VOID",-173],["_BOOL",-173],["CHAR",-173],["SHORT",-173],["INT",-173],["LONG",-173],["FLOAT",-173],["DOUBLE",-173],["_COMPLEX",-173],["SIGNED",-173],["UNSIGNED",-173],["__INT128",-173],["_ATOMIC",-173],["CONST",-173],["RESTRICT",-173],["VOLATILE",-173],["_ALIGNAS",-173],["__ATTRIBUTE__",-173],["COMMA",-173],["RPAREN",-173],["LBRACKET",-173]]],[370,[["LPAREN",370],["TIMES",33],["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RPAREN",-412],["LBRACKET",346]]],[371,[["LPAREN",370],["COMMA",-234],["RPAREN",-234],["LBRACKET",346]]],[397,[["LPAREN",516],["COMMA",-408],["RPAREN",-408]]],[398,[["LPAREN",517],["COMMA",-409],["RPAREN",-409]]],[422,[["LPAREN",534],["VOLATILE",535],["INLINE",536],["GOTO",537]]],[423,[["LPAREN",-9],["VOLATILE",-9],["INLINE",-9],["GOTO",-9]]],[424,[["LPAREN",-10],["VOLATILE",-10],["INLINE",-10],["GOTO",-10]]],[479,[["LPAREN",482],["__ATTRIBUTE__",-71],["COMMA",-71],["RPAREN",-71],["LBRACKET",481]]],[480,[["LPAREN",493],["__ATTRIBUTE__",-235],["COMMA",-235],["RPAREN",-235],["LBRACKET",492]]],[526,[["LPAREN",593]]],[535,[["LPAREN",-397],["VOLATILE",-397],["INLINE",-397],["GOTO",-397]]],[536,[["LPAREN",-398],["VOLATILE",-398],["INLINE",-398],["GOTO",-398]]],[537,[["LPAREN",-399],["VOLATILE",-399],["INLINE",-399],["GOTO",-399]]],[564,[["LPAREN",-237],["__ATTRIBUTE__",-237],["COMMA",-237],["RPAREN",-237],["LBRACKET",-237]]],[565,[["LPAREN",-243],["__ATTRIBUTE__",-243],["COMMA",-243],["RPAREN",-243],["LBRACKET",-243]]],[567,[["LPAREN",-241],["__ATTRIBUTE__",-241],["COMMA",-241],["RPAREN",-241],["LBRACKET",-241]]],[618,[["LPAREN",-64],["__ATTRIBUTE__",-64],["COMMA",-64],["RPAREN",-64],["LBRACKET",-64]]],[619,[["LPAREN",-65],["__ATTRIBUTE__",-65],["COMMA",-65],["RPAREN",-65],["LBRACKET",-65]]],[620,[["LPAREN",-239],["__ATTRIBUTE__",-239],["COMMA",-239],["RPAREN",-239],["LBRACKET",-239]]],[623,[["LPAREN",-238],["__ATTRIBUTE__",-238],["COMMA",-238],["RPAREN",-238],["LBRACKET",-238]]],[624,[["LPAREN",-240],["__ATTRIBUTE__",-240],["COMMA",-240],["RPAREN",-240],["LBRACKET",-240]]],[625,[["LPAREN",-242],["__ATTRIBUTE__",-242],["COMMA",-242],["RPAREN",-242],["LBRACKET",-242]]],[655,[["LPAREN",-60],["__ATTRIBUTE__",-60],["COMMA",-60],["RPAREN",-60],["LBRACKET",-60]]],[656,[["LPAREN",-63],["__ATTRIBUTE__",-63],["COMMA",-63],["RPAREN",-63],["LBRACKET",-63]]],[659,[["LPAREN",-244],["__ATTRIBUTE__",-244],["COMMA",-244],["RPAREN",-244],["LBRACKET",-244]]],[660,[["LPAREN",-245],["__ATTRIBUTE__",-245],["COMMA",-245],["RPAREN",-245],["LBRACKET",-245]]],[682,[["LPAREN",-61],["__ATTRIBUTE__",-61],["COMMA",-61],["RPAREN",-61],["LBRACKET",-61]]],[683,[["LPAREN",-62],["__ATTRIBUTE__",-62],["COMMA",-62],["RPAREN",-62],["LBRACKET",-62]]],[691,[["LPAREN",703],["STRING_LITERAL",286]]],[12,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",78],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["LBRACE",-412]]],[73,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",78],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["LBRACE",-20]]],[74,[["TYPEID",-109],["ENUM",-109],["VOID",-109],["_BOOL",-109],["CHAR",-109],["SHORT",-109],["INT",-109],["LONG",-109],["FLOAT",-109],["DOUBLE",-109],["_COMPLEX",-109],["SIGNED",-109],["UNSIGNED",-109],["__INT128",-109],["_ATOMIC",-109],["TYPEOF",-109],["CONST",-109],["RESTRICT",-109],["VOLATILE",-109],["AUTO",-109],["REGISTER",-109],["STATIC",-109],["EXTERN",-109],["TYPEDEF",-109],["_THREAD_LOCAL",-109],["INLINE",-109],["_NORETURN",-109],["_ALIGNAS",-109],["__ATTRIBUTE__",-109],["STRUCT",-109],["UNION",-109],["LBRACE",-109]]],[138,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69]]],[145,[["TYPEID",-110],["ENUM",-110],["VOID",-110],["_BOOL",-110],["CHAR",-110],["SHORT",-110],["INT",-110],["LONG",-110],["FLOAT",-110],["DOUBLE",-110],["_COMPLEX",-110],["SIGNED",-110],["UNSIGNED",-110],["__INT128",-110],["_ATOMIC",-110],["TYPEOF",-110],["CONST",-110],["RESTRICT",-110],["VOLATILE",-110],["AUTO",-110],["REGISTER",-110],["STATIC",-110],["EXTERN",-110],["TYPEDEF",-110],["_THREAD_LOCAL",-110],["INLINE",-110],["_NORETURN",-110],["_ALIGNAS",-110],["__ATTRIBUTE__",-110],["STRUCT",-110],["UNION",-110],["LBRACE",-110]]],[212,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",117],["TYPEOF",55],["STRUCT",68],["UNION",69]]],[226,[["TYPEID",-209],["ENUM",-209],["VOID",-209],["_BOOL",-209],["CHAR",-209],["SHORT",-209],["INT",-209],["LONG",-209],["FLOAT",-209],["DOUBLE",-209],["_COMPLEX",-209],["SIGNED",-209],["UNSIGNED",-209],["__INT128",-209],["_ATOMIC",-209],["TYPEOF",-209],["CONST",-209],["RESTRICT",-209],["VOLATILE",-209],["__ATTRIBUTE__",-209],["STRUCT",-209],["UNION",-209]]],[228,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",78],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69]]],[230,[["TYPEID",-211],["ENUM",-211],["VOID",-211],["_BOOL",-211],["CHAR",-211],["SHORT",-211],["INT",-211],["LONG",-211],["FLOAT",-211],["DOUBLE",-211],["_COMPLEX",-211],["SIGNED",-211],["UNSIGNED",-211],["__INT128",-211],["_ATOMIC",-211],["TYPEOF",-211],["CONST",-211],["RESTRICT",-211],["VOLATILE",-211],["__ATTRIBUTE__",-211],["STRUCT",-211],["UNION",-211]]],[321,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69]]],[326,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69]]],[336,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["ELLIPSIS",473]]],[373,[["TYPEID",-210],["ENUM",-210],["VOID",-210],["_BOOL",-210],["CHAR",-210],["SHORT",-210],["INT",-210],["LONG",-210],["FLOAT",-210],["DOUBLE",-210],["_COMPLEX",-210],["SIGNED",-210],["UNSIGNED",-210],["__INT128",-210],["_ATOMIC",-210],["TYPEOF",-210],["CONST",-210],["RESTRICT",-210],["VOLATILE",-210],["__ATTRIBUTE__",-210],["STRUCT",-210],["UNION",-210]]],[374,[["TYPEID",-212],["ENUM",-212],["VOID",-212],["_BOOL",-212],["CHAR",-212],["SHORT",-212],["INT",-212],["LONG",-212],["FLOAT",-212],["DOUBLE",-212],["_COMPLEX",-212],["SIGNED",-212],["UNSIGNED",-212],["__INT128",-212],["_ATOMIC",-212],["TYPEOF",-212],["CONST",-212],["RESTRICT",-212],["VOLATILE",-212],["__ATTRIBUTE__",-212],["STRUCT",-212],["UNION",-212]]],[493,[["TYPEID",39],["ENUM",40],["VOID",42],["_BOOL",43],["CHAR",44],["SHORT",45],["INT",46],["LONG",47],["FLOAT",48],["DOUBLE",49],["_COMPLEX",50],["SIGNED",51],["UNSIGNED",52],["__INT128",53],["_ATOMIC",54],["TYPEOF",55],["CONST",56],["RESTRICT",57],["VOLATILE",58],["AUTO",59],["REGISTER",60],["STATIC",32],["EXTERN",61],["TYPEDEF",62],["_THREAD_LOCAL",63],["INLINE",64],["_NORETURN",65],["_ALIGNAS",66],["__ATTRIBUTE__",67],["STRUCT",68],["UNION",69],["RPAREN",-412]]],[338,[["__ATTRIBUTE__",67],["COMMA",-412],["RPAREN",-412]]],[339,[["__ATTRIBUTE__",67],["COMMA",-412],["RPAREN",-412]]],[340,[["__ATTRIBUTE__",67],["COMMA",-412],["RPAREN",-412]]],[343,[["__ATTRIBUTE__",-1],["COMMA",-1],["RPAREN",-1]]],[344,[["__ATTRIBUTE__",-2],["COMMA",-2],["RPAREN",-2]]],[353,[["__ATTRIBUTE__",67],["RBRACE",-412],["EQUALS",-412],["COMMA",-412]]],[71,[["LBRACE",144]]],[72,[["LBRACE",-19]]],[129,[["LBRACE",144]]],[130,[["LBRACE",144]]],[136,[["LBRACE",144]]],[137,[["LBRACE",144]]],[147,[["LBRACE",144]]],[219,[["LBRACE",-376]]],[220,[["LBRACE",-377]]],[410,[["WHILE",526]]],[99,[["STRING_LITERAL",158]]],[102,[["STRING_LITERAL",158]]],[157,[["STRING_LITERAL",286],["RPAREN",285]]],[200,[["STRING_LITERAL",286],["RPAREN",327]]],[279,[["STRING_LITERAL",158]]],[289,[["STRING_LITERAL",158]]],[428,[["STRING_LITERAL",286],["RPAREN",542]]],[437,[["STRING_LITERAL",286],["RPAREN",549]]],[534,[["STRING_LITERAL",158]]],[596,[["STRING_LITERAL",286],["COLON",642],["RPAREN",641]]],[642,[["STRING_LITERAL",-412],["COLON",-412],["RPAREN",-412],["LBRACKET",674]]],[669,[["STRING_LITERAL",-13],["COLON",-7],["RPAREN",-7]]],[672,[["STRING_LITERAL",158]]],[673,[["STRING_LITERAL",-14]]],[688,[["STRING_LITERAL",-412],["COLON",-412],["RPAREN",-412],["LBRACKET",674]]],[690,[["STRING_LITERAL",-412],["LBRACKET",674]]],[702,[["STRING_LITERAL",-13]]],[704,[["STRING_LITERAL",-395]]],[705,[["STRING_LITERAL",-396]]],[708,[["STRING_LITERAL",158],["COLON",-412],["RPAREN",-412]]],[711,[["STRING_LITERAL",286],["COLON",-390],["COMMA",-390],["RPAREN",-390]]],[719,[["STRING_LITERAL",158]]],[726,[["STRING_LITERAL",286],["COLON",-389],["COMMA",-389],["RPAREN",-389]]],[240,[["RBRACE",358]]],[351,[["RBRACE",358],["COMMA",496]]],[352,[["RBRACE",-196],["COMMA",-196]]],[354,[["RBRACE",358],["COMMA",496]]],[497,[["RBRACE",-201],["EQUALS",576],["COMMA",-201]]],[575,[["RBRACE",-198],["COMMA",-198]]],[597,[["RBRACE",358]]],[598,[["RBRACE",-36],["COMMA",644]]],[608,[["RBRACE",358],["COMMA",651]]],[626,[["RBRACE",-202],["COMMA",-202]]],[645,[["RBRACE",-225],["COMMA",-225]]],[694,[["RBRACE",-226],["COMMA",-226]]],[602,[["EQUALS",646],["LBRACKET",604],["PERIOD",605]]],[603,[["EQUALS",-228],["LBRACKET",-228],["PERIOD",-228]]],[647,[["EQUALS",-229],["LBRACKET",-229],["PERIOD",-229]]],[649,[["EQUALS",-231],["LBRACKET",-231],["PERIOD",-231]]],[677,[["EQUALS",-230],["LBRACKET",-230],["PERIOD",-230]]],[706,[["EQUALS",-232],["LBRACKET",-232],["PERIOD",-232]]],[259,[["COLON",405]]],[404,[["COLON",520],["ELLIPSIS",521]]],[414,[["COLON",403]]],[438,[["COLON",550],["COMMA",377]]],[508,[["COLON",582]]],[589,[["COLON",632]]],[668,[["COLON",688],["RPAREN",689]]],[670,[["COLON",-8],["COMMA",690],["RPAREN",-8]]],[671,[["COLON",-387],["COMMA",-387],["RPAREN",-387]]],[699,[["COLON",708],["RPAREN",709]]],[701,[["COLON",-386],["COMMA",-386],["RPAREN",-386]]],[712,[["COLON",717],["RPAREN",718]]],[713,[["COLON",-11],["RPAREN",-11]]],[714,[["COLON",-12],["COMMA",719],["RPAREN",-12]]],[716,[["COLON",-388],["COMMA",-388],["RPAREN",-388]]],[161,[["COMMA",289],["RPAREN",290]]],[206,[["COMMA",336],["RPAREN",-213]]],[208,[["COMMA",337],["RPAREN",-32]]],[209,[["COMMA",-215],["RPAREN",-215]]],[210,[["COMMA",-220],["RPAREN",-220]]],[232,[["COMMA",377],["RPAREN",376]]],[288,[["COMMA",377],["RPAREN",436]]],[365,[["COMMA",-233],["RPAREN",-233]]],[393,[["COMMA",515],["RPAREN",514]]],[394,[["COMMA",-404],["RPAREN",-404]]],[395,[["COMMA",-406],["RPAREN",-406]]],[396,[["COMMA",-407],["RPAREN",-407]]],[457,[["COMMA",377],["RBRACKET",551]]],[458,[["COMMA",553],["RPAREN",552]]],[460,[["COMMA",-349],["RPAREN",-349]]],[467,[["COMMA",556]]],[474,[["COMMA",-216],["RPAREN",-216]]],[475,[["COMMA",-221],["RPAREN",-221]]],[476,[["COMMA",-217],["RPAREN",-217]]],[477,[["COMMA",-218],["RPAREN",-218]]],[478,[["COMMA",-219],["RPAREN",-219]]],[523,[["COMMA",377],["RPAREN",590]]],[524,[["COMMA",377],["RPAREN",591]]],[525,[["COMMA",377],["RPAREN",592]]],[585,[["COMMA",-405],["RPAREN",-405]]],[586,[["COMMA",553],["RPAREN",630]]],[587,[["COMMA",553],["RPAREN",631]]],[611,[["COMMA",-350],["RPAREN",-350]]],[630,[["COMMA",-410],["RPAREN",-410]]],[631,[["COMMA",-411],["RPAREN",-411]]],[638,[["COMMA",377],["RPAREN",664]]],[681,[["COMMA",377],["RBRACKET",696]]],[722,[["COMMA",728],["RPAREN",-4]]],[723,[["COMMA",-393],["RPAREN",-393]]],[724,[["COMMA",-394],["RPAREN",-394]]],[730,[["COMMA",-391],["RPAREN",-391]]],[731,[["COMMA",-392],["RPAREN",-392]]],[100,[["RPAREN",159]]],[149,[["RPAREN",275]]],[204,[["RPAREN",334]]],[205,[["RPAREN",335]]],[207,[["RPAREN",-31]]],[224,[["RPAREN",364]]],[233,[["RPAREN",378]]],[237,[["RPAREN",391]]],[238,[["RPAREN",392]]],[283,[["RPAREN",433]]],[284,[["RPAREN",434]]],[287,[["RPAREN",435]]],[375,[["RPAREN",511]]],[465,[["RPAREN",554]]],[466,[["RPAREN",555]]],[473,[["RPAREN",-214]]],[483,[["RPAREN",564]]],[484,[["RPAREN",565]]],[486,[["RPAREN",-37]]],[487,[["RPAREN",-38]]],[514,[["RPAREN",584]]],[562,[["RPAREN",618]]],[563,[["RPAREN",619]]],[572,[["RPAREN",625]]],[612,[["RPAREN",652],["LBRACKET",654],["PERIOD",653]]],[613,[["RPAREN",-346],["LBRACKET",-346],["PERIOD",-346]]],[666,[["RPAREN",687]]],[680,[["RPAREN",-347],["LBRACKET",-347],["PERIOD",-347]]],[686,[["RPAREN",697]]],[696,[["RPAREN",-348],["LBRACKET",-348],["PERIOD",-348]]],[710,[["RPAREN",716]]],[720,[["RPAREN",727]]],[721,[["RPAREN",-3]]],[328,[["RBRACKET",469]]],[330,[["RBRACKET",-15]]],[331,[["RBRACKET",-16]]],[429,[["RBRACKET",543]]],[471,[["RBRACKET",557]]],[472,[["RBRACKET",558]]],[489,[["RBRACKET",567]]],[545,[["RBRACKET",606]]],[546,[["RBRACKET",607]]],[566,[["RBRACKET",620]]],[570,[["RBRACKET",623]]],[614,[["RBRACKET",655]]],[621,[["RBRACKET",659]]],[622,[["RBRACKET",660]]],[648,[["RBRACKET",677],["ELLIPSIS",678]]],[657,[["RBRACKET",682]]],[658,[["RBRACKET",683]]],[692,[["RBRACKET",704]]],[693,[["RBRACKET",705]]],[695,[["RBRACKET",706]]]],"goto":[[0,[["translation_unit_or_empty",1],["translation_unit",2],["empty",3],["external_declaration",4],["function_definition",5],["declaration",6],["pp_directive",7],["pppragma_directive",8],["static_assert",10],["global_asm",11],["id_declarator",12],["declaration_specifiers",13],["decl_body",14],["direct_id_declarator",21],["pointer",22],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",28],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41]]],[12,[["empty",72],["declaration",74],["declaration_specifiers",75],["decl_body",14],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",76],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",77],["typeof_specifier",38],["struct_or_union",41],["declaration_list_opt",71],["declaration_list",73]]],[13,[["empty",90],["id_declarator",79],["direct_id_declarator",21],["pointer",87],["type_qualifier",80],["storage_class_specifier",81],["function_specifier",82],["type_specifier_no_typeid",83],["alignment_specifier",84],["gcc_attribute",85],["init_declarator_list_opt",86],["init_declarator_list",91],["init_declarator",92],["declarator",93],["typeid_declarator",94],["direct_typeid_declarator",95]]],[23,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",106]]],[24,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",110]]],[25,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",111]]],[28,[["empty",115],["id_declarator",119],["direct_id_declarator",21],["pointer",22],["type_specifier_no_typeid",26],["type_specifier",112],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["id_init_declarator_list_opt",113],["id_init_declarator_list",116],["id_init_declarator",118]]],[29,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",120]]],[30,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",121]]],[33,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",122],["type_qualifier_list",124]]],[37,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",126]]],[40,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",129],["attrs_id_typeid",130],["gcc_attributes",132]]],[41,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",136],["attrs_id_typeid",137],["gcc_attributes",132]]],[75,[["empty",90],["id_declarator",146],["direct_id_declarator",21],["pointer",87],["type_qualifier",80],["storage_class_specifier",81],["function_specifier",82],["type_specifier_no_typeid",83],["alignment_specifier",84],["gcc_attribute",85],["init_declarator_list_opt",86],["init_declarator_list",91],["init_declarator",92],["declarator",93],["typeid_declarator",94],["direct_typeid_declarator",95]]],[76,[["empty",115],["id_declarator",119],["direct_id_declarator",21],["pointer",22],["type_specifier_no_typeid",26],["type_specifier",112],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["id_init_declarator_list_opt",113],["id_init_declarator_list",116],["id_init_declarator",118]]],[77,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",126]]],[79,[["empty",72],["declaration",74],["declaration_specifiers",75],["decl_body",14],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",76],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",77],["typeof_specifier",38],["struct_or_union",41],["declaration_list_opt",147],["declaration_list",73]]],[93,[["empty",152],["asm_label_opt",151],["asm_label",153]]],[103,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",201],["type_qualifier_list",203]]],[104,[["empty",207],["declaration_specifiers",211],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",212],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41],["identifier",210],["parameter_type_list",204],["identifier_list_opt",205],["parameter_list",206],["identifier_list",208],["parameter_declaration",209]]],[109,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",126]]],[119,[["empty",152],["asm_label_opt",214],["asm_label",153]]],[143,[["empty",241],["declaration",244],["pppragma_directive",252],["static_assert",253],["declaration_specifiers",75],["decl_body",14],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",76],["alignment_specifier",29],["gcc_attribute",273],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",77],["typeof_specifier",38],["struct_or_union",41],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["block_item_list_opt",240],["block_item_list",242],["block_item",243],["statement",245],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260]]],[151,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",277],["gcc_attributes",278]]],[155,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",280],["type_qualifier_list",282]]],[156,[["empty",207],["declaration_specifiers",211],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",212],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41],["identifier",210],["parameter_type_list",283],["identifier_list_opt",284],["parameter_list",206],["identifier_list",208],["parameter_declaration",209]]],[201,[["empty",330],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",331],["assignment_expression_opt",328]]],[202,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",332],["type_qualifier_list",124]]],[211,[["empty",343],["id_declarator",338],["direct_id_declarator",21],["pointer",341],["type_qualifier",80],["storage_class_specifier",81],["function_specifier",82],["type_specifier_no_typeid",83],["alignment_specifier",84],["gcc_attribute",85],["typeid_noparen_declarator",339],["abstract_declarator_opt",340],["direct_typeid_noparen_declarator",342],["abstract_declarator",344],["direct_abstract_declarator",348]]],[214,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",350],["gcc_attributes",278]]],[225,[["empty",343],["pointer",371],["type_qualifier",367],["type_specifier_no_typeid",366],["alignment_specifier",368],["gcc_attribute",369],["abstract_declarator_opt",365],["abstract_declarator",344],["direct_abstract_declarator",348]]],[239,[["empty",395],["gcc_attribute_list",393],["gcc_attribute_item",394]]],[242,[["empty",401],["declaration",244],["pppragma_directive",252],["static_assert",253],["declaration_specifiers",75],["decl_body",14],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",76],["alignment_specifier",29],["gcc_attribute",273],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",77],["typeof_specifier",38],["struct_or_union",41],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["block_item",400],["statement",245],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260]]],[265,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",410],["pppragma_directive_list",411]]],[271,[["empty",423],["asm_qualifiers_opt",422],["asm_qualifiers",424]]],[273,[["empty",107],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["declaration_specifiers_no_type",108],["alignment_specifier",29],["gcc_attribute",30],["atomic_specifier",109],["declaration_specifiers_no_type_opt",121]]],[280,[["empty",330],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",331],["assignment_expression_opt",429]]],[281,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",431],["type_qualifier_list",124]]],[338,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",476],["gcc_attributes",278]]],[339,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",477],["gcc_attributes",278]]],[340,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",478],["gcc_attributes",278]]],[345,[["empty",486],["id_declarator",100],["declaration_specifiers",211],["direct_id_declarator",21],["pointer",485],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",212],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41],["parameter_type_list",487],["parameter_list",206],["parameter_declaration",209],["abstract_declarator",483],["direct_abstract_declarator",348],["parameter_type_list_opt",484]]],[346,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",488],["type_qualifier_list",491]]],[353,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",497],["gcc_attributes",278]]],[356,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",501],["gcc_attributes",278]]],[359,[["empty",504],["id_declarator",146],["direct_id_declarator",21],["pointer",87],["type_qualifier",367],["type_specifier_no_typeid",366],["alignment_specifier",368],["gcc_attribute",503],["declarator",507],["typeid_declarator",94],["direct_typeid_declarator",95],["gcc_attributes_opt",508],["gcc_attributes",278],["struct_declarator_list_opt",502],["struct_declarator_list",505],["struct_declarator",506]]],[363,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",510],["gcc_attributes",278]]],[370,[["empty",486],["declaration_specifiers",211],["pointer",371],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",212],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41],["parameter_type_list",487],["parameter_list",206],["parameter_declaration",209],["abstract_declarator",483],["direct_abstract_declarator",348],["parameter_type_list_opt",484]]],[402,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",518],["pppragma_directive_list",411]]],[403,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",519],["pppragma_directive_list",411]]],[405,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",522],["pppragma_directive_list",411]]],[411,[["empty",401],["pppragma_directive",528],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",527],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260]]],[415,[["empty",401],["declaration",530],["declaration_specifiers",75],["decl_body",14],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",76],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",77],["typeof_specifier",38],["struct_or_union",41],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["expression_opt",529]]],[481,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",559],["type_qualifier_list",561]]],[482,[["empty",207],["declaration_specifiers",211],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",212],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41],["identifier",210],["parameter_type_list",562],["identifier_list_opt",563],["parameter_list",206],["identifier_list",208],["parameter_declaration",209]]],[488,[["empty",330],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",331],["assignment_expression_opt",566]]],[490,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",568],["type_qualifier_list",124]]],[492,[["empty",330],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",331],["assignment_expression_opt",570]]],[493,[["empty",486],["declaration_specifiers",211],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",212],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41],["parameter_type_list",487],["parameter_list",206],["parameter_declaration",209],["parameter_type_list_opt",572]]],[495,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",574],["gcc_attributes",278]]],[498,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",577],["gcc_attributes",278]]],[499,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",578],["gcc_attributes",278]]],[507,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",581],["gcc_attributes",278]]],[509,[["empty",131],["gcc_attribute",133],["gcc_attributes_opt",583],["gcc_attributes",278]]],[515,[["empty",395],["gcc_attribute_item",585]]],[520,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",588],["pppragma_directive_list",411]]],[530,[["empty",401],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["expression_opt",595]]],[540,[["empty",599],["initializer_list_opt",597],["initializer_list",598],["designation_opt",600],["designation",601],["designator_list",602],["designator",603]]],[548,[["empty",609],["initializer_list",608],["designation_opt",600],["designation",601],["designator_list",602],["designator",603]]],[559,[["empty",330],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",331],["assignment_expression_opt",614]]],[560,[["empty",123],["type_qualifier",125],["type_qualifier_list_opt",616],["type_qualifier_list",124]]],[580,[["empty",131],["id_declarator",146],["direct_id_declarator",21],["pointer",87],["gcc_attribute",133],["declarator",507],["typeid_declarator",94],["direct_typeid_declarator",95],["gcc_attributes_opt",508],["gcc_attributes",278],["struct_declarator",627]]],[590,[["empty",401],["pppragma_directive",635],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",634],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",633],["pppragma_directive_list",411]]],[591,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",636],["pppragma_directive_list",411]]],[592,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",637],["pppragma_directive_list",411]]],[594,[["empty",401],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["expression_opt",639]]],[632,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",662],["pppragma_directive_list",411]]],[640,[["empty",401],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["expression_opt",666]]],[642,[["empty",669],["asm_operands_opt",668],["asm_operands",670],["asm_operand",671],["asm_symbolic_name_opt",672],["asm_symbolic_name",673]]],[644,[["empty",609],["brace_close",675],["designation_opt",676],["designation",601],["designator_list",602],["designator",603]]],[651,[["empty",609],["brace_close",679],["designation_opt",676],["designation",601],["designator_list",602],["designator",603]]],[663,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",684],["pppragma_directive_list",411]]],[665,[["empty",401],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["expression_opt",686]]],[687,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",698],["pppragma_directive_list",411]]],[688,[["empty",669],["asm_operands_opt",699],["asm_operands",670],["asm_operand",671],["asm_symbolic_name_opt",672],["asm_symbolic_name",673]]],[690,[["empty",702],["asm_operand",701],["asm_symbolic_name_opt",672],["asm_symbolic_name",673]]],[697,[["empty",401],["pppragma_directive",413],["static_assert",253],["gcc_attribute",133],["gcc_attributes",272],["compound_statement",248],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",262],["assignment_expression",234],["statement",412],["labeled_statement",246],["expression_statement",247],["selection_statement",249],["iteration_statement",250],["jump_statement",251],["asm_statement",254],["attribute_statement",255],["expression_opt",260],["pragmacomp_or_statement",707],["pppragma_directive_list",411]]],[708,[["empty",713],["unified_string_literal",711],["asm_string_list_opt",712],["asm_string_list",714]]],[717,[["empty",721],["asm_goto_list_opt",720],["asm_goto_list",722]]],[2,[["external_declaration",70],["function_definition",5],["declaration",6],["pp_directive",7],["pppragma_directive",8],["static_assert",10],["global_asm",11],["id_declarator",12],["declaration_specifiers",13],["decl_body",14],["direct_id_declarator",21],["pointer",22],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",28],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41]]],[73,[["declaration",145],["declaration_specifiers",75],["decl_body",14],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",76],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",77],["typeof_specifier",38],["struct_or_union",41]]],[222,[["pppragma_directive",361],["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["specifier_qualifier_list",359],["qualifier_attr_list",228],["struct_declaration_list",355],["brace_close",356],["struct_declaration",357]]],[223,[["pppragma_directive",361],["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["specifier_qualifier_list",359],["qualifier_attr_list",228],["struct_declaration_list",362],["brace_close",363],["struct_declaration",357]]],[355,[["pppragma_directive",361],["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["specifier_qualifier_list",359],["qualifier_attr_list",228],["brace_close",499],["struct_declaration",500]]],[362,[["pppragma_directive",361],["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["specifier_qualifier_list",359],["qualifier_attr_list",228],["brace_close",509],["struct_declaration",500]]],[18,[["id_declarator",100],["direct_id_declarator",21],["pointer",22]]],[89,[["id_declarator",100],["direct_id_declarator",21],["pointer",87],["typeid_declarator",149],["direct_typeid_declarator",95]]],[150,[["id_declarator",146],["direct_id_declarator",21],["pointer",87],["init_declarator",276],["declarator",93],["typeid_declarator",94],["direct_typeid_declarator",95]]],[213,[["id_declarator",146],["direct_id_declarator",21],["pointer",87],["init_declarator",349],["declarator",93],["typeid_declarator",94],["direct_typeid_declarator",95]]],[336,[["declaration_specifiers",211],["type_qualifier",23],["storage_class_specifier",24],["function_specifier",25],["type_specifier_no_typeid",26],["type_specifier",27],["declaration_specifiers_no_type",212],["alignment_specifier",29],["gcc_attribute",30],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",37],["typeof_specifier",38],["struct_or_union",41],["parameter_declaration",474]]],[22,[["direct_id_declarator",105]]],[87,[["direct_id_declarator",105],["direct_typeid_declarator",148]]],[341,[["direct_id_declarator",105],["direct_typeid_noparen_declarator",479],["direct_abstract_declarator",480]]],[485,[["direct_id_declarator",105],["direct_abstract_declarator",480]]],[122,[["pointer",215]]],[124,[["type_qualifier",216]]],[138,[["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["type_name",224],["specifier_qualifier_list",225],["qualifier_attr_list",228]]],[139,[["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["type_name",233],["specifier_qualifier_list",225],["qualifier_attr_list",228],["expression",232],["assignment_expression",234]]],[140,[["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["unified_string_literal",162],["constant_expression",238],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["type_name",237],["specifier_qualifier_list",225],["qualifier_attr_list",228]]],[160,[["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["type_name",287],["specifier_qualifier_list",225],["qualifier_attr_list",228],["expression",288],["assignment_expression",234]]],[203,[["type_qualifier",216]]],[228,[["type_qualifier",373],["type_specifier_no_typeid",26],["type_specifier",372],["gcc_attribute",374],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41]]],[231,[["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["compound_statement",375],["brace_open",143],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["type_name",287],["specifier_qualifier_list",225],["qualifier_attr_list",228],["expression",288],["assignment_expression",234]]],[282,[["type_qualifier",216]]],[320,[["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["type_name",465],["specifier_qualifier_list",225],["qualifier_attr_list",228],["expression",288],["assignment_expression",234]]],[321,[["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["type_name",466],["specifier_qualifier_list",225],["qualifier_attr_list",228]]],[326,[["type_qualifier",226],["type_specifier_no_typeid",26],["type_specifier",227],["alignment_specifier",229],["gcc_attribute",230],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41],["type_name",467],["specifier_qualifier_list",225],["qualifier_attr_list",228]]],[491,[["type_qualifier",216]]],[561,[["type_qualifier",216]]],[212,[["type_specifier_no_typeid",26],["type_specifier",112],["typedef_name",34],["enum_specifier",35],["struct_or_union_specifier",36],["atomic_specifier",114],["typeof_specifier",38],["struct_or_union",41]]],[132,[["gcc_attribute",221]]],[272,[["gcc_attribute",221]]],[278,[["gcc_attribute",221]]],[71,[["compound_statement",142],["brace_open",143]]],[147,[["compound_statement",274],["brace_open",143]]],[129,[["brace_open",217]]],[130,[["brace_open",218]]],[136,[["brace_open",222]]],[137,[["brace_open",223]]],[426,[["brace_open",540],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",539],["initializer",538]]],[435,[["brace_open",548],["unified_string_literal",162],["unary_expression",547],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[494,[["brace_open",540],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",539],["initializer",573]]],[554,[["brace_open",548],["unified_string_literal",162],["unary_expression",547],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[600,[["brace_open",540],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",539],["initializer",645]]],[676,[["brace_open",540],["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",539],["initializer",694]]],[99,[["unified_string_literal",157]]],[101,[["unified_string_literal",162],["constant_expression",161],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[102,[["unified_string_literal",200]]],[171,[["unified_string_literal",162],["unary_expression",316],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[172,[["unified_string_literal",162],["unary_expression",317],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[173,[["unified_string_literal",162],["unary_expression",318],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[174,[["unified_string_literal",162],["unary_expression",319],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[258,[["unified_string_literal",162],["constant_expression",404],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[270,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",420],["assignment_expression",234]]],[279,[["unified_string_literal",428]]],[289,[["unified_string_literal",437]]],[291,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",438],["assignment_expression",234]]],[292,[["unified_string_literal",162],["binary_expression",439],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[293,[["unified_string_literal",162],["binary_expression",440],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[294,[["unified_string_literal",162],["binary_expression",441],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[295,[["unified_string_literal",162],["binary_expression",442],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[296,[["unified_string_literal",162],["binary_expression",443],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[297,[["unified_string_literal",162],["binary_expression",444],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[298,[["unified_string_literal",162],["binary_expression",445],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[299,[["unified_string_literal",162],["binary_expression",446],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[300,[["unified_string_literal",162],["binary_expression",447],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[301,[["unified_string_literal",162],["binary_expression",448],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[302,[["unified_string_literal",162],["binary_expression",449],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[303,[["unified_string_literal",162],["binary_expression",450],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[304,[["unified_string_literal",162],["binary_expression",451],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[305,[["unified_string_literal",162],["binary_expression",452],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[306,[["unified_string_literal",162],["binary_expression",453],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[307,[["unified_string_literal",162],["binary_expression",454],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[308,[["unified_string_literal",162],["binary_expression",455],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[309,[["unified_string_literal",162],["binary_expression",456],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[310,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",457],["assignment_expression",234]]],[311,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",460],["argument_expression_list",458]]],[332,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",471]]],[333,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",472]]],[377,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",512]]],[379,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",513]]],[407,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",523],["assignment_expression",234]]],[408,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",524],["assignment_expression",234]]],[409,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",525],["assignment_expression",234]]],[427,[["unified_string_literal",162],["constant_expression",541],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[431,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",545]]],[432,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",546]]],[516,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",460],["argument_expression_list",586]]],[517,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",460],["argument_expression_list",587]]],[521,[["unified_string_literal",162],["constant_expression",589],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[534,[["unified_string_literal",596]]],[550,[["unified_string_literal",162],["conditional_expression",610],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[553,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",611]]],[568,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",621]]],[569,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",622]]],[576,[["unified_string_literal",162],["constant_expression",626],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[582,[["unified_string_literal",162],["constant_expression",629],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[593,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",638],["assignment_expression",234]]],[604,[["unified_string_literal",162],["constant_expression",648],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[616,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",657]]],[617,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["assignment_expression",658]]],[628,[["unified_string_literal",162],["constant_expression",661],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[654,[["unified_string_literal",162],["conditional_expression",235],["binary_expression",164],["unary_expression",236],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182],["expression",681],["assignment_expression",234]]],[672,[["unified_string_literal",691]]],[678,[["unified_string_literal",162],["constant_expression",695],["conditional_expression",163],["binary_expression",164],["unary_expression",165],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[703,[["unified_string_literal",162],["unary_expression",710],["postfix_expression",170],["unary_operator",173],["primary_expression",176],["identifier",180],["constant",181],["unified_wstring_literal",182]]],[719,[["unified_string_literal",726]]],[337,[["identifier",475]]],[556,[["identifier",613],["offsetof_member_designator",612]]],[605,[["identifier",649]]],[653,[["identifier",680]]],[371,[["direct_abstract_declarator",480]]],[217,[["enumerator_list",351],["enumerator",352]]],[218,[["enumerator_list",354],["enumerator",352]]],[496,[["enumerator",575]]],[240,[["brace_close",399]]],[351,[["brace_close",495]]],[354,[["brace_close",498]]],[597,[["brace_close",643]]],[608,[["brace_close",650]]],[236,[["assignment_operator",379]]],[602,[["designator",647]]]],"productions":[["S' -> translation_unit_or_empty","S'",1,null,null,null],["abstract_declarator_opt -> empty","abstract_declarator_opt",1,"p_abstract_declarator_opt","plyparser.py",59],["abstract_declarator_opt -> abstract_declarator","abstract_declarator_opt",1,"p_abstract_declarator_opt","plyparser.py",60],["asm_goto_list_opt -> empty","asm_goto_list_opt",1,"p_asm_goto_list_opt","plyparser.py",59],["asm_goto_list_opt -> asm_goto_list","asm_goto_list_opt",1,"p_asm_goto_list_opt","plyparser.py",60],["asm_label_opt -> empty","asm_label_opt",1,"p_asm_label_opt","plyparser.py",59],["asm_label_opt -> asm_label","asm_label_opt",1,"p_asm_label_opt","plyparser.py",60],["asm_operands_opt -> empty","asm_operands_opt",1,"p_asm_operands_opt","plyparser.py",59],["asm_operands_opt -> asm_operands","asm_operands_opt",1,"p_asm_operands_opt","plyparser.py",60],["asm_qualifiers_opt -> empty","asm_qualifiers_opt",1,"p_asm_qualifiers_opt","plyparser.py",59],["asm_qualifiers_opt -> asm_qualifiers","asm_qualifiers_opt",1,"p_asm_qualifiers_opt","plyparser.py",60],["asm_string_list_opt -> empty","asm_string_list_opt",1,"p_asm_string_list_opt","plyparser.py",59],["asm_string_list_opt -> asm_string_list","asm_string_list_opt",1,"p_asm_string_list_opt","plyparser.py",60],["asm_symbolic_name_opt -> empty","asm_symbolic_name_opt",1,"p_asm_symbolic_name_opt","plyparser.py",59],["asm_symbolic_name_opt -> asm_symbolic_name","asm_symbolic_name_opt",1,"p_asm_symbolic_name_opt","plyparser.py",60],["assignment_expression_opt -> empty","assignment_expression_opt",1,"p_assignment_expression_opt","plyparser.py",59],["assignment_expression_opt -> assignment_expression","assignment_expression_opt",1,"p_assignment_expression_opt","plyparser.py",60],["block_item_list_opt -> empty","block_item_list_opt",1,"p_block_item_list_opt","plyparser.py",59],["block_item_list_opt -> block_item_list","block_item_list_opt",1,"p_block_item_list_opt","plyparser.py",60],["declaration_list_opt -> empty","declaration_list_opt",1,"p_declaration_list_opt","plyparser.py",59],["declaration_list_opt -> declaration_list","declaration_list_opt",1,"p_declaration_list_opt","plyparser.py",60],["declaration_specifiers_no_type_opt -> empty","declaration_specifiers_no_type_opt",1,"p_declaration_specifiers_no_type_opt","plyparser.py",59],["declaration_specifiers_no_type_opt -> declaration_specifiers_no_type","declaration_specifiers_no_type_opt",1,"p_declaration_specifiers_no_type_opt","plyparser.py",60],["designation_opt -> empty","designation_opt",1,"p_designation_opt","plyparser.py",59],["designation_opt -> designation","designation_opt",1,"p_designation_opt","plyparser.py",60],["expression_opt -> empty","expression_opt",1,"p_expression_opt","plyparser.py",59],["expression_opt -> expression","expression_opt",1,"p_expression_opt","plyparser.py",60],["gcc_attributes_opt -> empty","gcc_attributes_opt",1,"p_gcc_attributes_opt","plyparser.py",59],["gcc_attributes_opt -> gcc_attributes","gcc_attributes_opt",1,"p_gcc_attributes_opt","plyparser.py",60],["id_init_declarator_list_opt -> empty","id_init_declarator_list_opt",1,"p_id_init_declarator_list_opt","plyparser.py",59],["id_init_declarator_list_opt -> id_init_declarator_list","id_init_declarator_list_opt",1,"p_id_init_declarator_list_opt","plyparser.py",60],["identifier_list_opt -> empty","identifier_list_opt",1,"p_identifier_list_opt","plyparser.py",59],["identifier_list_opt -> identifier_list","identifier_list_opt",1,"p_identifier_list_opt","plyparser.py",60],["init_declarator_list_opt -> empty","init_declarator_list_opt",1,"p_init_declarator_list_opt","plyparser.py",59],["init_declarator_list_opt -> init_declarator_list","init_declarator_list_opt",1,"p_init_declarator_list_opt","plyparser.py",60],["initializer_list_opt -> empty","initializer_list_opt",1,"p_initializer_list_opt","plyparser.py",59],["initializer_list_opt -> initializer_list","initializer_list_opt",1,"p_initializer_list_opt","plyparser.py",60],["parameter_type_list_opt -> empty","parameter_type_list_opt",1,"p_parameter_type_list_opt","plyparser.py",59],["parameter_type_list_opt -> parameter_type_list","parameter_type_list_opt",1,"p_parameter_type_list_opt","plyparser.py",60],["struct_declarator_list_opt -> empty","struct_declarator_list_opt",1,"p_struct_declarator_list_opt","plyparser.py",59],["struct_declarator_list_opt -> struct_declarator_list","struct_declarator_list_opt",1,"p_struct_declarator_list_opt","plyparser.py",60],["type_qualifier_list_opt -> empty","type_qualifier_list_opt",1,"p_type_qualifier_list_opt","plyparser.py",59],["type_qualifier_list_opt -> type_qualifier_list","type_qualifier_list_opt",1,"p_type_qualifier_list_opt","plyparser.py",60],["direct_id_declarator -> ID","direct_id_declarator",1,"p_direct_id_declarator_1","plyparser.py",138],["direct_id_declarator -> LPAREN id_declarator RPAREN","direct_id_declarator",3,"p_direct_id_declarator_2","plyparser.py",138],["direct_id_declarator -> direct_id_declarator LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET","direct_id_declarator",5,"p_direct_id_declarator_3","plyparser.py",138],["direct_id_declarator -> direct_id_declarator LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET","direct_id_declarator",6,"p_direct_id_declarator_4","plyparser.py",138],["direct_id_declarator -> direct_id_declarator LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET","direct_id_declarator",6,"p_direct_id_declarator_4","plyparser.py",139],["direct_id_declarator -> direct_id_declarator LBRACKET type_qualifier_list_opt TIMES RBRACKET","direct_id_declarator",5,"p_direct_id_declarator_5","plyparser.py",138],["direct_id_declarator -> direct_id_declarator LPAREN parameter_type_list RPAREN","direct_id_declarator",4,"p_direct_id_declarator_6","plyparser.py",138],["direct_id_declarator -> direct_id_declarator LPAREN identifier_list_opt RPAREN","direct_id_declarator",4,"p_direct_id_declarator_6","plyparser.py",139],["direct_typeid_declarator -> TYPEID","direct_typeid_declarator",1,"p_direct_typeid_declarator_1","plyparser.py",138],["direct_typeid_declarator -> LPAREN typeid_declarator RPAREN","direct_typeid_declarator",3,"p_direct_typeid_declarator_2","plyparser.py",138],["direct_typeid_declarator -> direct_typeid_declarator LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET","direct_typeid_declarator",5,"p_direct_typeid_declarator_3","plyparser.py",138],["direct_typeid_declarator -> direct_typeid_declarator LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET","direct_typeid_declarator",6,"p_direct_typeid_declarator_4","plyparser.py",138],["direct_typeid_declarator -> direct_typeid_declarator LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET","direct_typeid_declarator",6,"p_direct_typeid_declarator_4","plyparser.py",139],["direct_typeid_declarator -> direct_typeid_declarator LBRACKET type_qualifier_list_opt TIMES RBRACKET","direct_typeid_declarator",5,"p_direct_typeid_declarator_5","plyparser.py",138],["direct_typeid_declarator -> direct_typeid_declarator LPAREN parameter_type_list RPAREN","direct_typeid_declarator",4,"p_direct_typeid_declarator_6","plyparser.py",138],["direct_typeid_declarator -> direct_typeid_declarator LPAREN identifier_list_opt RPAREN","direct_typeid_declarator",4,"p_direct_typeid_declarator_6","plyparser.py",139],["direct_typeid_noparen_declarator -> TYPEID","direct_typeid_noparen_declarator",1,"p_direct_typeid_noparen_declarator_1","plyparser.py",138],["direct_typeid_noparen_declarator -> direct_typeid_noparen_declarator LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET","direct_typeid_noparen_declarator",5,"p_direct_typeid_noparen_declarator_3","plyparser.py",138],["direct_typeid_noparen_declarator -> direct_typeid_noparen_declarator LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET","direct_typeid_noparen_declarator",6,"p_direct_typeid_noparen_declarator_4","plyparser.py",138],["direct_typeid_noparen_declarator -> direct_typeid_noparen_declarator LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET","direct_typeid_noparen_declarator",6,"p_direct_typeid_noparen_declarator_4","plyparser.py",139],["direct_typeid_noparen_declarator -> direct_typeid_noparen_declarator LBRACKET type_qualifier_list_opt TIMES RBRACKET","direct_typeid_noparen_declarator",5,"p_direct_typeid_noparen_declarator_5","plyparser.py",138],["direct_typeid_noparen_declarator -> direct_typeid_noparen_declarator LPAREN parameter_type_list RPAREN","direct_typeid_noparen_declarator",4,"p_direct_typeid_noparen_declarator_6","plyparser.py",138],["direct_typeid_noparen_declarator -> direct_typeid_noparen_declarator LPAREN identifier_list_opt RPAREN","direct_typeid_noparen_declarator",4,"p_direct_typeid_noparen_declarator_6","plyparser.py",139],["id_declarator -> direct_id_declarator","id_declarator",1,"p_id_declarator_1","plyparser.py",138],["id_declarator -> pointer direct_id_declarator","id_declarator",2,"p_id_declarator_2","plyparser.py",138],["typeid_declarator -> direct_typeid_declarator","typeid_declarator",1,"p_typeid_declarator_1","plyparser.py",138],["typeid_declarator -> pointer direct_typeid_declarator","typeid_declarator",2,"p_typeid_declarator_2","plyparser.py",138],["typeid_noparen_declarator -> direct_typeid_noparen_declarator","typeid_noparen_declarator",1,"p_typeid_noparen_declarator_1","plyparser.py",138],["typeid_noparen_declarator -> pointer direct_typeid_noparen_declarator","typeid_noparen_declarator",2,"p_typeid_noparen_declarator_2","plyparser.py",138],["translation_unit_or_empty -> translation_unit","translation_unit_or_empty",1,"p_translation_unit_or_empty","c_parser.py",531],["translation_unit_or_empty -> empty","translation_unit_or_empty",1,"p_translation_unit_or_empty","c_parser.py",532],["translation_unit -> external_declaration","translation_unit",1,"p_translation_unit_1","c_parser.py",540],["translation_unit -> translation_unit external_declaration","translation_unit",2,"p_translation_unit_2","c_parser.py",546],["external_declaration -> function_definition","external_declaration",1,"p_external_declaration_1","c_parser.py",556],["external_declaration -> declaration","external_declaration",1,"p_external_declaration_2","c_parser.py",561],["external_declaration -> pp_directive","external_declaration",1,"p_external_declaration_3","c_parser.py",566],["external_declaration -> pppragma_directive","external_declaration",1,"p_external_declaration_3","c_parser.py",567],["external_declaration -> SEMI","external_declaration",1,"p_external_declaration_4","c_parser.py",572],["external_declaration -> static_assert","external_declaration",1,"p_external_declaration_5","c_parser.py",577],["external_declaration -> global_asm","external_declaration",1,"p_external_declaration_6","c_parser.py",582],["global_asm -> ASM LPAREN unified_string_literal RPAREN SEMI","global_asm",5,"p_global_asm","c_parser.py",587],["static_assert -> _STATIC_ASSERT LPAREN constant_expression COMMA unified_string_literal RPAREN","static_assert",6,"p_static_assert_declaration","c_parser.py",592],["static_assert -> _STATIC_ASSERT LPAREN constant_expression RPAREN","static_assert",4,"p_static_assert_declaration","c_parser.py",593],["pp_directive -> PPHASH","pp_directive",1,"p_pp_directive","c_parser.py",601],["pppragma_directive -> PPPRAGMA","pppragma_directive",1,"p_pppragma_directive","c_parser.py",612],["pppragma_directive -> PPPRAGMA PPPRAGMASTR","pppragma_directive",2,"p_pppragma_directive","c_parser.py",613],["pppragma_directive -> _PRAGMA LPAREN unified_string_literal RPAREN","pppragma_directive",4,"p_pppragma_directive","c_parser.py",614],["pppragma_directive_list -> pppragma_directive","pppragma_directive_list",1,"p_pppragma_directive_list","c_parser.py",624],["pppragma_directive_list -> pppragma_directive_list pppragma_directive","pppragma_directive_list",2,"p_pppragma_directive_list","c_parser.py",625],["function_definition -> id_declarator declaration_list_opt compound_statement","function_definition",3,"p_function_definition_1","c_parser.py",632],["function_definition -> declaration_specifiers id_declarator declaration_list_opt compound_statement","function_definition",4,"p_function_definition_2","c_parser.py",645],["statement -> labeled_statement","statement",1,"p_statement","c_parser.py",660],["statement -> expression_statement","statement",1,"p_statement","c_parser.py",661],["statement -> compound_statement","statement",1,"p_statement","c_parser.py",662],["statement -> selection_statement","statement",1,"p_statement","c_parser.py",663],["statement -> iteration_statement","statement",1,"p_statement","c_parser.py",664],["statement -> jump_statement","statement",1,"p_statement","c_parser.py",665],["statement -> pppragma_directive","statement",1,"p_statement","c_parser.py",666],["statement -> static_assert","statement",1,"p_statement","c_parser.py",667],["statement -> asm_statement","statement",1,"p_statement","c_parser.py",668],["statement -> attribute_statement","statement",1,"p_statement","c_parser.py",669],["pragmacomp_or_statement -> pppragma_directive_list statement","pragmacomp_or_statement",2,"p_pragmacomp_or_statement","c_parser.py",717],["pragmacomp_or_statement -> statement","pragmacomp_or_statement",1,"p_pragmacomp_or_statement","c_parser.py",718],["decl_body -> declaration_specifiers init_declarator_list_opt","decl_body",2,"p_decl_body","c_parser.py",737],["decl_body -> declaration_specifiers_no_type id_init_declarator_list_opt","decl_body",2,"p_decl_body","c_parser.py",738],["declaration -> decl_body SEMI","declaration",2,"p_declaration","c_parser.py",800],["declaration_list -> declaration","declaration_list",1,"p_declaration_list","c_parser.py",809],["declaration_list -> declaration_list declaration","declaration_list",2,"p_declaration_list","c_parser.py",810],["declaration_specifiers_no_type -> type_qualifier declaration_specifiers_no_type_opt","declaration_specifiers_no_type",2,"p_declaration_specifiers_no_type_1","c_parser.py",820],["declaration_specifiers_no_type -> storage_class_specifier declaration_specifiers_no_type_opt","declaration_specifiers_no_type",2,"p_declaration_specifiers_no_type_2","c_parser.py",825],["declaration_specifiers_no_type -> function_specifier declaration_specifiers_no_type_opt","declaration_specifiers_no_type",2,"p_declaration_specifiers_no_type_3","c_parser.py",830],["declaration_specifiers_no_type -> atomic_specifier declaration_specifiers_no_type_opt","declaration_specifiers_no_type",2,"p_declaration_specifiers_no_type_4","c_parser.py",837],["declaration_specifiers_no_type -> alignment_specifier declaration_specifiers_no_type_opt","declaration_specifiers_no_type",2,"p_declaration_specifiers_no_type_5","c_parser.py",842],["declaration_specifiers_no_type -> gcc_attribute declaration_specifiers_no_type_opt","declaration_specifiers_no_type",2,"p_declaration_specifiers_no_type_attrs","c_parser.py",847],["declaration_specifiers -> declaration_specifiers type_qualifier","declaration_specifiers",2,"p_declaration_specifiers_1","c_parser.py",852],["declaration_specifiers -> declaration_specifiers storage_class_specifier","declaration_specifiers",2,"p_declaration_specifiers_2","c_parser.py",857],["declaration_specifiers -> declaration_specifiers function_specifier","declaration_specifiers",2,"p_declaration_specifiers_3","c_parser.py",862],["declaration_specifiers -> declaration_specifiers type_specifier_no_typeid","declaration_specifiers",2,"p_declaration_specifiers_4","c_parser.py",867],["declaration_specifiers -> type_specifier","declaration_specifiers",1,"p_declaration_specifiers_5","c_parser.py",872],["declaration_specifiers -> declaration_specifiers_no_type type_specifier","declaration_specifiers",2,"p_declaration_specifiers_6","c_parser.py",877],["declaration_specifiers -> declaration_specifiers alignment_specifier","declaration_specifiers",2,"p_declaration_specifiers_7","c_parser.py",882],["declaration_specifiers -> declaration_specifiers gcc_attribute","declaration_specifiers",2,"p_declaration_specifiers_attrs","c_parser.py",887],["storage_class_specifier -> AUTO","storage_class_specifier",1,"p_storage_class_specifier","c_parser.py",892],["storage_class_specifier -> REGISTER","storage_class_specifier",1,"p_storage_class_specifier","c_parser.py",893],["storage_class_specifier -> STATIC","storage_class_specifier",1,"p_storage_class_specifier","c_parser.py",894],["storage_class_specifier -> EXTERN","storage_class_specifier",1,"p_storage_class_specifier","c_parser.py",895],["storage_class_specifier -> TYPEDEF","storage_class_specifier",1,"p_storage_class_specifier","c_parser.py",896],["storage_class_specifier -> _THREAD_LOCAL","storage_class_specifier",1,"p_storage_class_specifier","c_parser.py",897],["function_specifier -> INLINE","function_specifier",1,"p_function_specifier","c_parser.py",902],["function_specifier -> _NORETURN","function_specifier",1,"p_function_specifier","c_parser.py",903],["type_specifier_no_typeid -> VOID","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",908],["type_specifier_no_typeid -> _BOOL","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",909],["type_specifier_no_typeid -> CHAR","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",910],["type_specifier_no_typeid -> SHORT","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",911],["type_specifier_no_typeid -> INT","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",912],["type_specifier_no_typeid -> LONG","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",913],["type_specifier_no_typeid -> FLOAT","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",914],["type_specifier_no_typeid -> DOUBLE","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",915],["type_specifier_no_typeid -> _COMPLEX","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",916],["type_specifier_no_typeid -> SIGNED","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",917],["type_specifier_no_typeid -> UNSIGNED","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",918],["type_specifier_no_typeid -> __INT128","type_specifier_no_typeid",1,"p_type_specifier_no_typeid","c_parser.py",919],["type_specifier -> typedef_name","type_specifier",1,"p_type_specifier","c_parser.py",924],["type_specifier -> enum_specifier","type_specifier",1,"p_type_specifier","c_parser.py",925],["type_specifier -> struct_or_union_specifier","type_specifier",1,"p_type_specifier","c_parser.py",926],["type_specifier -> type_specifier_no_typeid","type_specifier",1,"p_type_specifier","c_parser.py",927],["type_specifier -> atomic_specifier","type_specifier",1,"p_type_specifier","c_parser.py",928],["type_specifier -> typeof_specifier","type_specifier",1,"p_type_specifier","c_parser.py",929],["typeof_specifier -> TYPEOF LPAREN expression RPAREN","typeof_specifier",4,"p_type_specifier_gnu_typeof","c_parser.py",934],["typeof_specifier -> TYPEOF LPAREN type_name RPAREN","typeof_specifier",4,"p_type_specifier_gnu_typeof","c_parser.py",935],["atomic_specifier -> _ATOMIC LPAREN type_name RPAREN","atomic_specifier",4,"p_atomic_specifier","c_parser.py",941],["type_qualifier -> CONST","type_qualifier",1,"p_type_qualifier","c_parser.py",948],["type_qualifier -> RESTRICT","type_qualifier",1,"p_type_qualifier","c_parser.py",949],["type_qualifier -> VOLATILE","type_qualifier",1,"p_type_qualifier","c_parser.py",950],["type_qualifier -> _ATOMIC","type_qualifier",1,"p_type_qualifier","c_parser.py",951],["init_declarator_list -> init_declarator","init_declarator_list",1,"p_init_declarator_list","c_parser.py",956],["init_declarator_list -> init_declarator_list COMMA init_declarator","init_declarator_list",3,"p_init_declarator_list","c_parser.py",957],["init_declarator -> declarator asm_label_opt gcc_attributes_opt","init_declarator",3,"p_init_declarator","c_parser.py",965],["init_declarator -> declarator asm_label_opt gcc_attributes_opt EQUALS initializer","init_declarator",5,"p_init_declarator","c_parser.py",966],["init_declarator -> declarator asm_label_opt gcc_attributes_opt COLON constant_expression","init_declarator",5,"p_init_declarator","c_parser.py",967],["id_init_declarator_list -> id_init_declarator","id_init_declarator_list",1,"p_id_init_declarator_list","c_parser.py",972],["id_init_declarator_list -> id_init_declarator_list COMMA init_declarator","id_init_declarator_list",3,"p_id_init_declarator_list","c_parser.py",973],["id_init_declarator -> id_declarator asm_label_opt gcc_attributes_opt","id_init_declarator",3,"p_id_init_declarator","c_parser.py",978],["id_init_declarator -> id_declarator asm_label_opt gcc_attributes_opt EQUALS initializer","id_init_declarator",5,"p_id_init_declarator","c_parser.py",979],["specifier_qualifier_list -> specifier_qualifier_list type_specifier_no_typeid","specifier_qualifier_list",2,"p_specifier_qualifier_list_1","c_parser.py",986],["specifier_qualifier_list -> specifier_qualifier_list type_qualifier","specifier_qualifier_list",2,"p_specifier_qualifier_list_2","c_parser.py",991],["specifier_qualifier_list -> type_specifier","specifier_qualifier_list",1,"p_specifier_qualifier_list_3","c_parser.py",996],["specifier_qualifier_list -> qualifier_attr_list type_specifier","specifier_qualifier_list",2,"p_specifier_qualifier_list_4","c_parser.py",1001],["specifier_qualifier_list -> alignment_specifier","specifier_qualifier_list",1,"p_specifier_qualifier_list_5","c_parser.py",1006],["specifier_qualifier_list -> specifier_qualifier_list alignment_specifier","specifier_qualifier_list",2,"p_specifier_qualifier_list_6","c_parser.py",1011],["specifier_qualifier_list -> specifier_qualifier_list gcc_attribute","specifier_qualifier_list",2,"p_specifier_qualifier_list_attr","c_parser.py",1016],["struct_or_union_specifier -> struct_or_union ID","struct_or_union_specifier",2,"p_struct_or_union_specifier_1","c_parser.py",1024],["struct_or_union_specifier -> struct_or_union TYPEID","struct_or_union_specifier",2,"p_struct_or_union_specifier_1","c_parser.py",1025],["struct_or_union_specifier -> struct_or_union gcc_attributes_opt brace_open struct_declaration_list brace_close gcc_attributes_opt","struct_or_union_specifier",6,"p_struct_or_union_specifier_2","c_parser.py",1036],["struct_or_union_specifier -> struct_or_union gcc_attributes_opt brace_open brace_close gcc_attributes_opt","struct_or_union_specifier",5,"p_struct_or_union_specifier_2","c_parser.py",1037],["struct_or_union_specifier -> struct_or_union attrs_id_typeid brace_open struct_declaration_list brace_close gcc_attributes_opt","struct_or_union_specifier",6,"p_struct_or_union_specifier_3","c_parser.py",1047],["struct_or_union_specifier -> struct_or_union attrs_id_typeid brace_open brace_close gcc_attributes_opt","struct_or_union_specifier",5,"p_struct_or_union_specifier_3","c_parser.py",1048],["struct_or_union -> STRUCT","struct_or_union",1,"p_struct_or_union","c_parser.py",1058],["struct_or_union -> UNION","struct_or_union",1,"p_struct_or_union","c_parser.py",1059],["struct_declaration_list -> struct_declaration","struct_declaration_list",1,"p_struct_declaration_list","c_parser.py",1066],["struct_declaration_list -> struct_declaration_list struct_declaration","struct_declaration_list",2,"p_struct_declaration_list","c_parser.py",1067],["struct_declaration -> specifier_qualifier_list struct_declarator_list_opt SEMI","struct_declaration",3,"p_struct_declaration_1","c_parser.py",1075],["struct_declaration -> SEMI","struct_declaration",1,"p_struct_declaration_2","c_parser.py",1113],["struct_declaration -> pppragma_directive","struct_declaration",1,"p_struct_declaration_3","c_parser.py",1118],["struct_declarator_list -> struct_declarator","struct_declarator_list",1,"p_struct_declarator_list","c_parser.py",1123],["struct_declarator_list -> struct_declarator_list COMMA struct_declarator","struct_declarator_list",3,"p_struct_declarator_list","c_parser.py",1124],["struct_declarator -> declarator gcc_attributes_opt","struct_declarator",2,"p_struct_declarator_1","c_parser.py",1134],["struct_declarator -> declarator gcc_attributes_opt COLON constant_expression","struct_declarator",4,"p_struct_declarator_2","c_parser.py",1139],["struct_declarator -> gcc_attributes_opt COLON constant_expression","struct_declarator",3,"p_struct_declarator_2","c_parser.py",1140],["enum_specifier -> ENUM ID","enum_specifier",2,"p_enum_specifier_1","c_parser.py",1148],["enum_specifier -> ENUM TYPEID","enum_specifier",2,"p_enum_specifier_1","c_parser.py",1149],["enum_specifier -> ENUM gcc_attributes_opt brace_open enumerator_list brace_close gcc_attributes_opt","enum_specifier",6,"p_enum_specifier_2","c_parser.py",1154],["enum_specifier -> ENUM attrs_id_typeid brace_open enumerator_list brace_close gcc_attributes_opt","enum_specifier",6,"p_enum_specifier_3","c_parser.py",1159],["enumerator_list -> enumerator","enumerator_list",1,"p_enumerator_list","c_parser.py",1164],["enumerator_list -> enumerator_list COMMA","enumerator_list",2,"p_enumerator_list","c_parser.py",1165],["enumerator_list -> enumerator_list COMMA enumerator","enumerator_list",3,"p_enumerator_list","c_parser.py",1166],["alignment_specifier -> _ALIGNAS LPAREN type_name RPAREN","alignment_specifier",4,"p_alignment_specifier","c_parser.py",1177],["alignment_specifier -> _ALIGNAS LPAREN constant_expression RPAREN","alignment_specifier",4,"p_alignment_specifier","c_parser.py",1178],["enumerator -> ID gcc_attributes_opt","enumerator",2,"p_enumerator","c_parser.py",1183],["enumerator -> ID gcc_attributes_opt EQUALS constant_expression","enumerator",4,"p_enumerator","c_parser.py",1184],["declarator -> id_declarator","declarator",1,"p_declarator","c_parser.py",1207],["declarator -> typeid_declarator","declarator",1,"p_declarator","c_parser.py",1208],["pointer -> TIMES type_qualifier_list_opt","pointer",2,"p_pointer","c_parser.py",1320],["pointer -> TIMES type_qualifier_list_opt pointer","pointer",3,"p_pointer","c_parser.py",1321],["type_qualifier_list -> type_qualifier","type_qualifier_list",1,"p_type_qualifier_list","c_parser.py",1350],["type_qualifier_list -> type_qualifier_list type_qualifier","type_qualifier_list",2,"p_type_qualifier_list","c_parser.py",1351],["qualifier_attr_list -> type_qualifier","qualifier_attr_list",1,"p_type_qualifier_list_1","c_parser.py",1356],["qualifier_attr_list -> qualifier_attr_list type_qualifier","qualifier_attr_list",2,"p_type_qualifier_list_2","c_parser.py",1361],["qualifier_attr_list -> gcc_attribute","qualifier_attr_list",1,"p_type_qualifier_list_3","c_parser.py",1366],["qualifier_attr_list -> qualifier_attr_list gcc_attribute","qualifier_attr_list",2,"p_type_qualifier_list_4","c_parser.py",1371],["parameter_type_list -> parameter_list","parameter_type_list",1,"p_parameter_type_list","c_parser.py",1376],["parameter_type_list -> parameter_list COMMA ELLIPSIS","parameter_type_list",3,"p_parameter_type_list","c_parser.py",1377],["parameter_list -> parameter_declaration","parameter_list",1,"p_parameter_list","c_parser.py",1385],["parameter_list -> parameter_list COMMA parameter_declaration","parameter_list",3,"p_parameter_list","c_parser.py",1386],["parameter_declaration -> declaration_specifiers id_declarator gcc_attributes_opt","parameter_declaration",3,"p_parameter_declaration_1","c_parser.py",1405],["parameter_declaration -> declaration_specifiers typeid_noparen_declarator gcc_attributes_opt","parameter_declaration",3,"p_parameter_declaration_1","c_parser.py",1406],["parameter_declaration -> declaration_specifiers abstract_declarator_opt gcc_attributes_opt","parameter_declaration",3,"p_parameter_declaration_2","c_parser.py",1419],["identifier_list -> identifier","identifier_list",1,"p_identifier_list","c_parser.py",1454],["identifier_list -> identifier_list COMMA identifier","identifier_list",3,"p_identifier_list","c_parser.py",1455],["initializer -> assignment_expression","initializer",1,"p_initializer_1","c_parser.py",1464],["initializer -> brace_open initializer_list_opt brace_close","initializer",3,"p_initializer_2","c_parser.py",1469],["initializer -> brace_open initializer_list COMMA brace_close","initializer",4,"p_initializer_2","c_parser.py",1470],["initializer_list -> designation_opt initializer","initializer_list",2,"p_initializer_list","c_parser.py",1478],["initializer_list -> initializer_list COMMA designation_opt initializer","initializer_list",4,"p_initializer_list","c_parser.py",1479],["designation -> designator_list EQUALS","designation",2,"p_designation","c_parser.py",1490],["designator_list -> designator","designator_list",1,"p_designator_list","c_parser.py",1498],["designator_list -> designator_list designator","designator_list",2,"p_designator_list","c_parser.py",1499],["designator -> LBRACKET constant_expression RBRACKET","designator",3,"p_designator","c_parser.py",1504],["designator -> PERIOD identifier","designator",2,"p_designator","c_parser.py",1505],["designator -> LBRACKET constant_expression ELLIPSIS constant_expression RBRACKET","designator",5,"p_range_designator","c_parser.py",1510],["type_name -> specifier_qualifier_list abstract_declarator_opt","type_name",2,"p_type_name","c_parser.py",1515],["abstract_declarator -> pointer","abstract_declarator",1,"p_abstract_declarator_1","c_parser.py",1528],["abstract_declarator -> pointer direct_abstract_declarator","abstract_declarator",2,"p_abstract_declarator_2","c_parser.py",1536],["abstract_declarator -> direct_abstract_declarator","abstract_declarator",1,"p_abstract_declarator_3","c_parser.py",1541],["direct_abstract_declarator -> LPAREN abstract_declarator RPAREN","direct_abstract_declarator",3,"p_direct_abstract_declarator_1","c_parser.py",1551],["direct_abstract_declarator -> direct_abstract_declarator LBRACKET assignment_expression_opt RBRACKET","direct_abstract_declarator",4,"p_direct_abstract_declarator_2","c_parser.py",1555],["direct_abstract_declarator -> LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET","direct_abstract_declarator",4,"p_direct_abstract_declarator_3","c_parser.py",1566],["direct_abstract_declarator -> direct_abstract_declarator LBRACKET TIMES RBRACKET","direct_abstract_declarator",4,"p_direct_abstract_declarator_4","c_parser.py",1576],["direct_abstract_declarator -> LBRACKET TIMES RBRACKET","direct_abstract_declarator",3,"p_direct_abstract_declarator_5","c_parser.py",1587],["direct_abstract_declarator -> direct_abstract_declarator LPAREN parameter_type_list_opt RPAREN","direct_abstract_declarator",4,"p_direct_abstract_declarator_6","c_parser.py",1596],["direct_abstract_declarator -> LPAREN parameter_type_list_opt RPAREN","direct_abstract_declarator",3,"p_direct_abstract_declarator_7","c_parser.py",1606],["direct_abstract_declarator -> LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET","direct_abstract_declarator",5,"p_direct_abstract_declarator_8","c_parser.py",1614],["direct_abstract_declarator -> LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET","direct_abstract_declarator",5,"p_direct_abstract_declarator_8","c_parser.py",1615],["block_item -> declaration","block_item",1,"p_block_item","c_parser.py",1631],["block_item -> statement","block_item",1,"p_block_item","c_parser.py",1632],["block_item_list -> block_item","block_item_list",1,"p_block_item_list","c_parser.py",1639],["block_item_list -> block_item_list block_item","block_item_list",2,"p_block_item_list","c_parser.py",1640],["compound_statement -> brace_open block_item_list_opt brace_close","compound_statement",3,"p_compound_statement_1","c_parser.py",1646],["labeled_statement -> ID COLON pragmacomp_or_statement","labeled_statement",3,"p_labeled_statement_1","c_parser.py",1652],["labeled_statement -> TYPEID COLON pragmacomp_or_statement","labeled_statement",3,"p_labeled_statement_1","c_parser.py",1653],["labeled_statement -> CASE constant_expression COLON pragmacomp_or_statement","labeled_statement",4,"p_labeled_statement_2","c_parser.py",1658],["labeled_statement -> CASE constant_expression ELLIPSIS constant_expression COLON pragmacomp_or_statement","labeled_statement",6,"p_labeled_statement_range","c_parser.py",1662],["labeled_statement -> DEFAULT COLON pragmacomp_or_statement","labeled_statement",3,"p_labeled_statement_3","c_parser.py",1670],["labeled_statement -> ID COLON","labeled_statement",2,"p_labeled_statement_4","c_parser.py",1674],["labeled_statement -> TYPEID COLON","labeled_statement",2,"p_labeled_statement_4","c_parser.py",1675],["labeled_statement -> CASE constant_expression COLON","labeled_statement",3,"p_labeled_statement_5","c_parser.py",1680],["labeled_statement -> CASE constant_expression ELLIPSIS constant_expression COLON","labeled_statement",5,"p_labeled_statement_range_2","c_parser.py",1684],["labeled_statement -> DEFAULT COLON","labeled_statement",2,"p_labeled_statement_6","c_parser.py",1692],["selection_statement -> IF LPAREN expression RPAREN pragmacomp_or_statement","selection_statement",5,"p_selection_statement_1","c_parser.py",1696],["selection_statement -> IF LPAREN expression RPAREN statement ELSE pragmacomp_or_statement","selection_statement",7,"p_selection_statement_2","c_parser.py",1700],["selection_statement -> SWITCH LPAREN expression RPAREN pragmacomp_or_statement","selection_statement",5,"p_selection_statement_3","c_parser.py",1704],["iteration_statement -> WHILE LPAREN expression RPAREN pragmacomp_or_statement","iteration_statement",5,"p_iteration_statement_1","c_parser.py",1709],["iteration_statement -> DO pragmacomp_or_statement WHILE LPAREN expression RPAREN SEMI","iteration_statement",7,"p_iteration_statement_2","c_parser.py",1713],["iteration_statement -> FOR LPAREN expression_opt SEMI expression_opt SEMI expression_opt RPAREN pragmacomp_or_statement","iteration_statement",9,"p_iteration_statement_3","c_parser.py",1717],["iteration_statement -> FOR LPAREN declaration expression_opt SEMI expression_opt RPAREN pragmacomp_or_statement","iteration_statement",8,"p_iteration_statement_4","c_parser.py",1721],["jump_statement -> GOTO ID SEMI","jump_statement",3,"p_jump_statement_1","c_parser.py",1726],["jump_statement -> GOTO TYPEID SEMI","jump_statement",3,"p_jump_statement_1","c_parser.py",1727],["jump_statement -> BREAK SEMI","jump_statement",2,"p_jump_statement_2","c_parser.py",1732],["jump_statement -> CONTINUE SEMI","jump_statement",2,"p_jump_statement_3","c_parser.py",1736],["jump_statement -> RETURN expression SEMI","jump_statement",3,"p_jump_statement_4","c_parser.py",1740],["jump_statement -> RETURN SEMI","jump_statement",2,"p_jump_statement_4","c_parser.py",1741],["expression_statement -> expression_opt SEMI","expression_statement",2,"p_expression_statement","c_parser.py",1746],["expression -> assignment_expression","expression",1,"p_expression","c_parser.py",1753],["expression -> expression COMMA assignment_expression","expression",3,"p_expression","c_parser.py",1754],["assignment_expression -> LPAREN compound_statement RPAREN","assignment_expression",3,"p_parenthesized_compound_expression","c_parser.py",1766],["typedef_name -> TYPEID","typedef_name",1,"p_typedef_name","c_parser.py",1770],["assignment_expression -> conditional_expression","assignment_expression",1,"p_assignment_expression","c_parser.py",1774],["assignment_expression -> unary_expression assignment_operator assignment_expression","assignment_expression",3,"p_assignment_expression","c_parser.py",1775],["assignment_operator -> EQUALS","assignment_operator",1,"p_assignment_operator","c_parser.py",1788],["assignment_operator -> XOREQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1789],["assignment_operator -> TIMESEQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1790],["assignment_operator -> DIVEQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1791],["assignment_operator -> MODEQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1792],["assignment_operator -> PLUSEQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1793],["assignment_operator -> MINUSEQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1794],["assignment_operator -> LSHIFTEQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1795],["assignment_operator -> RSHIFTEQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1796],["assignment_operator -> ANDEQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1797],["assignment_operator -> OREQUAL","assignment_operator",1,"p_assignment_operator","c_parser.py",1798],["constant_expression -> conditional_expression","constant_expression",1,"p_constant_expression","c_parser.py",1803],["conditional_expression -> binary_expression","conditional_expression",1,"p_conditional_expression","c_parser.py",1807],["conditional_expression -> binary_expression CONDOP expression COLON conditional_expression","conditional_expression",5,"p_conditional_expression","c_parser.py",1808],["binary_expression -> unary_expression","binary_expression",1,"p_binary_expression","c_parser.py",1816],["binary_expression -> binary_expression TIMES binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1817],["binary_expression -> binary_expression DIVIDE binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1818],["binary_expression -> binary_expression MOD binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1819],["binary_expression -> binary_expression PLUS binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1820],["binary_expression -> binary_expression MINUS binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1821],["binary_expression -> binary_expression RSHIFT binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1822],["binary_expression -> binary_expression LSHIFT binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1823],["binary_expression -> binary_expression LT binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1824],["binary_expression -> binary_expression LE binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1825],["binary_expression -> binary_expression GE binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1826],["binary_expression -> binary_expression GT binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1827],["binary_expression -> binary_expression EQ binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1828],["binary_expression -> binary_expression NE binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1829],["binary_expression -> binary_expression AND binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1830],["binary_expression -> binary_expression OR binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1831],["binary_expression -> binary_expression XOR binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1832],["binary_expression -> binary_expression LAND binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1833],["binary_expression -> binary_expression LOR binary_expression","binary_expression",3,"p_binary_expression","c_parser.py",1834],["unary_expression -> LPAREN type_name RPAREN unary_expression","unary_expression",4,"p_cast_expression_2","c_parser.py",1842],["unary_expression -> postfix_expression","unary_expression",1,"p_unary_expression_1","c_parser.py",1846],["unary_expression -> PLUSPLUS unary_expression","unary_expression",2,"p_unary_expression_2","c_parser.py",1850],["unary_expression -> MINUSMINUS unary_expression","unary_expression",2,"p_unary_expression_2","c_parser.py",1851],["unary_expression -> unary_operator unary_expression","unary_expression",2,"p_unary_expression_2","c_parser.py",1852],["unary_expression -> SIZEOF unary_expression","unary_expression",2,"p_unary_expression_3","c_parser.py",1857],["unary_expression -> SIZEOF LPAREN type_name RPAREN","unary_expression",4,"p_unary_expression_3","c_parser.py",1858],["unary_expression -> _ALIGNOF LPAREN type_name RPAREN","unary_expression",4,"p_unary_expression_3","c_parser.py",1859],["unary_operator -> AND","unary_operator",1,"p_unary_operator","c_parser.py",1867],["unary_operator -> TIMES","unary_operator",1,"p_unary_operator","c_parser.py",1868],["unary_operator -> PLUS","unary_operator",1,"p_unary_operator","c_parser.py",1869],["unary_operator -> MINUS","unary_operator",1,"p_unary_operator","c_parser.py",1870],["unary_operator -> NOT","unary_operator",1,"p_unary_operator","c_parser.py",1871],["unary_operator -> LNOT","unary_operator",1,"p_unary_operator","c_parser.py",1872],["postfix_expression -> primary_expression","postfix_expression",1,"p_postfix_expression_1","c_parser.py",1877],["postfix_expression -> postfix_expression LBRACKET expression RBRACKET","postfix_expression",4,"p_postfix_expression_2","c_parser.py",1881],["postfix_expression -> postfix_expression LPAREN argument_expression_list RPAREN","postfix_expression",4,"p_postfix_expression_3","c_parser.py",1885],["postfix_expression -> postfix_expression LPAREN RPAREN","postfix_expression",3,"p_postfix_expression_3","c_parser.py",1886],["postfix_expression -> postfix_expression PERIOD ID","postfix_expression",3,"p_postfix_expression_4","c_parser.py",1891],["postfix_expression -> postfix_expression PERIOD TYPEID","postfix_expression",3,"p_postfix_expression_4","c_parser.py",1892],["postfix_expression -> postfix_expression ARROW ID","postfix_expression",3,"p_postfix_expression_4","c_parser.py",1893],["postfix_expression -> postfix_expression ARROW TYPEID","postfix_expression",3,"p_postfix_expression_4","c_parser.py",1894],["postfix_expression -> postfix_expression PLUSPLUS","postfix_expression",2,"p_postfix_expression_5","c_parser.py",1900],["postfix_expression -> postfix_expression MINUSMINUS","postfix_expression",2,"p_postfix_expression_5","c_parser.py",1901],["postfix_expression -> LPAREN type_name RPAREN brace_open initializer_list brace_close","postfix_expression",6,"p_postfix_expression_6","c_parser.py",1906],["postfix_expression -> LPAREN type_name RPAREN brace_open initializer_list COMMA brace_close","postfix_expression",7,"p_postfix_expression_6","c_parser.py",1907],["primary_expression -> identifier","primary_expression",1,"p_primary_expression_1","c_parser.py",1912],["primary_expression -> constant","primary_expression",1,"p_primary_expression_2","c_parser.py",1916],["primary_expression -> unified_string_literal","primary_expression",1,"p_primary_expression_3","c_parser.py",1920],["primary_expression -> unified_wstring_literal","primary_expression",1,"p_primary_expression_3","c_parser.py",1921],["primary_expression -> LPAREN expression RPAREN","primary_expression",3,"p_primary_expression_4","c_parser.py",1926],["primary_expression -> OFFSETOF LPAREN type_name COMMA offsetof_member_designator RPAREN","primary_expression",6,"p_primary_expression_5","c_parser.py",1930],["offsetof_member_designator -> identifier","offsetof_member_designator",1,"p_offsetof_member_designator","c_parser.py",1938],["offsetof_member_designator -> offsetof_member_designator PERIOD identifier","offsetof_member_designator",3,"p_offsetof_member_designator","c_parser.py",1939],["offsetof_member_designator -> offsetof_member_designator LBRACKET expression RBRACKET","offsetof_member_designator",4,"p_offsetof_member_designator","c_parser.py",1940],["argument_expression_list -> assignment_expression","argument_expression_list",1,"p_argument_expression_list","c_parser.py",1952],["argument_expression_list -> argument_expression_list COMMA assignment_expression","argument_expression_list",3,"p_argument_expression_list","c_parser.py",1953],["identifier -> ID","identifier",1,"p_identifier","c_parser.py",1962],["constant -> INT_CONST_DEC","constant",1,"p_constant_1","c_parser.py",1966],["constant -> INT_CONST_OCT","constant",1,"p_constant_1","c_parser.py",1967],["constant -> INT_CONST_HEX","constant",1,"p_constant_1","c_parser.py",1968],["constant -> INT_CONST_BIN","constant",1,"p_constant_1","c_parser.py",1969],["constant -> INT_CONST_CHAR","constant",1,"p_constant_1","c_parser.py",1970],["constant -> FLOAT_CONST","constant",1,"p_constant_2","c_parser.py",1989],["constant -> HEX_FLOAT_CONST","constant",1,"p_constant_2","c_parser.py",1990],["constant -> CHAR_CONST","constant",1,"p_constant_3","c_parser.py",2003],["constant -> WCHAR_CONST","constant",1,"p_constant_3","c_parser.py",2004],["constant -> U8CHAR_CONST","constant",1,"p_constant_3","c_parser.py",2005],["constant -> U16CHAR_CONST","constant",1,"p_constant_3","c_parser.py",2006],["constant -> U32CHAR_CONST","constant",1,"p_constant_3","c_parser.py",2007],["unified_string_literal -> STRING_LITERAL","unified_string_literal",1,"p_unified_string_literal","c_parser.py",2018],["unified_string_literal -> unified_string_literal STRING_LITERAL","unified_string_literal",2,"p_unified_string_literal","c_parser.py",2019],["unified_wstring_literal -> WSTRING_LITERAL","unified_wstring_literal",1,"p_unified_wstring_literal","c_parser.py",2029],["unified_wstring_literal -> U8STRING_LITERAL","unified_wstring_literal",1,"p_unified_wstring_literal","c_parser.py",2030],["unified_wstring_literal -> U16STRING_LITERAL","unified_wstring_literal",1,"p_unified_wstring_literal","c_parser.py",2031],["unified_wstring_literal -> U32STRING_LITERAL","unified_wstring_literal",1,"p_unified_wstring_literal","c_parser.py",2032],["unified_wstring_literal -> unified_wstring_literal WSTRING_LITERAL","unified_wstring_literal",2,"p_unified_wstring_literal","c_parser.py",2033],["unified_wstring_literal -> unified_wstring_literal U8STRING_LITERAL","unified_wstring_literal",2,"p_unified_wstring_literal","c_parser.py",2034],["unified_wstring_literal -> unified_wstring_literal U16STRING_LITERAL","unified_wstring_literal",2,"p_unified_wstring_literal","c_parser.py",2035],["unified_wstring_literal -> unified_wstring_literal U32STRING_LITERAL","unified_wstring_literal",2,"p_unified_wstring_literal","c_parser.py",2036],["attrs_id_typeid -> ID","attrs_id_typeid",1,"p_attrs_id_typeid","c_parser.py",2046],["attrs_id_typeid -> TYPEID","attrs_id_typeid",1,"p_attrs_id_typeid","c_parser.py",2047],["attrs_id_typeid -> gcc_attributes ID","attrs_id_typeid",2,"p_attrs_id_typeid","c_parser.py",2048],["attrs_id_typeid -> gcc_attributes TYPEID","attrs_id_typeid",2,"p_attrs_id_typeid","c_parser.py",2049],["brace_open -> LBRACE","brace_open",1,"p_brace_open","c_parser.py",2057],["brace_close -> RBRACE","brace_close",1,"p_brace_close","c_parser.py",2063],["attribute_statement -> gcc_attributes SEMI","attribute_statement",2,"p_attr_stmt","c_parser.py",2069],["asm_statement -> ASM asm_qualifiers_opt LPAREN unified_string_literal RPAREN SEMI","asm_statement",6,"p_asm_1","c_parser.py",2074],["asm_statement -> ASM asm_qualifiers_opt LPAREN unified_string_literal COLON asm_operands_opt RPAREN SEMI","asm_statement",8,"p_asm_2","c_parser.py",2079],["asm_statement -> ASM asm_qualifiers_opt LPAREN unified_string_literal COLON asm_operands_opt COLON asm_operands_opt RPAREN SEMI","asm_statement",10,"p_asm_3","c_parser.py",2084],["asm_statement -> ASM asm_qualifiers_opt LPAREN unified_string_literal COLON asm_operands_opt COLON asm_operands_opt COLON asm_string_list_opt RPAREN SEMI","asm_statement",12,"p_asm_4","c_parser.py",2089],["asm_statement -> ASM asm_qualifiers_opt LPAREN unified_string_literal COLON asm_operands_opt COLON asm_operands_opt COLON asm_string_list_opt COLON asm_goto_list_opt RPAREN SEMI","asm_statement",14,"p_asm_5","c_parser.py",2094],["asm_operands -> asm_operands COMMA asm_operand","asm_operands",3,"p_asm_operands","c_parser.py",2099],["asm_operands -> asm_operand","asm_operands",1,"p_asm_operands","c_parser.py",2100],["asm_operand -> asm_symbolic_name_opt unified_string_literal LPAREN unary_expression RPAREN","asm_operand",5,"p_asm_operand","c_parser.py",2105],["asm_string_list -> asm_string_list COMMA unified_string_literal","asm_string_list",3,"p_asm_string_list","c_parser.py",2110],["asm_string_list -> unified_string_literal","asm_string_list",1,"p_asm_string_list","c_parser.py",2111],["asm_goto_list -> asm_goto_list COMMA ID","asm_goto_list",3,"p_asm_goto_list","c_parser.py",2116],["asm_goto_list -> asm_goto_list COMMA TYPEID","asm_goto_list",3,"p_asm_goto_list","c_parser.py",2117],["asm_goto_list -> ID","asm_goto_list",1,"p_asm_goto_list","c_parser.py",2118],["asm_goto_list -> TYPEID","asm_goto_list",1,"p_asm_goto_list","c_parser.py",2119],["asm_symbolic_name -> LBRACKET ID RBRACKET","asm_symbolic_name",3,"p_asm_symbolic_name","c_parser.py",2124],["asm_symbolic_name -> LBRACKET TYPEID RBRACKET","asm_symbolic_name",3,"p_asm_symbolic_name","c_parser.py",2125],["asm_qualifiers -> asm_qualifiers_opt VOLATILE","asm_qualifiers",2,"p_asm_qualifiers","c_parser.py",2130],["asm_qualifiers -> asm_qualifiers_opt INLINE","asm_qualifiers",2,"p_asm_qualifiers","c_parser.py",2131],["asm_qualifiers -> asm_qualifiers_opt GOTO","asm_qualifiers",2,"p_asm_qualifiers","c_parser.py",2132],["asm_label -> ASM LPAREN unified_string_literal RPAREN","asm_label",4,"p_asm_label","c_parser.py",2137],["gcc_attributes -> gcc_attribute","gcc_attributes",1,"p_gcc_attributes","c_parser.py",2142],["gcc_attributes -> gcc_attributes gcc_attribute","gcc_attributes",2,"p_gcc_attributes","c_parser.py",2143],["gcc_attribute -> __ATTRIBUTE__ LPAREN LPAREN gcc_attribute_list RPAREN RPAREN","gcc_attribute",6,"p_gcc_attribute","c_parser.py",2148],["gcc_attribute_list -> gcc_attribute_item","gcc_attribute_list",1,"p_gcc_attribute_list","c_parser.py",2153],["gcc_attribute_list -> gcc_attribute_list COMMA gcc_attribute_item","gcc_attribute_list",3,"p_gcc_attribute_list","c_parser.py",2154],["gcc_attribute_item -> empty","gcc_attribute_item",1,"p_gcc_attribute_item","c_parser.py",2159],["gcc_attribute_item -> CONST","gcc_attribute_item",1,"p_gcc_attribute_item","c_parser.py",2160],["gcc_attribute_item -> ID","gcc_attribute_item",1,"p_gcc_attribute_item","c_parser.py",2161],["gcc_attribute_item -> TYPEID","gcc_attribute_item",1,"p_gcc_attribute_item","c_parser.py",2162],["gcc_attribute_item -> ID LPAREN argument_expression_list RPAREN","gcc_attribute_item",4,"p_gcc_attribute_item","c_parser.py",2163],["gcc_attribute_item -> TYPEID LPAREN argument_expression_list RPAREN","gcc_attribute_item",4,"p_gcc_attribute_item","c_parser.py",2164],["empty -> ","empty",0,"p_empty","c_parser.py",2178]]} diff --git a/packages/romdev-pycparser/test/c_ast.test.js b/packages/romdev-pycparser/test/c_ast.test.js new file mode 100644 index 00000000..64056daa --- /dev/null +++ b/packages/romdev-pycparser/test/c_ast.test.js @@ -0,0 +1,85 @@ +// Port of pycparser tests/test_c_ast.py. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { c_ast, NodeVisitor, nodeRepr } from "../src/index.js"; + +test("BinaryOp", () => { + const b1 = new c_ast.BinaryOp({ op: "+", left: new c_ast.Constant({ type: "int", value: "6" }), right: new c_ast.ID({ name: "joe" }) }); + assert.ok(b1.left instanceof c_ast.Constant); + assert.equal(b1.left.type, "int"); + assert.equal(b1.left.value, "6"); + assert.ok(b1.right instanceof c_ast.ID); + assert.equal(b1.right.name, "joe"); +}); + +test("weakref works on nodes", () => { + // Python also checks weakref.getweakrefcount; JS has no such counter, so + // only the dereference half of the upstream test is portable. + const c1 = new c_ast.Constant({ type: "float", value: "3.14" }); + const wr = new WeakRef(c1); + assert.equal(wr.deref().type, "float"); +}); + +class ConstantVisitor extends NodeVisitor { + constructor() { super(); this.values = []; } + visit_Constant(node) { this.values.push(node.value); } +} + +test("NodeVisitor scalar children", () => { + const b1 = new c_ast.BinaryOp({ op: "+", left: new c_ast.Constant({ type: "int", value: "6" }), right: new c_ast.ID({ name: "joe" }) }); + let cv = new ConstantVisitor(); + cv.visit(b1); + assert.deepEqual(cv.values, ["6"]); + const b2 = new c_ast.BinaryOp({ op: "*", left: new c_ast.Constant({ type: "int", value: "111" }), right: b1 }); + const b3 = new c_ast.BinaryOp({ op: "^", left: b2, right: b1 }); + cv = new ConstantVisitor(); + cv.visit(b3); + assert.deepEqual(cv.values, ["111", "6", "6"]); +}); + +function listTree() { + const c1 = new c_ast.Constant({ type: "float", value: "5.6" }); + const c2 = new c_ast.Constant({ type: "char", value: "t" }); + const b1 = new c_ast.BinaryOp({ op: "+", left: c1, right: c2 }); + const b2 = new c_ast.BinaryOp({ op: "-", left: b1, right: c2 }); + return new c_ast.Compound({ block_items: [b1, b2, c1, c2] }); +} + +test("NodeVisitor list children", () => { + const cv = new ConstantVisitor(); + cv.visit(listTree()); + assert.deepEqual(cv.values, ["5.6", "t", "5.6", "t", "t", "5.6", "t"]); +}); + +test("repr", () => { + const expected = "Compound(block_items=[BinaryOp(op='+',\n" + + " left=Constant(type='float',\n" + + " value='5.6'\n" + + " ),\n" + + " right=Constant(type='char',\n" + + " value='t'\n" + + " )\n" + + " ),\n" + + " BinaryOp(op='-',\n" + + " left=BinaryOp(op='+',\n" + + " left=Constant(type='float',\n" + + " value='5.6'\n" + + " ),\n" + + " right=Constant(type='char',\n" + + " value='t'\n" + + " )\n" + + " ),\n" + + " right=Constant(type='char',\n" + + " value='t'\n" + + " )\n" + + " ),\n" + + " Constant(type='float',\n" + + " value='5.6'\n" + + " ),\n" + + " Constant(type='char',\n" + + " value='t'\n" + + " )\n" + + " ]\n" + + " )"; + assert.equal(nodeRepr(listTree()), expected); +}); diff --git a/packages/romdev-pycparser/test/c_generator.test.js b/packages/romdev-pycparser/test/c_generator.test.js new file mode 100644 index 00000000..97448f15 --- /dev/null +++ b/packages/romdev-pycparser/test/c_generator.test.js @@ -0,0 +1,485 @@ +// Port of pycparser tests/test_c_generator.py. +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { CParser, CGenerator, NodeVisitor, c_ast, AssertionError } from "../src/index.js"; +import { compareAsts } from "./helpers.js"; +import { parse_file_with_cpp, cFile, CPP_SKIP } from "./cpp.js"; + +const _c_parser = new CParser(); +const parseToAst = (src) => _c_parser.parse(src); + +describe("TestFunctionDeclGeneration", () => { + test("partial funcdecl generation", () => { + const src = String.raw` + void noop(void); + void *something(void *thing); + int add(int x, int y);`; + const ast = parseToAst(src); + const stubs = []; + class V extends NodeVisitor { + visit_FuncDecl(node) { stubs.push(new CGenerator().visit(node)); } + } + new V().visit(ast); + assert.equal(stubs.length, 3); + assert.ok(stubs.includes("void noop(void)")); + assert.ok(stubs.includes("void *something(void *thing)")); + assert.ok(stubs.includes("int add(int x, int y)")); + }); +}); + +const runCtoC = (src, reduce_parentheses = false) => new CGenerator(reduce_parentheses).visit(parseToAst(src)); + +function assertCtoC(src, reduce_parentheses = false) { + const src2 = runCtoC(src, reduce_parentheses); + assert.ok(compareAsts(parseToAst(src), parseToAst(src2)), `${JSON.stringify(src)} != ${JSON.stringify(src2)}`); + return src2; +} + +describe("TestCtoC", () => { + test("trivial decls", () => { + assertCtoC("int a;"); + assertCtoC("int b, a;"); + assertCtoC("int c, b, a;"); + assertCtoC("auto int a;"); + assertCtoC("register int a;"); + assertCtoC("_Thread_local int a;"); + }); + + test("complex decls", () => { + assertCtoC("int** (*a)(void);"); + assertCtoC("int** (*a)(void*, int);"); + assertCtoC("int (*b)(char * restrict k, float);"); + assertCtoC("int (*b)(char * _Atomic k, float);"); + assertCtoC("int (*b)(char * _Atomic volatile k, float);"); + assertCtoC("int test(const char* const* arg);"); + assertCtoC("int test(const char** const arg);"); + }); + + test("alignment", () => { + assertCtoC("_Alignas(32) int b;"); + assertCtoC("int _Alignas(32) a;"); + assertCtoC("_Alignas(32) _Atomic(int) b;"); + assertCtoC("_Atomic(int) _Alignas(32) b;"); + assertCtoC("_Alignas(long long) int a;"); + assertCtoC("int _Alignas(long long) a;"); + assertCtoC(` + typedef struct node_t { + _Alignas(64) void* next; + int data; + } node; + `); + assertCtoC(` + typedef struct node_t { + void _Alignas(64) * next; + int data; + } node; + `); + }); + + test("ternary", () => { + assertCtoC(` + int main(void) + { + int a, b; + (a == 0) ? (b = 1) : (b = 2); + }`); + }); + + test("casts", () => { + assertCtoC(` + int main() { + int b = (int) f; + int c = (int*) f; + }`); + assertCtoC(` + int main() { + int a = (int) b + 8; + int t = (int) c; + } + `); + }); + + test("initlist", () => assertCtoC("int arr[] = {1, 2, 3};")); + + test("exprs", () => { + assertCtoC(` + int main(void) + { + int a; + int b = a++; + int c = ++a; + int d = a--; + int e = --a; + }`); + }); + + test("statements", () => { + assertCtoC(` + int main() { + int a; + a = 5; + ; + b = - - a; + return a; + }`); + }); + + test("struct decl", () => { + assertCtoC(` + typedef struct node_t { + struct node_t* next; + int data; + } node; + `); + }); + + test("krstyle", () => { + assertCtoC(` + int main(argc, argv) + int argc; + char** argv; + { + return 0; + } + `); + }); + + test("switchcase", () => { + assertCtoC(` + int main() { + switch (myvar) { + case 10: + { + k = 10; + p = k + 1; + break; + } + case 20: + case 30: + return 20; + default: + break; + } + } + `); + }); + + test("nest initializer list", () => { + assertCtoC(` + int main() + { + int i[1][1] = { { 1 } }; + }`); + }); + + test("nest named initializer", () => { + assertCtoC(`struct test + { + int i; + struct test_i_t + { + int k; + } test_i; + int j; + }; + struct test test_var = {.i = 0, .test_i = {.k = 1}, .j = 2}; + `); + }); + + test("expr list in initializer list", () => { + assertCtoC(` + int main() + { + int i[1] = { (1, 2) }; + }`); + }); + + test("issue36", () => { + assertCtoC(` + int main() { + }`); + }); + + test("issue37", () => { + assertCtoC(` + int main(void) + { + unsigned size; + size = sizeof(size); + return 0; + }`); + }); + + test("issue66", () => { + assertCtoC(` + struct foo; + `); + assertCtoC(` + struct foo {}; + `); + }); + + test("issue83", () => { + assertCtoC(` + void x(void) { + int i = (9, k); + } + `); + }); + + test("issue84", () => { + assertCtoC(` + void x(void) { + for (int i = 0;;) + i; + } + `); + }); + + test("issue246", () => { + assertCtoC(` + int array[3] = {[0] = 0, [1] = 1, [1+1] = 2}; + `); + }); + + test("noreturn", () => { + assertCtoC(` + _Noreturn int x(void) { + abort(); + } + `); + }); + + test("exprlist with semi", () => { + assertCtoC(` + void x() { + if (i < j) + tmp = C[i], C[i] = C[j], C[j] = tmp; + if (i <= j) + i++, j--; + } + `); + }); + + test("exprlist with compound", () => { + assertCtoC(` + void test(){ + (sizeof (0), ({ if (0) ; else ; })); + } + `); + }); + + test("exprlist with subexprlist", () => { + assertCtoC(` + void x() { + (a = b, (b = c, c = a)); + } + `); + }); + + test("comma operator funcarg", () => { + assertCtoC(` + void f(int x) { return x; } + int main(void) { f((1, 2)); return 0; } + `); + }); + + test("comma op in ternary", () => { + assertCtoC(` + void f() { + (0, 0) ? (0, 0) : (0, 0); + } + `); + }); + + test("comma op assignment", () => { + assertCtoC(` + void f() { + i = (a, b, c); + } + `); + }); + + test("pragma", () => { + assertCtoC(` + #pragma foo + void f() { + #pragma bar + i = (a, b, c); + if (d) + #pragma qux + j = e; + if (d) + #pragma qux + #pragma quux + j = e; + } + typedef struct s { + #pragma baz + } s; + `); + }); + + test("compound literal", () => { + assertCtoC("char **foo = (char *[]){ \"x\", \"y\", \"z\" };"); + assertCtoC("int i = ++(int){ 1 };"); + assertCtoC("struct foo_s foo = (struct foo_s){ 1, 2 };"); + }); + + test("enum", () => { + assertCtoC(` + enum e + { + a, + b = 2, + c = 3 + }; + `); + assertCtoC(` + enum f + { + g = 4, + h, + i + }; + `); + }); + + test("enum typedef", () => assertCtoC("typedef enum EnumName EnumTypedefName;")); + + test("struct union enum attributes", () => { + assertCtoC(` + struct ForwardDeclaration __attribute__((packed)); + `); + assertCtoC(` + struct StructName { int member; } __attribute__((packed)); + `); + assertCtoC(` + union UnionName { int member; } __attribute__((packed)); + `); + assertCtoC(` + enum EnumName { ENUM_VALUE } __attribute__((packed)); + `); + }); + + test("generate struct union enum exception", () => { + const generator = new CGenerator(); + assert.throws(() => generator._generate_struct_union_enum( + new c_ast.Struct({ name: "TestStruct", gcc_attributes: [], decls: [] }), ""), AssertionError); + }); + + test("array decl", () => { + assertCtoC("int g(const int a[const 20]){}"); + const ast = parseToAst("const int a[const 20];"); + const generator = new CGenerator(); + assert.equal(generator.visit(ast.ext[0].type), "const int [const 20]"); + assert.equal(generator.visit(ast.ext[0].type.type), "const int"); + }); + + test("ptr decl", () => { + const src = "const int ** const x;"; + assertCtoC(src); + const ast = parseToAst(src); + const generator = new CGenerator(); + assert.equal(generator.visit(ast.ext[0].type), "const int ** const"); + assert.equal(generator.visit(ast.ext[0].type.type), "const int *"); + assert.equal(generator.visit(ast.ext[0].type.type.type), "const int"); + }); + + test("atomic qual", () => { + assertCtoC("_Atomic int x;"); + assertCtoC("_Atomic int* x;"); + assertCtoC("int* _Atomic x;"); + const s1 = "_Atomic(int) x;"; + assert.equal(runCtoC(s1), "_Atomic int x;\n"); + assertCtoC(s1); + const s2 = "_Atomic(int*) x;"; + assert.equal(runCtoC(s2), "int * _Atomic x;\n"); + assertCtoC(s2); + const s3 = "_Atomic(_Atomic(int)*) x;"; + assert.equal(runCtoC(s3), "_Atomic int * _Atomic x;\n"); + assertCtoC(s3); + const s4 = "typedef _Atomic(int) atomic_int;"; + assert.equal(runCtoC(s4), "typedef _Atomic int atomic_int;\n"); + assertCtoC(s4); + const s5 = "typedef _Atomic(_Atomic(_Atomic(int (*)(void)) *) *) t;"; + assert.equal(runCtoC(s5), "typedef int (* _Atomic * _Atomic * _Atomic t)(void);\n"); + assertCtoC(s5); + assertCtoC(` + typedef struct node_t { + _Atomic(void*) a; + _Atomic(void) *b; + _Atomic void *c; + } node; + `); + }); + + test("nested sizeof", () => { + let src = "1"; + for (let i = 0; i < 30; i++) src = "sizeof(" + src + ")"; + assertCtoC("int x = " + src + ";"); + }); + + test("static assert", () => { + assertCtoC("_Static_assert(sizeof(int) == sizeof(int), \"123\");"); + assertCtoC("int main() { _Static_assert(sizeof(int) == sizeof(int), \"123\"); } "); + assertCtoC("_Static_assert(sizeof(int) == sizeof(int));"); + }); + + test("reduce parentheses binaryops", () => { + const c1 = "int x = a + b + c + d;"; + assert.equal(runCtoC(c1), "int x = ((a + b) + c) + d;\n"); + assert.equal(runCtoC(c1, true), "int x = a + b + c + d;\n"); + const snippets = [ + "int x = a*b*c*d;", + "int x = a+b*c*d;", + "int x = a*b+c*d;", + "int x = a*b*c+d;", + "int x = (a+b)*c*d;", + "int x = (a+b)*(c+d);", + "int x = (a+b)/(c-d);", + "int x = a+b-c-d;", + "int x = a+(b-c)-d;", + ]; + for (const src of snippets) { + const src2 = assertCtoC(src, true); + const count = (s) => s.split("(").length - 1; + assert.equal(count(src2), count(src), `${src2} did not have minimum number of parenthesis, should be like ${src}.`); + } + }); +}); + +describe("TestCasttoC", () => { + test("to type", () => { + const generator = new CGenerator(); + const test_fun = new c_ast.FuncCall(new c_ast.ID("test_fun"), new c_ast.ExprList([])); + const ast1 = parseToAst("int *x;"); + const int_ptr_type = ast1.ext[0].type; + const int_type = int_ptr_type.type; + assert.equal(generator.visit(new c_ast.Cast(int_ptr_type, test_fun)), "(int *) test_fun()"); + assert.equal(generator.visit(new c_ast.Cast(int_type, test_fun)), "(int) test_fun()"); + }); + + test("to type with cpp", { skip: CPP_SKIP }, async () => { + const generator = new CGenerator(); + const test_fun = new c_ast.FuncCall(new c_ast.ID("test_fun"), new c_ast.ExprList([])); + const ast2 = await parse_file_with_cpp(cFile("memmgr.h")); + const void_ptr_type = ast2.ext.at(-3).type.type; + const void_type = void_ptr_type.type; + assert.equal(generator.visit(new c_ast.Cast(void_ptr_type, test_fun)), "(void *) test_fun()"); + assert.equal(generator.visit(new c_ast.Cast(void_type, test_fun)), "(void) test_fun()"); + }); + + test("nested else if line breaks", () => { + const generator = new CGenerator(); + const If = c_ast.If, C = c_ast.Compound; + const a1 = new If(null, null, null); + const a2 = new If(null, null, new If(null, null, null)); + const a3 = new If(null, null, new If(null, null, new If(null, null, null))); + const a4 = new If(null, new C([]), new If(null, new C([]), new If(null, new C([]), null))); + assert.equal(generator.visit(a1), "if ()\n \n"); + assert.equal(generator.visit(a2), "if ()\n \nelse\n if ()\n \n"); + assert.equal(generator.visit(a3), "if ()\n \nelse\n if ()\n \nelse\n if ()\n \n"); + assert.equal(generator.visit(a4), "if ()\n{\n}\nelse\n if ()\n{\n}\nelse\n if ()\n{\n}\n"); + }); +}); diff --git a/packages/romdev-pycparser/test/c_lexer.test.js b/packages/romdev-pycparser/test/c_lexer.test.js new file mode 100644 index 00000000..fed4a1fc --- /dev/null +++ b/packages/romdev-pycparser/test/c_lexer.test.js @@ -0,0 +1,347 @@ +// Port of pycparser tests/test_c_lexer.py. +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { CLexer } from "../src/index.js"; + +function tokenList(clex) { + const out = []; + for (;;) { + const t = clex.token(); + if (t == null) return out; + out.push(t); + } +} +const tokenTypes = (clex) => tokenList(clex).map((t) => t.type); + +describe("TestCLexerNoErrors", () => { + const makeLexer = (on_lbrace_func = () => {}, on_rbrace_func = () => {}) => { + const clex = new CLexer({ + error_func: (msg) => assert.fail(msg), + on_lbrace_func, + on_rbrace_func, + type_lookup_func: (typ) => typ.startsWith("mytype"), + }); + clex.build(); + return clex; + }; + const assertTokensTypes = (str, types) => { + const clex = makeLexer(); + clex.input(str); + assert.deepEqual(tokenTypes(clex), types); + }; + + test("trivial tokens", () => { + assertTokensTypes("1", ["INT_CONST_DEC"]); + assertTokensTypes("-", ["MINUS"]); + assertTokensTypes("volatile", ["VOLATILE"]); + assertTokensTypes("...", ["ELLIPSIS"]); + assertTokensTypes("++", ["PLUSPLUS"]); + assertTokensTypes("case int", ["CASE", "INT"]); + assertTokensTypes("caseint", ["ID"]); + assertTokensTypes("$dollar cent$", ["ID", "ID"]); + assertTokensTypes("i ^= 1;", ["ID", "XOREQUAL", "INT_CONST_DEC", "SEMI"]); + }); + + test("id typeid", () => { + assertTokensTypes("myt", ["ID"]); + assertTokensTypes("mytype", ["TYPEID"]); + assertTokensTypes("mytype6 var", ["TYPEID", "ID"]); + }); + + test("integer constants", () => { + assertTokensTypes("12", ["INT_CONST_DEC"]); + assertTokensTypes("12u", ["INT_CONST_DEC"]); + assertTokensTypes("12l", ["INT_CONST_DEC"]); + assertTokensTypes("199872Ul", ["INT_CONST_DEC"]); + assertTokensTypes("199872lU", ["INT_CONST_DEC"]); + assertTokensTypes("199872LL", ["INT_CONST_DEC"]); + assertTokensTypes("199872ull", ["INT_CONST_DEC"]); + assertTokensTypes("199872llu", ["INT_CONST_DEC"]); + assertTokensTypes("1009843200000uLL", ["INT_CONST_DEC"]); + assertTokensTypes("1009843200000LLu", ["INT_CONST_DEC"]); + assertTokensTypes("077", ["INT_CONST_OCT"]); + assertTokensTypes("0123456L", ["INT_CONST_OCT"]); + assertTokensTypes("0xf7", ["INT_CONST_HEX"]); + assertTokensTypes("0b110", ["INT_CONST_BIN"]); + assertTokensTypes("0x01202AAbbf7Ul", ["INT_CONST_HEX"]); + assertTokensTypes("'12'", ["INT_CONST_CHAR"]); + assertTokensTypes("'123'", ["INT_CONST_CHAR"]); + assertTokensTypes("'1AB4'", ["INT_CONST_CHAR"]); + assertTokensTypes(String.raw`'1A\n4'`, ["INT_CONST_CHAR"]); + assertTokensTypes("xf7", ["ID"]); + assertTokensTypes("-1", ["MINUS", "INT_CONST_DEC"]); + }); + + test("special names", () => { + assertTokensTypes("sizeof offsetof", ["SIZEOF", "OFFSETOF"]); + }); + + test("new keywords", () => { + assertTokensTypes("_Bool", ["_BOOL"]); + assertTokensTypes("_Atomic", ["_ATOMIC"]); + assertTokensTypes("_Alignas _Alignof", ["_ALIGNAS", "_ALIGNOF"]); + }); + + test("floating constants", () => { + assertTokensTypes("1.5f", ["FLOAT_CONST"]); + assertTokensTypes("01.5", ["FLOAT_CONST"]); + assertTokensTypes(".15L", ["FLOAT_CONST"]); + assertTokensTypes("0.", ["FLOAT_CONST"]); + assertTokensTypes(".", ["PERIOD"]); + assertTokensTypes("3.3e-3", ["FLOAT_CONST"]); + assertTokensTypes(".7e25L", ["FLOAT_CONST"]); + assertTokensTypes("6.e+125f", ["FLOAT_CONST"]); + assertTokensTypes("666e666", ["FLOAT_CONST"]); + assertTokensTypes("00666e+3", ["FLOAT_CONST"]); + assertTokensTypes("0x0666e+3", ["INT_CONST_HEX", "PLUS", "INT_CONST_DEC"]); + }); + + test("hexadecimal floating constants", () => { + assertTokensTypes("0xDE.488641p0", ["HEX_FLOAT_CONST"]); + assertTokensTypes("0x.488641p0", ["HEX_FLOAT_CONST"]); + assertTokensTypes("0X12.P0", ["HEX_FLOAT_CONST"]); + }); + + test("char constants", () => { + assertTokensTypes(String.raw`'x'`, ["CHAR_CONST"]); + assertTokensTypes(String.raw`L'x'`, ["WCHAR_CONST"]); + assertTokensTypes(String.raw`u8'x'`, ["U8CHAR_CONST"]); + assertTokensTypes(String.raw`u'x'`, ["U16CHAR_CONST"]); + assertTokensTypes(String.raw`U'x'`, ["U32CHAR_CONST"]); + assertTokensTypes(String.raw`'\t'`, ["CHAR_CONST"]); + assertTokensTypes(String.raw`'\''`, ["CHAR_CONST"]); + assertTokensTypes(String.raw`'\?'`, ["CHAR_CONST"]); + assertTokensTypes(String.raw`'\0'`, ["CHAR_CONST"]); + assertTokensTypes(String.raw`'\012'`, ["CHAR_CONST"]); + assertTokensTypes(String.raw`'\x2f'`, ["CHAR_CONST"]); + assertTokensTypes(String.raw`'\x2f12'`, ["CHAR_CONST"]); + assertTokensTypes(String.raw`L'\xaf'`, ["WCHAR_CONST"]); + }); + + test("on rbrace lbrace", () => { + const braces = []; + const clex = makeLexer(() => braces.push("{"), () => braces.push("}")); + clex.input("hello { there } } and again }}{"); + tokenList(clex); + assert.deepEqual(braces, ["{", "}", "}", "}", "}", "{"]); + }); + + test("string literal", () => { + assertTokensTypes("\"a string\"", ["STRING_LITERAL"]); + assertTokensTypes("L\"ing\"", ["WSTRING_LITERAL"]); + assertTokensTypes("u8\"ing\"", ["U8STRING_LITERAL"]); + assertTokensTypes("u\"ing\"", ["U16STRING_LITERAL"]); + assertTokensTypes("U\"ing\"", ["U32STRING_LITERAL"]); + assertTokensTypes("\"i am a string too \t\"", ["STRING_LITERAL"]); + assertTokensTypes(String.raw`"esc\ape \"\'\? \0234 chars \rule"`, ["STRING_LITERAL"]); + assertTokensTypes(String.raw`"hello 'joe' wanna give it a \"go\"?"`, ["STRING_LITERAL"]); + // Python non-raw '\123' is the octal escape for 'S'. + assertTokensTypes("\"" + "S".repeat(16) + "\"", ["STRING_LITERAL"]); + assertTokensTypes(String.raw`"\x"`, ["STRING_LITERAL"]); + assertTokensTypes(String.raw`"\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z\A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z"`, ["STRING_LITERAL"]); + assertTokensTypes(String.raw`"C:\x\fa\x1e\xited"`, ["STRING_LITERAL"]); + assertTokensTypes(String.raw`"jx\9"`, ["STRING_LITERAL"]); + assertTokensTypes(String.raw`"fo\9999999"`, ["STRING_LITERAL"]); + }); + + test("mess", () => { + assertTokensTypes(String.raw`[{}]()`, ["LBRACKET", "LBRACE", "RBRACE", "RBRACKET", "LPAREN", "RPAREN"]); + assertTokensTypes(String.raw`()||!C&~Z?J`, ["LPAREN", "RPAREN", "LOR", "LNOT", "ID", "AND", "NOT", "ID", "CONDOP", "ID"]); + assertTokensTypes(String.raw`+-*/%|||&&&^><>=<===!=`, ["PLUS", "MINUS", "TIMES", "DIVIDE", "MOD", + "LOR", "OR", "LAND", "AND", "XOR", "GT", "LT", "GE", "LE", "EQ", "NE"]); + assertTokensTypes(String.raw`++--->?.,;:`, ["PLUSPLUS", "MINUSMINUS", "ARROW", "CONDOP", "PERIOD", "COMMA", "SEMI", "COLON"]); + }); + + test("exprs", () => { + assertTokensTypes("bb-cc", ["ID", "MINUS", "ID"]); + assertTokensTypes("foo & 0xFF", ["ID", "AND", "INT_CONST_HEX"]); + assertTokensTypes("(2+k) * 62", ["LPAREN", "INT_CONST_DEC", "PLUS", "ID", "RPAREN", "TIMES", "INT_CONST_DEC"]); + assertTokensTypes("x | y >> z", ["ID", "OR", "ID", "RSHIFT", "ID"]); + assertTokensTypes("x <<= z << 5", ["ID", "LSHIFTEQUAL", "ID", "LSHIFT", "INT_CONST_DEC"]); + assertTokensTypes("x = y > 0 ? y : -6", ["ID", "EQUALS", "ID", "GT", "INT_CONST_OCT", "CONDOP", "ID", "COLON", "MINUS", "INT_CONST_DEC"]); + assertTokensTypes("a+++b", ["ID", "PLUSPLUS", "PLUS", "ID"]); + }); + + test("statements", () => { + assertTokensTypes("for (int i = 0; i < n; ++i)", ["FOR", "LPAREN", "INT", "ID", "EQUALS", "INT_CONST_OCT", "SEMI", + "ID", "LT", "ID", "SEMI", "PLUSPLUS", "ID", "RPAREN"]); + assertTokensTypes("self: goto self;", ["ID", "COLON", "GOTO", "ID", "SEMI"]); + assertTokensTypes(` switch (typ) + { + case TYPE_ID: + m = 5; + break; + default: + m = 8; + }`, ["SWITCH", "LPAREN", "ID", "RPAREN", "LBRACE", "CASE", "ID", "COLON", "ID", "EQUALS", "INT_CONST_DEC", "SEMI", + "BREAK", "SEMI", "DEFAULT", "COLON", "ID", "EQUALS", "INT_CONST_DEC", "SEMI", "RBRACE"]); + }); + + test("preprocessor line", () => { + assertTokensTypes("#abracadabra", ["PPHASH", "ID"]); + const str = String.raw` + 546 + #line 66 "kwas\df.h" + id 4 + dsf + # 9 + armo + #line 10 "..\~..\test.h" + tok1 + #line 99999 "include/me.h" + tok2 + `; + const clex = makeLexer(); + clex.input(str); + clex.reset_lineno(); + const t1 = clex.token(); + assert.equal(t1.type, "INT_CONST_DEC"); + assert.equal(t1.lineno, 2); + const t2 = clex.token(); + assert.equal(t2.type, "ID"); + assert.equal(t2.value, "id"); + assert.equal(t2.lineno, 66); + assert.equal(clex.filename, String.raw`kwas\df.h`); + let t; + for (let i = 0; i < 3; i++) t = clex.token(); + assert.equal(t.type, "ID"); + assert.equal(t.value, "armo"); + assert.equal(t.lineno, 9); + assert.equal(clex.filename, String.raw`kwas\df.h`); + const t4 = clex.token(); + assert.equal(t4.type, "ID"); + assert.equal(t4.value, "tok1"); + assert.equal(t4.lineno, 10); + assert.equal(clex.filename, String.raw`..\~..\test.h`); + const t5 = clex.token(); + assert.equal(t5.type, "ID"); + assert.equal(t5.value, "tok2"); + assert.equal(t5.lineno, 99999); + assert.equal(clex.filename, "include/me.h"); + }); + + test("preprocessor line funny", () => { + const str = String.raw` + #line 10 "..\6\joe.h" + 10 + `; + const clex = makeLexer(); + clex.input(str); + clex.reset_lineno(); + const t1 = clex.token(); + assert.equal(t1.type, "INT_CONST_DEC"); + assert.equal(t1.lineno, 10); + assert.equal(clex.filename, String.raw`..\6\joe.h`); + }); + + test("preprocessor pragma", () => { + const str = ` + 42 + #pragma + #pragma helo me + #pragma once + # pragma omp parallel private(th_id) + #\tpragma {pack: 2, smack: 3} + #pragma "nowit.h" + #pragma "string" + #pragma somestring="some_other_string" + #pragma id 124124 and numbers 0235495 + _Pragma("something else") + 59 + `; + const clex = makeLexer(); + clex.input(str); + clex.reset_lineno(); + assert.equal(clex.token().type, "INT_CONST_DEC"); + assert.equal(clex.token().type, "PPPRAGMA"); + assert.equal(clex.token().type, "PPPRAGMA"); + const t4 = clex.token(); + assert.equal(t4.type, "PPPRAGMASTR"); + assert.equal(t4.value, "helo me"); + for (let i = 0; i < 3; i++) clex.token(); + const t5 = clex.token(); + assert.equal(t5.type, "PPPRAGMASTR"); + assert.equal(t5.value, "omp parallel private(th_id)"); + for (let i = 0; i < 5; i++) { + assert.equal(clex.token().type, "PPPRAGMA"); + assert.equal(clex.token().type, "PPPRAGMASTR"); + } + const t6a = clex.token(), t6l = clex.token(), t6b = clex.token(), t6r = clex.token(); + assert.equal(t6a.type, "_PRAGMA"); + assert.equal(t6l.type, "LPAREN"); + assert.equal(t6b.type, "STRING_LITERAL"); + assert.equal(t6b.value, "\"something else\""); + assert.equal(t6r.type, "RPAREN"); + const t7 = clex.token(); + assert.equal(t7.type, "INT_CONST_DEC"); + assert.equal(t7.lineno, 13); + }); +}); + +const ERR_ILLEGAL_CHAR = "Illegal character"; +const ERR_OCTAL = "Invalid octal constant"; +const ERR_UNMATCHED_QUOTE = "Unmatched '"; +const ERR_INVALID_CCONST = "Invalid char constant"; +const ERR_STRING_ESCAPE = "String contains invalid escape"; +const ERR_FILENAME_BEFORE_LINE = "filename before line"; +const ERR_LINENUM_MISSING = "line number missing"; +const ERR_INVALID_LINE_DIRECTIVE = "invalid #line directive"; +const ERR_COMMENT = "Comments are not supported"; + +describe("TestCLexerErrors", () => { + const assertLexerError = (str, errorLike) => { + let error = ""; + const clex = new CLexer({ + error_func: (msg) => { error = msg; }, + on_lbrace_func: () => {}, + on_rbrace_func: () => {}, + type_lookup_func: () => false, + }); + clex.build(); + clex.input(str); + tokenTypes(clex); + assert.ok(new RegExp(errorLike).test(error), `\nExpected error matching: ${errorLike}\nGot: ${error}`); + }; + + test("trivial tokens", () => { + assertLexerError("@", ERR_ILLEGAL_CHAR); + assertLexerError("`", ERR_ILLEGAL_CHAR); + assertLexerError("\\", ERR_ILLEGAL_CHAR); + }); + + test("integer constants", () => { + assertLexerError("029", ERR_OCTAL); + assertLexerError("012345678", ERR_OCTAL); + }); + + test("char constants", () => { + assertLexerError("'", ERR_UNMATCHED_QUOTE); + assertLexerError("'b\n", ERR_UNMATCHED_QUOTE); + assertLexerError("'\\xaa\n'", ERR_UNMATCHED_QUOTE); + assertLexerError(String.raw`'123\12a'`, ERR_INVALID_CCONST); + assertLexerError(String.raw`'123\xabg'`, ERR_INVALID_CCONST); + assertLexerError("''", ERR_INVALID_CCONST); + assertLexerError("'abcjx'", ERR_INVALID_CCONST); + assertLexerError(String.raw`'\*'`, ERR_INVALID_CCONST); + }); + + test("string literals", () => { + assertLexerError("\"jx\\`\"", ERR_STRING_ESCAPE); + assertLexerError(String.raw`"hekllo\* on ix"`, ERR_STRING_ESCAPE); + assertLexerError(String.raw`L"hekllo\* on ix"`, ERR_STRING_ESCAPE); + const o = String.raw`\123`, x = String.raw`\xf1\x23`, bt = "\\`"; + assertLexerError("\"" + o.repeat(19) + bt + o.repeat(20) + "\"", ERR_STRING_ESCAPE); + assertLexerError("\"" + x.repeat(9) + String.raw`\x23` + bt + x.repeat(10) + "\"", ERR_STRING_ESCAPE); + assertLexerError("\"" + o.repeat(15) + bt + o.repeat(18) + String.raw`\12\123456`, ERR_ILLEGAL_CHAR); + const h = String.raw`\x23`; + assertLexerError("\"" + h.repeat(15) + bt + h.repeat(18) + String.raw`\x2\x23456`, ERR_ILLEGAL_CHAR); + }); + + test("preprocessor", () => { + assertLexerError("#line \"ka\"", ERR_FILENAME_BEFORE_LINE); + assertLexerError("#line df", ERR_INVALID_LINE_DIRECTIVE); + assertLexerError("#line \n", ERR_LINENUM_MISSING); + assertLexerError("//", ERR_COMMENT); + assertLexerError("/*", ERR_COMMENT); + }); +}); diff --git a/packages/romdev-pycparser/test/c_parser.test.js b/packages/romdev-pycparser/test/c_parser.test.js new file mode 100644 index 00000000..007c7ca3 --- /dev/null +++ b/packages/romdev-pycparser/test/c_parser.test.js @@ -0,0 +1,2580 @@ +// Port of pycparser tests/test_c_parser.py (m2c / decomp-permuter fork). +// Converted mechanically from the upstream file and fixed by hand; every +// test case and expected value is upstream's. Python tuples in expected +// values are arrays here (expand_init returns an array for a +// NamedInitializer where upstream returns a 2-tuple). +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, readFileSync } from "node:fs"; +import { CParser, ParseError, NodeVisitor, c_ast } from "../src/index.js"; + +const { + ArrayDecl, ArrayRef, Assignment, Alignas, BinaryOp, Case, Compound, Constant, Decl, Default, DoWhile, + EmptyStatement, Enum, Enumerator, EnumeratorList, FileAST, For, FuncCall, FuncDecl, FuncDef, ID, + IdentifierType, If, Label, NamedInitializer, PtrDecl, Return, StaticAssert, Struct, StructRef, Switch, + TypeDecl, Typedef, Typename, UnaryOp, Union, While, Pragma, +} = c_ast; +// Python type(x): the node class. +const type = (x) => x.constructor; + +const _c_parser = new CParser(); + +/** Converts the declaration into a nested list. */ +function expand_decl(decl) { + const typ = decl.constructor; + if (typ === TypeDecl) return ["TypeDecl", expand_decl(decl.type)]; + if (typ === IdentifierType) return ["IdentifierType", decl.names]; + if (typ === ID) return ["ID", decl.name]; + if (typ === Struct || typ === Union) { + const decls = (decl.decls || []).map((d) => expand_decl(d)); + return [typ.name, decl.name, decls]; + } + if (typ === Enum) { + let values; + if (decl.values == null) values = null; + else { + assert.ok(decl.values instanceof EnumeratorList); + values = decl.values.enumerators.map((e) => e.name); + } + return ["Enum", decl.name, values]; + } + if (typ === Alignas) return ["Alignas", expand_init(decl.alignment)]; + if (typ === StaticAssert) { + if (decl.message) return ["StaticAssert", decl.cond.value, decl.message.value]; + return ["StaticAssert", decl.cond.value]; + } + const nested = expand_decl(decl.type); + if (typ === Decl) { + const r = ["Decl"]; + if (decl.quals && decl.quals.length) r.push(decl.quals); + if (decl.align && decl.align.length) r.push(expand_decl(decl.align[0])); + r.push(decl.name, nested); + return r; + } + if (typ === Typename) { + if (decl.quals && decl.quals.length) return ["Typename", decl.quals, nested]; + return ["Typename", nested]; + } + if (typ === ArrayDecl) { + const dimval = decl.dim ? decl.dim.value : ""; + return ["ArrayDecl", dimval, decl.dim_quals, nested]; + } + if (typ === PtrDecl) { + if (decl.quals && decl.quals.length) return ["PtrDecl", decl.quals, nested]; + return ["PtrDecl", nested]; + } + if (typ === Typedef) return ["Typedef", decl.name, nested]; + if (typ === FuncDecl) { + const params = decl.args ? decl.args.params.map((p) => expand_decl(p)) : []; + return ["FuncDecl", params, nested]; + } + return undefined; +} + +/** Converts an initialization into a nested list. */ +function expand_init(init) { + const typ = init == null ? null : init.constructor; + if (typ === NamedInitializer) { + const des = init.name.map((dp) => expand_init(dp)); + return [des, expand_init(init.expr)]; + } + if (typ === c_ast.InitList || typ === c_ast.ExprList) return init.exprs.map((e) => expand_init(e)); + if (typ === Constant) return ["Constant", init.type, init.value]; + if (typ === ID) return ["ID", init.name]; + if (typ === Decl) return ["Decl", init.name]; + if (typ === UnaryOp) return ["UnaryOp", init.op, expand_decl(init.expr)]; + if (typ === BinaryOp) return ["BinaryOp", expand_init(init.left), init.op, expand_init(init.right)]; + if (typ === Compound) { + let blocks = []; + if (init.block_items) blocks = init.block_items.map((i) => expand_init(i)); + return ["Compound", blocks]; + } + if (typ === Typename) return expand_decl(init); + return [typ == null ? "NoneType" : typ.name]; +} + +class TestCParser_base { + constructor() { this.cparser = _c_parser; } + + parse(txt, filename = "") { return this.cparser.parse(txt, filename); } + + assert_coord(node, line, column = null, file = null) { + assert.equal(node.coord.line, line); + if (column != null) assert.equal(node.coord.column, column); + if (file) assert.equal(node.coord.file, file); + } + + assertEqual(a, b) { assert.deepStrictEqual(a, b); } + + assertIsInstance(a, cls) { assert.ok(a instanceof cls, `${a?.constructor?.name} is not ${cls.name}`); } + + assertTrue(x) { assert.ok(x); } + + assertRaises(err, fn, ...args) { assert.throws(() => fn.apply(this, args), err); } +} + + + +describe("TestCParser_fundamentals", () => { const self = new TestCParser_base(); + self.get_decl = (txt, index = 0) => { let t; + ` Given a source and an index returns the expanded + declaration at that index. + + FileAST holds a list of 'external declarations'. + index is the offset of the desired declaration in that + list. + ` + t = self.parse(txt).ext[index]; + return expand_decl(t); + + }; + self.get_decl_init = (txt, index = 0) => { let t; + ` Returns the expanded initializer of the declaration + at index. + ` + t = self.parse(txt).ext[index]; + return expand_init(t.init); + + }; + test("FileAST", () => { let t, t2; + t = self.parse("int a; char c;"); + self.assertIsInstance(t, FileAST); + self.assertEqual(t.ext.length, 2); + + // empty file + t2 = self.parse(""); + self.assertIsInstance(t2, FileAST); + self.assertEqual(t2.ext.length, 0); + + }); + test("empty_toplevel_decl", () => { let code, t; + code = "int foo;;"; + t = self.parse(code); + self.assertIsInstance(t, FileAST); + self.assertEqual(t.ext.length, 1); + self.assertEqual(self.get_decl(code), + ["Decl", "foo", + ["TypeDecl", ["IdentifierType", ["int"]]]]); + + }); + test("initial_semi", () => { let t; + t = self.parse(";"); + self.assertEqual(t.ext.length, 0); + t = self.parse(";int foo;"); + self.assertEqual(t.ext.length, 1); + self.assertEqual(expand_decl(t.ext[0]), + ["Decl", "foo", + ["TypeDecl", ["IdentifierType", ["int"]]]]); + + }); + test("coords", () => { let t1, f1, t1_1, f1_1, t1_2, f1_2, t2, t3, f3, t4, f4, t5, t6; + ` Tests the "coordinates" of parsed elements - file + name, line and column numbers, with modification + inserted by #line directives. + ` + self.assert_coord(self.parse("int a;").ext[0], 1, 5); + + t1 = ` + int a; + int b;\n\n + int c; + `; + f1 = self.parse(t1, "test.c"); + self.assert_coord(f1.ext[0], 2, 13, "test.c"); + self.assert_coord(f1.ext[1], 3, 13, "test.c"); + self.assert_coord(f1.ext[2], 6, 13, "test.c"); + + t1_1 = ` + int main() { + k = p; + printf("%d", b); + return 0; + }`; + f1_1 = self.parse(t1_1, "test.c"); + self.assert_coord(f1_1.ext[0].body.block_items[0], 3, 13, "test.c"); + self.assert_coord(f1_1.ext[0].body.block_items[1], 4, 13, "test.c"); + + t1_2 = ` + int main () { + int p = (int) k; + }`; + f1_2 = self.parse(t1_2, "test.c"); + // make sure that the Cast has a coord (issue 23) + self.assert_coord(f1_2.ext[0].body.block_items[0].init, 3, 21, "test.c"); + + t2 = ` + #line 99 + int c; + `; + self.assert_coord(self.parse(t2).ext[0], 99, 13); + + t3 = ` + int dsf; + char p; + #line 3000 "in.h" + char d; + `; + f3 = self.parse(t3, "test.c"); + self.assert_coord(f3.ext[0], 2, 13, "test.c"); + self.assert_coord(f3.ext[1], 3, 14, "test.c"); + self.assert_coord(f3.ext[2], 3000, 14, "in.h"); + + t4 = ` + #line 20 "restore.h" + int maydler(char); + + #line 30 "includes/daween.ph" + long j, k; + + #line 50000 + char* ro; + `; + f4 = self.parse(t4, "myb.c"); + self.assert_coord(f4.ext[0], 20, 13, "restore.h"); + self.assert_coord(f4.ext[1], 30, 14, "includes/daween.ph"); + self.assert_coord(f4.ext[2], 30, 17, "includes/daween.ph"); + self.assert_coord(f4.ext[3], 50000, 13, "includes/daween.ph"); + + t5 = ` + int + #line 99 + c; + `; + self.assert_coord(self.parse(t5).ext[0], 99, 9); + + // coord for ellipsis + t6 = ` + int foo(int j, + ...) { + }`; + self.parse(t6, "z.c"); + self.assert_coord(self.parse(t6).ext[0].decl.type.args.params[1], 3, 17); + + }); + test("forloop_coord", () => { let t, s, forloop; + t = `\ + void foo() { + for(int z=0; z<4; + z++){} + } + `; + s = self.parse(t, "f.c"); + forloop = s.ext[0].body.block_items[0]; + self.assert_coord(forloop.init, 2, 13, "f.c"); + self.assert_coord(forloop.cond, 2, 26, "f.c"); + self.assert_coord(forloop.next, 3, 17, "f.c"); + + }); + test("simple_decls", () => { + self.assertEqual(self.get_decl("int a;"), + ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]); + + self.assertEqual(self.get_decl("unsigned int a;"), + ["Decl", "a", ["TypeDecl", ["IdentifierType", ["unsigned", "int"]]]]); + + self.assertEqual(self.get_decl("_Bool a;"), + ["Decl", "a", ["TypeDecl", ["IdentifierType", ["_Bool"]]]]); + + self.assertEqual(self.get_decl("float _Complex fcc;"), + ["Decl", "fcc", ["TypeDecl", ["IdentifierType", ["float", "_Complex"]]]]); + + self.assertEqual(self.get_decl("char* string;"), + ["Decl", "string", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]]); + + self.assertEqual(self.get_decl("long ar[15];"), + ["Decl", "ar", + ["ArrayDecl", "15", [], + ["TypeDecl", ["IdentifierType", ["long"]]]]]); + + self.assertEqual(self.get_decl("long long ar[15];"), + ["Decl", "ar", + ["ArrayDecl", "15", [], + ["TypeDecl", ["IdentifierType", ["long", "long"]]]]]); + + self.assertEqual(self.get_decl("unsigned ar[];"), + ["Decl", "ar", + ["ArrayDecl", "", [], + ["TypeDecl", ["IdentifierType", ["unsigned"]]]]]); + + self.assertEqual(self.get_decl("int strlen(char* s);"), + ["Decl", "strlen", + ["FuncDecl", + [["Decl", "s", + ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["char"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(self.get_decl("int strcmp(char* s1, char* s2);"), + ["Decl", "strcmp", + ["FuncDecl", + [ ["Decl", "s1", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]], + ["Decl", "s2", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]] + ], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + // function return values and parameters may not have type information + self.assertEqual(self.get_decl("extern foobar(foo, bar);"), + ["Decl", "foobar", + ["FuncDecl", + [ ["ID", "foo"], + ["ID", "bar"] + ], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + }); + test("int128", () => { + self.assertEqual(self.get_decl("__int128 a;"), + ["Decl", "a", ["TypeDecl", ["IdentifierType", ["__int128"]]]]); + + + }); + test("nested_decls", () => { + self.assertEqual(self.get_decl("char** ar2D;"), + ["Decl", "ar2D", + ["PtrDecl", ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["char"]]]]]]); + + self.assertEqual(self.get_decl("int (*a)[1][2];"), + ["Decl", "a", + ["PtrDecl", + ["ArrayDecl", "1", [], + ["ArrayDecl", "2", [], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]); + + self.assertEqual(self.get_decl("int *a[1][2];"), + ["Decl", "a", + ["ArrayDecl", "1", [], + ["ArrayDecl", "2", [], + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]]]]]); + + self.assertEqual(self.get_decl("char* const* p;"), + ["Decl", "p", + ["PtrDecl", ["PtrDecl", ["const"], + ["TypeDecl", ["IdentifierType", ["char"]]]]]]); + + self.assertEqual(self.get_decl("const char* const* p;"), + ["Decl", ["const"], "p", + ["PtrDecl", ["PtrDecl", ["const"], + ["TypeDecl", ["IdentifierType", ["char"]]]]]]); + + self.assertEqual(self.get_decl("char* * const p;"), + ["Decl", "p", + ["PtrDecl", ["const"], ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["char"]]]]]]); + + self.assertEqual(self.get_decl("char ***ar3D[40];"), + ["Decl", "ar3D", + ["ArrayDecl", "40", [], + ["PtrDecl", ["PtrDecl", ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["char"]]]]]]]]); + + self.assertEqual(self.get_decl("char (***ar3D)[40];"), + ["Decl", "ar3D", + ["PtrDecl", ["PtrDecl", ["PtrDecl", + ["ArrayDecl", "40", [], ["TypeDecl", ["IdentifierType", ["char"]]]]]]]]); + + self.assertEqual(self.get_decl("int (*const*const x)(char, int);"), + ["Decl", + "x", + ["PtrDecl", + ["const"], + ["PtrDecl", + ["const"], + ["FuncDecl", + [["Typename", ["TypeDecl", ["IdentifierType", ["char"]]]], + ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]); + + self.assertEqual(self.get_decl("int (*x[4])(char, int);"), + ["Decl", "x", + ["ArrayDecl", "4", [], + ["PtrDecl", + ["FuncDecl", + [ ["Typename", ["TypeDecl", ["IdentifierType", ["char"]]]], + ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]); + + self.assertEqual(self.get_decl("char *(*(**foo [][8])())[];"), + ["Decl", "foo", + ["ArrayDecl", "", [], + ["ArrayDecl", "8", [], + ["PtrDecl", ["PtrDecl", + ["FuncDecl", + [], + ["PtrDecl", + ["ArrayDecl", "", [], + ["PtrDecl", + ["TypeDecl", + ["IdentifierType", ["char"]]]]]]]]]]]]); + + // explore named and unnamed function pointer parameters, + // with and without qualifiers + + // unnamed w/o quals + self.assertEqual(self.get_decl("int (*k)(int);"), + ["Decl", "k", + ["PtrDecl", + ["FuncDecl", + [["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + + // unnamed w/ quals + self.assertEqual(self.get_decl("int (*k)(const int);"), + ["Decl", "k", + ["PtrDecl", + ["FuncDecl", + [["Typename", ["const"], ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + + // named w/o quals + self.assertEqual(self.get_decl("int (*k)(int q);"), + ["Decl", "k", + ["PtrDecl", + ["FuncDecl", + [["Decl", "q", ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + + // named w/ quals + self.assertEqual(self.get_decl("int (*k)(const volatile int q);"), + ["Decl", "k", + ["PtrDecl", + ["FuncDecl", + [["Decl", ["const", "volatile"], "q", + ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + + self.assertEqual(self.get_decl("int (*k)(_Atomic volatile int q);"), + ["Decl", "k", + ["PtrDecl", + ["FuncDecl", + [["Decl", ["_Atomic", "volatile"], "q", + ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + + self.assertEqual(self.get_decl("int (*k)(const volatile int* q);"), + ["Decl", "k", + ["PtrDecl", + ["FuncDecl", + [["Decl", ["const", "volatile"], "q", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + + // restrict qualifier + self.assertEqual(self.get_decl("int (*k)(restrict int* q);"), + ["Decl", "k", + ["PtrDecl", + ["FuncDecl", + [["Decl", ["restrict"], "q", + ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["int"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + + }); + test("func_decls_with_array_dim_qualifiers", () => { + // named function parameter + self.assertEqual(self.get_decl("int zz(int p[static 10]);"), + ["Decl", "zz", + ["FuncDecl", + [["Decl", "p", ["ArrayDecl", "10", ["static"], + ["TypeDecl", ["IdentifierType", ["int"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + // anonymous function parameter + self.assertEqual(self.get_decl("int zz(int [static 10]);"), + ["Decl", "zz", + ["FuncDecl", + [["Typename", + ["ArrayDecl", "10", ["static"], + ["TypeDecl", ["IdentifierType", ["int"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + self.assertEqual(self.get_decl("int zz(int [static const restrict 10]);"), + ["Decl", "zz", + ["FuncDecl", + [["Typename", + ["ArrayDecl", "10", ["static", "const", "restrict"], + ["TypeDecl", ["IdentifierType", ["int"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(self.get_decl("int zz(int p[const 10]);"), + ["Decl", "zz", + ["FuncDecl", + [["Decl", "p", ["ArrayDecl", "10", ["const"], + ["TypeDecl", ["IdentifierType", ["int"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(self.get_decl("int zz(int p[restrict][5]);"), + ["Decl", "zz", + ["FuncDecl", + [["Decl", "p", ["ArrayDecl", "", ["restrict"], + ["ArrayDecl", "5", [], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(self.get_decl("int zz(int p[const restrict static 10][5]);"), + ["Decl", "zz", + ["FuncDecl", + [["Decl", "p", ["ArrayDecl", "10", ["const", "restrict", "static"], + ["ArrayDecl", "5", [], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + // unnamed function parameter + self.assertEqual(self.get_decl("int zz(int [const 10]);"), + ["Decl", "zz", + ["FuncDecl", + [["Typename", ["ArrayDecl", "10", ["const"], + ["TypeDecl", ["IdentifierType", ["int"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(self.get_decl("int zz(int [restrict][5]);"), + ["Decl", "zz", + ["FuncDecl", + [["Typename", ["ArrayDecl", "", ["restrict"], + ["ArrayDecl", "5", [], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(self.get_decl("int zz(int [const restrict volatile 10][5]);"), + ["Decl", "zz", + ["FuncDecl", + [["Typename", ["ArrayDecl", "10", ["const", "restrict", "volatile"], + ["ArrayDecl", "5", [], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + }); + test("qualifiers_storage_specifiers", () => { let d1, d2, pdecl; + const assert_qs = (txt, index, quals, storage) => { let d; + d = self.parse(txt).ext[index]; + self.assertEqual(d.quals, quals); + self.assertEqual(d.storage, storage); + + }; + assert_qs("extern int p;", 0, [], ["extern"]); + assert_qs("_Thread_local int p;", 0, [], ["_Thread_local"]); + assert_qs("const long p = 6;", 0, ["const"], []); + assert_qs("_Atomic int p;", 0, ["_Atomic"], []); + assert_qs("_Atomic restrict int* p;", 0, ["_Atomic", "restrict"], []); + + d1 = "static const int p, q, r;"; + for (let i = 0; i < 3; i++) { + assert_qs(d1, i, ["const"], ["static"]); + + } + d2 = "static char * const p;"; + assert_qs(d2, 0, [], ["static"]); + pdecl = self.parse(d2).ext[0].type; + self.assertIsInstance(pdecl, PtrDecl); + self.assertEqual(pdecl.quals, ["const"]); + + }); + test("atomic_specifier", () => { let s; + self.assertEqual(self.get_decl("_Atomic(int) ai;"), + ["Decl", ["_Atomic"], + "ai", + ["TypeDecl", ["IdentifierType", ["int"]]]]); + + self.assertEqual(self.get_decl("_Atomic(int*) ai;"), + ["Decl", + "ai", + ["PtrDecl", ["_Atomic"], ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(self.get_decl("_Atomic(_Atomic(int)*) aai;"), + ["Decl", ["_Atomic"], + "aai", + ["PtrDecl", ["_Atomic"], ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + // Multiple declarations with _Atomic(...) + s = "_Atomic(int) foo, bar;"; + self.assertEqual(self.get_decl(s, 0), + ["Decl", ["_Atomic"], + "foo", + ["TypeDecl", ["IdentifierType", ["int"]]]]); + self.assertEqual(self.get_decl(s, 1), + ["Decl", ["_Atomic"], + "bar", + ["TypeDecl", ["IdentifierType", ["int"]]]]); + + // typedefs with _Atomic specifiers. + s = "typedef _Atomic(int) atomic_int;"; + self.assertEqual(self.get_decl(s, 0), + ["Typedef", "atomic_int", ["TypeDecl", ["IdentifierType", ["int"]]]]); + + s = "typedef _Atomic(_Atomic(_Atomic(int (*)(void)) *) *) t;"; + self.assertEqual(self.get_decl(s, 0), + ["Typedef", "t", + ["PtrDecl", ["_Atomic"], + ["PtrDecl", ["_Atomic"], + ["PtrDecl", ["_Atomic"], + ["FuncDecl", [["Typename", ["TypeDecl", ["IdentifierType", ["void"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]]); + + }); + test("sizeof", () => { let e, compound, s1, s2, s3; + e = ` + void foo() + { + int a = sizeof k; + int b = sizeof(int); + int c = sizeof(int**);; + + char* p = "just to make sure this parses w/o error..."; + int d = sizeof(int()); + } + `; + compound = self.parse(e).ext[0].body; + + s1 = compound.block_items[0].init; + self.assertIsInstance(s1, UnaryOp); + self.assertEqual(s1.op, "sizeof"); + self.assertIsInstance(s1.expr, ID); + self.assertEqual(s1.expr.name, "k"); + + s2 = compound.block_items[1].init; + self.assertEqual(expand_decl(s2.expr), + ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]); + + s3 = compound.block_items[2].init; + self.assertEqual(expand_decl(s3.expr), + ["Typename", + ["PtrDecl", + ["PtrDecl", + ["TypeDecl", + ["IdentifierType", ["int"]]]]]]); + + }); + test("alignof", () => { let r; + r = self.parse("int a = _Alignof(int);"); + self.assertEqual(expand_decl(r.ext[0]), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]); + self.assertEqual(expand_init(r.ext[0].init), ["UnaryOp", "_Alignof", + ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(expand_decl(self.parse("_Alignas(_Alignof(int)) char a;").ext[0]), + ["Decl", ["Alignas", + ["UnaryOp", "_Alignof", ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]]], + "a", ["TypeDecl", ["IdentifierType", ["char"]]]]); + + self.assertEqual(expand_decl(self.parse("_Alignas(4) char a;").ext[0]), + ["Decl", ["Alignas", + ["Constant", "int", "4"]], + "a", ["TypeDecl", ["IdentifierType", ["char"]]]]); + + self.assertEqual(expand_decl(self.parse("_Alignas(int) char a;").ext[0]), + ["Decl", ["Alignas", + ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]], + "a", ["TypeDecl", ["IdentifierType", ["char"]]]]); + + }); + test("offsetof", () => { let e, compound, s1, s3, s4; + const expand_ref = (n) => { + if ((n instanceof StructRef)) { + return ["StructRef", expand_ref(n.name), expand_ref(n.field)]; + } + else if ((n instanceof ArrayRef)) { + return ["ArrayRef", expand_ref(n.name), expand_ref(n.subscript)]; + } + else if ((n instanceof ID)) { + return ["ID", n.name]; + } + else if ((n instanceof Constant)) { + return ["Constant", n.type, n.value]; + } + else { + throw new Error("Unexpected type " + n.constructor.name); + + } + }; + e = ` + void foo() { + int a = offsetof(struct S, p); + a.b = offsetof(struct sockaddr, sp) + strlen(bar); + int a = offsetof(struct S, p.q.r); + int a = offsetof(struct S, p[5].q[4][5]); + } + `; + compound = self.parse(e).ext[0].body; + s1 = compound.block_items[0].init; + self.assertIsInstance(s1, FuncCall); + self.assertIsInstance(s1.name, ID); + self.assertEqual(s1.name.name, "offsetof"); + self.assertIsInstance(s1.args.exprs[0], Typename); + self.assertIsInstance(s1.args.exprs[1], ID); + s3 = compound.block_items[2].init; + self.assertIsInstance(s3.args.exprs[1], StructRef); + self.assertEqual(expand_ref(s3.args.exprs[1]), + ["StructRef", + ["StructRef", ["ID", "p"], ["ID", "q"]], + ["ID", "r"]]); + s4 = compound.block_items[3].init; + self.assertIsInstance(s4.args.exprs[1], ArrayRef); + self.assertEqual(expand_ref(s4.args.exprs[1]), + ["ArrayRef", + ["ArrayRef", + ["StructRef", + ["ArrayRef", ["ID", "p"], ["Constant", "int", "5"]], + ["ID", "q"]], + ["Constant", "int", "4"]], + ["Constant", "int", "5"]]); + + }); + test("compound_statement", () => { let e, compound; + e = ` + void foo() { + } + `; + compound = self.parse(e).ext[0].body; + self.assertIsInstance(compound, Compound); + self.assert_coord(compound, 2); + + // The C99 compound literal feature + // + }); + test("compound_literals", () => { let ps1, compound; + ps1 = self.parse(String.raw` + void foo() { + p = (long long){k}; + tc = (struct jk){.a = {1, 2}, .b[0] = t}; + }`); + + compound = ps1.ext[0].body.block_items[0].rvalue; + self.assertEqual(expand_decl(compound.type), + ["Typename", ["TypeDecl", ["IdentifierType", ["long", "long"]]]]); + self.assertEqual(expand_init(compound.init), + [["ID", "k"]]); + + compound = ps1.ext[0].body.block_items[1].rvalue; + self.assertEqual(expand_decl(compound.type), + ["Typename", ["TypeDecl", ["Struct", "jk", []]]]); + self.assertEqual(expand_init(compound.init), + [ + [[["ID", "a"]], [["Constant", "int", "1"], ["Constant", "int", "2"]]], + [[["ID", "b"], ["Constant", "int", "0"]], ["ID", "t"]]]); + + }); + test("parenthesized_compounds", () => { let e, body; + e = self.parse(String.raw` + void foo() { + int a; + ({}); + ({ 1; }); + ({ 1; 2; }); + int b = ({ 1; }); + int c, d = ({ int x = 1; x + 2; }); + a = ({ int x = 1; 2 * x; }); + }`); + body = e.ext[0].body.block_items; + + self.assertIsInstance(body[1], Compound); + self.assertEqual(body[1].block_items, null); + + self.assertIsInstance(body[2], Compound); + self.assertEqual(body[2].block_items.length, 1); + self.assertIsInstance(body[2].block_items[0], Constant); + + self.assertIsInstance(body[3], Compound); + self.assertEqual(body[3].block_items.length, 2); + self.assertIsInstance(body[3].block_items[0], Constant); + self.assertIsInstance(body[3].block_items[1], Constant); + + self.assertIsInstance(body[4], Decl); + self.assertEqual(expand_init(body[4].init), + ["Compound", [["Constant", "int", "1"]]]); + + self.assertIsInstance(body[5], Decl); + self.assertEqual(body[5].init, null); + + self.assertIsInstance(body[6], Decl); + self.assertEqual(expand_init(body[6].init), + ["Compound", [["Decl", "x"], ["BinaryOp", ["ID", "x"], "+", ["Constant", "int", "2"]]]]); + + self.assertIsInstance(body[7], Assignment); + self.assertIsInstance(body[7].rvalue, Compound); + self.assertEqual(expand_init(body[7].rvalue), + ["Compound", [["Decl", "x"], ["BinaryOp", ["Constant", "int", "2"], "*", ["ID", "x"]]]]); + + }); + test("enums", () => { let e1, e1_type, e2, e2_type, e2_elist, e3, e3_type, e3_elist; + e1 = "enum mycolor op;"; + e1_type = self.parse(e1).ext[0].type.type; + + self.assertIsInstance(e1_type, Enum); + self.assertEqual(e1_type.name, "mycolor"); + self.assertEqual(e1_type.values, null); + + e2 = "enum mysize {large=20, small, medium} shoes;"; + e2_type = self.parse(e2).ext[0].type.type; + + self.assertIsInstance(e2_type, Enum); + self.assertEqual(e2_type.name, "mysize"); + + e2_elist = e2_type.values; + self.assertIsInstance(e2_elist, EnumeratorList); + + for (const e2_eval of e2_elist.enumerators) { + self.assertIsInstance(e2_eval, Enumerator); + + } + self.assertEqual(e2_elist.enumerators[0].name, "large"); + self.assertEqual(e2_elist.enumerators[0].value.value, "20"); + self.assertEqual(e2_elist.enumerators[2].name, "medium"); + self.assertEqual(e2_elist.enumerators[2].value, null); + + // enum with trailing comma (C99 feature) + e3 = ` + enum + { + red, + blue, + green, + } color; + `; + + e3_type = self.parse(e3).ext[0].type.type; + self.assertIsInstance(e3_type, Enum); + e3_elist = e3_type.values; + self.assertIsInstance(e3_elist, EnumeratorList); + + for (const e3_eval of e3_elist.enumerators) { + self.assertIsInstance(e3_eval, Enumerator); + + } + self.assertEqual(e3_elist.enumerators[0].name, "red"); + self.assertEqual(e3_elist.enumerators[0].value, null); + self.assertEqual(e3_elist.enumerators[1].name, "blue"); + self.assertEqual(e3_elist.enumerators[2].name, "green"); + + }); + test("typedef", () => { let s1, s2, ps2, s3, ps3, s4, ps4, s5, ps5, s6, ps6; + // without typedef, error + s1 = ` + node k; + `; + self.assertRaises(ParseError, self.parse, s1); + + // now with typedef, works + s2 = ` + typedef void* node; + node k; + `; + ps2 = self.parse(s2); + self.assertEqual(expand_decl(ps2.ext[0]), + ["Typedef", "node", + ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["void"]]]]]); + + self.assertEqual(expand_decl(ps2.ext[1]), + ["Decl", "k", + ["TypeDecl", ["IdentifierType", ["node"]]]]); + + s3 = ` + typedef int T; + typedef T *pT; + + pT aa, bb; + `; + ps3 = self.parse(s3); + self.assertEqual(expand_decl(ps3.ext[3]), + ["Decl", "bb", + ["TypeDecl", ["IdentifierType", ["pT"]]]]); + + s4 = ` + typedef char* __builtin_va_list; + typedef __builtin_va_list __gnuc_va_list; + `; + ps4 = self.parse(s4); + self.assertEqual(expand_decl(ps4.ext[1]), + ["Typedef", "__gnuc_va_list", + ["TypeDecl", + ["IdentifierType", ["__builtin_va_list"]]]]); + + s5 = `typedef struct tagHash Hash;`; + ps5 = self.parse(s5); + self.assertEqual(expand_decl(ps5.ext[0]), + ["Typedef", "Hash", ["TypeDecl", ["Struct", "tagHash", []]]]); + + s6 = `typedef int (* const * const T)(void);`; + ps6 = self.parse(s6); + self.assertEqual(expand_decl(ps6.ext[0]), + ["Typedef", + "T", + ["PtrDecl", + ["const"], + ["PtrDecl", + ["const"], + ["FuncDecl", + [["Typename", ["TypeDecl", ["IdentifierType", ["void"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]); + + }); + test("struct_union", () => { let s1, s2, s21, s3, s4, s5, s6, s6_ast, s7, s7_ast, s8, s8_ast; + s1 = ` + struct { + int id; + char* name; + } joe; + `; + + self.assertEqual(expand_decl(self.parse(s1).ext[0]), + ["Decl", "joe", + ["TypeDecl", ["Struct", null, + [ ["Decl", "id", + ["TypeDecl", + ["IdentifierType", ["int"]]]], + ["Decl", "name", + ["PtrDecl", + ["TypeDecl", + ["IdentifierType", ["char"]]]]]]]]]); + + s2 = ` + struct node p; + `; + self.assertEqual(expand_decl(self.parse(s2).ext[0]), + ["Decl", "p", + ["TypeDecl", ["Struct", "node", []]]]); + + s21 = ` + union pri ra; + `; + self.assertEqual(expand_decl(self.parse(s21).ext[0]), + ["Decl", "ra", + ["TypeDecl", ["Union", "pri", []]]]); + + s3 = ` + struct node* p; + `; + self.assertEqual(expand_decl(self.parse(s3).ext[0]), + ["Decl", "p", + ["PtrDecl", + ["TypeDecl", ["Struct", "node", []]]]]); + + s4 = ` + struct node; + `; + self.assertEqual(expand_decl(self.parse(s4).ext[0]), + ["Decl", null, + ["Struct", "node", []]]); + + s5 = ` + union + { + struct + { + int type; + } n; + + struct + { + int type; + int intnode; + } ni; + } u; + `; + self.assertEqual(expand_decl(self.parse(s5).ext[0]), + ["Decl", "u", + ["TypeDecl", + ["Union", null, + [["Decl", "n", + ["TypeDecl", + ["Struct", null, + [["Decl", "type", + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]], + ["Decl", "ni", + ["TypeDecl", + ["Struct", null, + [["Decl", "type", + ["TypeDecl", ["IdentifierType", ["int"]]]], + ["Decl", "intnode", + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]]]]]]); + + s6 = ` + typedef struct foo_tag + { + void* data; + } foo, *pfoo; + `; + s6_ast = self.parse(s6); + + self.assertEqual(expand_decl(s6_ast.ext[0]), + ["Typedef", "foo", + ["TypeDecl", + ["Struct", "foo_tag", + [["Decl", "data", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["void"]]]]]]]]]); + + self.assertEqual(expand_decl(s6_ast.ext[1]), + ["Typedef", "pfoo", + ["PtrDecl", + ["TypeDecl", + ["Struct", "foo_tag", + [["Decl", "data", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["void"]]]]]]]]]]); + + s7 = String.raw` + struct _on_exit_args { + void * _fnargs[32]; + void * _dso_handle[32]; + + long _fntypes; + #line 77 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + long _is_cxa; + }; + `; + + s7_ast = self.parse(s7, "test.c"); + self.assert_coord(s7_ast.ext[0].type.decls[2], 6, 22, "test.c"); + self.assert_coord(s7_ast.ext[0].type.decls[3], 78, 22, + String.raw`D:\eli\cpp_stuff\libc_include/sys/reent.h`); + + s8 = ` + typedef enum tagReturnCode {SUCCESS, FAIL} ReturnCode; + + typedef struct tagEntry + { + char* key; + char* value; + } Entry; + + + typedef struct tagNode + { + Entry* entry; + + struct tagNode* next; + } Node; + + typedef struct tagHash + { + unsigned int table_size; + + Node** heads; + + } Hash; + `; + s8_ast = self.parse(s8); + self.assertEqual(expand_decl(s8_ast.ext[3]), + ["Typedef", "Hash", + ["TypeDecl", ["Struct", "tagHash", + [["Decl", "table_size", + ["TypeDecl", ["IdentifierType", ["unsigned", "int"]]]], + ["Decl", "heads", + ["PtrDecl", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["Node"]]]]]]]]]]); + + }); + test("struct_enum", () => { let s1, s2; + s1 = ` + struct Foo { + enum Bar { A = 1 }; + }; + `; + self.assertEqual(expand_decl(self.parse(s1).ext[0]), + ["Decl", null, + ["Struct", "Foo", + [["Decl", null, + ["Enum", "Bar", ["A"]]]]]]); + s2 = ` + struct Foo { + enum Bar { A = 1, B, C } bar; + enum Baz { D = A } baz; + } foo; + `; + self.assertEqual(expand_decl(self.parse(s2).ext[0]), + ["Decl", "foo", + ["TypeDecl", ["Struct", "Foo", + [["Decl", "bar", + ["TypeDecl", ["Enum", "Bar", ["A", "B", "C"]]]], + ["Decl", "baz", + ["TypeDecl", ["Enum", "Baz", ["D"]]]]]]]]); + + }); + test("struct_with_extra_semis_inside", () => { let s1, s1_ast, s2, s2_ast; + s1 = ` + struct { + int a;; + } foo; + `; + s1_ast = self.parse(s1); + self.assertEqual(expand_decl(s1_ast.ext[0]), + ["Decl", "foo", + ["TypeDecl", ["Struct", null, + [["Decl", "a", + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]]); + + s2 = ` + struct { + int a;;;; + float b, c; + ;; + char d; + } foo; + `; + s2_ast = self.parse(s2); + self.assertEqual(expand_decl(s2_ast.ext[0]), + ["Decl", "foo", + ["TypeDecl", ["Struct", null, + [["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]], + ["Decl", "b", ["TypeDecl", ["IdentifierType", ["float"]]]], + ["Decl", "c", ["TypeDecl", ["IdentifierType", ["float"]]]], + ["Decl", "d", + ["TypeDecl", ["IdentifierType", ["char"]]]]]]]]); + + }); + test("struct_with_initial_semi", () => { let s1, s1_ast; + s1 = ` + struct { + ;int a; + } foo; + `; + s1_ast = self.parse(s1); + self.assertEqual(expand_decl(s1_ast.ext[0]), + ["Decl", "foo", + ["TypeDecl", ["Struct", null, + [["Decl", "a", + ["TypeDecl", ["IdentifierType", ["int"]]]]]]]]); + + }); + test("anonymous_struct_union", () => { let s1, s2, s3, s4; + s1 = ` + union + { + union + { + int i; + long l; + }; + + struct + { + int type; + int intnode; + }; + } u; + `; + + self.assertEqual(expand_decl(self.parse(s1).ext[0]), + ["Decl", "u", + ["TypeDecl", + ["Union", null, + [["Decl", null, + ["Union", null, + [["Decl", "i", + ["TypeDecl", + ["IdentifierType", ["int"]]]], + ["Decl", "l", + ["TypeDecl", + ["IdentifierType", ["long"]]]]]]], + ["Decl", null, + ["Struct", null, + [["Decl", "type", + ["TypeDecl", + ["IdentifierType", ["int"]]]], + ["Decl", "intnode", + ["TypeDecl", + ["IdentifierType", ["int"]]]]]]]]]]]); + + s2 = ` + struct + { + int i; + union + { + int id; + char* name; + }; + float f; + } joe; + `; + + self.assertEqual(expand_decl(self.parse(s2).ext[0]), + ["Decl", "joe", + ["TypeDecl", + ["Struct", null, + [["Decl", "i", + ["TypeDecl", + ["IdentifierType", ["int"]]]], + ["Decl", null, + ["Union", null, + [["Decl", "id", + ["TypeDecl", + ["IdentifierType", ["int"]]]], + ["Decl", "name", + ["PtrDecl", + ["TypeDecl", + ["IdentifierType", ["char"]]]]]]]], + ["Decl", "f", + ["TypeDecl", + ["IdentifierType", ["float"]]]]]]]]); + + // ISO/IEC 9899:201x Committee Draft 2010-11-16, N1539 + // section 6.7.2.1, par. 19, example 1 + s3 = ` + struct v { + union { + struct { int i, j; }; + struct { long k, l; } w; + }; + int m; + } v1; + `; + + self.assertEqual(expand_decl(self.parse(s3).ext[0]), + ["Decl", "v1", + ["TypeDecl", + ["Struct", "v", + [["Decl", null, + ["Union", null, + [["Decl", null, + ["Struct", null, + [["Decl", "i", + ["TypeDecl", + ["IdentifierType", ["int"]]]], + ["Decl", "j", + ["TypeDecl", + ["IdentifierType", ["int"]]]]]]], + ["Decl", "w", + ["TypeDecl", + ["Struct", null, + [["Decl", "k", + ["TypeDecl", + ["IdentifierType", ["long"]]]], + ["Decl", "l", + ["TypeDecl", + ["IdentifierType", ["long"]]]]]]]]]]], + ["Decl", "m", + ["TypeDecl", + ["IdentifierType", ["int"]]]]]]]]); + + s4 = ` + struct v { + int i; + float; + } v2;`; + // just make sure this doesn't raise ParseError + self.parse(s4); + + }); + test("struct_members_namespace", () => { let s1, s1_ast; + ` Tests that structure/union member names reside in a separate + namespace and can be named after existing types. + ` + s1 = ` + typedef int Name; + typedef Name NameArray[10]; + + struct { + Name Name; + Name NameArray[3]; + } sye; + + void main(void) + { + sye.Name = 1; + } + `; + + s1_ast = self.parse(s1); + self.assertEqual(expand_decl(s1_ast.ext[2]), + ["Decl", "sye", + ["TypeDecl", ["Struct", null, + [ ["Decl", "Name", + ["TypeDecl", + ["IdentifierType", ["Name"]]]], + ["Decl", "NameArray", + ["ArrayDecl", "3", [], + ["TypeDecl", ["IdentifierType", ["Name"]]]]]]]]]); + self.assertEqual(s1_ast.ext[3].body.block_items[0].lvalue.field.name, "Name"); + + }); + test("struct_bitfields", () => { let s1, parsed_struct; + // a struct with two bitfields, one unnamed + s1 = ` + struct { + int k:6; + int :2; + } joe; + `; + + parsed_struct = self.parse(s1).ext[0]; + + // We can see here the name of the decl for the unnamed bitfield is + // None, but expand_decl doesn't show bitfield widths + // ... + self.assertEqual(expand_decl(parsed_struct), + ["Decl", "joe", + ["TypeDecl", ["Struct", null, + [ ["Decl", "k", + ["TypeDecl", + ["IdentifierType", ["int"]]]], + ["Decl", null, + ["TypeDecl", + ["IdentifierType", ["int"]]]]]]]]); + + // ... + // so we test them manually + self.assertEqual(parsed_struct.type.type.decls[0].bitsize.value, "6"); + self.assertEqual(parsed_struct.type.type.decls[1].bitsize.value, "2"); + + }); + test("struct_empty", () => { let s1, parsed_struct, s2, s3; + ` + Tests that parsing an empty struct works. + + Empty structs do NOT follow C99 (See 6.2.5-20 of the C99 standard). + This is nevertheless supported by some compilers (clang, gcc), + especially when using FORTIFY code. + Some compilers (visual) will fail to compile with an error. + ` + // an empty struct. This is NOT C99 compliant + s1 = ` + struct foo { }; + `; + + parsed_struct = self.parse(s1).ext[0]; + self.assertEqual(expand_decl(parsed_struct), + ["Decl", null, ["Struct", "foo", []]]); + + s2 = `struct { } foo;`; + parsed_struct = self.parse(s2).ext[0]; + self.assertEqual(expand_decl(parsed_struct), + ["Decl", "foo", ["TypeDecl", ["Struct", null, []]]]); + + s3 = `union { } foo;`; + parsed_struct = self.parse(s3).ext[0]; + self.assertEqual(expand_decl(parsed_struct), + ["Decl", "foo", ["TypeDecl", ["Union", null, []]]]); + + }); + test("tags_namespace", () => { let s1, s1_ast, s2, s2_ast, s3, s3_type; + ` Tests that the tags of structs/unions/enums reside in a separate namespace and + can be named after existing types. + ` + s1 = ` + typedef int tagEntry; + + struct tagEntry + { + char* key; + char* value; + } Entry; + `; + + s1_ast = self.parse(s1); + self.assertEqual(expand_decl(s1_ast.ext[1]), + ["Decl", "Entry", + ["TypeDecl", ["Struct", "tagEntry", + [["Decl", "key", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]], + ["Decl", "value", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]]]]]]); + + s2 = ` + struct tagEntry; + + typedef struct tagEntry tagEntry; + + struct tagEntry + { + char* key; + char* value; + } Entry; + `; + + s2_ast = self.parse(s2); + self.assertEqual(expand_decl(s2_ast.ext[2]), + ["Decl", "Entry", + ["TypeDecl", ["Struct", "tagEntry", + [["Decl", "key", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]], + ["Decl", "value", + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]]]]]]); + + s3 = ` + typedef int mytag; + + enum mytag {ABC, CDE}; + enum mytag joe; + `; + + s3_type = self.parse(s3).ext[1].type; + + self.assertIsInstance(s3_type, Enum); + self.assertEqual(s3_type.name, "mytag"); + + }); + test("multi_decls", () => { let d1, d2; + d1 = "int a, b;"; + + self.assertEqual(self.get_decl(d1, 0), + ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]); + self.assertEqual(self.get_decl(d1, 1), + ["Decl", "b", ["TypeDecl", ["IdentifierType", ["int"]]]]); + + d2 = "char* p, notp, ar[4];"; + self.assertEqual(self.get_decl(d2, 0), + ["Decl", "p", + ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["char"]]]]]); + self.assertEqual(self.get_decl(d2, 1), + ["Decl", "notp", ["TypeDecl", ["IdentifierType", ["char"]]]]); + self.assertEqual(self.get_decl(d2, 2), + ["Decl", "ar", + ["ArrayDecl", "4", [], + ["TypeDecl", ["IdentifierType", ["char"]]]]]); + + }); + test("invalid_multiple_types_error", () => { let bad; + bad = [ + "int enum {ab, cd} fubr;", + "enum kid char brbr;"]; + + for (const b of bad) { + self.assertRaises(ParseError, self.parse, b); + + } + }); + test("invalid_typedef_storage_qual_error", () => { let bad; + ` Tests that using typedef as a storage qualifier is correctly flagged + as an error. + ` + bad = "typedef const int foo(int a) { return 0; }"; + self.assertRaises(ParseError, self.parse, bad); + + }); + test("duplicate_typedef", () => { let d1, d2, d3; + ` Tests that redeclarations of existing types are parsed correctly. + This is non-standard, but allowed by many compilers. + ` + d1 = ` + typedef int numbertype; + typedef int numbertype; + `; + + self.assertEqual(self.get_decl(d1, 0), + ["Typedef", "numbertype", + ["TypeDecl", ["IdentifierType", ["int"]]]]); + self.assertEqual(self.get_decl(d1, 1), + ["Typedef", "numbertype", + ["TypeDecl", ["IdentifierType", ["int"]]]]); + + d2 = ` + typedef int (*funcptr)(int x); + typedef int (*funcptr)(int x); + `; + self.assertEqual(self.get_decl(d2, 0), + ["Typedef", "funcptr", + ["PtrDecl", ["FuncDecl", + [["Decl", "x", ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + self.assertEqual(self.get_decl(d2, 1), + ["Typedef", "funcptr", + ["PtrDecl", ["FuncDecl", + [["Decl", "x", ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]]); + + d3 = ` + typedef int numberarray[5]; + typedef int numberarray[5]; + `; + self.assertEqual(self.get_decl(d3, 0), + ["Typedef", "numberarray", + ["ArrayDecl", "5", [], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + self.assertEqual(self.get_decl(d3, 1), + ["Typedef", "numberarray", + ["ArrayDecl", "5", [], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + }); + test("decl_inits", () => { let d1, d1_1, d1_2, d2, d21, d3, d4, d5, d51, d52, d53, d54, d55, d56, d57, d58, d59, d6, d61, d62, d63; + d1 = "int a = 16;"; + //~ self.parse(d1).show() + self.assertEqual(self.get_decl(d1), + ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]); + self.assertEqual(self.get_decl_init(d1), + ["Constant", "int", "16"]); + + d1_1 = "float f = 0xEF.56p1;"; + self.assertEqual(self.get_decl_init(d1_1), + ["Constant", "double", "0xEF.56p1"]); + + d1_2 = "int bitmask = 0b1001010;"; + self.assertEqual(self.get_decl_init(d1_2), + ["Constant", "int", "0b1001010"]); + + d2 = "long ar[] = {7, 8, 9};"; + self.assertEqual(self.get_decl(d2), + ["Decl", "ar", + ["ArrayDecl", "", [], + ["TypeDecl", ["IdentifierType", ["long"]]]]]); + self.assertEqual(self.get_decl_init(d2), + [ ["Constant", "int", "7"], + ["Constant", "int", "8"], + ["Constant", "int", "9"]]); + + d21 = "long ar[4] = {};"; + self.assertEqual(self.get_decl_init(d21), []); + + d3 = "char p = j;"; + self.assertEqual(self.get_decl(d3), + ["Decl", "p", ["TypeDecl", ["IdentifierType", ["char"]]]]); + self.assertEqual(self.get_decl_init(d3), + ["ID", "j"]); + + d4 = "char x = 'c', *p = {0, 1, 2, {4, 5}, 6};"; + self.assertEqual(self.get_decl(d4, 0), + ["Decl", "x", ["TypeDecl", ["IdentifierType", ["char"]]]]); + self.assertEqual(self.get_decl_init(d4, 0), + ["Constant", "char", "'c'"]); + self.assertEqual(self.get_decl(d4, 1), + ["Decl", "p", + ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["char"]]]]]); + + self.assertEqual(self.get_decl_init(d4, 1), + [ ["Constant", "int", "0"], + ["Constant", "int", "1"], + ["Constant", "int", "2"], + [["Constant", "int", "4"], + ["Constant", "int", "5"]], + ["Constant", "int", "6"]]); + + d5 = "float d = 1.0;"; + self.assertEqual(self.get_decl_init(d5), + ["Constant", "double", "1.0"]); + + d51 = "float ld = 1.0l;"; + self.assertEqual(self.get_decl_init(d51), + ["Constant", "long double", "1.0l"]); + + d52 = "float ld = 1.0L;"; + self.assertEqual(self.get_decl_init(d52), + ["Constant", "long double", "1.0L"]); + + d53 = "float ld = 1.0f;"; + self.assertEqual(self.get_decl_init(d53), + ["Constant", "float", "1.0f"]); + + d54 = "float ld = 1.0F;"; + self.assertEqual(self.get_decl_init(d54), + ["Constant", "float", "1.0F"]); + + d55 = "float ld = 0xDE.38p0;"; + self.assertEqual(self.get_decl_init(d55), + ["Constant", "double", "0xDE.38p0"]); + + d56 = "float ld = 0xDE.38p0f;"; + self.assertEqual(self.get_decl_init(d56), + ["Constant", "float", "0xDE.38p0f"]); + + d57 = "float ld = 0xDE.38p0F;"; + self.assertEqual(self.get_decl_init(d57), + ["Constant", "float", "0xDE.38p0F"]); + + d58 = "float ld = 0xDE.38p0l;"; + self.assertEqual(self.get_decl_init(d58), + ["Constant", "long double", "0xDE.38p0l"]); + + d59 = "float ld = 0xDE.38p0L;"; + self.assertEqual(self.get_decl_init(d59), + ["Constant", "long double", "0xDE.38p0L"]); + + d6 = "int i = 1;"; + self.assertEqual(self.get_decl_init(d6), + ["Constant", "int", "1"]); + + d61 = "long int li = 1l;"; + self.assertEqual(self.get_decl_init(d61), + ["Constant", "long int", "1l"]); + + d62 = "unsigned int ui = 1u;"; + self.assertEqual(self.get_decl_init(d62), + ["Constant", "unsigned int", "1u"]); + + d63 = "unsigned long long int ulli = 1LLU;"; + self.assertEqual(self.get_decl_init(d63), + ["Constant", "unsigned long long int", "1LLU"]); + + }); + test("decl_named_inits", () => { let d1, d2, d3; + d1 = "int a = {.k = 16};"; + self.assertEqual(self.get_decl_init(d1), + [[ [["ID", "k"]], + ["Constant", "int", "16"]]]); + + d2 = "int a = { [0].a = {1}, [1].a[0] = 2 };"; + self.assertEqual(self.get_decl_init(d2), + [ + [[["Constant", "int", "0"], ["ID", "a"]], + [["Constant", "int", "1"]]], + [[["Constant", "int", "1"], ["ID", "a"], ["Constant", "int", "0"]], + ["Constant", "int", "2"]]]); + + d3 = "int a = { .a = 1, .c = 3, 4, .b = 5};"; + self.assertEqual(self.get_decl_init(d3), + [ + [[["ID", "a"]], ["Constant", "int", "1"]], + [[["ID", "c"]], ["Constant", "int", "3"]], + ["Constant", "int", "4"], + [[["ID", "b"]], ["Constant", "int", "5"]]]); + + }); + test("function_definitions", () => { let f1, f2, f3, f4; + const parse_fdef = (str) => { + return self.parse(str).ext[0]; + + }; + const fdef_decl = (fdef) => { + return expand_decl(fdef.decl); + + }; + f1 = parse_fdef(` + int factorial(int p) + { + return 3; + } + `); + + self.assertEqual(fdef_decl(f1), + ["Decl", "factorial", + ["FuncDecl", + [["Decl", "p", ["TypeDecl", ["IdentifierType", ["int"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + self.assertEqual(type(f1.body.block_items[0]), Return); + + f2 = parse_fdef(` + char* zzz(int p, char* c) + { + int a; + char b; + + a = b + 2; + return 3; + } + `); + + self.assertEqual(fdef_decl(f2), + ["Decl", "zzz", + ["FuncDecl", + [ ["Decl", "p", ["TypeDecl", ["IdentifierType", ["int"]]]], + ["Decl", "c", ["PtrDecl", + ["TypeDecl", ["IdentifierType", ["char"]]]]]], + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]]]); + + self.assertEqual(f2.body.block_items.map(type), + [Decl, Decl, Assignment, Return]); + + f3 = parse_fdef(` + char* zzz(p, c) + long p, *c; + { + int a; + char b; + + a = b + 2; + return 3; + } + `); + + self.assertEqual(fdef_decl(f3), + ["Decl", "zzz", + ["FuncDecl", + [ ["ID", "p"], + ["ID", "c"]], + ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]]]); + + self.assertEqual(f3.body.block_items.map(type), + [Decl, Decl, Assignment, Return]); + + self.assertEqual(expand_decl(f3.param_decls[0]), + ["Decl", "p", ["TypeDecl", ["IdentifierType", ["long"]]]]); + self.assertEqual(expand_decl(f3.param_decls[1]), + ["Decl", "c", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["long"]]]]]); + + // function return values and parameters may not have type information + f4 = parse_fdef(` + que(p) + { + return 3; + } + `); + + self.assertEqual(fdef_decl(f4), + ["Decl", "que", + ["FuncDecl", + [["ID", "p"]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + }); + test("static_assert", () => { let f1; + f1 = self.parse(` + _Static_assert(1, "123"); + int factorial(int p) + { + _Static_assert(2, "456"); + _Static_assert(3); + } + `); + + self.assertEqual(expand_decl(f1.ext[0]), ["StaticAssert", "1", "\"123\""]); + self.assertEqual(expand_decl(f1.ext[1].body.block_items[0]), ["StaticAssert", "2", "\"456\""]); + self.assertEqual(expand_decl(f1.ext[1].body.block_items[2]), ["StaticAssert", "3"]); + + }); + test("unified_string_literals", () => { let d1, d2, d3, d4, d5, d6; + // simple string, for reference + d1 = self.get_decl_init("char* s = \"hello\";"); + self.assertEqual(d1, ["Constant", "string", "\"hello\""]); + + d2 = self.get_decl_init("char* s = \"hello\" \" world\";"); + self.assertEqual(d2, ["Constant", "string", "\"hello world\""]); + + // the test case from issue 6 + d3 = self.parse(String.raw` + int main() { + fprintf(stderr, + "Wrong Params?\n" + "Usage:\n" + "%s \n", + argv[0] + ); + } + `); + + self.assertEqual( + d3.ext[0].body.block_items[0].args.exprs[1].value, + String.raw`"Wrong Params?\nUsage:\n%s \n"`); + + d4 = self.get_decl_init("char* s = \"\" \"foobar\";"); + self.assertEqual(d4, ["Constant", "string", "\"foobar\""]); + + d5 = self.get_decl_init(String.raw`char* s = "foo\"" "bar";`); + self.assertEqual(d5, ["Constant", "string", String.raw`"foo\"bar"`]); + + // This is not correct based on the the C spec, but testing it here to + // see the behavior in action. Will have to fix this + // for https://github.com/eliben/pycparser/issues/392 + // + // The spec says in section 6.4.5 that "escape sequences are converted + // into single members of the execution character set just prior to + // adjacent string literal concatenation". + d6 = self.get_decl_init(String.raw`char* s = "\1" "23";`); + self.assertEqual(d6, ["Constant", "string", String.raw`"\123"`]); + + }); + test("unified_wstring_literals", () => { let d1, d2; + d1 = self.get_decl_init("char* s = L\"hello\" L\"world\";"); + self.assertEqual(d1, ["Constant", "string", "L\"helloworld\""]); + + d2 = self.get_decl_init("char* s = L\"hello \" L\"world\" L\" and I\";"); + self.assertEqual(d2, ["Constant", "string", "L\"hello world and I\""]); + + }); + test("inline_specifier", () => { let ps2; + ps2 = self.parse("static inline void inlinefoo(void);"); + self.assertEqual(ps2.ext[0].funcspec, ["inline"]); + + }); + test("noreturn_specifier", () => { let ps2; + ps2 = self.parse("static _Noreturn void noreturnfoo(void);"); + self.assertEqual(ps2.ext[0].funcspec, ["_Noreturn"]); + + // variable length array + }); + test("vla", () => { let ps2; + ps2 = self.parse(String.raw` + int main() { + int size; + int var[size = 5]; + + int var2[*]; + } + `); + self.assertIsInstance(ps2.ext[0].body.block_items[1].type.dim, Assignment); + self.assertIsInstance(ps2.ext[0].body.block_items[2].type.dim, ID); + + }); + test("pragma", () => { let s1, s1_ast; + s1 = String.raw` + #pragma bar + void main() { + #pragma foo + for(;;) {} + #pragma baz + { + int i = 0; + } + #pragma + } + struct s { + #pragma baz + } s; + _Pragma("other \"string\"") + `; + s1_ast = self.parse(s1); + self.assertIsInstance(s1_ast.ext[0], Pragma); + self.assertEqual(s1_ast.ext[0].string, "bar"); + self.assertEqual(s1_ast.ext[0].coord.line, 2); + + self.assertIsInstance(s1_ast.ext[1].body.block_items[0], Pragma); + self.assertEqual(s1_ast.ext[1].body.block_items[0].string, "foo"); + self.assertEqual(s1_ast.ext[1].body.block_items[0].coord.line, 4); + + self.assertIsInstance(s1_ast.ext[1].body.block_items[2], Pragma); + self.assertEqual(s1_ast.ext[1].body.block_items[2].string, "baz"); + self.assertEqual(s1_ast.ext[1].body.block_items[2].coord.line, 6); + + self.assertIsInstance(s1_ast.ext[1].body.block_items[4], Pragma); + self.assertEqual(s1_ast.ext[1].body.block_items[4].string, ""); + self.assertEqual(s1_ast.ext[1].body.block_items[4].coord.line, 10); + + self.assertIsInstance(s1_ast.ext[2].type.type.decls[0], Pragma); + self.assertEqual(s1_ast.ext[2].type.type.decls[0].string, "baz"); + self.assertEqual(s1_ast.ext[2].type.type.decls[0].coord.line, 13); + + self.assertIsInstance(s1_ast.ext[3], Pragma); + self.assertEqual(s1_ast.ext[3].string.value, String.raw`"other \"string\""`); + self.assertEqual(s1_ast.ext[3].coord.line, 15); + + }); + test("pragmacomp_or_statement", () => { let s1, s1_ast; + s1 = String.raw` + void main() { + int sum = 0; + for (int i; i < 3; i++) + #pragma omp critical + sum += 1; + + while(sum < 10) + #pragma omp critical + sum += 1; + + mylabel: + #pragma foo + sum += 10; + + if (sum > 10) + #pragma bar + #pragma baz + sum = 10; + + switch (sum) + case 10: + #pragma foo + sum = 20; + } + `; + s1_ast = self.parse(s1); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1], For); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Pragma); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Assignment); + self.assertIsInstance(s1_ast.ext[0].body.block_items[2], While); + self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, Compound); + self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt.block_items[0], Pragma); + self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt.block_items[1], Assignment); + self.assertIsInstance(s1_ast.ext[0].body.block_items[3], Label); + self.assertIsInstance(s1_ast.ext[0].body.block_items[3].stmt, Compound); + self.assertIsInstance(s1_ast.ext[0].body.block_items[3].stmt.block_items[0], Pragma); + self.assertIsInstance(s1_ast.ext[0].body.block_items[3].stmt.block_items[1], Assignment); + self.assertIsInstance(s1_ast.ext[0].body.block_items[4], If); + self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue, Compound); + self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue.block_items[0], Pragma); + self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue.block_items[1], Pragma); + self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue.block_items[2], Assignment); + self.assertIsInstance(s1_ast.ext[0].body.block_items[5], Switch); + self.assertIsInstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0], Compound); + self.assertIsInstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[0], + Pragma); + self.assertIsInstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[1], + Assignment); + + + }); +}); +describe("TestCParser_whole_code", () => { const self = new TestCParser_base(); + // Testing of parsing whole chunks of code. Since upstream does not want + // to rely on the structure of ASTs too much, most of these tests are + // implemented with visitors. + + // A simple helper visitor that lists the values of all the + // Constant nodes it sees. + class ConstantVisitor extends NodeVisitor { + constructor() { super(); this.values = []; } + visit_Constant(node) { this.values.push(node.value); } + } + + // This visitor counts the amount of references to the ID + // with the name provided to it in the constructor. + class IDNameCounter extends NodeVisitor { + constructor(name) { super(); this.name = name; this.nrefs = 0; } + visit_ID(node) { if (node.name == this.name) this.nrefs += 1; } + } + + // Counts the amount of nodes of a given class + class NodeKlassCounter extends NodeVisitor { + constructor(node_klass) { super(); this.klass = node_klass; this.n = 0; } + generic_visit(node) { + if (node.constructor === this.klass) this.n += 1; + NodeVisitor.prototype.generic_visit.call(this, node); + } + } + + const parsedOf = (code) => (typeof code === "string" ? self.parse(code) : code); + + self.assert_all_Constants = (code, constants) => { + const cv = new ConstantVisitor(); + cv.visit(parsedOf(code)); + self.assertEqual(cv.values, constants); + }; + + self.assert_num_ID_refs = (code, name, num) => { + const iv = new IDNameCounter(name); + iv.visit(parsedOf(code)); + self.assertEqual(iv.nrefs, num); + }; + + self.assert_num_klass_nodes = (code, klass, num) => { + const cv = new NodeKlassCounter(klass); + cv.visit(parsedOf(code)); + self.assertEqual(cv.n, num); + }; + + test("expressions", () => { let e1, e2, s1, ps1; + e1 = `int k = (r + 10.0) >> 6 + 8 << (3 & 0x14);`; + self.assert_all_Constants(e1, ["10.0", "6", "8", "3", "0x14"]); + + e2 = String.raw`char n = '\n', *prefix = "st_";`; + self.assert_all_Constants(e2, [String.raw`'\n'`, "\"st_\""]); + + s1 = String.raw`int main() { + int i = 5, j = 6, k = 1; + if ((i=j && k == 1) || k > j) + printf("Hello, world\n"); + return 0; + }`; + ps1 = self.parse(s1); + self.assert_all_Constants(ps1, + ["5", "6", "1", "1", "\"Hello, world\\n\"", "0"]); + self.assert_num_ID_refs(ps1, "i", 1); + self.assert_num_ID_refs(ps1, "j", 2); + + + }); + test("statements", () => { let s1, ps1, s2, ps2, s3, ps3; + s1 = String.raw` + void foo(){ + if (sp == 1) + if (optind >= argc || + argv[optind][0] != '-' || argv[optind][1] == '\0') + return -1; + else if (strcmp(argv[optind], "--") == 0) { + optind++; + return -1; + } + } + `; + + self.assert_all_Constants(s1, + ["1", "0", String.raw`'-'`, "1", String.raw`'\0'`, "1", String.raw`"--"`, "0", "1"]); + + ps1 = self.parse(s1); + self.assert_num_ID_refs(ps1, "argv", 3); + self.assert_num_ID_refs(ps1, "optind", 5); + + self.assert_num_klass_nodes(ps1, If, 3); + self.assert_num_klass_nodes(ps1, Return, 2); + self.assert_num_klass_nodes(ps1, FuncCall, 1); // strcmp + self.assert_num_klass_nodes(ps1, BinaryOp, 7); + + // In the following code, Hash and Node were defined as + // int to pacify the parser that sees they're used as + // types + // + s2 = String.raw` + typedef int Hash, Node; + + void HashDestroy(Hash* hash) + { + unsigned int i; + + if (hash == NULL) + return; + + for (i = 0; i < hash->table_size; ++i) + { + Node* temp = hash->heads[i]; + + while (temp != NULL) + { + Node* temp2 = temp; + + free(temp->entry->key); + free(temp->entry->value); + free(temp->entry); + + temp = temp->next; + + free(temp2); + } + } + + free(hash->heads); + hash->heads = NULL; + + free(hash); + } + `; + + ps2 = self.parse(s2); + self.assert_num_klass_nodes(ps2, FuncCall, 6); + self.assert_num_klass_nodes(ps2, FuncDef, 1); + self.assert_num_klass_nodes(ps2, For, 1); + self.assert_num_klass_nodes(ps2, While, 1); + self.assert_num_klass_nodes(ps2, StructRef, 10); + + // declarations don't count + self.assert_num_ID_refs(ps2, "hash", 6); + self.assert_num_ID_refs(ps2, "i", 4); + + s3 = String.raw` + void x(void) { + int a, b; + if (a < b) + do { + a = 0; + } while (0); + else if (a == b) { + a = 1; + } + } + `; + + ps3 = self.parse(s3); + self.assert_num_klass_nodes(ps3, DoWhile, 1); + self.assert_num_ID_refs(ps3, "a", 4); + self.assert_all_Constants(ps3, ["0", "0", "1"]); + + }); + test("empty_statements", () => { let s1, ps1; + s1 = String.raw` + void foo(void){ + ; + return;; + + ; + } + `; + ps1 = self.parse(s1); + self.assert_num_klass_nodes(ps1, EmptyStatement, 3); + self.assert_num_klass_nodes(ps1, Return, 1); + self.assert_coord(ps1.ext[0].body.block_items[0], 3); + self.assert_coord(ps1.ext[0].body.block_items[1], 4); + self.assert_coord(ps1.ext[0].body.block_items[2], 4); + self.assert_coord(ps1.ext[0].body.block_items[3], 6); + + }); + test("switch_statement", () => { let s1, ps1, switch_, block, s2, ps2, s3, ps3; + const assert_case_node = (node, const_value) => { + self.assertIsInstance(node, Case); + self.assertIsInstance(node.expr, Constant); + self.assertEqual(node.expr.value, const_value); + + }; + const assert_default_node = (node) => { + self.assertIsInstance(node, Default); + + }; + s1 = String.raw` + int foo(void) { + switch (myvar) { + case 10: + k = 10; + p = k + 1; + return 10; + case 20: + case 30: + return 20; + default: + break; + } + return 0; + } + `; + ps1 = self.parse(s1); + switch_ = ps1.ext[0].body.block_items[0]; + + block = switch_.stmt.block_items; + self.assertEqual(block.length, 4); + assert_case_node(block[0], "10"); + self.assertEqual(block[0].stmts.length, 3); + assert_case_node(block[1], "20"); + self.assertEqual(block[1].stmts.length, 0); + assert_case_node(block[2], "30"); + self.assertEqual(block[2].stmts.length, 1); + assert_default_node(block[3]); + + s2 = String.raw` + int foo(void) { + switch (myvar) { + default: + joe = moe; + return 10; + case 10: + case 20: + case 30: + case 40: + break; + } + return 0; + } + `; + ps2 = self.parse(s2); + switch_ = ps2.ext[0].body.block_items[0]; + + block = switch_.stmt.block_items; + self.assertEqual(block.length, 5); + assert_default_node(block[0]); + self.assertEqual(block[0].stmts.length, 2); + assert_case_node(block[1], "10"); + self.assertEqual(block[1].stmts.length, 0); + assert_case_node(block[2], "20"); + self.assertEqual(block[1].stmts.length, 0); + assert_case_node(block[3], "30"); + self.assertEqual(block[1].stmts.length, 0); + assert_case_node(block[4], "40"); + self.assertEqual(block[4].stmts.length, 1); + + s3 = String.raw` + int foo(void) { + switch (myvar) { + } + return 0; + } + `; + ps3 = self.parse(s3); + switch_ = ps3.ext[0].body.block_items[0]; + + self.assertEqual(switch_.stmt.block_items, []); + + }); + test("for_statement", () => { let s2, ps2, s3, ps3, s4, ps4; + s2 = String.raw` + void x(void) + { + int i; + for (i = 0; i < 5; ++i) { + x = 50; + } + } + `; + ps2 = self.parse(s2); + self.assert_num_klass_nodes(ps2, For, 1); + // here there are 3 refs to 'i' since the declaration doesn't count as + // a ref in the visitor + // + self.assert_num_ID_refs(ps2, "i", 3); + + s3 = String.raw` + void x(void) + { + for (int i = 0; i < 5; ++i) { + x = 50; + } + } + `; + ps3 = self.parse(s3); + self.assert_num_klass_nodes(ps3, For, 1); + // here there are 2 refs to 'i' since the declaration doesn't count as + // a ref in the visitor + // + self.assert_num_ID_refs(ps3, "i", 2); + + s4 = String.raw` + void x(void) { + for (int i = 0;;) + i; + } + `; + ps4 = self.parse(s4); + self.assert_num_ID_refs(ps4, "i", 1); + + }); + // Upstream reads these from tests/c_files (copied under fixtures/ from + // pycparser b5c6024) with open() in text mode, i.e. universal newlines. + const cFile = (name) => new URL("./fixtures/c_files/" + name, import.meta.url); + const noFile = (name) => (existsSync(cFile(name)) ? false : `upstream fixture c_files/${name} is not shipped with the vendored fork`); + + test("whole_file", { skip: noFile("memmgr_with_h.c") }, () => { + // See how pycparser handles a whole, real C file. + const code = readFileSync(cFile("memmgr_with_h.c"), "utf8").replace(/\r\n?/g, "\n"); + const p = self.parse(code); + + self.assert_num_klass_nodes(p, FuncDef, 5); + + // each FuncDef also has a FuncDecl. 4 declarations + // + 5 definitions, overall 9 + self.assert_num_klass_nodes(p, FuncDecl, 9); + + self.assert_num_klass_nodes(p, Typedef, 4); + + self.assertEqual(p.ext[4].coord.line, 88); + self.assertEqual(p.ext[4].coord.file, "./memmgr.h"); + + self.assertEqual(p.ext[6].coord.line, 10); + self.assertEqual(p.ext[6].coord.file, "memmgr.c"); + }); + + test("whole_file_with_stdio", { skip: noFile("cppd_with_stdio_h.c") }, () => { + // Parse a whole file with stdio.h included by cpp + const code = readFileSync(cFile("cppd_with_stdio_h.c"), "utf8").replace(/\r\n?/g, "\n"); + const p = self.parse(code); + + self.assertIsInstance(p.ext[0], Typedef); + self.assertEqual(p.ext[0].coord.line, 213); + self.assertEqual(p.ext[0].coord.file, String.raw`D:\eli\cpp_stuff\libc_include/stddef.h`); + + self.assertIsInstance(p.ext.at(-1), FuncDef); + self.assertEqual(p.ext.at(-1).coord.line, 15); + self.assertEqual(p.ext.at(-1).coord.file, "example_c_file.c"); + + self.assertIsInstance(p.ext.at(-8), Typedef); + self.assertIsInstance(p.ext.at(-8).type, TypeDecl); + self.assertEqual(p.ext.at(-8).name, "cookie_io_functions_t"); + }); +}); +describe("TestCParser_typenames", () => { const self = new TestCParser_base(); + ` Test issues related to the typedef-name problem. + ` + test("innerscope_typedef", () => { let s1, s2; + // should fail since TT is not a type in bar + s1 = String.raw` + void foo() { + typedef char TT; + TT x; + } + void bar() { + TT y; + } + `; + self.assertRaises(ParseError, self.parse, s1); + + // should succeed since TT is not a type in bar + s2 = String.raw` + void foo() { + typedef char TT; + TT x; + } + void bar() { + unsigned TT; + } + `; + self.assertIsInstance(self.parse(s2), FileAST); + + }); + test("ambiguous_parameters", () => { let s1, s1_ast, s2, s2_ast, s3, s3_ast; + // From ISO/IEC 9899:TC2, 6.7.5.3.11: + // "If, in a parameter declaration, an identifier can be treated either + // as a typedef name or as a parameter name, it shall be taken as a + // typedef name." + + // foo takes an int named aa + // bar takes a function taking a TT + s1 = String.raw` + typedef char TT; + int foo(int (aa)); + int bar(int (TT)); + `; + s1_ast = self.parse(s1); + self.assertEqual(expand_decl(s1_ast.ext[1].type.args.params[0]), + ["Decl", "aa", ["TypeDecl", ["IdentifierType", ["int"]]]]); + self.assertEqual(expand_decl(s1_ast.ext[2].type.args.params[0]), + ["Typename", ["FuncDecl", + [["Typename", ["TypeDecl", ["IdentifierType", ["TT"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + // foo takes a function taking a char + // bar takes a function taking a function taking a char + s2 = String.raw` + typedef char TT; + int foo(int (aa (char))); + int bar(int (TT (char))); + `; + s2_ast = self.parse(s2); + self.assertEqual(expand_decl(s2_ast.ext[1].type.args.params[0]), + ["Decl", "aa", ["FuncDecl", + [["Typename", ["TypeDecl", ["IdentifierType", ["char"]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + self.assertEqual(expand_decl(s2_ast.ext[2].type.args.params[0]), + ["Typename", ["FuncDecl", + [["Typename", ["FuncDecl", + [["Typename", ["TypeDecl", ["IdentifierType", ["char"]]]]], + ["TypeDecl", ["IdentifierType", ["TT"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + + // foo takes an int array named aa + // bar takes a function taking a TT array + s3 = String.raw` + typedef char TT; + int foo(int (aa[])); + int bar(int (TT[])); + `; + s3_ast = self.parse(s3); + self.assertEqual(expand_decl(s3_ast.ext[1].type.args.params[0]), + ["Decl", "aa", ["ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["int"]]]]]); + self.assertEqual(expand_decl(s3_ast.ext[2].type.args.params[0]), + ["Typename", ["FuncDecl", + [["Typename", ["ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["TT"]]]]]], + ["TypeDecl", ["IdentifierType", ["int"]]]]]); + + }); + test("innerscope_reuse_typedef_name", () => { let s1, s1_ast, s2, s2_ast, s3, s3_ast, s4, s4_ast, s5, s6, s6_ast, items, s7, s7_ast, s8, s8_ast; + // identifiers can be reused in inner scopes; the original should be + // restored at the end of the block + s1 = String.raw` + typedef char TT; + void foo(void) { + unsigned TT; + TT = 10; + } + TT x = 5; + `; + s1_ast = self.parse(s1); + self.assertEqual(expand_decl(s1_ast.ext[1].body.block_items[0]), + ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]); + self.assertEqual(expand_decl(s1_ast.ext[2]), + ["Decl", "x", ["TypeDecl", ["IdentifierType", ["TT"]]]]); + + // this should be recognized even with an initializer + s2 = String.raw` + typedef char TT; + void foo(void) { + unsigned TT = 10; + } + `; + s2_ast = self.parse(s2); + self.assertEqual(expand_decl(s2_ast.ext[1].body.block_items[0]), + ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]); + + // before the second local variable, TT is a type; after, it's a + // variable + s3 = String.raw` + typedef char TT; + void foo(void) { + TT tt = sizeof(TT); + unsigned TT = 10; + } + `; + s3_ast = self.parse(s3); + self.assertEqual(expand_decl(s3_ast.ext[1].body.block_items[0]), + ["Decl", "tt", ["TypeDecl", ["IdentifierType", ["TT"]]]]); + self.assertEqual(expand_decl(s3_ast.ext[1].body.block_items[1]), + ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]); + + // a variable and its type can even share the same name + s4 = String.raw` + typedef char TT; + void foo(void) { + TT TT = sizeof(TT); + unsigned uu = TT * 2; + } + `; + s4_ast = self.parse(s4); + self.assertEqual(expand_decl(s4_ast.ext[1].body.block_items[0]), + ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["TT"]]]]); + self.assertEqual(expand_decl(s4_ast.ext[1].body.block_items[1]), + ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]); + + // ensure an error is raised if a type, redeclared as a variable, is + // used as a type + s5 = String.raw` + typedef char TT; + void foo(void) { + unsigned TT = 10; + TT erroneous = 20; + } + `; + self.assertRaises(ParseError, self.parse, s5); + + // reusing a type name should work with multiple declarators + s6 = String.raw` + typedef char TT; + void foo(void) { + unsigned TT, uu; + } + `; + s6_ast = self.parse(s6); + items = s6_ast.ext[1].body.block_items; + self.assertEqual(expand_decl(items[0]), + ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]); + self.assertEqual(expand_decl(items[1]), + ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]); + + // reusing a type name should work after a pointer + s7 = String.raw` + typedef char TT; + void foo(void) { + unsigned * TT; + } + `; + s7_ast = self.parse(s7); + items = s7_ast.ext[1].body.block_items; + self.assertEqual(expand_decl(items[0]), + ["Decl", "TT", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]]); + + // redefine a name in the middle of a multi-declarator declaration + s8 = String.raw` + typedef char TT; + void foo(void) { + int tt = sizeof(TT), TT, uu = sizeof(TT); + int uu = sizeof(tt); + } + `; + s8_ast = self.parse(s8); + items = s8_ast.ext[1].body.block_items; + self.assertEqual(expand_decl(items[0]), + ["Decl", "tt", ["TypeDecl", ["IdentifierType", ["int"]]]]); + self.assertEqual(expand_decl(items[1]), + ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["int"]]]]); + self.assertEqual(expand_decl(items[2]), + ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["int"]]]]); + + // Don't test this until we have support for it + // self.assertEqual(expand_init(items[0].init), + // ['UnaryOp', 'sizeof', ['Typename', ['TypeDecl', ['IdentifierType', ['TT']]]]]) + // self.assertEqual(expand_init(items[2].init), + // ['UnaryOp', 'sizeof', ['ID', 'TT']]) + + }); + test("parameter_reuse_typedef_name", () => { let s1, s1_ast, s2, s2_ast, s3; + // identifiers can be reused as parameter names; parameter name scope + // begins and ends with the function body; it's important that TT is + // used immediately before the LBRACE or after the RBRACE, to test + // a corner case + s1 = String.raw` + typedef char TT; + void foo(unsigned TT, TT bar) { + TT = 10; + } + TT x = 5; + `; + s1_ast = self.parse(s1); + self.assertEqual(expand_decl(s1_ast.ext[1].decl), + ["Decl", "foo", + ["FuncDecl", + [ ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], + ["Decl", "bar", ["TypeDecl", ["IdentifierType", ["TT"]]]]], + ["TypeDecl", ["IdentifierType", ["void"]]]]]); + + // the scope of a parameter name in a function declaration ends at the + // end of the declaration...so it is effectively never used; it's + // important that TT is used immediately after the declaration, to + // test a corner case + s2 = String.raw` + typedef char TT; + void foo(unsigned TT, TT bar); + TT x = 5; + `; + s2_ast = self.parse(s2); + self.assertEqual(expand_decl(s2_ast.ext[1]), + ["Decl", "foo", + ["FuncDecl", + [ ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], + ["Decl", "bar", ["TypeDecl", ["IdentifierType", ["TT"]]]]], + ["TypeDecl", ["IdentifierType", ["void"]]]]]); + + // ensure an error is raised if a type, redeclared as a parameter, is + // used as a type + s3 = String.raw` + typedef char TT; + void foo(unsigned TT, TT bar) { + TT erroneous = 20; + } + `; + self.assertRaises(ParseError, self.parse, s3); + + }); + test("nested_function_decls", () => { let s1; + // parameter names of nested function declarations must not escape into + // the top-level function _definition's_ scope; the following must + // succeed because TT is still a typedef inside foo's body + s1 = String.raw` + typedef char TT; + void foo(unsigned bar(int TT)) { + TT x = 10; + } + `; + self.assertIsInstance(self.parse(s1), FileAST); + + }); + test("samescope_reuse_name", () => { let s1, s2; + // a typedef name cannot be reused as an object name in the same scope + s1 = String.raw` + typedef char TT; + char TT = 5; + `; + self.assertRaises(ParseError, self.parse, s1); + + // ...and vice-versa + s2 = String.raw` + char TT = 5; + typedef char TT; + `; + self.assertRaises(ParseError, self.parse, s2); + + }); + test("label_empty_statement", () => { let s1, s1_ast; + // Labels with empty statements and no semicolon should be parsed correctly + s1 = String.raw` + int main() { + int i = 0; + label0: i++; + label1: + } + `; + s1_ast = self.parse(s1); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Label); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, UnaryOp); + self.assertIsInstance(s1_ast.ext[0].body.block_items[2], Label); + self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, EmptyStatement); + + }); + test("case_empty_statement", () => { let s1, s2, s1_ast, s2_ast; + // Labels with empty statements and no semicolon should be parsed correctly + s1 = String.raw` + int main() { + int i = 0; + switch (i) { + case 0: + i = 1; + case 1: + } + return i; + } + `; + s2 = String.raw` + int main() { + int i = 0; + switch (i) { + case 0: + i = 1; + default: + } + return i; + } + `; + s1_ast = self.parse(s1); + s2_ast = self.parse(s2); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Switch); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Case); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0].stmts[0], Assignment); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Case); + self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0], EmptyStatement); + self.assertIsInstance(s2_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0], EmptyStatement); + + }); +}); diff --git a/packages/romdev-pycparser/test/cpp.js b/packages/romdev-pycparser/test/cpp.js new file mode 100644 index 00000000..ee77d373 --- /dev/null +++ b/packages/romdev-pycparser/test/cpp.js @@ -0,0 +1,43 @@ +// Upstream's cpp-backed tests (use_cpp=True) shell out to the host `cpp`. +// Here the preprocessor is romdev's WASM one: the mips gcc toolchain's cc1 in +// -E mode, driven by romdevtools' src/decomp/cpp.js. No host tool is spawned. +import path from "node:path"; +import { existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { preprocess } from "../../romdevtools/src/decomp/cpp.js"; +import { parse_file } from "../src/index.js"; + +export const C_FILES = fileURLToPath(new URL("./fixtures/c_files/", import.meta.url)); +export const FAKE_LIBC = fileURLToPath(new URL("./fixtures/fake_libc_include/", import.meta.url)); +export const cFile = (name) => path.join(C_FILES, name); + +/** + * Why the use_cpp cases cannot run here, or false. The preprocessor is the + * mips gcc cc1 in romdev-toolchain-mips-gcc, whose wasm/ payload is gitignored + * (built locally, or filled from npm by scripts/fetch-payloads.mjs). Without + * it those cases skip with this reason instead of failing on a missing file, + * like romdevtools' test/helpers/test-rom.js. + */ +export const CPP_SKIP = (() => { + let dir = null; + try { dir = path.dirname(fileURLToPath(import.meta.resolve("romdev-toolchain-mips-gcc"))); } catch { + const sibling = fileURLToPath(new URL("../../romdev-toolchain-mips-gcc/", import.meta.url)); + if (existsSync(path.join(sibling, "package.json"))) dir = sibling; + } + if (!dir) return "romdev-toolchain-mips-gcc (the WASM cpp) is not installed"; + const absent = ["wasm/cc1.mjs", "wasm/cc1.wasm"].filter((f) => !existsSync(path.join(dir, f))); + return absent.length ? `romdev-toolchain-mips-gcc payload absent (${absent.join(", ")}): gitignored WASM, built locally or filled from npm by scripts/fetch-payloads.mjs` : false; +})(); + +/** + * pycparser.parse_file(filename, use_cpp=True, cpp_args=...) with the WASM cpp. + * Like upstream's tests, the file is named relative to the working directory + * (here: its own directory), so line markers carry that spelling. + */ +export async function parse_file_with_cpp(filename, cpp_args = []) { + const cwd = path.dirname(filename); + const r = await preprocess({ cwd, args: [...cpp_args, path.basename(filename)] }); + if (r.exitCode !== 0) throw new Error(`cpp failed (${r.exitCode}): ${r.log}`); + const text = r.output.toString("utf8"); + return parse_file(filename, { use_cpp: true, preprocess: () => text }); +} diff --git a/packages/romdev-pycparser/test/fixtures/LICENSE.pycparser-fixtures b/packages/romdev-pycparser/test/fixtures/LICENSE.pycparser-fixtures new file mode 100644 index 00000000..bee14a47 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/LICENSE.pycparser-fixtures @@ -0,0 +1,27 @@ +pycparser -- A C parser in Python + +Copyright (c) 2008-2022, Eli Bendersky +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +* Neither the name of the copyright holder nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/romdev-pycparser/test/fixtures/c_files/c11.c b/packages/romdev-pycparser/test/fixtures/c_files/c11.c new file mode 100644 index 00000000..ff111626 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/c11.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +/* C11 thread locals */ +_Thread_local int flag; +thread_local int flag2; +_Atomic int flag3; +_Atomic(int) flag4; +_Atomic(_Atomic(int) *) flag5; +atomic_bool flag6; +_Alignas(32) int q32; +_Alignas(long long) int qll; +alignas(64) int qqq; + +static_assert(sizeof(flag) == sizeof(flag2), "Really unexpected size difference"); + +noreturn void func2(void) +{ + abort(); +} + +_Noreturn void func(void) +{ + func2(); +} + +int main() +{ + _Static_assert(sizeof(flag) == sizeof(flag2), "Unexpected size difference"); + _Static_assert(sizeof(flag) == sizeof(flag2)); + static_assert(sizeof(flag) == sizeof(flag2), "Unexpected size difference"); + static_assert(sizeof(flag) == sizeof(flag3), "Unexpected size difference"); + static_assert(sizeof(flag) == sizeof(flag4), "Unexpected size difference"); + static_assert(_Alignof(int) == sizeof(int), "Unexpected int alignment"); + static_assert(alignof(int) == sizeof(int), "Unexpected int alignment"); + + wchar_t *w = L"12345"; + char16_t *c16 = u"12345"; + char32_t *c32 = U"12345"; + char *u8 = u8"12345"; + + wchar_t wc = L'1'; + char16_t c16c = u'1'; + char32_t c32c = U'1'; + char u8c = u8'1'; + + printf("Flag: %d\n", flag); + printf("Flag2: %d\n", flag2); + func(); +} diff --git a/packages/romdev-pycparser/test/fixtures/c_files/cppd_with_stdio_h.c b/packages/romdev-pycparser/test/fixtures/c_files/cppd_with_stdio_h.c new file mode 100644 index 00000000..ab1426a7 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/cppd_with_stdio_h.c @@ -0,0 +1,5038 @@ +#line 1 "example_c_file.c" + + +#line 1 "D:\eli\cpp_stuff\libc_include/stdio.h" + +#line 19 "D:\eli\cpp_stuff\libc_include/stdio.h" + + +#line 25 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + +#line 11 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/newlib.h" + +#line 3 "D:\eli\cpp_stuff\libc_include/newlib.h" +#line 16 "D:\eli\cpp_stuff\libc_include/_ansi.h" +#line 1 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + +#line 1 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" + + + + +#line 52 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" + + + +#line 58 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" + + + + + + + + + + + + + + + + + + + + + + +#line 83 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" + +#line 86 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" + +#line 89 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" + + +#line 95 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 5 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + +#line 11 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 143 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + + + + + +#line 157 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 195 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + + + +#line 207 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + +#line 17 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + +#line 21 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 30 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 19 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 26 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 30 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 35 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 39 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 42 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + +#line 53 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 56 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + +#line 67 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + +#line 76 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + +#line 98 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + +#line 108 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + +#line 126 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + +#line 131 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 170 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +typedef long unsigned int size_t; + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 243 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 246 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 290 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + +#line 302 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + +#line 310 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 361 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + +#line 365 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 418 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 422 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + +#line 427 "D:\eli\cpp_stuff\libc_include/stddef.h" +#line 35 "D:\eli\cpp_stuff\libc_include/stdio.h" + + +#line 1 "D:\eli\cpp_stuff\libc_include/stdarg.h" + +#line 19 "D:\eli\cpp_stuff\libc_include/stdarg.h" + + +#line 26 "D:\eli\cpp_stuff\libc_include/stdarg.h" + + +#line 30 "D:\eli\cpp_stuff\libc_include/stdarg.h" + + + + + + + + + + + + + + +typedef char* __builtin_va_list; +typedef __builtin_va_list __gnuc_va_list; + + + +#line 50 "D:\eli\cpp_stuff\libc_include/stdarg.h" + + + + + + + + + + + + +#line 66 "D:\eli\cpp_stuff\libc_include/stdarg.h" + + + + + + + + + + + +#line 80 "D:\eli\cpp_stuff\libc_include/stdarg.h" + + + + + + + + + + + + + + + +#line 98 "D:\eli\cpp_stuff\libc_include/stdarg.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 38 "D:\eli\cpp_stuff\libc_include/stdio.h" + + +#line 44 "D:\eli\cpp_stuff\libc_include/stdio.h" + +#line 1 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + +#line 6 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + +#line 11 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + + + + + + + +#line 21 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 14 "D:\eli\cpp_stuff\libc_include/sys/reent.h" +#line 1 "D:\eli\cpp_stuff\libc_include/sys/_types.h" + + + +#line 8 "D:\eli\cpp_stuff\libc_include/sys/_types.h" + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/machine/_types.h" + +#line 4 "D:\eli\cpp_stuff\libc_include/machine/_types.h" + + + +#line 1 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" + +#line 4 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" + + + + + + + + + +#line 15 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" + +#line 17 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" + + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/limits.h" + + + +#line 1 "D:\eli\cpp_stuff\libc_include/newlib.h" + +#line 3 "D:\eli\cpp_stuff\libc_include/newlib.h" +#line 5 "D:\eli\cpp_stuff\libc_include/limits.h" + + + + + + + + + + + + + +#line 19 "D:\eli\cpp_stuff\libc_include/limits.h" + + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + +#line 11 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 143 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + + + + + +#line 157 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 195 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + + + + + +#line 207 "D:\eli\cpp_stuff\libc_include/sys/config.h" + + + + + + + +#line 25 "D:\eli\cpp_stuff\libc_include/limits.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 79 "D:\eli\cpp_stuff\libc_include/limits.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 23 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" + + + +typedef signed char __int8_t ; +typedef unsigned char __uint8_t ; + + + + + + + + +typedef signed short __int16_t; +typedef unsigned short __uint16_t; + + + + + + + + +typedef __int16_t __int_least16_t; +typedef __uint16_t __uint_least16_t; + + + + + + + + + + +typedef signed int __int32_t; +typedef unsigned int __uint32_t; + + + + + + + + + + + + + + + + +typedef __int32_t __int_least32_t; +typedef __uint32_t __uint_least32_t; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 8 "D:\eli\cpp_stuff\libc_include/machine/_types.h" + +#line 13 "D:\eli\cpp_stuff\libc_include/sys/_types.h" +#line 1 "D:\eli\cpp_stuff\libc_include/sys/lock.h" + + + + + +typedef int _LOCK_T; +typedef int _LOCK_RECURSIVE_T; + + + + + + + + + + + + + + + +#line 14 "D:\eli\cpp_stuff\libc_include/sys/_types.h" + + +typedef long _off_t; + + + + + + + +typedef short __dev_t; + + + + +typedef unsigned short __uid_t; + + +typedef unsigned short __gid_t; + + + + typedef long long _off64_t; + + + +#line 43 "D:\eli\cpp_stuff\libc_include/sys/_types.h" + +typedef long _fpos_t; + + + + + + + + + + + +typedef int _ssize_t; + + + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 19 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 26 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 30 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 35 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 39 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 42 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + +#line 53 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 56 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + +#line 67 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + +#line 76 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + +#line 98 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + +#line 108 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + +#line 126 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + +#line 131 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 170 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 243 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 246 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 290 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + +#line 302 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + +#line 310 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +typedef unsigned int wint_t; + + + + + +#line 361 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + +#line 365 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 418 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 422 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + +#line 427 "D:\eli\cpp_stuff\libc_include/stddef.h" +#line 64 "D:\eli\cpp_stuff\libc_include/sys/_types.h" + + + +typedef struct +{ + int __count; + union + { + wint_t __wch; + unsigned char __wchb[4]; + } __value; +} _mbstate_t; + + + +typedef _LOCK_RECURSIVE_T _flock_t; + + + + +typedef void *_iconv_t; + + + +#line 15 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + +typedef unsigned long __ULong; + + + + + + + + + + + + + + + +struct _reent; + + +#line 43 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + +struct _Bigint +{ + struct _Bigint *_next; + int _k, _maxwds, _sign, _wds; + __ULong _x[1]; +}; + + +struct __tm +{ + int __tm_sec; + int __tm_min; + int __tm_hour; + int __tm_mday; + int __tm_mon; + int __tm_year; + int __tm_wday; + int __tm_yday; + int __tm_isdst; +}; + + +#line 68 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + +struct _on_exit_args { + void * _fnargs[32]; + void * _dso_handle[32]; + + __ULong _fntypes; +#line 77 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + __ULong _is_cxa; +}; + + + + + + + + + +struct _atexit { + struct _atexit *_next; + int _ind; + + void (*_fns[32])(void); + struct _on_exit_args _on_exit_args; +}; + + + +#line 104 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + +struct __sbuf { + unsigned char *_base; + int _size; +}; + + +#line 134 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + +#line 141 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + +struct __sFILE { + unsigned char *_p; + int _r; + int _w; + short _flags; + short _file; + struct __sbuf _bf; + int _lbfsize; + + + + + + + char * _cookie; + + int(*_read)(); +#line 176 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + int(*_write)(); +#line 178 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + _fpos_t(*_seek)(); + int(*_close)(); + + + struct __sbuf _ub; + unsigned char *_up; + int _ur; + + + unsigned char _ubuf[3]; + unsigned char _nbuf[1]; + + + struct __sbuf _lb; + + + int _blksize; + int _offset; + + + struct _reent *_data; + + + + _flock_t _lock; + +}; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +typedef struct __sFILE __FILE; + + + +struct _glue +{ + struct _glue *_next; + int _niobs; + __FILE *_iobs; +}; + + +#line 284 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + +struct _rand48 { + unsigned short _seed[3]; + unsigned short _mult[3]; + unsigned short _add; + + + + +}; + + + + + + + +#line 313 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 344 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + +#line 350 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 420 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 452 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + +#line 474 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 478 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 482 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + +#line 494 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + +#line 496 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 503 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + +#line 505 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 508 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 531 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + +#line 533 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 536 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + +struct _reent +{ + int _errno; + + +#line 571 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + __FILE *_stdin, *_stdout, *_stderr; + + int _inc; + char _emergency[25]; + + int _current_category; + char *_current_locale; + + int __sdidinit; + + void(*__cleanup)(); + + + struct _Bigint *_result; + int _result_k; + struct _Bigint *_p5s; + struct _Bigint **_freelist; + + + int _cvtlen; + char *_cvtbuf; + + union + { + struct + { + unsigned int _unused_rand; + char * _strtok_last; + char _asctime_buf[26]; + struct __tm _localtime_buf; + int _gamma_signgam; + unsigned long long _rand_next; + struct _rand48 _r48; + _mbstate_t _mblen_state; + _mbstate_t _mbtowc_state; + _mbstate_t _wctomb_state; + char _l64a_buf[8]; + char _signal_buf[24]; + int _getdate_err; + _mbstate_t _mbrlen_state; + _mbstate_t _mbrtowc_state; + _mbstate_t _mbsrtowcs_state; + _mbstate_t _wcrtomb_state; + _mbstate_t _wcsrtombs_state; + } _reent; + +#line 619 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + struct + { + + unsigned char * _nextf[30]; + unsigned int _nmalloc[30]; + } _unused; + } _new; + + + struct _atexit *_atexit; + struct _atexit _atexit0; + + + void (**(_sig_func))(int); + + +#line 637 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + struct _glue __sglue; + __FILE __sf[3]; +}; + + +#line 689 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 751 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 791 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + +extern struct _reent *_impure_ptr; +extern struct _reent * _global_impure_ptr; + +void _reclaim_reent(); + + + + + + + + + + + + + + + + + + + + + + +#line 46 "D:\eli\cpp_stuff\libc_include/stdio.h" +#line 1 "D:\eli\cpp_stuff\libc_include/sys/types.h" + +#line 17 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + +#line 1 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + +#line 11 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + + + + + + + +#line 21 "D:\eli\cpp_stuff\libc_include/_ansi.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 21 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/machine/_types.h" + +#line 4 "D:\eli\cpp_stuff\libc_include/machine/_types.h" + + + + + +#line 26 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + +#line 33 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/sys/_types.h" + + + +#line 8 "D:\eli\cpp_stuff\libc_include/sys/_types.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 43 "D:\eli\cpp_stuff\libc_include/sys/_types.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 62 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 19 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 26 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 30 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 35 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 39 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 42 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + +#line 53 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 56 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + +#line 67 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + +#line 76 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + +#line 98 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + +#line 108 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + +#line 126 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + +#line 131 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + +typedef long int ptrdiff_t; + + + + + + + + + + + + + + + + + +#line 170 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 243 "D:\eli\cpp_stuff\libc_include/stddef.h" + + +#line 246 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 290 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + +#line 302 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + +#line 310 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + +typedef int wchar_t; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 361 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + +#line 365 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 418 "D:\eli\cpp_stuff\libc_include/stddef.h" + +#line 422 "D:\eli\cpp_stuff\libc_include/stddef.h" + + + + +#line 427 "D:\eli\cpp_stuff\libc_include/stddef.h" +#line 70 "D:\eli\cpp_stuff\libc_include/sys/types.h" +#line 1 "D:\eli\cpp_stuff\libc_include/machine/types.h" + + + + +#line 9 "D:\eli\cpp_stuff\libc_include/machine/types.h" + + + + + + + + + + +typedef long int __off_t; +typedef int __pid_t; + + + +typedef long int __loff_t; + + + + + + +#line 71 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + +#line 79 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + + + + + + + + + + +typedef unsigned char u_char; +typedef unsigned short u_short; +typedef unsigned int u_int; +typedef unsigned long u_long; + + + +typedef unsigned short ushort; +typedef unsigned int uint; + + + +typedef unsigned long clock_t; + + + + +typedef long time_t; + + + + +struct timespec { + time_t tv_sec; + long tv_nsec; +}; + +struct itimerspec { + struct timespec it_interval; + struct timespec it_value; +}; + + +typedef long daddr_t; +typedef char * caddr_t; + + + +#line 131 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + +typedef unsigned short ino_t; + + + + + + + + + + + + + + + + + + + + + +#line 160 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + +typedef _off_t off_t; +typedef __dev_t dev_t; +typedef __uid_t uid_t; +typedef __gid_t gid_t; + + +typedef int pid_t; + +typedef long key_t; + +typedef _ssize_t ssize_t; + + + + + + + + + + + + + +typedef unsigned int mode_t; + + + + +typedef unsigned short nlink_t; + + +#line 200 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + +#line 209 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + +typedef long fd_mask; + + + + + + +#line 221 "D:\eli\cpp_stuff\libc_include/sys/types.h" +typedef struct _types_fd_set { + fd_mask fds_bits[(((64)+(((sizeof (fd_mask) * 8))-1))/((sizeof (fd_mask) * 8)))]; +} _types_fd_set; + + + + + + + +#line 236 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + + + + + +typedef unsigned long clockid_t; + + + + +typedef unsigned long timer_t; + + + +typedef unsigned long useconds_t; +typedef long suseconds_t; + +#line 1 "D:\eli\cpp_stuff\libc_include/sys/features.h" + +#line 20 "D:\eli\cpp_stuff\libc_include/sys/features.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 257 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + +#line 266 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + + +#line 273 "D:\eli\cpp_stuff\libc_include/sys/types.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 47 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + +typedef __FILE FILE; + + + + + + + + +typedef _fpos_t fpos_t; + + + + + +#line 1 "D:\eli\cpp_stuff\libc_include/sys/stdio.h" + + + +#line 1 "D:\eli\cpp_stuff\libc_include/sys/lock.h" + + + + + + + + + + + + + + + + + + + + + + +#line 5 "D:\eli\cpp_stuff\libc_include/sys/stdio.h" +#line 1 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + +#line 6 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 43 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + +#line 68 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + +#line 77 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + +#line 104 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + +#line 134 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + +#line 141 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 284 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + +#line 313 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 344 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + +#line 350 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 420 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 452 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + +#line 474 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 478 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 482 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + +#line 494 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + +#line 496 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 503 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + +#line 505 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 508 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 531 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + +#line 533 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 536 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 571 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 619 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + +#line 637 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + +#line 689 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + +#line 751 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 791 "D:\eli\cpp_stuff\libc_include/sys/reent.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 6 "D:\eli\cpp_stuff\libc_include/sys/stdio.h" + + +#line 11 "D:\eli\cpp_stuff\libc_include/sys/stdio.h" + + + + + + + + + + + + + + + + + +#line 66 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + + + + + + + + + + + + + + + + + + +#line 96 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 163 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + + + +FILE * tmpfile(); +char * tmpnam(); +int fclose(); +int fflush(); +FILE * freopen(); +void setbuf(); +int setvbuf(); +int fprintf(); +#line 179 "D:\eli\cpp_stuff\libc_include/stdio.h" +int fscanf(); +#line 181 "D:\eli\cpp_stuff\libc_include/stdio.h" +int printf(); +#line 183 "D:\eli\cpp_stuff\libc_include/stdio.h" +int scanf(); +#line 185 "D:\eli\cpp_stuff\libc_include/stdio.h" +int sscanf(); +#line 187 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vfprintf(); +#line 189 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vprintf(); +#line 191 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vsprintf(); +#line 193 "D:\eli\cpp_stuff\libc_include/stdio.h" +int fgetc(); +char * fgets(); +int fputc(); +int fputs(); +int getc(); +int getchar(); +char * gets(); +int putc(); +int putchar(); +int puts(); +int ungetc(); +size_t fread(); +size_t fwrite(); + + + +int fgetpos(); + +int fseek(); + + + +int fsetpos(); + +long ftell(); +void rewind(); +void clearerr(); +int feof(); +int ferror(); +void perror(); + +FILE * fopen(); +int sprintf(); +#line 227 "D:\eli\cpp_stuff\libc_include/stdio.h" +int remove(); +int rename(); + + + + + + +int fseeko(); +off_t ftello(); + + +int asiprintf(); +#line 241 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * asniprintf(); +#line 243 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * asnprintf(); +#line 245 "D:\eli\cpp_stuff\libc_include/stdio.h" +int asprintf(); +#line 247 "D:\eli\cpp_stuff\libc_include/stdio.h" + +int diprintf(); +#line 250 "D:\eli\cpp_stuff\libc_include/stdio.h" + +int fcloseall(); +int fiprintf(); +#line 254 "D:\eli\cpp_stuff\libc_include/stdio.h" +int fiscanf(); +#line 256 "D:\eli\cpp_stuff\libc_include/stdio.h" +int iprintf(); +#line 258 "D:\eli\cpp_stuff\libc_include/stdio.h" +int iscanf(); +#line 260 "D:\eli\cpp_stuff\libc_include/stdio.h" +int siprintf(); +#line 262 "D:\eli\cpp_stuff\libc_include/stdio.h" +int siscanf(); +#line 264 "D:\eli\cpp_stuff\libc_include/stdio.h" +int snprintf(); +#line 266 "D:\eli\cpp_stuff\libc_include/stdio.h" +int sniprintf(); +#line 268 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * tempnam(); +int vasiprintf(); +#line 271 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * vasniprintf(); +#line 273 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * vasnprintf(); +#line 275 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vasprintf(); +#line 277 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vdiprintf(); +#line 279 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vfiprintf(); +#line 281 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vfiscanf(); +#line 283 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vfscanf(); +#line 285 "D:\eli\cpp_stuff\libc_include/stdio.h" +int viprintf(); +#line 287 "D:\eli\cpp_stuff\libc_include/stdio.h" +int viscanf(); +#line 289 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vscanf(); +#line 291 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vsiprintf(); +#line 293 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vsiscanf(); +#line 295 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vsniprintf(); +#line 297 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vsnprintf(); +#line 299 "D:\eli\cpp_stuff\libc_include/stdio.h" +int vsscanf(); +#line 301 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + +#line 307 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + +FILE * fdopen(); + +int fileno(); +int getw(); +int pclose(); +FILE * popen(); +int putw(); +void setbuffer(); +int setlinebuf(); +int getc_unlocked(); +int getchar_unlocked(); +void flockfile(); +int ftrylockfile(); +void funlockfile(); +int putc_unlocked(); +int putchar_unlocked(); + + + +#line 331 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + +int dprintf(); +#line 337 "D:\eli\cpp_stuff\libc_include/stdio.h" + +FILE * fmemopen(); + + +FILE * open_memstream(); + +int vdprintf(); +#line 345 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + +#line 351 "D:\eli\cpp_stuff\libc_include/stdio.h" + +int _asiprintf_r(); +#line 354 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * _asniprintf_r(); +#line 356 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * _asnprintf_r(); +#line 358 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _asprintf_r(); +#line 360 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _diprintf_r(); +#line 362 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _dprintf_r(); +#line 364 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _fclose_r(); +int _fcloseall_r(); +FILE * _fdopen_r(); +int _fflush_r(); +char * _fgets_r(); +int _fiprintf_r(); +#line 371 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _fiscanf_r(); +#line 373 "D:\eli\cpp_stuff\libc_include/stdio.h" +FILE * _fmemopen_r(); +FILE * _fopen_r(); +int _fprintf_r(); +#line 377 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _fputc_r(); +int _fputs_r(); +size_t _fread_r(); +int _fscanf_r(); +#line 382 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _fseek_r(); +long _ftell_r(); +size_t _fwrite_r(); +int _getc_r(); +int _getc_unlocked_r(); +int _getchar_r(); +int _getchar_unlocked_r(); +char * _gets_r(); +int _iprintf_r(); +#line 392 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _iscanf_r(); +#line 394 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _mkstemp_r(); +char * _mktemp_r(); +FILE * _open_memstream_r(); +void _perror_r(); +int _printf_r(); +#line 400 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _putc_r(); +int _putc_unlocked_r(); +int _putchar_unlocked_r(); +int _putchar_r(); +int _puts_r(); +int _remove_r(); +int _rename_r(); +#line 408 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _scanf_r(); +#line 410 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _siprintf_r(); +#line 412 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _siscanf_r(); +#line 414 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _sniprintf_r(); +#line 416 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _snprintf_r(); +#line 418 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _sprintf_r(); +#line 420 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _sscanf_r(); +#line 422 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * _tempnam_r(); +FILE * _tmpfile_r(); +char * _tmpnam_r(); +int _ungetc_r(); +int _vasiprintf_r(); +#line 428 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * _vasniprintf_r(); +#line 430 "D:\eli\cpp_stuff\libc_include/stdio.h" +char * _vasnprintf_r(); +#line 432 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vasprintf_r(); +#line 434 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vdiprintf_r(); +#line 436 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vdprintf_r(); +#line 438 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vfiprintf_r(); +#line 440 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vfiscanf_r(); +#line 442 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vfprintf_r(); +#line 444 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vfscanf_r(); +#line 446 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _viprintf_r(); +#line 448 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _viscanf_r(); +#line 450 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vprintf_r(); +#line 452 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vscanf_r(); +#line 454 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vsiprintf_r(); +#line 456 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vsiscanf_r(); +#line 458 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vsniprintf_r(); +#line 460 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vsnprintf_r(); +#line 462 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vsprintf_r(); +#line 464 "D:\eli\cpp_stuff\libc_include/stdio.h" +int _vsscanf_r(); +#line 466 "D:\eli\cpp_stuff\libc_include/stdio.h" + +ssize_t __getdelim(); +ssize_t __getline(); + + + + + + + + + + + + + + + + + + + + + + +#line 493 "D:\eli\cpp_stuff\libc_include/stdio.h" + +int __srget_r(); +int __swbuf_r(); + + +#line 500 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + + + + + +FILE * funopen(); +#line 514 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + +#line 518 "D:\eli\cpp_stuff\libc_include/stdio.h" + +#line 520 "D:\eli\cpp_stuff\libc_include/stdio.h" + +typedef ssize_t cookie_read_function_t(void *__cookie, char *__buf, size_t __n); +typedef ssize_t cookie_write_function_t(void *__cookie, const char *__buf, + size_t __n); + + + + +typedef int cookie_seek_function_t(void *__cookie, off_t *__off, int __whence); + +typedef int cookie_close_function_t(void *__cookie); +typedef struct +{ + +#line 535 "D:\eli\cpp_stuff\libc_include/stdio.h" + cookie_read_function_t *read; + cookie_write_function_t *write; + cookie_seek_function_t *seek; + cookie_close_function_t *close; +} cookie_io_functions_t; +FILE * fopencookie(); +#line 542 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + +#line 549 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + +#line 574 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + +#line 580 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + + + + + + + + + + + + + + + + + + +#line 603 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + + + + +#line 613 "D:\eli\cpp_stuff\libc_include/stdio.h" + +#line 621 "D:\eli\cpp_stuff\libc_include/stdio.h" + + +#line 626 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#line 657 "D:\eli\cpp_stuff\libc_include/stdio.h" + + + + + + + + + + + + + + + +#line 4 "example_c_file.c" + +#line 8 "example_c_file.c" + +char tav = 'b'; +char maav = L"'guruguru\n"; +char* moral = "ain't I \\\"\\\t\" a nice string?\"\""; +char* comment_inside = "but you will /* see it */!!!!"; +char* i_have_newlines = "line one\nline two\nline three"; + +int main() +{ + auto char* multi = "a multi"; +} + + + + + diff --git a/packages/romdev-pycparser/test/fixtures/c_files/empty.h b/packages/romdev-pycparser/test/fixtures/c_files/empty.h new file mode 100644 index 00000000..635750a1 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/empty.h @@ -0,0 +1,8 @@ +#define PERFECTLY +#define NORMAL +#define TO +#define HAVE +#define HEADER +#define WITH +#define ONLY +#define DEFINES diff --git a/packages/romdev-pycparser/test/fixtures/c_files/example_c_file.c b/packages/romdev-pycparser/test/fixtures/c_files/example_c_file.c new file mode 100644 index 00000000..17b2ac4d --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/example_c_file.c @@ -0,0 +1,12 @@ +char tav = 'b'; +char* moral = "ain't I \\\"\\\t\" a nice string?\"\""; +char* comment_inside = "but you will /* see it */!!!!"; +char* i_have_newlines = "line one\nline two\nline three"; + +int main() +{ + auto char* multi = "a multi"; +} + + + diff --git a/packages/romdev-pycparser/test/fixtures/c_files/hdir/9/inc.h b/packages/romdev-pycparser/test/fixtures/c_files/hdir/9/inc.h new file mode 100644 index 00000000..0c96cbd4 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/hdir/9/inc.h @@ -0,0 +1 @@ +extern int ie; diff --git a/packages/romdev-pycparser/test/fixtures/c_files/memmgr.c b/packages/romdev-pycparser/test/fixtures/c_files/memmgr.c new file mode 100644 index 00000000..6036ec67 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/memmgr.c @@ -0,0 +1,206 @@ +//---------------------------------------------------------------- +// Statically-allocated memory manager +// +// by Eli Bendersky (eliben@gmail.com) +// +// This code is in the public domain. +//---------------------------------------------------------------- +#include "memmgr.h" + +typedef ulong Align; + +union mem_header_union +{ + struct + { + // Pointer to the next block in the free list + // + union mem_header_union* next; + + // Size of the block (in quantas of sizeof(mem_header_t)) + // + ulong size; + } s; + + // Used to align headers in memory to a boundary + // + Align align_dummy; +}; + +typedef union mem_header_union mem_header_t; + +// Initial empty list +// +static mem_header_t base; + +// Start of free list +// +static mem_header_t* freep = 0; + +// Static pool for new allocations +// +static byte pool[POOL_SIZE] = {0}; +static ulong pool_free_pos = 0; + + +void memmgr_init() +{ + base.s.next = 0; + base.s.size = 0; + freep = 0; + pool_free_pos = 0; +} + + +static mem_header_t* get_mem_from_pool(ulong nquantas) +{ + ulong total_req_size; + + mem_header_t* h; + + if (nquantas < MIN_POOL_ALLOC_QUANTAS) + nquantas = MIN_POOL_ALLOC_QUANTAS; + + total_req_size = nquantas * sizeof(mem_header_t); + + if (pool_free_pos + total_req_size <= POOL_SIZE) + { + h = (mem_header_t*) (pool + pool_free_pos); + h->s.size = nquantas; + memmgr_free((void*) (h + 1)); + pool_free_pos += total_req_size; + } + else + { + return 0; + } + + return freep; +} + + +// Allocations are done in 'quantas' of header size. +// The search for a free block of adequate size begins at the point 'freep' +// where the last block was found. +// If a too-big block is found, it is split and the tail is returned (this +// way the header of the original needs only to have its size adjusted). +// The pointer returned to the user points to the free space within the block, +// which begins one quanta after the header. +// +void* memmgr_alloc(ulong nbytes) +{ + mem_header_t* p; + mem_header_t* prevp; + + // Calculate how many quantas are required: we need enough to house all + // the requested bytes, plus the header. The -1 and +1 are there to make sure + // that if nbytes is a multiple of nquantas, we don't allocate too much + // + ulong nquantas = (nbytes + sizeof(mem_header_t) - 1) / sizeof(mem_header_t) + 1; + + // First alloc call, and no free list yet ? Use 'base' for an initial + // denegerate block of size 0, which points to itself + // + if ((prevp = freep) == 0) + { + base.s.next = freep = prevp = &base; + base.s.size = 0; + } + + for (p = prevp->s.next; ; prevp = p, p = p->s.next) + { + // big enough ? + if (p->s.size >= nquantas) + { + // exactly ? + if (p->s.size == nquantas) + { + // just eliminate this block from the free list by pointing + // its prev's next to its next + // + prevp->s.next = p->s.next; + } + else // too big + { + p->s.size -= nquantas; + p += p->s.size; + p->s.size = nquantas; + } + + freep = prevp; + return (void*) (p + 1); + } + // Reached end of free list ? + // Try to allocate the block from the pool. If that succeeds, + // get_mem_from_pool adds the new block to the free list and + // it will be found in the following iterations. If the call + // to get_mem_from_pool doesn't succeed, we've run out of + // memory + // + else if (p == freep) + { + if ((p = get_mem_from_pool(nquantas)) == 0) + { + #ifdef DEBUG_MEMMGR_FATAL + printf("!! Memory allocation failed !!\n"); + #endif + return 0; + } + } + } +} + + +// Scans the free list, starting at freep, looking the the place to insert the +// free block. This is either between two existing blocks or at the end of the +// list. In any case, if the block being freed is adjacent to either neighbor, +// the adjacent blocks are combined. +// +void memmgr_free(void* ap) +{ + mem_header_t* block; + mem_header_t* p; + + // acquire pointer to block header + block = ((mem_header_t*) ap) - 1; + + // Find the correct place to place the block in (the free list is sorted by + // address, increasing order) + // + for (p = freep; !(block > p && block < p->s.next); p = p->s.next) + { + // Since the free list is circular, there is one link where a + // higher-addressed block points to a lower-addressed block. + // This condition checks if the block should be actually + // inserted between them + // + if (p >= p->s.next && (block > p || block < p->s.next)) + break; + } + + // Try to combine with the higher neighbor + // + if (block + block->s.size == p->s.next) + { + block->s.size += p->s.next->s.size; + block->s.next = p->s.next->s.next; + } + else + { + block->s.next = p->s.next; + } + + // Try to combine with the lower neighbor + // + if (p + p->s.size == block) + { + p->s.size += block->s.size; + p->s.next = block->s.next; + } + else + { + p->s.next = block; + } + + freep = p; +} diff --git a/packages/romdev-pycparser/test/fixtures/c_files/memmgr.h b/packages/romdev-pycparser/test/fixtures/c_files/memmgr.h new file mode 100644 index 00000000..8eee907f --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/memmgr.h @@ -0,0 +1,96 @@ +//---------------------------------------------------------------- +// Statically-allocated memory manager +// +// by Eli Bendersky (eliben@gmail.com) +// +// This code is in the public domain. +//---------------------------------------------------------------- +#ifndef MEMMGR_H +#define MEMMGR_H + +// +// Memory manager: dynamically allocates memory from +// a fixed pool that is allocated statically at link-time. +// +// Usage: after calling memmgr_init() in your +// initialization routine, just use memmgr_alloc() instead +// of malloc() and memmgr_free() instead of free(). +// Naturally, you can use the preprocessor to define +// malloc() and free() as aliases to memmgr_alloc() and +// memmgr_free(). This way the manager will be a drop-in +// replacement for the standard C library allocators, and can +// be useful for debugging memory allocation problems and +// leaks. +// +// Preprocessor flags you can define to customize the +// memory manager: +// +// DEBUG_MEMMGR_FATAL +// Allow printing out a message when allocations fail +// +// DEBUG_MEMMGR_SUPPORT_STATS +// Allow printing out of stats in function +// memmgr_print_stats When this is disabled, +// memmgr_print_stats does nothing. +// +// Note that in production code on an embedded system +// you'll probably want to keep those undefined, because +// they cause printf to be called. +// +// POOL_SIZE +// Size of the pool for new allocations. This is +// effectively the heap size of the application, and can +// be changed in accordance with the available memory +// resources. +// +// MIN_POOL_ALLOC_QUANTAS +// Internally, the memory manager allocates memory in +// quantas roughly the size of two ulong objects. To +// minimize pool fragmentation in case of multiple allocations +// and deallocations, it is advisable to not allocate +// blocks that are too small. +// This flag sets the minimal amount of quantas for +// an allocation. If the size of a ulong is 4 and you +// set this flag to 16, the minimal size of an allocation +// will be 4 * 2 * 16 = 128 bytes +// If you have a lot of small allocations, keep this value +// low to conserve memory. If you have mostly large +// allocations, it is best to make it higher, to avoid +// fragmentation. +// +// Notes: +// 1. This memory manager is *not thread safe*. Use it only +// for single thread/task applications. +// + +#define DEBUG_MEMMGR_SUPPORT_STATS 1 + +#define POOL_SIZE 8 * 1024 +#define MIN_POOL_ALLOC_QUANTAS 16 + + +typedef unsigned char byte; +typedef unsigned long ulong; + + + +// Initialize the memory manager. This function should be called +// only once in the beginning of the program. +// +void memmgr_init(); + +// 'malloc' clone +// +void* memmgr_alloc(ulong nbytes); + +// 'free' clone +// +void memmgr_free(void* ap); + +// Prints statistics about the current state of the memory +// manager +// +void memmgr_print_stats(); + + +#endif // MEMMGR_H diff --git a/packages/romdev-pycparser/test/fixtures/c_files/memmgr_with_h.c b/packages/romdev-pycparser/test/fixtures/c_files/memmgr_with_h.c new file mode 100644 index 00000000..8ea6ff6d --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/memmgr_with_h.c @@ -0,0 +1,350 @@ +#line 1 "memmgr.c" + + + + + + + +#line 1 "./memmgr.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +typedef unsigned char byte; +typedef unsigned long ulong; + + + + + + +void memmgr_init(); + + + +void* memmgr_alloc(ulong nbytes); + + + +void memmgr_free(void* ap); + + + + +void memmgr_print_stats(); + + + +#line 9 "memmgr.c" + +typedef ulong Align; + +union mem_header_union +{ + struct + { + + + union mem_header_union* next; + + + + ulong size; + } s; + + + + Align align_dummy; +}; + +typedef union mem_header_union mem_header_t; + + + +static mem_header_t base; + + + +static mem_header_t* freep = 0; + + + +static byte pool[8 * 1024] = {0}; +static ulong pool_free_pos = 0; + + +void memmgr_init() +{ + base.s.next = 0; + base.s.size = 0; + freep = 0; + pool_free_pos = 0; +} + + +void memmgr_print_stats() +{ + + mem_header_t* p; + + printf("------ Memory manager stats ------\n\n"); + printf( "Pool: free_pos = %lu (%lu bytes left)\n\n", + pool_free_pos,8 * 1024 - pool_free_pos); + + p = (mem_header_t*) pool; + + while (p < (mem_header_t*) (pool + pool_free_pos)) + { + printf( " * Addr: 0x%8lu; Size: %8lu\n", + p, p->s.size); + + p += p->s.size; + } + + printf("\nFree list:\n\n"); + + if (freep) + { + p = freep; + + while (1) + { + printf( " * Addr: 0x%8lu; Size: %8lu; Next: 0x%8lu\n", + p, p->s.size, p->s.next); + + p = p->s.next; + + if (p == freep) + break; + } + } + else + { + printf("Empty\n"); + } + + printf("\n"); + +} + + +static mem_header_t* get_mem_from_pool(ulong nquantas) +{ + ulong total_req_size; + + mem_header_t* h; + + if (nquantas < 16) + nquantas = 16; + + total_req_size = nquantas * sizeof(mem_header_t); + + if (pool_free_pos + total_req_size <= 8 * 1024) + { + h = (mem_header_t*) (pool + pool_free_pos); + h->s.size = nquantas; + memmgr_free((void*) (h + 1)); + pool_free_pos += total_req_size; + } + else + { + return 0; + } + + return freep; +} + + + + + + + + + + +void* memmgr_alloc(ulong nbytes) +{ + mem_header_t* p; + mem_header_t* prevp; + + + + + + ulong nquantas = (nbytes + sizeof(mem_header_t) - 1) / sizeof(mem_header_t) + 1; + + + + + if ((prevp = freep) == 0) + { + base.s.next = freep = prevp = &base; + base.s.size = 0; + } + + for (p = prevp->s.next; ; prevp = p, p = p->s.next) + { + + if (p->s.size >= nquantas) + { + + if (p->s.size == nquantas) + { + + + + prevp->s.next = p->s.next; + } + else + { + p->s.size -= nquantas; + p += p->s.size; + p->s.size = nquantas; + } + + freep = prevp; + return (void*) (p + 1); + } + + + + + + + + else if (p == freep) + { + if ((p = get_mem_from_pool(nquantas)) == 0) + { + + + + return 0; + } + } + } +} + + + + + + + +void memmgr_free(void* ap) +{ + mem_header_t* block; + mem_header_t* p; + + + block = ((mem_header_t*) ap) - 1; + + + + + for (p = freep; !(block > p && block < p->s.next); p = p->s.next) + { + + + + + + if (p >= p->s.next && (block > p || block < p->s.next)) + break; + } + + + + if (block + block->s.size == p->s.next) + { + block->s.size += p->s.next->s.size; + block->s.next = p->s.next->s.next; + } + else + { + block->s.next = p->s.next; + } + + + + if (p + p->s.size == block) + { + p->s.size += block->s.size; + p->s.next = block->s.next; + } + else + { + p->s.next = block; + } + + freep = p; +} diff --git a/packages/romdev-pycparser/test/fixtures/c_files/simplemain.c b/packages/romdev-pycparser/test/fixtures/c_files/simplemain.c new file mode 100644 index 00000000..abbe5d83 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/simplemain.c @@ -0,0 +1,5 @@ +#include "hdir\emptydir\..\9\inc.h" + +int main() { + return 0; +} diff --git a/packages/romdev-pycparser/test/fixtures/c_files/year.c b/packages/romdev-pycparser/test/fixtures/c_files/year.c new file mode 100644 index 00000000..eb33c1f6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/c_files/year.c @@ -0,0 +1,60 @@ +#include +#include +#include +#include + +/* C99 bools */ +_Bool just_a_flag = false; +bool another_flag = true; + +void convert(int thousands, int hundreds, int tens, int ones) +{ +char *num[] = {"", "One", "Two", "Three", "Four", "Five", "Six", + "Seven", "Eight", "Nine"}; + +char *for_ten[] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", + "Seventy", "Eighty", "Ninety"}; + +char *af_ten[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", + "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Ninteen"}; + + printf("\nThe year in words is:\n"); + + printf("%s thousand", num[thousands]); + if (hundreds != 0) + printf(" %s hundred", num[hundreds]); + + if (tens != 1) + printf(" %s %s", for_ten[tens], num[ones]); + else + printf(" %s", af_ten[ones]); + + va_list jajaja; +} + + +int main() +{ +int year; +int n1000, n100, n10, n1; + + printf("\nEnter the year (4 digits): "); + scanf("%d", &year); + + if (year > 9999 || year < 1000) + { + printf("\nError !! The year must contain 4 digits."); + exit(EXIT_FAILURE); + } + + n1000 = year/1000; + n100 = ((year)%1000)/100; + n10 = (year%100)/10; + n1 = ((year%10)%10); + + convert(n1000, n100, n10, n1); + +return 0; +} + + diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/Intrinsic.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/Intrinsic.h new file mode 100644 index 00000000..ab7ebb36 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/Intrinsic.h @@ -0,0 +1,4 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" +#include "_X11_fake_defines.h" +#include "_X11_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/Xlib.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/Xlib.h new file mode 100644 index 00000000..ab7ebb36 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/Xlib.h @@ -0,0 +1,4 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" +#include "_X11_fake_defines.h" +#include "_X11_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/_X11_fake_defines.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/_X11_fake_defines.h new file mode 100644 index 00000000..c88774bb --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/_X11_fake_defines.h @@ -0,0 +1,16 @@ +#ifndef _X11_FAKE_DEFINES_H +#define _X11_FAKE_DEFINES_H + +#define Atom CARD32 +#define Bool int +#define KeySym CARD32 +#define Pixmap CARD32 +#define Time CARD32 +#define _XFUNCPROTOBEGIN +#define _XFUNCPROTOEND +#define _Xconst const + +#define _X_RESTRICT_KYWD +#define Cardinal unsigned int +#define Boolean int +#endif diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/_X11_fake_typedefs.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/_X11_fake_typedefs.h new file mode 100644 index 00000000..39011421 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/X11/_X11_fake_typedefs.h @@ -0,0 +1,38 @@ +#ifndef _X11_FAKE_TYPEDEFS_H +#define _X11_FAKE_TYPEDEFS_H + +typedef char* XPointer; +typedef unsigned char KeyCode; +typedef unsigned int CARD32; +typedef unsigned long VisualID; +typedef unsigned long XIMResetState; +typedef unsigned long XID; +typedef XID Window; +typedef XID Colormap; +typedef XID Cursor; +typedef XID Drawable; +typedef void* XtPointer; +typedef XtPointer XtRequestId; +typedef struct Display Display; +typedef struct Screen Screen; +typedef struct Status Status; +typedef struct Visual Visual; +typedef struct Widget *Widget; +typedef struct XColor XColor; +typedef struct XClassHint XClassHint; +typedef struct XEvent XEvent; +typedef struct XFontStruct XFontStruct; +typedef struct XGCValues XGCValues; +typedef struct XKeyEvent XKeyEvent; +typedef struct XKeyPressedEvent XKeyPressedEvent; +typedef struct XPoint XPoint; +typedef struct XRectangle XRectangle; +typedef struct XSelectionRequestEvent XSelectionRequestEvent; +typedef struct XWindowChanges XWindowChanges; +typedef struct _XGC _XCG; +typedef struct _XGC *GC; +typedef struct _XIC *XIC; +typedef struct _XIM *XIM; +typedef struct _XImage XImage; + +#endif diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/_ansi.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/_ansi.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/_ansi.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/_fake_defines.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/_fake_defines.h new file mode 100644 index 00000000..852744a6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/_fake_defines.h @@ -0,0 +1,262 @@ +#ifndef _FAKE_DEFINES_H +#define _FAKE_DEFINES_H + +#define NULL 0 +#define BUFSIZ 1024 +#define FOPEN_MAX 20 +#define FILENAME_MAX 1024 + +#ifndef SEEK_SET +#define SEEK_SET 0 /* set file offset to offset */ +#endif +#ifndef SEEK_CUR +#define SEEK_CUR 1 /* set file offset to current plus offset */ +#endif +#ifndef SEEK_END +#define SEEK_END 2 /* set file offset to EOF plus offset */ +#endif + +#define __LITTLE_ENDIAN 1234 +#define LITTLE_ENDIAN __LITTLE_ENDIAN +#define __BIG_ENDIAN 4321 +#define BIG_ENDIAN __BIG_ENDIAN +#define __BYTE_ORDER __LITTLE_ENDIAN +#define BYTE_ORDER __BYTE_ORDER + +#define EXIT_FAILURE 1 +#define EXIT_SUCCESS 0 + +#define SCHAR_MIN -128 +#define SCHAR_MAX 127 +#define CHAR_MIN -128 +#define CHAR_MAX 127 +#define UCHAR_MAX 255 +#define SHRT_MIN -32768 +#define SHRT_MAX 32767 +#define USHRT_MAX 65535 +#define INT_MIN -2147483648 +#define INT_MAX 2147483647 +#define UINT_MAX 4294967295U +#define LONG_MIN -9223372036854775808L +#define LONG_MAX 9223372036854775807L +#define ULONG_MAX 18446744073709551615UL +#define RAND_MAX 32767 + +/* C99 inttypes.h defines */ +#define PRId8 "d" +#define PRIi8 "i" +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRId16 "d" +#define PRIi16 "i" +#define PRIo16 "o" +#define PRIu16 "u" +#define PRIx16 "x" +#define PRIX16 "X" +#define PRId32 "d" +#define PRIi32 "i" +#define PRIo32 "o" +#define PRIu32 "u" +#define PRIx32 "x" +#define PRIX32 "X" +#define PRId64 "d" +#define PRIi64 "i" +#define PRIo64 "o" +#define PRIu64 "u" +#define PRIx64 "x" +#define PRIX64 "X" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIdLEAST16 "d" +#define PRIiLEAST16 "i" +#define PRIoLEAST16 "o" +#define PRIuLEAST16 "u" +#define PRIxLEAST16 "x" +#define PRIXLEAST16 "X" +#define PRIdLEAST32 "d" +#define PRIiLEAST32 "i" +#define PRIoLEAST32 "o" +#define PRIuLEAST32 "u" +#define PRIxLEAST32 "x" +#define PRIXLEAST32 "X" +#define PRIdLEAST64 "d" +#define PRIiLEAST64 "i" +#define PRIoLEAST64 "o" +#define PRIuLEAST64 "u" +#define PRIxLEAST64 "x" +#define PRIXLEAST64 "X" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" +#define PRIdFAST16 "d" +#define PRIiFAST16 "i" +#define PRIoFAST16 "o" +#define PRIuFAST16 "u" +#define PRIxFAST16 "x" +#define PRIXFAST16 "X" +#define PRIdFAST32 "d" +#define PRIiFAST32 "i" +#define PRIoFAST32 "o" +#define PRIuFAST32 "u" +#define PRIxFAST32 "x" +#define PRIXFAST32 "X" +#define PRIdFAST64 "d" +#define PRIiFAST64 "i" +#define PRIoFAST64 "o" +#define PRIuFAST64 "u" +#define PRIxFAST64 "x" +#define PRIXFAST64 "X" +#define PRIdPTR "d" +#define PRIiPTR "i" +#define PRIoPTR "o" +#define PRIuPTR "u" +#define PRIxPTR "x" +#define PRIXPTR "X" +#define PRIdMAX "d" +#define PRIiMAX "i" +#define PRIoMAX "o" +#define PRIuMAX "u" +#define PRIxMAX "x" +#define PRIXMAX "X" +#define SCNd8 "d" +#define SCNi8 "i" +#define SCNo8 "o" +#define SCNu8 "u" +#define SCNx8 "x" +#define SCNd16 "d" +#define SCNi16 "i" +#define SCNo16 "o" +#define SCNu16 "u" +#define SCNx16 "x" +#define SCNd32 "d" +#define SCNi32 "i" +#define SCNo32 "o" +#define SCNu32 "u" +#define SCNx32 "x" +#define SCNd64 "d" +#define SCNi64 "i" +#define SCNo64 "o" +#define SCNu64 "u" +#define SCNx64 "x" +#define SCNdLEAST8 "d" +#define SCNiLEAST8 "i" +#define SCNoLEAST8 "o" +#define SCNuLEAST8 "u" +#define SCNxLEAST8 "x" +#define SCNdLEAST16 "d" +#define SCNiLEAST16 "i" +#define SCNoLEAST16 "o" +#define SCNuLEAST16 "u" +#define SCNxLEAST16 "x" +#define SCNdLEAST32 "d" +#define SCNiLEAST32 "i" +#define SCNoLEAST32 "o" +#define SCNuLEAST32 "u" +#define SCNxLEAST32 "x" +#define SCNdLEAST64 "d" +#define SCNiLEAST64 "i" +#define SCNoLEAST64 "o" +#define SCNuLEAST64 "u" +#define SCNxLEAST64 "x" +#define SCNdFAST8 "d" +#define SCNiFAST8 "i" +#define SCNoFAST8 "o" +#define SCNuFAST8 "u" +#define SCNxFAST8 "x" +#define SCNdFAST16 "d" +#define SCNiFAST16 "i" +#define SCNoFAST16 "o" +#define SCNuFAST16 "u" +#define SCNxFAST16 "x" +#define SCNdFAST32 "d" +#define SCNiFAST32 "i" +#define SCNoFAST32 "o" +#define SCNuFAST32 "u" +#define SCNxFAST32 "x" +#define SCNdFAST64 "d" +#define SCNiFAST64 "i" +#define SCNoFAST64 "o" +#define SCNuFAST64 "u" +#define SCNxFAST64 "x" +#define SCNdPTR "d" +#define SCNiPTR "i" +#define SCNoPTR "o" +#define SCNuPTR "u" +#define SCNxPTR "x" +#define SCNdMAX "d" +#define SCNiMAX "i" +#define SCNoMAX "o" +#define SCNuMAX "u" +#define SCNxMAX "x" + +/* C99 stdbool.h defines */ +#define __bool_true_false_are_defined 1 +#define false 0 +#define true 1 + +/* va_arg macros and type*/ +#define va_start(_ap, _type) __builtin_va_start((_ap)) +#define va_arg(_ap, _type) __builtin_va_arg((_ap)) +#define va_end(_list) + +/* Vectors */ +#define __m128 int +#define __m128_u int +#define __m128d int +#define __m128d_u int +#define __m128i int +#define __m128i_u int +#define __m256 int +#define __m256_u int +#define __m256d int +#define __m256d_u int +#define __m256i int +#define __m256i_u int +#define __m512 int +#define __m512_u int +#define __m512d int +#define __m512d_u int +#define __m512i int +#define __m512i_u int + +/* C11 stdnoreturn.h defines */ +#define __noreturn_is_defined 1 +#define noreturn _Noreturn + +/* C11 threads.h defines */ +#define thread_local _Thread_local + +/* C11 assert.h defines */ +#define static_assert _Static_assert + +/* C11 stdatomic.h defines */ +#define ATOMIC_BOOL_LOCK_FREE 0 +#define ATOMIC_CHAR_LOCK_FREE 0 +#define ATOMIC_CHAR16_T_LOCK_FREE 0 +#define ATOMIC_CHAR32_T_LOCK_FREE 0 +#define ATOMIC_WCHAR_T_LOCK_FREE 0 +#define ATOMIC_SHORT_LOCK_FREE 0 +#define ATOMIC_INT_LOCK_FREE 0 +#define ATOMIC_LONG_LOCK_FREE 0 +#define ATOMIC_LLONG_LOCK_FREE 0 +#define ATOMIC_POINTER_LOCK_FREE 0 +#define ATOMIC_VAR_INIT(value) (value) +#define ATOMIC_FLAG_INIT { 0 } +#define kill_dependency(y) (y) + +/* C11 stdalign.h defines */ +#define alignas _Alignas +#define alignof _Alignof +#define __alignas_is_defined 1 +#define __alignof_is_defined 1 + +#endif diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/_fake_typedefs.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/_fake_typedefs.h new file mode 100644 index 00000000..b52d93ba --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/_fake_typedefs.h @@ -0,0 +1,236 @@ +#ifndef _FAKE_TYPEDEFS_H +#define _FAKE_TYPEDEFS_H + +typedef int size_t; +typedef int __builtin_va_list; +typedef int __gnuc_va_list; +typedef int va_list; +typedef int __int8_t; +typedef int __uint8_t; +typedef int __int16_t; +typedef int __uint16_t; +typedef int __int_least16_t; +typedef int __uint_least16_t; +typedef int __int32_t; +typedef int __uint32_t; +typedef int __int64_t; +typedef int __uint64_t; +typedef int __int_least32_t; +typedef int __uint_least32_t; +typedef int __s8; +typedef int __u8; +typedef int __s16; +typedef int __u16; +typedef int __s32; +typedef int __u32; +typedef int __s64; +typedef int __u64; +typedef int _LOCK_T; +typedef int _LOCK_RECURSIVE_T; +typedef int _off_t; +typedef int __dev_t; +typedef int __uid_t; +typedef int __gid_t; +typedef int _off64_t; +typedef int _fpos_t; +typedef int _ssize_t; +typedef int wint_t; +typedef int _mbstate_t; +typedef int _flock_t; +typedef int _iconv_t; +typedef int __ULong; +typedef int __FILE; +typedef int ptrdiff_t; +typedef int wchar_t; +typedef int char16_t; +typedef int char32_t; +typedef int __off_t; +typedef int __pid_t; +typedef int __loff_t; +typedef int u_char; +typedef int u_short; +typedef int u_int; +typedef int u_long; +typedef int ushort; +typedef int uint; +typedef int clock_t; +typedef int time_t; +typedef int daddr_t; +typedef int caddr_t; +typedef int ino_t; +typedef int off_t; +typedef int dev_t; +typedef int uid_t; +typedef int gid_t; +typedef int pid_t; +typedef int key_t; +typedef int ssize_t; +typedef int mode_t; +typedef int nlink_t; +typedef int fd_mask; +typedef int _types_fd_set; +typedef int clockid_t; +typedef int timer_t; +typedef int useconds_t; +typedef int suseconds_t; +typedef int FILE; +typedef int fpos_t; +typedef int cookie_read_function_t; +typedef int cookie_write_function_t; +typedef int cookie_seek_function_t; +typedef int cookie_close_function_t; +typedef int cookie_io_functions_t; +typedef int div_t; +typedef int ldiv_t; +typedef int lldiv_t; +typedef int sigset_t; +typedef int __sigset_t; +typedef int _sig_func_ptr; +typedef int sig_atomic_t; +typedef int __tzrule_type; +typedef int __tzinfo_type; +typedef int mbstate_t; +typedef int sem_t; +typedef int pthread_t; +typedef int pthread_attr_t; +typedef int pthread_mutex_t; +typedef int pthread_mutexattr_t; +typedef int pthread_cond_t; +typedef int pthread_condattr_t; +typedef int pthread_key_t; +typedef int pthread_once_t; +typedef int pthread_rwlock_t; +typedef int pthread_rwlockattr_t; +typedef int pthread_spinlock_t; +typedef int pthread_barrier_t; +typedef int pthread_barrierattr_t; +typedef int jmp_buf; +typedef int rlim_t; +typedef int sa_family_t; +typedef int sigjmp_buf; +typedef int stack_t; +typedef int siginfo_t; +typedef int z_stream; + +/* C99 exact-width integer types */ +typedef int int8_t; +typedef int uint8_t; +typedef int int16_t; +typedef int uint16_t; +typedef int int32_t; +typedef int uint32_t; +typedef int int64_t; +typedef int uint64_t; + +/* C99 minimum-width integer types */ +typedef int int_least8_t; +typedef int uint_least8_t; +typedef int int_least16_t; +typedef int uint_least16_t; +typedef int int_least32_t; +typedef int uint_least32_t; +typedef int int_least64_t; +typedef int uint_least64_t; + +/* C99 fastest minimum-width integer types */ +typedef int int_fast8_t; +typedef int uint_fast8_t; +typedef int int_fast16_t; +typedef int uint_fast16_t; +typedef int int_fast32_t; +typedef int uint_fast32_t; +typedef int int_fast64_t; +typedef int uint_fast64_t; + +/* C99 integer types capable of holding object pointers */ +typedef int intptr_t; +typedef int uintptr_t; + +/* C99 greatest-width integer types */ +typedef int intmax_t; +typedef int uintmax_t; + +/* C99 stdbool.h bool type. _Bool is built-in in C99 */ +typedef _Bool bool; + +/* GNU Extension for 64-bit targets */ +#ifdef __SIZEOF_INT128__ +typedef int __int128_t; +typedef int __uint128_t; +#endif /* __SIZEOF_INT128__ */ + +/* Mir typedefs */ +typedef void* MirEGLNativeWindowType; +typedef void* MirEGLNativeDisplayType; +typedef struct MirConnection MirConnection; +typedef struct MirSurface MirSurface; +typedef struct MirSurfaceSpec MirSurfaceSpec; +typedef struct MirScreencast MirScreencast; +typedef struct MirPromptSession MirPromptSession; +typedef struct MirBufferStream MirBufferStream; +typedef struct MirPersistentId MirPersistentId; +typedef struct MirBlob MirBlob; +typedef struct MirDisplayConfig MirDisplayConfig; + +/* xcb typedefs */ +typedef struct xcb_connection_t xcb_connection_t; +typedef uint32_t xcb_window_t; +typedef uint32_t xcb_visualid_t; + +/* dirent typedef */ +typedef void* DIR; + +/* socket typedefs */ +typedef __uint32_t __socklen_t; +typedef __socklen_t socklen_t; +typedef unsigned short __kernel_sa_family_t; + +/* C11 stdatomic.h types */ +typedef _Atomic(_Bool) atomic_bool; +typedef _Atomic(char) atomic_char; +typedef _Atomic(signed char) atomic_schar; +typedef _Atomic(unsigned char) atomic_uchar; +typedef _Atomic(short) atomic_short; +typedef _Atomic(unsigned short) atomic_ushort; +typedef _Atomic(int) atomic_int; +typedef _Atomic(unsigned int) atomic_uint; +typedef _Atomic(long) atomic_long; +typedef _Atomic(unsigned long) atomic_ulong; +typedef _Atomic(long long) atomic_llong; +typedef _Atomic(unsigned long long) atomic_ullong; +typedef _Atomic(uint_least16_t) atomic_char16_t; +typedef _Atomic(uint_least32_t) atomic_char32_t; +typedef _Atomic(wchar_t) atomic_wchar_t; +typedef _Atomic(int_least8_t) atomic_int_least8_t; +typedef _Atomic(uint_least8_t) atomic_uint_least8_t; +typedef _Atomic(int_least16_t) atomic_int_least16_t; +typedef _Atomic(uint_least16_t) atomic_uint_least16_t; +typedef _Atomic(int_least32_t) atomic_int_least32_t; +typedef _Atomic(uint_least32_t) atomic_uint_least32_t; +typedef _Atomic(int_least64_t) atomic_int_least64_t; +typedef _Atomic(uint_least64_t) atomic_uint_least64_t; +typedef _Atomic(int_fast8_t) atomic_int_fast8_t; +typedef _Atomic(uint_fast8_t) atomic_uint_fast8_t; +typedef _Atomic(int_fast16_t) atomic_int_fast16_t; +typedef _Atomic(uint_fast16_t) atomic_uint_fast16_t; +typedef _Atomic(int_fast32_t) atomic_int_fast32_t; +typedef _Atomic(uint_fast32_t) atomic_uint_fast32_t; +typedef _Atomic(int_fast64_t) atomic_int_fast64_t; +typedef _Atomic(uint_fast64_t) atomic_uint_fast64_t; +typedef _Atomic(intptr_t) atomic_intptr_t; +typedef _Atomic(uintptr_t) atomic_uintptr_t; +typedef _Atomic(size_t) atomic_size_t; +typedef _Atomic(ptrdiff_t) atomic_ptrdiff_t; +typedef _Atomic(intmax_t) atomic_intmax_t; +typedef _Atomic(uintmax_t) atomic_uintmax_t; +typedef struct atomic_flag { atomic_bool _Value; } atomic_flag; +typedef enum memory_order { + memory_order_relaxed, + memory_order_consume, + memory_order_acquire, + memory_order_release, + memory_order_acq_rel, + memory_order_seq_cst +} memory_order; + +#endif diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/_syslist.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/_syslist.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/_syslist.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/aio.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/aio.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/aio.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/alloca.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/alloca.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/alloca.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/ar.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ar.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ar.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/argz.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/argz.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/argz.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/arpa/inet.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/arpa/inet.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/arpa/inet.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/asm-generic/int-ll64.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/asm-generic/int-ll64.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/asm-generic/int-ll64.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/assert.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/assert.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/assert.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/complex.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/complex.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/complex.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/cpio.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/cpio.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/cpio.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/ctype.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ctype.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ctype.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/dirent.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/dirent.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/dirent.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/dlfcn.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/dlfcn.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/dlfcn.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/emmintrin.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/emmintrin.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/emmintrin.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/endian.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/endian.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/endian.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/envz.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/envz.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/envz.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/errno.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/errno.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/errno.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/fastmath.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fastmath.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fastmath.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/fcntl.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fcntl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fcntl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/features.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/features.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/features.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/fenv.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fenv.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fenv.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/float.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/float.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/float.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/fmtmsg.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fmtmsg.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fmtmsg.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/fnmatch.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fnmatch.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/fnmatch.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/ftw.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ftw.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ftw.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/getopt.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/getopt.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/getopt.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/glob.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/glob.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/glob.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/grp.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/grp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/grp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/iconv.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/iconv.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/iconv.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/ieeefp.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ieeefp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ieeefp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/immintrin.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/immintrin.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/immintrin.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/inttypes.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/inttypes.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/inttypes.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/iso646.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/iso646.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/iso646.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/langinfo.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/langinfo.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/langinfo.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/libgen.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/libgen.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/libgen.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/libintl.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/libintl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/libintl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/limits.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/limits.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/limits.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/linux/socket.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/linux/socket.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/linux/socket.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/linux/version.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/linux/version.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/linux/version.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/locale.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/locale.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/locale.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/malloc.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/malloc.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/malloc.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/math.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/math.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/math.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/mir_toolkit/client_types.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/mir_toolkit/client_types.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/mir_toolkit/client_types.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/monetary.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/monetary.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/monetary.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/mqueue.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/mqueue.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/mqueue.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/ndbm.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ndbm.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ndbm.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/net/if.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/net/if.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/net/if.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/netdb.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/netdb.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/netdb.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/netinet/in.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/netinet/in.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/netinet/in.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/netinet/tcp.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/netinet/tcp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/netinet/tcp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/newlib.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/newlib.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/newlib.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/nl_types.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/nl_types.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/nl_types.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/err.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/err.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/err.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/evp.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/evp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/evp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/hmac.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/hmac.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/hmac.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/ssl.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/ssl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/ssl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/x509v3.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/x509v3.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/openssl/x509v3.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/paths.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/paths.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/paths.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/poll.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/poll.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/poll.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/process.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/process.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/process.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/pthread.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/pthread.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/pthread.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/pwd.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/pwd.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/pwd.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/reent.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/reent.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/reent.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/regdef.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/regdef.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/regdef.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/regex.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/regex.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/regex.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sched.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sched.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sched.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/search.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/search.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/search.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/semaphore.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/semaphore.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/semaphore.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/setjmp.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/setjmp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/setjmp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/signal.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/signal.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/signal.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/smmintrin.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/smmintrin.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/smmintrin.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/spawn.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/spawn.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/spawn.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdalign.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdalign.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdalign.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdarg.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdarg.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdarg.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdatomic.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdatomic.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdatomic.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdbool.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdbool.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdbool.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stddef.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stddef.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stddef.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdint.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdint.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdint.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdio.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdio.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdio.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdlib.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdlib.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdlib.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdnoreturn.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdnoreturn.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stdnoreturn.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/string.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/string.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/string.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/strings.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/strings.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/strings.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/stropts.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stropts.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/stropts.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/ioctl.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/ioctl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/ioctl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/ipc.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/ipc.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/ipc.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/mman.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/mman.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/mman.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/msg.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/msg.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/msg.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/poll.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/poll.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/poll.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/resource.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/resource.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/resource.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/select.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/select.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/select.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/sem.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/sem.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/sem.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/shm.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/shm.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/shm.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/socket.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/socket.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/socket.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/stat.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/stat.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/stat.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/statvfs.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/statvfs.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/statvfs.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/sysctl.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/sysctl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/sysctl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/time.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/time.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/time.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/times.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/times.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/times.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/types.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/types.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/types.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/uio.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/uio.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/uio.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/un.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/un.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/un.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/utsname.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/utsname.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/utsname.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/wait.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/wait.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/sys/wait.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/syslog.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/syslog.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/syslog.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/tar.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/tar.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/tar.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/termios.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/termios.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/termios.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/tgmath.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/tgmath.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/tgmath.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/threads.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/threads.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/threads.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/time.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/time.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/time.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/trace.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/trace.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/trace.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/ulimit.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ulimit.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/ulimit.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/unctrl.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/unctrl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/unctrl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/unistd.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/unistd.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/unistd.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/utime.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/utime.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/utime.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/utmp.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/utmp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/utmp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/utmpx.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/utmpx.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/utmpx.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/wchar.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/wchar.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/wchar.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/wctype.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/wctype.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/wctype.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/wordexp.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/wordexp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/wordexp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/xcb/xcb.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/xcb/xcb.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/xcb/xcb.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/packages/romdev-pycparser/test/fixtures/fake_libc_include/zlib.h b/packages/romdev-pycparser/test/fixtures/fake_libc_include/zlib.h new file mode 100644 index 00000000..af326008 --- /dev/null +++ b/packages/romdev-pycparser/test/fixtures/fake_libc_include/zlib.h @@ -0,0 +1,33 @@ +#ifndef ZLIB_H +#define ZLIB_H + +#include "_fake_defines.h" +#include "_fake_typedefs.h" + +typedef int uInt; +typedef int uLong; +#if !defined(__MACTYPES__) +typedef int Byte; +#endif + +typedef int Bytef; +typedef int charf; +typedef int intf; +typedef int uIntf; +typedef int uLongf; + +typedef int voidpc; +typedef int voidpf; +typedef int voidp; + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +typedef int Z_U4; +#endif + +typedef int z_crc_t; +typedef int z_size_t; + +typedef int alloc_func; +typedef int free_func; + +#endif diff --git a/packages/romdev-pycparser/test/general.test.js b/packages/romdev-pycparser/test/general.test.js new file mode 100644 index 00000000..27e9b6b2 --- /dev/null +++ b/packages/romdev-pycparser/test/general.test.js @@ -0,0 +1,48 @@ +// Port of pycparser tests/test_general.py. +// +// Upstream's c_files fixtures and utils/fake_libc_include (pycparser b5c6024) +// are copied under fixtures/. use_cpp cases run through romdev's WASM cpp +// (see cpp.js); nothing is spawned on the host. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { parse_file, c_ast } from "../src/index.js"; +import { parse_file_with_cpp, C_FILES, FAKE_LIBC, CPP_SKIP } from "./cpp.js"; + +const cFile = (name) => fileURLToPath(new URL("./fixtures/c_files/" + name, import.meta.url)); +const missing = (name) => (existsSync(cFile(name)) ? false : `upstream fixture c_files/${name} is not shipped with the vendored fork`); + +test("without cpp", { skip: missing("example_c_file.c") }, () => { + const ast = parse_file(cFile("example_c_file.c")); + assert.ok(ast instanceof c_ast.FileAST); +}); + +test("with cpp", { skip: CPP_SKIP }, async () => { + const ast = await parse_file_with_cpp(cFile("memmgr.c"), ["-I" + C_FILES]); + assert.ok(ast instanceof c_ast.FileAST); + const ast2 = await parse_file_with_cpp(cFile("year.c"), ["-I" + FAKE_LIBC]); + assert.ok(ast2 instanceof c_ast.FileAST); +}); + +test("cpp funkydir", async () => { + // Upstream: "This test contains Windows specific path escapes" and returns + // early on every other platform; mirrored exactly. + if (process.platform !== "win32") return; + const ast = await parse_file_with_cpp(cFile("simplemain.c"), ["-I" + C_FILES]); + assert.ok(ast instanceof c_ast.FileAST); +}); + +test("no real content after cpp", { skip: CPP_SKIP }, async () => { + const ast = await parse_file_with_cpp(cFile("empty.h")); + assert.ok(ast instanceof c_ast.FileAST); +}); + +test("c11 with cpp", { skip: CPP_SKIP }, async () => { + const ast = await parse_file_with_cpp(cFile("c11.c"), ["-I" + FAKE_LIBC]); + assert.ok(ast instanceof c_ast.FileAST); +}); + +test("use_cpp without a preprocess function is refused", () => { + assert.throws(() => parse_file(cFile("empty.h"), { use_cpp: true }), /preprocess/); +}); diff --git a/packages/romdev-pycparser/test/helpers.js b/packages/romdev-pycparser/test/helpers.js new file mode 100644 index 00000000..09b505e6 --- /dev/null +++ b/packages/romdev-pycparser/test/helpers.js @@ -0,0 +1,29 @@ +// Shared helpers for the ported pycparser tests. +import { Node } from "../src/index.js"; + +function pyType(x) { + if (x === null || x === undefined) return "NoneType"; + if (Array.isArray(x)) return "list"; + if (x instanceof Node) return "node:" + x.constructor.name; + if (typeof x === "object") return "obj:" + x.constructor.name; + return typeof x; +} + +/** tests/test_c_generator.py compare_asts */ +export function compareAsts(ast1, ast2) { + if (pyType(ast1) !== pyType(ast2)) return false; + if (Array.isArray(ast1)) { + if (ast1.length !== ast2.length) return false; + for (let i = 0; i < ast1.length; i++) if (!compareAsts(ast1[i], ast2[i])) return false; + return true; + } + if (ast1 instanceof Node) { + for (const attr of ast1.attr_names) if (!compareAsts(ast1[attr], ast2[attr])) return false; + const c1 = ast1.children(), c2 = ast2.children(); + if (c1.length !== c2.length) return false; + for (let i = 0; i < c1.length; i++) if (!compareAsts(c1[i], c2[i])) return false; + return true; + } + if (ast1 == null) return true; + return ast1 === ast2; +} diff --git a/packages/romdev-rabbitizer/LICENSE b/packages/romdev-rabbitizer/LICENSE new file mode 100644 index 00000000..10a2aa35 --- /dev/null +++ b/packages/romdev-rabbitizer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Decompollaborate + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/romdev-rabbitizer/NOTICE b/packages/romdev-rabbitizer/NOTICE new file mode 100644 index 00000000..fd3c2e79 --- /dev/null +++ b/packages/romdev-rabbitizer/NOTICE @@ -0,0 +1,26 @@ +romdev-rabbitizer +================= + +This package ships rabbitizer, the MIPS instruction decoder, compiled from its +C library to WebAssembly, plus a JavaScript binding for it made for romdev. + +Components and attribution +-------------------------- + +1. rabbitizer + https://github.com/Decompollaborate/rabbitizer + Copyright (c) 2022 Decompollaborate. + Licensed under the MIT License (LICENSE). + wasm/rabbitizer-.wasm is built from the library's include/, + tables/ and src/ C sources at these commits: + 1.16.2 724a49a5b4dbfb99f1a9e6992e63964fd29c90c8 + 1.14.3 d5804fa488474830a47fbf9f3693048ec1e45589 + 1.13.0 1df4709dcc927d9d9cc5859a6e7eb98e864f8468 + The JS binding (src/) mirrors the API of rabbitizer's Python extension + module (the rabbitizer/ directory of the same repository); the enum tables + in csrc/rabbitizer_wasm.c follow that module's table macros. The upstream + C sources are available at the URL and commits above; the build recipe is + scripts/build-rabbitizer.sh in the romdev repository. + +2. romdev binding (src/, csrc/, test/) + Copyright (c) Luis Montes. Licensed under the MIT License. diff --git a/packages/romdev-rabbitizer/README.md b/packages/romdev-rabbitizer/README.md new file mode 100644 index 00000000..12fca3a5 --- /dev/null +++ b/packages/romdev-rabbitizer/README.md @@ -0,0 +1,70 @@ +# romdev-rabbitizer + +[rabbitizer](https://github.com/Decompollaborate/rabbitizer), the MIPS +instruction decoder, built from its C library to WebAssembly, with a +synchronous JavaScript binding that mirrors the API of rabbitizer's Python +module: the same class, method, property and enum names, the same argument +order and return values, and the same errors (Python exception names are kept +as the JS error `name`). No Python is needed. + +It ships three rabbitizer releases side by side, because each spimdisasm +release expects a specific one. It is part of +[romdev](https://github.com/monteslu/romdev). + +## Upstream and license + +- Upstream: rabbitizer (Decompollaborate), https://github.com/Decompollaborate/rabbitizer +- Built from these commits: + + | rabbitizer | commit | + |---|---| + | 1.16.2 | `724a49a5b4dbfb99f1a9e6992e63964fd29c90c8` | + | 1.14.3 | `d5804fa488474830a47fbf9f3693048ec1e45589` | + | 1.13.0 | `1df4709dcc927d9d9cc5859a6e7eb98e864f8468` | + +- License: MIT (rabbitizer and the romdev binding). See `LICENSE` and `NOTICE`. +- `wasm/rabbitizer-.wasm` is built by + `packages/romdevtools/scripts/build-rabbitizer.sh` in the romdev repo from the + library's C sources plus `csrc/rabbitizer_wasm.c` (the binding's C side, + shipped in this package). + +## How romdev uses it + +It is the instruction decoder under +[`romdev-spimdisasm`](https://www.npmjs.com/package/romdev-spimdisasm), which +[`romdev-splat`](https://www.npmjs.com/package/romdev-splat) uses to split and +disassemble N64 and PS1 decomp projects for romdevtools' `decomp` tool +(`decomp({op:'setup'})`, `decomp({op:'import'})`). spimdisasm 1.42.4 pairs with +rabbitizer 1.16.2, 1.39.3 with 1.14.3, and 1.35.0 with 1.13.0. + +## API + +```js +import * as rab from "romdev-rabbitizer/1.16.2"; + +const instr = new rab.Instruction(0x27BDFFE8); +instr.disassemble(); // "addiu $sp, $sp, -0x18" +``` + +Or pick a version at run time: + +```js +import { loadRabbitizerSync, VERSIONS } from "romdev-rabbitizer"; + +const rab = loadRabbitizerSync("1.14.3"); // one shared namespace per version +``` + +Exports: `.` (`loadRabbitizerSync`, async `loadRabbitizer`, `VERSIONS`, +`DEFAULT_VERSION`, the error classes) and `./1.16.2`, `./1.14.3`, `./1.13.0` +(each version's module namespace, loaded at import: `Instruction`, `config`, +`Utils`, `RegistersTracker`, the enums and the rest of the Python module's +names). Everything is synchronous. Like the Python module, `config` is global +per version. + +## Requirements + +Node >= 24, ESM only. No dependencies, no Python, no native code. + +## Versions + +romdev-rabbitizer 0.1.0 ships rabbitizer 1.16.2, 1.14.3 and 1.13.0. diff --git a/packages/romdev-rabbitizer/csrc/dump_test_entries.c b/packages/romdev-rabbitizer/csrc/dump_test_entries.c new file mode 100644 index 00000000..35fc4be3 --- /dev/null +++ b/packages/romdev-rabbitizer/csrc/dump_test_entries.c @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Build-time helper (never shipped): compiled together with one of the + * upstream tests/c/instruction_checks C files (built with AVOID_DEF_MAIN) + * to print that file's test_entries table as JSON lines, so the JS binding + * can be checked against every upstream expected disassembly string. + * Usage (see build-rabbitizer.sh): emcc -DAVOID_DEF_MAIN -include dump_test_entries.c ... + */ + +#include + +static void print_json_string(const char *s) { + if (s == NULL) { + fputs("null", stdout); + return; + } + putchar('"'); + for (; *s != '\0'; s++) { + unsigned char c = (unsigned char)*s; + if (c == '"' || c == '\\') { + printf("\\%c", c); + } else if (c < 0x20) { + printf("\\u%04x", c); + } else { + putchar(c); + } + } + putchar('"'); +} + +int main(void) { + for (size_t i = 0; i < test_entries_len; i++) { + const TestEntry *e = &test_entries[i]; + + printf("{\"category\":%d,\"word\":%u,\"immOverride\":", (int)e->category, (unsigned)e->word); + print_json_string(e->immOverride); + fputs(",\"expected\":", stdout); + print_json_string(e->expectedStr); + printf(",\"gnuMode\":%s}\n", e->gnuMode ? "true" : "false"); + } + return 0; +} diff --git a/packages/romdev-rabbitizer/csrc/rabbitizer_wasm.c b/packages/romdev-rabbitizer/csrc/rabbitizer_wasm.c new file mode 100644 index 00000000..0a9af844 --- /dev/null +++ b/packages/romdev-rabbitizer/csrc/rabbitizer_wasm.c @@ -0,0 +1,621 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Flat C export layer over the rabbitizer C library, compiled together with it + * into one standalone WASM module per rabbitizer version. src/index.js wraps + * these exports in classes that mirror the Python `rabbitizer` extension + * module (the rabbitizer/ directory C sources in the upstream repo). Every export is a thin call + * into the library; argument checks and Python-shaped errors live in JS. + * + * An Instruction's struct words live in its JS object and are copied into a + * static slot per call (see rab_instr_slot); a RegistersTracker is a malloc'd + * RabbitizerRegistersTracker. Pointers are passed to JS as i32. + */ + +#include +#include +#include +#include +#include + +#include "rabbitizer.h" + +#define EXPORT __attribute__((used, visibility("default"))) + +/* ------------------------------------------------------------------ */ +/* Version */ +/* ------------------------------------------------------------------ */ + +EXPORT int rab_version_major(void) { return RabVersion_Major; } +EXPORT int rab_version_minor(void) { return RabVersion_Minor; } +EXPORT int rab_version_patch(void) { return RabVersion_Patch; } +EXPORT const char *rab_version_str(void) { return RabVersion_Str; } +EXPORT const char *rab_version_author(void) { return RabVersion_Author; } + +/* ------------------------------------------------------------------ */ +/* Enum metadata, built with the same table includes and macros as the */ +/* Python binding sources in rabbitizer/enums/, so member names, order and */ +/* values match that version exactly. */ +/* ------------------------------------------------------------------ */ + +typedef struct RabEnumEntry { + const char *name; + int value; +} RabEnumEntry; + +#define RABBITIZER_DEF_ABI(name) { #name, RABBITIZER_ABI_##name }, +static const RabEnumEntry enum_Abi[] = { +#include "tables/Abi.inc" + RABBITIZER_DEF_ABI(MAX) +}; +#undef RABBITIZER_DEF_ABI + +#define RABBITIZER_DEF_INSTR_CATEGORY(name) { #name, RABBITIZER_INSTRCAT_##name }, +static const RabEnumEntry enum_InstrCategory[] = { +#include "tables/InstrCategory.inc" + RABBITIZER_DEF_INSTR_CATEGORY(MAX) +}; +#undef RABBITIZER_DEF_INSTR_CATEGORY + +#define RABBITIZER_DEF_INSTR_ID(prefix, caseBits, name, ...) { #prefix "_" #name, RABBITIZER_INSTR_ID_##prefix##_##name }, +#define RABBITIZER_DEF_INSTR_ID_ALTNAME(prefix, caseBits, name, altname, ...) RABBITIZER_DEF_INSTR_ID(prefix, caseBits, name, __VA_ARGS__) +static const RabEnumEntry enum_InstrId[] = { +#include "tables/InstrIds.inc" + RABBITIZER_DEF_INSTR_ID(ALL, , MAX, ) +}; +#undef RABBITIZER_DEF_INSTR_ID +#undef RABBITIZER_DEF_INSTR_ID_ALTNAME + +#define RABBITIZER_DEF_INSTR_ID_TYPE(prefix, name) { #prefix "_" #name, RAB_INSTR_ID_TYPE_##prefix##_##name }, +static const RabEnumEntry enum_InstrIdType[] = { +#include "tables/InstrIdType.inc" +}; +#undef RABBITIZER_DEF_INSTR_ID_TYPE + +#define RAB_DEF_OPERAND(prefix, operand) { #prefix "_" #operand, RAB_OPERAND_##prefix##_##operand }, +static const RabEnumEntry enum_OperandType[] = { + RAB_DEF_OPERAND(ALL, INVALID) +#include "tables/OperandTypes.inc" + RAB_DEF_OPERAND(ALL, MAX) +}; +#undef RAB_DEF_OPERAND + +#define RAB_DEF_ACCESSTYPE(name) { #name, RAB_ACCESSTYPE_##name }, +static const RabEnumEntry enum_AccessType[] = { +#include "tables/AccessType.inc" + RAB_DEF_ACCESSTYPE(MAX) +}; +#undef RAB_DEF_ACCESSTYPE + +#define RABBITIZER_DEF_REG(prefix, name, numeric, ...) { #name, RABBITIZER_REG_##prefix##_##name }, +#define RABBITIZER_DEF_REG_NODOLLAR(prefix, name, numeric, ...) RABBITIZER_DEF_REG(prefix, name, numeric) +static const RabEnumEntry enum_RegGprO32[] = { +#include "tables/registers/RabbitizerRegister_GprO32.inc" +}; +static const RabEnumEntry enum_RegGprN32[] = { +#include "tables/registers/RabbitizerRegister_GprN32.inc" +}; +static const RabEnumEntry enum_RegCop1O32[] = { +#include "tables/registers/RabbitizerRegister_Cop1O32.inc" +}; +static const RabEnumEntry enum_RegCop1N32[] = { +#include "tables/registers/RabbitizerRegister_Cop1N32.inc" +}; +static const RabEnumEntry enum_RegCop1N64[] = { +#include "tables/registers/RabbitizerRegister_Cop1N64.inc" +}; +#undef RABBITIZER_DEF_REG +#undef RABBITIZER_DEF_REG_NODOLLAR + +static const RabEnumEntry enum_TrinaryValue[] = { + { "NONE", RAB_TRINARY_VAL_NONE }, + { "FALSE", RAB_TRINARY_VAL_FALSE }, + { "TRUE", RAB_TRINARY_VAL_TRUE }, +}; + +#define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0])) + +typedef struct RabEnumTable { + const char *typeName; + const RabEnumEntry *entries; + int count; +} RabEnumTable; + +/* Same order as the Python module's attribute table. */ +static const RabEnumTable enum_tables[] = { + { "Abi", enum_Abi, ARRAY_LEN(enum_Abi) }, + { "InstrCategory", enum_InstrCategory, ARRAY_LEN(enum_InstrCategory) }, + { "InstrId", enum_InstrId, ARRAY_LEN(enum_InstrId) }, + { "InstrIdType", enum_InstrIdType, ARRAY_LEN(enum_InstrIdType) }, + { "OperandType", enum_OperandType, ARRAY_LEN(enum_OperandType) }, + { "AccessType", enum_AccessType, ARRAY_LEN(enum_AccessType) }, + { "RegGprO32", enum_RegGprO32, ARRAY_LEN(enum_RegGprO32) }, + { "RegGprN32", enum_RegGprN32, ARRAY_LEN(enum_RegGprN32) }, + { "RegCop1O32", enum_RegCop1O32, ARRAY_LEN(enum_RegCop1O32) }, + { "RegCop1N32", enum_RegCop1N32, ARRAY_LEN(enum_RegCop1N32) }, + { "RegCop1N64", enum_RegCop1N64, ARRAY_LEN(enum_RegCop1N64) }, + { "TrinaryValue", enum_TrinaryValue, ARRAY_LEN(enum_TrinaryValue) }, +}; + +EXPORT int rab_enum_table_count(void) { return ARRAY_LEN(enum_tables); } +EXPORT const char *rab_enum_table_name(int t) { return enum_tables[t].typeName; } +EXPORT int rab_enum_count(int t) { return enum_tables[t].count; } +EXPORT const char *rab_enum_name(int t, int i) { return enum_tables[t].entries[i].name; } +EXPORT int rab_enum_value(int t, int i) { return enum_tables[t].entries[i].value; } + +EXPORT int rab_abi_fromStr(const char *name) { return RabbitizerAbi_fromStr(name); } +EXPORT int rab_instrCategory_fromStr(const char *name) { return (int)RabbitizerInstrCategory_fromStr(name); } + +/* ------------------------------------------------------------------ */ +/* Global config (rabbitizer.config) */ +/* ------------------------------------------------------------------ */ + +/* Index order is mirrored by CONFIG_FIELDS in src/index.js. */ +#define CONFIG_FIELDS(X) \ + X(0, regNames, namedRegisters) \ + X(1, regNames, gprAbiNames) \ + X(2, regNames, fprAbiNames) \ + X(3, regNames, userFpcCsr) \ + X(4, regNames, vr4300Cop0NamedRegisters) \ + X(5, regNames, vr4300RspCop0NamedRegisters) \ + X(6, regNames, r4000AllegrexVfpuControlNamedRegisters) \ + X(7, pseudos, enablePseudos) \ + X(8, pseudos, pseudoBeqz) \ + X(9, pseudos, pseudoBnez) \ + X(10, pseudos, pseudoB) \ + X(11, pseudos, pseudoMove) \ + X(12, pseudos, pseudoNot) \ + X(13, pseudos, pseudoNeg) \ + X(14, pseudos, pseudoNegu) \ + X(15, pseudos, pseudoBal) \ + X(16, toolchainTweaks, treatJAsUnconditionalBranch) \ + X(17, toolchainTweaks, sn64DivFix) \ + X(18, toolchainTweaks, gnuMode) \ + X(19, misc, opcodeLJust) \ + X(20, misc, unknownInstrComment) \ + X(21, misc, omit0XOnSmallImm) \ + X(22, misc, upperCaseImm) \ + X(23, misc, expandJalr) + +EXPORT int rab_config_get(int field) { + switch (field) { +#define X(i, cat, name) case i: return (int)RabbitizerConfig_Cfg.cat.name; + CONFIG_FIELDS(X) +#undef X + } + return 0; +} + +/* Bool fields are stored as bool (value != 0), the rest as their own type. */ +EXPORT void rab_config_set(int field, int value) { + switch (field) { +#define X(i, cat, name) \ + case i: RabbitizerConfig_Cfg.cat.name = _Generic(RabbitizerConfig_Cfg.cat.name, bool: value != 0, default: value); break; + CONFIG_FIELDS(X) +#undef X + } +} + +/* ------------------------------------------------------------------ */ +/* Instruction */ +/* ------------------------------------------------------------------ */ + +/* + * An Instruction is plain data (RabbitizerInstruction_destroy is a no-op in + * every shipped version), so the JS object holds its own copy of the struct + * words and copies them into one of these two slots for each call; nothing is + * allocated per instruction on the WASM side. Two slots cover the calls that + * take two instructions (sameOpcode, unsetRegistersAfterFuncCall, processLui). + */ +static RabbitizerInstruction instrSlots[2]; + +EXPORT RabbitizerInstruction *rab_instr_slot(int i) { return &instrSlots[i]; } +EXPORT int rab_instr_sizeof(void) { return (int)sizeof(RabbitizerInstruction); } +EXPORT int rab_instr_offsetof_word(void) { return (int)offsetof(RabbitizerInstruction, word); } +EXPORT int rab_instr_offsetof_uniqueId(void) { return (int)offsetof(RabbitizerInstruction, uniqueId); } +EXPORT int rab_instr_offsetof_vram(void) { return (int)offsetof(RabbitizerInstruction, vram); } + +EXPORT void rab_instr_init(RabbitizerInstruction *self, uint32_t word, uint32_t vram, int category) { + switch ((RabbitizerInstrCategory)category) { + case RABBITIZER_INSTRCAT_RSP: + RabbitizerInstructionRsp_init(self, word, vram); + RabbitizerInstructionRsp_processUniqueId(self); + break; + + case RABBITIZER_INSTRCAT_R3000GTE: + RabbitizerInstructionR3000GTE_init(self, word, vram); + RabbitizerInstructionR3000GTE_processUniqueId(self); + break; + + case RABBITIZER_INSTRCAT_R5900: + RabbitizerInstructionR5900_init(self, word, vram); + RabbitizerInstructionR5900_processUniqueId(self); + break; + + case RABBITIZER_INSTRCAT_R4000ALLEGREX: + RabbitizerInstructionR4000Allegrex_init(self, word, vram); + RabbitizerInstructionR4000Allegrex_processUniqueId(self); + break; + + case RABBITIZER_INSTRCAT_CPU: + case RABBITIZER_INSTRCAT_MAX: + default: + RabbitizerInstruction_init(self, word, vram); + RabbitizerInstruction_processUniqueId(self); + break; + } +} + +EXPORT uint32_t rab_instr_getVram(const RabbitizerInstruction *self) { return self->vram; } +EXPORT void rab_instr_setVram(RabbitizerInstruction *self, uint32_t vram) { self->vram = vram; } +EXPORT int rab_instr_getInHandwrittenFunction(const RabbitizerInstruction *self) { return self->inHandwrittenFunction; } +EXPORT void rab_instr_setInHandwrittenFunction(RabbitizerInstruction *self, int v) { self->inHandwrittenFunction = v != 0; } +EXPORT int rab_instr_getUniqueId(const RabbitizerInstruction *self) { return self->uniqueId; } +EXPORT int rab_instr_getInstrIdType(const RabbitizerInstruction *self) { return self->instrIdType; } +EXPORT int rab_instr_getCategory(const RabbitizerInstruction *self) { return self->category; } +EXPORT const char *rab_instr_getOpcodeName(const RabbitizerInstruction *self) { return RabbitizerInstrId_getOpcodeName(self->uniqueId); } + +/* Register fields: -1 when the instruction does not have that operand (the + * Python binding raises in that case; JS builds the message). */ +#define REG_FIELD(name) \ + EXPORT int rab_instr_field_##name(const RabbitizerInstruction *self) { \ + if (!RabbitizerInstruction_hasOperandAlias(self, RAB_OPERAND_cpu_##name)) { \ + return -1; \ + } \ + return (int)RAB_INSTR_GET_##name(self); \ + } +REG_FIELD(rs) +REG_FIELD(rt) +REG_FIELD(rd) +REG_FIELD(fs) +REG_FIELD(ft) +REG_FIELD(fd) +#undef REG_FIELD + +EXPORT uint32_t rab_instr_field_sa(const RabbitizerInstruction *self) { return RAB_INSTR_GET_sa(self); } + +EXPORT int rab_instr_getFlag(const RabbitizerInstruction *self, int which) { + switch (which) { + case 0: return RAB_INSTR_FLAGS_GET_r5900DisasmAsData(self); + case 1: return RAB_INSTR_FLAGS_GET_r5900UseDollar(self); +#ifdef RAB_INSTR_FLAGS_GET_r5900ProdgSnAsInvertedRegs + case 2: return RAB_INSTR_FLAGS_GET_r5900ProdgSnAsInvertedRegs(self); +#endif + } + return 0; +} + +EXPORT void rab_instr_setFlag(RabbitizerInstruction *self, int which, int value) { + switch (which) { + case 0: RAB_INSTR_FLAGS_SET_r5900DisasmAsData(self, value); break; + case 1: RAB_INSTR_FLAGS_SET_r5900UseDollar(self, value); break; +#ifdef RAB_INSTR_FLAGS_SET_r5900ProdgSnAsInvertedRegs + case 2: RAB_INSTR_FLAGS_SET_r5900ProdgSnAsInvertedRegs(self, value); break; +#endif + } +} + +EXPORT int rab_has_flag_r5900ProdgSnAsInvertedRegs(void) { +#ifdef RAB_INSTR_FLAGS_GET_r5900ProdgSnAsInvertedRegs + return 1; +#else + return 0; +#endif +} + +EXPORT uint32_t rab_instr_getRaw(const RabbitizerInstruction *self) { return RabbitizerInstruction_getRaw(self); } + +EXPORT int rab_instr_hasImmediate(const RabbitizerInstruction *self) { + return RabbitizerInstruction_hasOperandAlias(self, RAB_OPERAND_cpu_immediate); +} +EXPORT uint32_t rab_instr_getImmediate(const RabbitizerInstruction *self) { return RAB_INSTR_GET_immediate(self); } +EXPORT int32_t rab_instr_getProcessedImmediate(const RabbitizerInstruction *self) { + return RabbitizerInstruction_getProcessedImmediate(self); +} + +EXPORT int rab_instr_hasLabel(const RabbitizerInstruction *self) { + return RabbitizerInstruction_hasOperandAlias(self, RAB_OPERAND_cpu_label); +} +EXPORT int rab_instr_hasBranchTargetLabel(const RabbitizerInstruction *self) { + return RabbitizerInstruction_hasOperand(self, RAB_OPERAND_cpu_branch_target_label); +} +EXPORT uint32_t rab_instr_getInstrIndexAsVram(const RabbitizerInstruction *self) { + return RabbitizerInstruction_getInstrIndexAsVram(self); +} +EXPORT int32_t rab_instr_getBranchOffset(const RabbitizerInstruction *self) { + return RabbitizerInstruction_getBranchOffset(self); +} +EXPORT int32_t rab_instr_getGenericBranchOffset(const RabbitizerInstruction *self, uint32_t currentVram) { + return RabbitizerInstruction_getGenericBranchOffset(self, currentVram); +} +EXPORT int32_t rab_instr_getBranchOffsetGeneric(const RabbitizerInstruction *self) { + return RabbitizerInstruction_getBranchOffsetGeneric(self); +} +EXPORT uint32_t rab_instr_getBranchVramGeneric(const RabbitizerInstruction *self) { + return RabbitizerInstruction_getBranchVramGeneric(self); +} +EXPORT int rab_instr_getDestinationGpr(const RabbitizerInstruction *self) { + return RabbitizerInstruction_getDestinationGpr(self); +} +EXPORT void rab_instr_blankOut(RabbitizerInstruction *self) { RabbitizerInstruction_blankOut(self); } +EXPORT const char *rab_instr_mapInstrToType(const RabbitizerInstruction *self) { + return RabbitizerInstruction_mapInstrToType(self); +} +EXPORT int rab_instr_sameOpcode(const RabbitizerInstruction *self, const RabbitizerInstruction *other) { + return RabbitizerInstruction_sameOpcode(self, other); +} +EXPORT int rab_instr_sameOpcodeButDifferentArguments(const RabbitizerInstruction *self, const RabbitizerInstruction *other) { + return RabbitizerInstruction_sameOpcodeButDifferentArguments(self, other); +} +EXPORT int rab_instr_hasOperand(const RabbitizerInstruction *self, int operand) { + return RabbitizerInstruction_hasOperand(self, (RabbitizerOperandType)operand); +} +EXPORT int rab_instr_hasOperandAlias(const RabbitizerInstruction *self, int operand) { + return RabbitizerInstruction_hasOperandAlias(self, (RabbitizerOperandType)operand); +} +EXPORT int rab_instr_getAccessType(const RabbitizerInstruction *self) { + return RabbitizerInstrDescriptor_getAccessType(self->descriptor); +} + +/* Instruction-level predicates (RabbitizerInstruction_). */ +#define INSTR_BOOL(name) \ + EXPORT int rab_ib_##name(const RabbitizerInstruction *self) { return RabbitizerInstruction_##name(self); } +INSTR_BOOL(outputsToGprZero) +INSTR_BOOL(isImplemented) +INSTR_BOOL(isLikelyHandwritten) +INSTR_BOOL(isNop) +INSTR_BOOL(isUnconditionalBranch) +INSTR_BOOL(isFunctionCall) +INSTR_BOOL(isReturn) +INSTR_BOOL(isJumptableJump) +INSTR_BOOL(isJrRa) +INSTR_BOOL(isJrNotRa) +INSTR_BOOL(hasDelaySlot) +INSTR_BOOL(isValid) +#undef INSTR_BOOL + +/* Descriptor-level predicates (RabbitizerInstrDescriptor_). */ +#define DESC_BOOL(name) \ + EXPORT int rab_db_##name(const RabbitizerInstruction *self) { return RabbitizerInstrDescriptor_##name(self->descriptor); } +DESC_BOOL(isUnknownType) +DESC_BOOL(isJType) +DESC_BOOL(isIType) +DESC_BOOL(isRType) +DESC_BOOL(isRegimmType) +DESC_BOOL(isBranch) +DESC_BOOL(isBranchLikely) +DESC_BOOL(isJump) +DESC_BOOL(isJumpWithAddress) +DESC_BOOL(isTrap) +DESC_BOOL(isFloat) +DESC_BOOL(isDouble) +DESC_BOOL(isUnsigned) +DESC_BOOL(modifiesRs) +DESC_BOOL(modifiesRt) +DESC_BOOL(modifiesRd) +DESC_BOOL(readsRs) +DESC_BOOL(readsRt) +DESC_BOOL(readsRd) +DESC_BOOL(readsHI) +DESC_BOOL(readsLO) +DESC_BOOL(modifiesHI) +DESC_BOOL(modifiesLO) +DESC_BOOL(modifiesFs) +DESC_BOOL(modifiesFt) +DESC_BOOL(modifiesFd) +DESC_BOOL(readsFs) +DESC_BOOL(readsFt) +DESC_BOOL(readsFd) +DESC_BOOL(notEmitedByCompilers) +DESC_BOOL(notEmittedByCompilers) +DESC_BOOL(canBeHi) +DESC_BOOL(canBeLo) +DESC_BOOL(doesLink) +DESC_BOOL(doesDereference) +DESC_BOOL(doesLoad) +DESC_BOOL(doesStore) +DESC_BOOL(maybeIsMove) +DESC_BOOL(isPseudo) +DESC_BOOL(doesUnsignedMemoryAccess) +#undef DESC_BOOL + +/* + * Disassembles into dst (capacity dstCap bytes, including the terminator). + * Returns the string length, or -(needed capacity) when dst is too small, in + * which case nothing is written and the caller retries with a bigger buffer. + * Returns INT32_MIN when the library wrote more than it asked for (the Python + * binding raises AssertionError in that case). + */ +EXPORT int32_t rab_instr_disassemble(const RabbitizerInstruction *self, char *dst, int32_t dstCap, + const char *immOverride, int32_t immOverrideLength, int extraLJust) { + size_t bufferSize = RabbitizerInstruction_getSizeForBuffer(self, (size_t)immOverrideLength, extraLJust); + size_t written; + + if (bufferSize + 1 > (size_t)dstCap) { + return -(int32_t)(bufferSize + 1); + } + written = RabbitizerInstruction_disassemble(self, dst, immOverride, (size_t)immOverrideLength, extraLJust); + if (written > bufferSize) { + return INT32_MIN; + } + return (int32_t)strlen(dst); +} + +/* ------------------------------------------------------------------ */ +/* RegistersTracker */ +/* ------------------------------------------------------------------ */ + +EXPORT RabbitizerRegistersTracker *rab_tracker_new(const RabbitizerRegistersTracker *other) { + RabbitizerRegistersTracker *self = malloc(sizeof(RabbitizerRegistersTracker)); + + if (self == NULL) { + return NULL; + } + RabbitizerRegistersTracker_init(self, other); + return self; +} + +EXPORT void rab_tracker_free(RabbitizerRegistersTracker *self) { + RabbitizerRegistersTracker_destroy(self); + free(self); +} + +EXPORT int rab_tracker_register_count(void) { return ARRAY_LEN(((RabbitizerRegistersTracker *)0)->registers); } + +/* Out-parameters are written to this static scratch struct and read by JS. */ +static struct { + int32_t i0; + uint32_t u0; + int32_t b0; + int32_t b1; +} out; + +EXPORT void *rab_out_ptr(void) { return &out; } + +EXPORT int rab_tracker_moveRegisters(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr) { + return RabbitizerRegistersTracker_moveRegisters(self, instr); +} +EXPORT void rab_tracker_overwriteRegisters(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, int instrOffset) { + RabbitizerRegistersTracker_overwriteRegisters(self, instr, instrOffset); +} +EXPORT void rab_tracker_unsetRegistersAfterFuncCall(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, + const RabbitizerInstruction *prevInstr) { + RabbitizerRegistersTracker_unsetRegistersAfterFuncCall(self, instr, prevInstr); +} +EXPORT int rab_tracker_getAddressIfCanSetType(const RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, + int instrOffset) { + uint32_t dstAddress = 0; + bool ok = RabbitizerRegistersTracker_getAddressIfCanSetType(self, instr, instrOffset, &dstAddress); + + out.u0 = dstAddress; + return ok; +} +EXPORT int rab_tracker_getJrInfo(const RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr) { + int dstOffset = 0; + uint32_t dstAddress = 0; + bool ok = RabbitizerRegistersTracker_getJrInfo(self, instr, &dstOffset, &dstAddress); + + out.i0 = dstOffset; + out.u0 = dstAddress; + return ok; +} + +static RabbitizerJrRegData jrRegDataOut; +EXPORT void rab_tracker_getJrRegData(const RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr) { + jrRegDataOut = RabbitizerRegistersTracker_getJrRegData(self, instr); +} +EXPORT void rab_jrRegData_init(void) { RabbitizerJrRegData_init(&jrRegDataOut); } +EXPORT int rab_jrRegData_hasInfo(void) { return jrRegDataOut.hasInfo; } +EXPORT int rab_jrRegData_offset(void) { return jrRegDataOut.offset; } +EXPORT uint32_t rab_jrRegData_address(void) { return jrRegDataOut.address; } +EXPORT int rab_jrRegData_checkedForBranching(void) { return jrRegDataOut.checkedForBranching; } +EXPORT int rab_jrRegData_lastBranchOffset(void) { return jrRegDataOut.lastBranchOffset; } + +EXPORT void rab_tracker_processLui(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, int instrOffset, + const RabbitizerInstruction *prevInstr) { + RabbitizerRegistersTracker_processLui(self, instr, instrOffset, prevInstr); +} +EXPORT void rab_tracker_processGpLoad(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, int instrOffset) { + RabbitizerRegistersTracker_processGpLoad(self, instr, instrOffset); +} +EXPORT int rab_tracker_getLuiOffsetForConstant(const RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr) { + int dstOffset = 0; + bool ok = RabbitizerRegistersTracker_getLuiOffsetForConstant(self, instr, &dstOffset); + + out.i0 = dstOffset; + return ok; +} +EXPORT void rab_tracker_processConstant(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, uint32_t value, + int instrOffset) { + RabbitizerRegistersTracker_processConstant(self, instr, value, instrOffset); +} +EXPORT int rab_tracker_getLuiOffsetForLo(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, int instrOffset) { + int dstOffset = 0; + bool dstIsGp = false; + bool ok = RabbitizerRegistersTracker_getLuiOffsetForLo(self, instr, instrOffset, &dstOffset, &dstIsGp); + + out.i0 = dstOffset; + out.b0 = dstIsGp; + return ok; +} + +static RabbitizerLoPairingInfo loPairingOut; +EXPORT void rab_tracker_preprocessLoAndGetInfo(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, + int instrOffset) { + loPairingOut = RabbitizerRegistersTracker_preprocessLoAndGetInfo(self, instr, instrOffset); +} +EXPORT void rab_loPairing_init(void) { RabbitizerLoPairingInfo_Init(&loPairingOut); } +EXPORT int rab_loPairing_instrOffset(void) { return loPairingOut.instrOffset; } +/* value is int64_t; returned as two halves so no BigInt crosses the boundary. */ +EXPORT uint32_t rab_loPairing_valueLo(void) { return (uint32_t)(uint64_t)loPairingOut.value; } +EXPORT int32_t rab_loPairing_valueHi(void) { return (int32_t)(loPairingOut.value >> 32); } +EXPORT int rab_loPairing_shouldProcess(void) { return loPairingOut.shouldProcess; } +EXPORT int rab_loPairing_isGpRel(void) { return loPairingOut.isGpRel; } +EXPORT int rab_loPairing_isGpGot(void) { return loPairingOut.isGpGot; } + +EXPORT void rab_tracker_processLo(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, uint32_t value, + int instrOffset) { + RabbitizerRegistersTracker_processLo(self, instr, value, instrOffset); +} +EXPORT void rab_tracker_processBranch(RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr, int instrOffset) { + RabbitizerRegistersTracker_processBranch(self, instr, instrOffset); +} +EXPORT int rab_tracker_hasLoButNoHi(const RabbitizerRegistersTracker *self, const RabbitizerInstruction *instr) { + return RabbitizerRegistersTracker_hasLoButNoHi(self, instr); +} + +/* ------------------------------------------------------------------ */ +/* TrackedRegisterState */ +/* ------------------------------------------------------------------ */ + +static RabbitizerTrackedRegisterState stateOut; + +/* TrackedRegisterState(registerNum) */ +EXPORT void rab_state_init(int registerNum) { + RabbitizerTrackedRegisterState_init(&stateOut, registerNum); +} + +/* RegistersTracker.__getitem__: a new state for the register number, then a + * copy of the tracked state, as the Python binding does. */ +EXPORT void rab_state_fromTracker(const RabbitizerRegistersTracker *tracker, int index) { + const RabbitizerTrackedRegisterState *state = &tracker->registers[index]; + + RabbitizerTrackedRegisterState_init(&stateOut, state->registerNum); + RabbitizerTrackedRegisterState_copyState(&stateOut, state); +} + +/* Field order mirrored by STATE_FIELDS in src/index.js. */ +EXPORT uint32_t rab_state_field(int field) { + switch (field) { + case 0: return (uint32_t)stateOut.registerNum; + case 1: return stateOut.hasLuiValue; + case 2: return (uint32_t)stateOut.luiOffset; + case 3: return stateOut.luiSetOnBranchLikely; + case 4: return stateOut.hasGpGot; + case 5: return (uint32_t)stateOut.gpGotOffset; + case 6: return stateOut.hasLoValue; + case 7: return (uint32_t)stateOut.loOffset; + case 8: return stateOut.dereferenced; + case 9: return (uint32_t)stateOut.dereferenceOffset; + case 10: return stateOut.checkedForBranching; + case 11: return (uint32_t)stateOut.lastBranchOffset; + case 12: return stateOut.value; + } + return 0; +} + +/* ------------------------------------------------------------------ */ +/* Utils */ +/* ------------------------------------------------------------------ */ + +EXPORT int32_t rab_utils_from2Complement(uint32_t number, int bits) { + return RabbitizerUtils_From2Complement(number, bits); +} +EXPORT uint32_t rab_utils_escapeString(char *dst, uint32_t dstSize, const char *src, uint32_t srcSize) { + return (uint32_t)RabbitizerUtils_escapeString(dst, dstSize, src, srcSize); +} +EXPORT uint32_t rab_utils_floatRepr_32From16(uint32_t hexRepr) { + return RabbitizerUtils_floatRepr_32From16((uint16_t)hexRepr); +} + +EXPORT void *rab_malloc(uint32_t size) { return malloc(size); } +EXPORT void rab_free(void *p) { free(p); } diff --git a/packages/romdev-rabbitizer/package.json b/packages/romdev-rabbitizer/package.json new file mode 100644 index 00000000..2aea39fe --- /dev/null +++ b/packages/romdev-rabbitizer/package.json @@ -0,0 +1,47 @@ +{ + "name": "romdev-rabbitizer", + "version": "0.1.0", + "description": "rabbitizer (MIPS instruction decoder) built from its C library to WASM, with a synchronous JS binding that mirrors the Python rabbitizer module API. Ships rabbitizer 1.16.2, 1.14.3 and 1.13.0.", + "type": "module", + "main": "src/index.js", + "exports": { + ".": "./src/index.js", + "./1.16.2": "./src/v1.16.2.js", + "./1.14.3": "./src/v1.14.3.js", + "./1.13.0": "./src/v1.13.0.js", + "./package.json": "./package.json" + }, + "files": [ + "src", + "wasm", + "csrc", + "LICENSE", + "NOTICE" + ], + "scripts": { + "test": "node --test --test-concurrency=4 'test/**/*.test.mjs'" + }, + "engines": { + "node": ">=24" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/monteslu/romdev.git", + "directory": "packages/romdev-rabbitizer" + }, + "homepage": "https://github.com/monteslu/romdev#readme", + "bugs": { + "url": "https://github.com/monteslu/romdev/issues" + }, + "author": "Luis Montes", + "upstream": { + "url": "https://github.com/Decompollaborate/rabbitizer", + "license": "MIT", + "versions": { + "1.16.2": "724a49a5b4dbfb99f1a9e6992e63964fd29c90c8", + "1.14.3": "d5804fa488474830a47fbf9f3693048ec1e45589", + "1.13.0": "1df4709dcc927d9d9cc5859a6e7eb98e864f8468" + } + } +} diff --git a/packages/romdev-rabbitizer/src/index.js b/packages/romdev-rabbitizer/src/index.js new file mode 100644 index 00000000..308941aa --- /dev/null +++ b/packages/romdev-rabbitizer/src/index.js @@ -0,0 +1,918 @@ +// JS binding for the rabbitizer MIPS instruction decoder, built from its C +// library to WASM (one module per pinned rabbitizer version). The API mirrors +// the Python `rabbitizer` extension module of the same version: same class, +// method, property and enum member names, same argument order, same return +// values (None -> null, tuples -> arrays) and the same errors for the same +// misuse (Python exception names are kept as the JS error `name`). +// +// Everything is synchronous: the WASM module is compiled and instantiated +// with the synchronous WebAssembly API the first time a version is loaded. + +import { readFileSync } from "node:fs"; + +/** Rabbitizer versions shipped in wasm/, newest first. */ +export const VERSIONS = Object.freeze(["1.16.2", "1.14.3", "1.13.0"]); +export const DEFAULT_VERSION = VERSIONS[0]; + +// --------------------------------------------------------------------------- +// Errors (named after the Python exceptions the extension module raises) +// --------------------------------------------------------------------------- + +export class RuntimeError extends Error { + constructor(message) { super(message); this.name = "RuntimeError"; } +} +export class ValueError extends Error { + constructor(message) { super(message); this.name = "ValueError"; } +} +export class IndexError extends Error { + constructor(message) { super(message); this.name = "IndexError"; } +} +export class OverflowError extends Error { + constructor(message) { super(message); this.name = "OverflowError"; } +} +export class AssertionError extends Error { + constructor(message) { super(message); this.name = "AssertionError"; } +} +export class MemoryError extends Error { + constructor(message) { super(message); this.name = "MemoryError"; } +} + +// --------------------------------------------------------------------------- +// Enum +// --------------------------------------------------------------------------- + +const INSPECT = Symbol.for("nodejs.util.inspect.custom"); + +/** + * An enum member. The loader creates exactly one object per member of each + * enum type of a version, so members compare by identity (`===`) and work as + * Map keys. Python compares members by (enum type, value) and orders them by + * value; use `.value` for ordering and `.equals()` for Python's `==`. + */ +export class Enum { + constructor(enumType, name, value) { + if (typeof enumType !== "string" || typeof name !== "string") { + throw new TypeError("Enum(enumType: str, name: str, value: int)"); + } + this.enumType = enumType; + this.name = name; + this.value = checkInt(value, "value"); + Object.freeze(this); + } + + /** Python `==`: same enum type and same value. */ + equals(other) { + return other instanceof Enum && other.enumType === this.enumType && other.value === this.value; + } + + toString() { + return `<${this.enumType}: ${this.name} (${this.value})>`; + } + + [INSPECT]() { + return this.toString(); + } +} + +// --------------------------------------------------------------------------- +// Argument helpers (PyArg_ParseTuple format semantics) +// --------------------------------------------------------------------------- + +function typeName(v) { + if (v === null || v === undefined) return "NoneType"; + if (typeof v === "object" || typeof v === "function") return v.constructor?.name ?? typeof v; + return typeof v; +} + +// "i": a C int; TypeError for a non-integer, OverflowError outside int range. +function checkInt(v, what) { + if (typeof v === "number" && Number.isInteger(v)) { + if (v < -2147483648 || v > 2147483647) { + throw new OverflowError(`signed integer is greater than maximum (${what})`); + } + return v; + } + if (typeof v === "boolean") return v ? 1 : 0; + if (typeof v === "bigint") return checkInt(Number(v), what); + throw new TypeError(`'${typeName(v)}' object cannot be interpreted as an integer (${what})`); +} + +// "I" / "H": an unsigned C int / short with no overflow check (the value is +// truncated to its low bits, as CPython does for these formats). +function uint32(v, what) { + if (typeof v === "number" && Number.isInteger(v)) return v >>> 0; + if (typeof v === "bigint") return Number(BigInt.asUintN(32, v)); + if (typeof v === "boolean") return v ? 1 : 0; + throw new TypeError(`'${typeName(v)}' object cannot be interpreted as an integer (${what})`); +} + +// --------------------------------------------------------------------------- +// Loader +// --------------------------------------------------------------------------- + +const cache = new Map(); + +/** + * Loads a rabbitizer version synchronously and returns its module namespace + * (the equivalent of `import rabbitizer` in Python). Each version is loaded + * once and shared: like the Python module, `config` is global per version. + * @param {string} [version] + */ +export function loadRabbitizerSync(version = DEFAULT_VERSION) { + let ns = cache.get(version); + if (ns) return ns; + if (!VERSIONS.includes(version)) { + throw new Error(`romdev-rabbitizer: unknown rabbitizer version '${version}' (have ${VERSIONS.join(", ")})`); + } + const bytes = readFileSync(new URL(`../wasm/rabbitizer-${version}.wasm`, import.meta.url)); + ns = createNamespace(new WebAssembly.Module(bytes), version); + cache.set(version, ns); + return ns; +} + +/** + * Async form of loadRabbitizerSync (same namespace object). + * @param {string} [version] + */ +export async function loadRabbitizer(version = DEFAULT_VERSION) { + return loadRabbitizerSync(version); +} + +function createNamespace(wasmModule, expectedVersion) { + let memory = null; + const imports = {}; + for (const imp of WebAssembly.Module.imports(wasmModule)) { + if (imp.kind !== "function") continue; + (imports[imp.module] ??= {})[imp.name] = + imp.name === "emscripten_notify_memory_growth" + ? () => refreshViews() + : () => { throw new RuntimeError(`romdev-rabbitizer: unexpected WASM import call ${imp.module}.${imp.name}`); }; + } + const instance = new WebAssembly.Instance(wasmModule, imports); + const ex = instance.exports; + memory = ex.memory; + ex._initialize?.(); + + // --- memory helpers ------------------------------------------------------ + + // Views over WASM memory; memory growth detaches them, and the module + // reports growth through emscripten_notify_memory_growth. + let u8 = new Uint8Array(memory.buffer); + let h32 = new Int32Array(memory.buffer); + function refreshViews() { + u8 = new Uint8Array(memory.buffer); + h32 = new Int32Array(memory.buffer); + } + const heap = () => (u8.buffer !== memory.buffer ? (refreshViews(), u8) : u8); + const utf8Decoder = new TextDecoder("utf-8"); + const utf8Encoder = new TextEncoder(); + + function readBytesAsString(ptr, len) { + const h = heap(); + let s = ""; + for (let i = 0; i < len; i++) { + const c = h[ptr + i]; + if (c >= 0x80) return utf8Decoder.decode(h.subarray(ptr, ptr + len)); + s += String.fromCharCode(c); + } + return s; + } + + function readCString(ptr) { + if (ptr === 0) return null; + const h = heap(); + let end = ptr; + while (h[end] !== 0) end++; + return readBytesAsString(ptr, end - ptr); + } + + function malloc(size) { + const p = ex.rab_malloc(size); + if (p === 0) throw new MemoryError("romdev-rabbitizer: WASM malloc failed"); + return p; + } + + // A reusable scratch buffer for strings passed into C. + let inBuf = malloc(256); + let inCap = 256; + // Writes `str` as UTF-8 plus a NUL terminator; returns the byte length. + function writeInString(str) { + const n = str.length; + let ascii = true; + for (let i = 0; i < n; i++) { + if (str.charCodeAt(i) >= 0x80) { ascii = false; break; } + } + let bytes = null; + const len = ascii ? n : (bytes = utf8Encoder.encode(str)).length; + if (len + 1 > inCap) { + ex.rab_free(inBuf); + inCap = Math.max(len + 1, inCap * 2); + inBuf = malloc(inCap); + } + const h = heap(); + if (ascii) { + for (let i = 0; i < n; i++) h[inBuf + i] = str.charCodeAt(i); + } else { + h.set(bytes, inBuf); + } + h[inBuf + len] = 0; + return len; + } + + let outBuf = malloc(1024); + let outCap = 1024; + + // --- enums --------------------------------------------------------------- + + // Per enum type: `list` indexed like the C enumvalues array (the Python + // binding looks members up by that index) and `ns`, the attribute object. + const enumTypes = {}; + for (let t = 0, tc = ex.rab_enum_table_count(); t < tc; t++) { + const typeNameStr = readCString(ex.rab_enum_table_name(t)); + const list = []; + const ns = {}; + for (let i = 0, n = ex.rab_enum_count(t); i < n; i++) { + const member = new Enum(typeNameStr, readCString(ex.rab_enum_name(t, i)), ex.rab_enum_value(t, i)); + list.push(member); + ns[member.name] = member; + } + enumTypes[typeNameStr] = { list, ns }; + } + const E = (name) => enumTypes[name]; + const InstrIdList = E("InstrId").list; + const InstrIdTypeList = E("InstrIdType").list; + const AccessTypeList = E("AccessType").list; + const TrinaryList = E("TrinaryValue").list; + const AbiList = E("Abi").list; + const GprO32List = E("RegGprO32").list; + const GprN32List = E("RegGprN32").list; + const Cop1O32List = E("RegCop1O32").list; + const Cop1N32List = E("RegCop1N32").list; + const Cop1N64List = E("RegCop1N64").list; + const ABI_N32 = E("Abi").ns.N32.value; + const ABI_N64 = E("Abi").ns.N64.value; + + const isEnumOf = (v, type) => v instanceof Enum && v.enumType === type; + + const Abi = Object.freeze(Object.assign(Object.create(null), E("Abi").ns, { + /** Abi.fromStr(name: str|None) -> Enum */ + fromStr(name) { + if (name === null || name === undefined) return AbiList[ex.rab_abi_fromStr(0)]; + if (typeof name !== "string") throw new TypeError(`argument 1 must be str or None, not ${typeName(name)}`); + writeInString(name); + return AbiList[ex.rab_abi_fromStr(inBuf)]; + }, + })); + + const InstrCategory = Object.freeze(Object.assign(Object.create(null), E("InstrCategory").ns, { + /** InstrCategory.fromStr(name: str|None) -> Enum|None */ + fromStr(name) { + let r; + if (name === null || name === undefined) { + r = ex.rab_instrCategory_fromStr(0); + } else { + if (typeof name !== "string") throw new TypeError(`argument 1 must be str or None, not ${typeName(name)}`); + writeInString(name); + r = ex.rab_instrCategory_fromStr(inBuf); + } + return r < 0 ? null : E("InstrCategory").list[r]; + }, + })); + + const frozenNs = (name) => Object.freeze(Object.assign(Object.create(null), E(name).ns)); + + // --- config -------------------------------------------------------------- + + // Order matches CONFIG_FIELDS in csrc/rabbitizer_wasm.c. + const CONFIG_FIELDS = [ + ["regNames_namedRegisters", "bool"], + ["regNames_gprAbiNames", "abi"], + ["regNames_fprAbiNames", "abi"], + ["regNames_userFpcCsr", "bool"], + ["regNames_vr4300Cop0NamedRegisters", "bool"], + ["regNames_vr4300RspCop0NamedRegisters", "bool"], + ["regNames_r4000AllegrexVfpuControlNamedRegisters", "bool"], + ["pseudos_enablePseudos", "bool"], + ["pseudos_pseudoBeqz", "bool"], + ["pseudos_pseudoBnez", "bool"], + ["pseudos_pseudoB", "bool"], + ["pseudos_pseudoMove", "bool"], + ["pseudos_pseudoNot", "bool"], + ["pseudos_pseudoNeg", "bool"], + ["pseudos_pseudoNegu", "bool"], + ["pseudos_pseudoBal", "bool"], + ["toolchainTweaks_treatJAsUnconditionalBranch", "bool"], + ["toolchainTweaks_sn64DivFix", "bool"], + ["toolchainTweaks_gnuMode", "bool"], + ["misc_opcodeLJust", "int"], + ["misc_unknownInstrComment", "bool"], + ["misc_omit0XOnSmallImm", "bool"], + ["misc_upperCaseImm", "bool"], + ["misc_expandJalr", "bool"], + ]; + + const config = {}; + CONFIG_FIELDS.forEach(([name, kind], index) => { + const dotted = name.replace("_", kind === "bool" ? "." : "_"); + let get, set; + if (kind === "bool") { + get = () => ex.rab_config_get(index) !== 0; + set = (v) => { + if (v === undefined) throw new TypeError(`Cannot delete '${dotted}' attribute`); + ex.rab_config_set(index, v ? 1 : 0); + }; + } else if (kind === "abi") { + get = () => { + const m = AbiList[ex.rab_config_get(index)]; + if (m === undefined) throw new RuntimeError(`Internal error: invalid enum value for '${name}'`); + return m; + }; + set = (v) => { + if (v === undefined) throw new TypeError(`Cannot delete '${name}' attribute`); + if (!(v instanceof Enum)) throw new TypeError(`Invalid value for '${name}' attribute`); + if (v.enumType !== "Abi") throw new ValueError(`Invalid value for '${name}' attribute`); + ex.rab_config_set(index, v.value); + }; + } else { + get = () => ex.rab_config_get(index); + set = (v) => { + if (v === undefined) throw new TypeError(`Cannot delete '${name}' attribute`); + ex.rab_config_set(index, checkInt(v, name)); + }; + } + Object.defineProperty(config, name, { get, set, enumerable: true }); + }); + Object.preventExtensions(config); + + // --- register enum lookups (RETURN_GPR / DEF_MEMBER_GET_REGCOP1) --------- + + function gprMember(reg) { + const abi = ex.rab_config_get(1); + const m = (abi === ABI_N32 || abi === ABI_N64 ? GprN32List : GprO32List)[reg]; + if (m === undefined) throw new RuntimeError("Internal error: invalid RegGpr enum value"); + return m; + } + + function cop1Member(reg) { + const abi = ex.rab_config_get(2); + const m = (abi === ABI_N32 ? Cop1N32List : abi === ABI_N64 ? Cop1N64List : Cop1O32List)[reg]; + if (m === undefined) throw new RuntimeError("Internal error: invalid RegCop1 enum value"); + return m; + } + + // --- Instruction --------------------------------------------------------- + + // An Instruction object holds its own copy of the C struct as nine int32 + // words (_w0.._w8); each call copies them into a static WASM slot. The + // struct is plain data in every shipped version (destroy is a no-op), so + // nothing needs freeing and no finalizer is registered per instruction. + if (ex.rab_instr_sizeof() !== 36 || ex.rab_instr_offsetof_word() !== 0 || + ex.rab_instr_offsetof_uniqueId() !== 8 || ex.rab_instr_offsetof_vram() !== 20) { + throw new Error("romdev-rabbitizer: unexpected RabbitizerInstruction layout; update src/index.js"); + } + const SLOT_A = ex.rab_instr_slot(0); + const SLOT_B = ex.rab_instr_slot(1); + const A32 = SLOT_A >> 2; + const B32 = SLOT_B >> 2; + + function toSlot(instr, base) { + const h = h32; + h[base] = instr._w0; h[base + 1] = instr._w1; h[base + 2] = instr._w2; + h[base + 3] = instr._w3; h[base + 4] = instr._w4; h[base + 5] = instr._w5; + h[base + 6] = instr._w6; h[base + 7] = instr._w7; h[base + 8] = instr._w8; + } + + function fromSlotA(instr) { + const h = h32; + instr._w0 = h[A32]; instr._w1 = h[A32 + 1]; instr._w2 = h[A32 + 2]; + instr._w3 = h[A32 + 3]; instr._w4 = h[A32 + 4]; instr._w5 = h[A32 + 5]; + instr._w6 = h[A32 + 6]; instr._w7 = h[A32 + 7]; instr._w8 = h[A32 + 8]; + } + + // Copies `instr` into slot A and returns the slot address. + const a = (instr) => (toSlot(instr, A32), SLOT_A); + + const opcodeNames = []; + function opcodeName(instr) { + const id = instr._w2; + let name = opcodeNames[id]; + if (name === undefined) name = opcodeNames[id] = readCString(ex.rab_instr_getOpcodeName(a(instr))); + return name; + } + + function checkInstr(instr, what) { + if (!(instr instanceof Instruction)) { + throw new TypeError(`argument '${what}' must be rabbitizer.Instruction, not ${typeName(instr)}`); + } + return instr; + } + + const hasFlagProdg = ex.rab_has_flag_r5900ProdgSnAsInvertedRegs() !== 0; + + class Instruction { + /** + * Instruction(word, vram=0, category=InstrCategory.CPU) + * @param {number} word + * @param {number} [vram] + * @param {Enum} [category] + */ + constructor(word, vram = 0, category = undefined) { + const w = uint32(word, "word"); + const v = uint32(vram, "vram"); + let cat = 0; + if (category !== undefined) { + if (!(category instanceof Enum)) { + throw new TypeError(`argument 3 must be rabbitizer.Enum, not ${typeName(category)}`); + } + if (category.enumType !== "InstrCategory") throw new ValueError("Invalid value for 'category' parameter"); + cat = category.value; + } + ex.rab_instr_init(SLOT_A, w, v, cat); + const h = h32; + /** @internal struct words */ + this._w0 = h[A32]; this._w1 = h[A32 + 1]; this._w2 = h[A32 + 2]; + this._w3 = h[A32 + 3]; this._w4 = h[A32 + 4]; this._w5 = h[A32 + 5]; + this._w6 = h[A32 + 6]; this._w7 = h[A32 + 7]; this._w8 = h[A32 + 8]; + } + + get vram() { return this._w5 >>> 0; } + set vram(v) { this._w5 = uint32(v, "vram") | 0; } + + get inHandwrittenFunction() { return ex.rab_instr_getInHandwrittenFunction(a(this)) !== 0; } + set inHandwrittenFunction(v) { + if (typeof v !== "boolean") throw new TypeError("attribute value type must be bool"); + ex.rab_instr_setInHandwrittenFunction(a(this), v ? 1 : 0); + fromSlotA(this); + } + + get rs() { return this.#reg(ex.rab_instr_field_rs(a(this)), "rs", gprMember); } + get rt() { return this.#reg(ex.rab_instr_field_rt(a(this)), "rt", gprMember); } + get rd() { return this.#reg(ex.rab_instr_field_rd(a(this)), "rd", gprMember); } + get sa() { return ex.rab_instr_field_sa(a(this)) >>> 0; } + get fs() { return this.#reg(ex.rab_instr_field_fs(a(this)), "fs", cop1Member); } + get ft() { return this.#reg(ex.rab_instr_field_ft(a(this)), "ft", cop1Member); } + get fd() { return this.#reg(ex.rab_instr_field_fd(a(this)), "fd", cop1Member); } + + #reg(r, name, lookup) { + if (r < 0) throw new RuntimeError(`'${opcodeName(this)}' instruction does not reference register '${name}'`); + return lookup(r); + } + + get uniqueId() { + const m = InstrIdList[this._w2]; + if (m === undefined) throw new RuntimeError("Internal error: invalid uniqueId enum value"); + return m; + } + + get instrIdType() { + const m = InstrIdTypeList[ex.rab_instr_getInstrIdType(a(this))]; + if (m === undefined) throw new RuntimeError("Internal error: invalid instrIdType enum value"); + return m; + } + + get flag_r5900DisasmAsData() { return TrinaryList[ex.rab_instr_getFlag(a(this), 0)]; } + set flag_r5900DisasmAsData(v) { ex.rab_instr_setFlag(a(this), 0, trinaryArg(v)); fromSlotA(this); } + get flag_r5900UseDollar() { return TrinaryList[ex.rab_instr_getFlag(a(this), 1)]; } + set flag_r5900UseDollar(v) { ex.rab_instr_setFlag(a(this), 1, trinaryArg(v)); fromSlotA(this); } + + getRaw() { return ex.rab_instr_getRaw(a(this)) >>> 0; } + + getImmediate() { + const p = a(this); + if (!ex.rab_instr_hasImmediate(p)) this.#noField("immediate"); + return ex.rab_instr_getImmediate(p) >>> 0; + } + + getProcessedImmediate() { + const p = a(this); + if (!ex.rab_instr_hasImmediate(p)) this.#noField("immediate"); + return ex.rab_instr_getProcessedImmediate(p); + } + + getInstrIndexAsVram() { + const p = a(this); + if (!ex.rab_instr_hasLabel(p)) this.#noField("jump label"); + return ex.rab_instr_getInstrIndexAsVram(p) >>> 0; + } + + getBranchOffset() { + const p = a(this); + if (!ex.rab_instr_hasBranchTargetLabel(p)) this.#noField("branch label"); + return ex.rab_instr_getBranchOffset(p); + } + + getGenericBranchOffset(currentVram) { + const cv = uint32(currentVram, "currentVram"); + return ex.rab_instr_getGenericBranchOffset(a(this), cv); + } + + getBranchOffsetGeneric() { + this.#checkBranchOrJump(); + return ex.rab_instr_getBranchOffsetGeneric(SLOT_A); + } + + getBranchVramGeneric() { + this.#checkBranchOrJump(); + return ex.rab_instr_getBranchVramGeneric(SLOT_A) >>> 0; + } + + #noField(field) { + throw new RuntimeError(`'${opcodeName(this)}' instruction does not have an '${field}' field`); + } + + // Leaves this instruction in slot A. + #checkBranchOrJump() { + const p = a(this); + if (!ex.rab_instr_hasLabel(p) && !ex.rab_instr_hasBranchTargetLabel(p)) { + throw new RuntimeError(`'${opcodeName(this)}' instruction does not not perform a branch or a jump.`); + } + } + + /** @returns {Enum|null} */ + getDestinationGpr() { + const r = ex.rab_instr_getDestinationGpr(a(this)); + return r < 0 ? null : gprMember(r); + } + + getOpcodeName() { return opcodeName(this); } + + blankOut() { + ex.rab_instr_blankOut(a(this)); + fromSlotA(this); + } + + /** @returns {string|null} */ + mapInstrToType() { return readCString(ex.rab_instr_mapInstrToType(a(this))); } + + sameOpcode(other) { + toSlot(checkInstr(other, "other"), B32); + return ex.rab_instr_sameOpcode(a(this), SLOT_B) !== 0; + } + + sameOpcodeButDifferentArguments(other) { + toSlot(checkInstr(other, "other"), B32); + return ex.rab_instr_sameOpcodeButDifferentArguments(a(this), SLOT_B) !== 0; + } + + hasOperand(operand) { return ex.rab_instr_hasOperand(a(this), operandArg(operand)) !== 0; } + + hasOperandAlias(operand) { return ex.rab_instr_hasOperandAlias(a(this), operandArg(operand)) !== 0; } + + getAccessType() { return AccessTypeList[ex.rab_instr_getAccessType(a(this))]; } + + /** + * disassemble(immOverride=None, extraLJust=0) -> str + * @param {string|null} [immOverride] + * @param {number} [extraLJust] + */ + disassemble(immOverride = null, extraLJust = 0) { + let immPtr = 0; + let immLen = 0; + if (immOverride !== null && immOverride !== undefined) { + if (typeof immOverride !== "string") { + throw new TypeError(`argument 1 must be str or None, not ${typeName(immOverride)}`); + } + if (immOverride.includes("\0")) throw new ValueError("embedded null character"); + immLen = writeInString(immOverride); + immPtr = inBuf; + } + const lj = extraLJust === 0 ? 0 : checkInt(extraLJust, "extraLJust"); + const p = a(this); + let n = ex.rab_instr_disassemble(p, outBuf, outCap, immPtr, immLen, lj); + if (n < 0 && n !== -2147483648) { + ex.rab_free(outBuf); + outCap = Math.max(-n, outCap * 2); + outBuf = malloc(outCap); + n = ex.rab_instr_disassemble(p, outBuf, outCap, immPtr, immLen, lj); + } + if (n === -2147483648) { + throw new AssertionError( + "Decoded instruction does not fit in the allocated buffer.\n" + + "This will produce a memory corruption error.\n" + + "This is not an user error, please report this bug.\n" + + ` word: 0x${this.getRaw().toString(16)}\n`, + ); + } + return readBytesAsString(outBuf, n); + } + + toString() { return this.disassemble(); } + + [INSPECT]() { + return `rabbitizer.Instruction(0x${this.getRaw().toString(16).toUpperCase().padStart(8, "0")}) # ${this.disassemble()}`; + } + } + + if (hasFlagProdg) { + Object.defineProperty(Instruction.prototype, "flag_r5900ProdgSnAsInvertedRegs", { + get() { return TrinaryList[ex.rab_instr_getFlag(a(this), 2)]; }, + set(v) { ex.rab_instr_setFlag(a(this), 2, trinaryArg(v)); fromSlotA(this); }, + configurable: true, + }); + } + + // Predicates: RabbitizerInstruction_ and RabbitizerInstrDescriptor_. + const INSTR_BOOLS = [ + "outputsToGprZero", "isImplemented", "isLikelyHandwritten", "isNop", "isUnconditionalBranch", + "isFunctionCall", "isReturn", "isJumptableJump", "isJrRa", "isJrNotRa", "hasDelaySlot", "isValid", + ]; + const DESC_BOOLS = [ + "isUnknownType", "isJType", "isIType", "isRType", "isRegimmType", "isBranch", "isBranchLikely", + "isJump", "isJumpWithAddress", "isTrap", "isFloat", "isDouble", "isUnsigned", "modifiesRs", + "modifiesRt", "modifiesRd", "readsRs", "readsRt", "readsRd", "readsHI", "readsLO", "modifiesHI", + "modifiesLO", "modifiesFs", "modifiesFt", "modifiesFd", "readsFs", "readsFt", "readsFd", + "notEmitedByCompilers", "notEmittedByCompilers", "canBeHi", "canBeLo", "doesLink", + "doesDereference", "doesLoad", "doesStore", "maybeIsMove", "isPseudo", "doesUnsignedMemoryAccess", + ]; + for (const [prefix, names] of [["rab_ib_", INSTR_BOOLS], ["rab_db_", DESC_BOOLS]]) { + for (const name of names) { + const fn = ex[prefix + name]; + if (typeof fn !== "function") throw new Error(`romdev-rabbitizer: WASM export ${prefix + name} missing`); + Object.defineProperty(Instruction.prototype, name, { + value: { [name]() { return fn(a(this)) !== 0; } }[name], + writable: true, + configurable: true, + }); + } + } + + function trinaryArg(v) { + if (v === undefined || v === null) throw new ValueError("NULL passed for 'value' parameter?"); + if (!isEnumOf(v, "TrinaryValue") || v.value < 0) throw new ValueError("Invalid value for 'value' parameter"); + return v.value; + } + + function operandArg(v) { + if (!(v instanceof Enum)) throw new TypeError(`argument 1 must be rabbitizer.Enum, not ${typeName(v)}`); + if (v.enumType !== "OperandType") throw new ValueError("Invalid value for 'operand' parameter"); + return v.value; + } + + // --- TrackedRegisterState / LoPairingInfo / JrRegData -------------------- + + // Order matches rab_state_field in csrc/rabbitizer_wasm.c. + const STATE_FIELDS = [ + ["registerNum", "int"], ["hasLuiValue", "bool"], ["luiOffset", "int"], ["luiSetOnBranchLikely", "bool"], + ["hasGpGot", "bool"], ["gpGotOffset", "int"], ["hasLoValue", "bool"], ["loOffset", "int"], + ["dereferenced", "bool"], ["dereferenceOffset", "int"], ["checkedForBranching", "bool"], + ["lastBranchOffset", "int"], ["value", "uint"], + ]; + const FROM_C = Symbol("fromC"); + + // Snapshot of one register's tracked state; read-only, like the Python type. + class TrackedRegisterState { + constructor(registerNum) { + if (registerNum !== FROM_C) ex.rab_state_init(checkInt(registerNum, "registerNum")); + for (let i = 0; i < STATE_FIELDS.length; i++) { + const [name, kind] = STATE_FIELDS[i]; + const raw = ex.rab_state_field(i); + this[name] = kind === "bool" ? raw !== 0 : kind === "int" ? raw | 0 : raw >>> 0; + } + Object.freeze(this); + } + } + + class LoPairingInfo { + #instrOffset; + #value; + #shouldProcess; + #isGpRel; + #isGpGot; + + constructor(fromC = undefined) { + if (fromC !== FROM_C) ex.rab_loPairing_init(); + this.#instrOffset = ex.rab_loPairing_instrOffset(); + this.#value = ex.rab_loPairing_valueHi() * 4294967296 + (ex.rab_loPairing_valueLo() >>> 0); + this.#shouldProcess = ex.rab_loPairing_shouldProcess() !== 0; + this.#isGpRel = ex.rab_loPairing_isGpRel() !== 0; + this.#isGpGot = ex.rab_loPairing_isGpGot() !== 0; + } + + get instrOffset() { return this.#instrOffset; } + get value() { return this.#value; } + get shouldProcess() { return this.#shouldProcess; } + set shouldProcess(v) { this.#shouldProcess = boolMember(v); } + get isGpRel() { return this.#isGpRel; } + set isGpRel(v) { this.#isGpRel = boolMember(v); } + get isGpGot() { return this.#isGpGot; } + set isGpGot(v) { this.#isGpGot = boolMember(v); } + } + + function boolMember(v) { + if (typeof v !== "boolean") throw new TypeError("attribute value type must be bool"); + return v; + } + + class JrRegData { + #hasInfo; + #offset; + #address; + #checkedForBranching; + #lastBranchOffset; + + constructor(fromC = undefined) { + if (fromC !== FROM_C) ex.rab_jrRegData_init(); + this.#hasInfo = ex.rab_jrRegData_hasInfo() !== 0; + this.#offset = ex.rab_jrRegData_offset(); + this.#address = ex.rab_jrRegData_address() >>> 0; + this.#checkedForBranching = ex.rab_jrRegData_checkedForBranching() !== 0; + this.#lastBranchOffset = ex.rab_jrRegData_lastBranchOffset(); + } + + hasInfo() { return this.#hasInfo; } + offset() { return this.#offset; } + address() { return this.#address; } + checkedForBranching() { return this.#checkedForBranching; } + lastBranchOffset() { return this.#lastBranchOffset; } + } + + // --- RegistersTracker ---------------------------------------------------- + + const trackerRegistry = new FinalizationRegistry((ptr) => ex.rab_tracker_free(ptr)); + const REGISTER_COUNT = ex.rab_tracker_register_count(); + const outView = () => new DataView(memory.buffer, ex.rab_out_ptr(), 16); + + class RegistersTracker { + /** RegistersTracker(other: RegistersTracker|None=None) */ + constructor(other = null) { + let otherPtr = 0; + if (other !== null && other !== undefined) { + if (!(other instanceof RegistersTracker)) { + throw new TypeError(`argument must be RegistersTracker or None, not ${typeName(other)}`); + } + otherPtr = other._ptr; + } + const p = ex.rab_tracker_new(otherPtr); + if (p === 0) throw new MemoryError("romdev-rabbitizer: WASM malloc failed"); + /** @internal */ + this._ptr = p; + trackerRegistry.register(this, p, this); + } + + /** Frees the WASM-side struct now (not in the Python API). */ + free() { + if (this._ptr !== 0) { + trackerRegistry.unregister(this); + ex.rab_tracker_free(this._ptr); + this._ptr = 0; + } + } + + [Symbol.dispose]() { this.free(); } + + moveRegisters(instr) { return ex.rab_tracker_moveRegisters(this._ptr, a(checkInstr(instr, "instr"))) !== 0; } + + overwriteRegisters(instr, instrOffset) { + ex.rab_tracker_overwriteRegisters(this._ptr, a(checkInstr(instr, "instr")), checkInt(instrOffset, "instrOffset")); + } + + unsetRegistersAfterFuncCall(instr, prevInstr) { + toSlot(checkInstr(prevInstr, "prevInstr"), B32); + ex.rab_tracker_unsetRegistersAfterFuncCall(this._ptr, a(checkInstr(instr, "instr")), SLOT_B); + } + + /** @returns {number|null} */ + getAddressIfCanSetType(instr, instrOffset) { + const ok = ex.rab_tracker_getAddressIfCanSetType(this._ptr, a(checkInstr(instr, "instr")), checkInt(instrOffset, "instrOffset")); + return ok ? outView().getUint32(4, true) : null; + } + + /** @deprecated use getJrRegData. @returns {[number, number]|null} */ + getJrInfo(instr) { + const ok = ex.rab_tracker_getJrInfo(this._ptr, a(checkInstr(instr, "instr"))); + if (!ok) return null; + const dv = outView(); + return [dv.getInt32(0, true), dv.getUint32(4, true)]; + } + + getJrRegData(instr) { + ex.rab_tracker_getJrRegData(this._ptr, a(checkInstr(instr, "instr"))); + return new JrRegData(FROM_C); + } + + processLui(instr, instrOffset, prevInstr = null) { + let prev = 0; + if (prevInstr !== null && prevInstr !== undefined) { + toSlot(checkInstr(prevInstr, "prevInstr"), B32); + prev = SLOT_B; + } + ex.rab_tracker_processLui(this._ptr, a(checkInstr(instr, "instr")), checkInt(instrOffset, "instrOffset"), prev); + } + + processGpLoad(instr, instrOffset) { + ex.rab_tracker_processGpLoad(this._ptr, a(checkInstr(instr, "instr")), checkInt(instrOffset, "instrOffset")); + } + + /** @returns {number|null} */ + getLuiOffsetForConstant(instr) { + const ok = ex.rab_tracker_getLuiOffsetForConstant(this._ptr, a(checkInstr(instr, "instr"))); + return ok ? outView().getInt32(0, true) : null; + } + + processConstant(instr, value, instrOffset) { + ex.rab_tracker_processConstant(this._ptr, a(checkInstr(instr, "instr")), uint32(value, "value"), checkInt(instrOffset, "instrOffset")); + } + + /** @deprecated use preprocessLoAndGetInfo. @returns {[number, boolean, boolean]} */ + getLuiOffsetForLo(instr, instrOffset) { + const ok = ex.rab_tracker_getLuiOffsetForLo(this._ptr, a(checkInstr(instr, "instr")), checkInt(instrOffset, "instrOffset")); + const dv = outView(); + return [dv.getInt32(0, true), dv.getInt32(8, true) !== 0, ok !== 0]; + } + + preprocessLoAndGetInfo(instr, instrOffset) { + ex.rab_tracker_preprocessLoAndGetInfo(this._ptr, a(checkInstr(instr, "instr")), checkInt(instrOffset, "instrOffset")); + return new LoPairingInfo(FROM_C); + } + + processLo(instr, value, instrOffset) { + ex.rab_tracker_processLo(this._ptr, a(checkInstr(instr, "instr")), uint32(value, "value"), checkInt(instrOffset, "instrOffset")); + } + + processBranch(instr, instrOffset) { + ex.rab_tracker_processBranch(this._ptr, a(checkInstr(instr, "instr")), checkInt(instrOffset, "instrOffset")); + } + + hasLoButNoHi(instr) { return ex.rab_tracker_hasLoButNoHi(this._ptr, a(checkInstr(instr, "instr"))) !== 0; } + + /** Python `tracker[index]`: a TrackedRegisterState snapshot. */ + __getitem__(index) { + const i = checkInt(index, "index"); + if (i < 0 || i >= REGISTER_COUNT) throw new IndexError("Index must be a value between 0 and 31"); + ex.rab_state_fromTracker(this._ptr, i); + return new TrackedRegisterState(FROM_C); + } + + getItem(index) { return this.__getitem__(index); } + } + + // --- Utils --------------------------------------------------------------- + + const Utils = Object.freeze({ + from2Complement(number, bits) { + return ex.rab_utils_from2Complement(uint32(number, "number"), checkInt(bits, "bits")); + }, + + escapeString(src) { + if (typeof src !== "string") throw new TypeError(`argument 1 must be str, not ${typeName(src)}`); + const srcSize = writeInString(src); + if (srcSize === 0) return ""; + const dstSize = 2 * srcSize; + const dst = malloc(dstSize); + try { + const wrote = ex.rab_utils_escapeString(dst, dstSize, inBuf, srcSize) >>> 0; + if (wrote > dstSize) throw new RuntimeError("Internal error on 'escapeString'"); + return readBytesAsString(dst, wrote); + } finally { + ex.rab_free(dst); + } + }, + + floatRepr_32From16(hex_repr) { + return ex.rab_utils_floatRepr_32From16(uint32(hex_repr, "hex_repr") & 0xffff) >>> 0; + }, + }); + + // --- namespace ----------------------------------------------------------- + + const versionStr = readCString(ex.rab_version_str()); + if (versionStr !== expectedVersion) { + throw new Error(`romdev-rabbitizer: wasm/rabbitizer-${expectedVersion}.wasm reports version ${versionStr}`); + } + + return Object.freeze({ + __version__: versionStr, + __version_info__: Object.freeze([ex.rab_version_major(), ex.rab_version_minor(), ex.rab_version_patch()]), + __author__: readCString(ex.rab_version_author()), + + Utils, + config, + + Enum, + Abi, + InstrCategory, + InstrId: frozenNs("InstrId"), + InstrIdType: frozenNs("InstrIdType"), + OperandType: frozenNs("OperandType"), + AccessType: frozenNs("AccessType"), + RegGprO32: frozenNs("RegGprO32"), + RegGprN32: frozenNs("RegGprN32"), + RegCop1O32: frozenNs("RegCop1O32"), + RegCop1N32: frozenNs("RegCop1N32"), + RegCop1N64: frozenNs("RegCop1N64"), + TrinaryValue: frozenNs("TrinaryValue"), + + Instruction, + LoPairingInfo, + TrackedRegisterState, + RegistersTracker, + JrRegData, + + RuntimeError, + ValueError, + IndexError, + OverflowError, + AssertionError, + MemoryError, + }); +} diff --git a/packages/romdev-rabbitizer/src/v1.13.0.js b/packages/romdev-rabbitizer/src/v1.13.0.js new file mode 100644 index 00000000..ebc38afa --- /dev/null +++ b/packages/romdev-rabbitizer/src/v1.13.0.js @@ -0,0 +1,14 @@ +// `import * as rabbitizer from "romdev-rabbitizer/1.13.0"`: the rabbitizer 1.13.0 +// module namespace, loaded synchronously at import (same object as +// loadRabbitizerSync("1.13.0")). +import { loadRabbitizerSync } from "./index.js"; + +const rabbitizer = loadRabbitizerSync("1.13.0"); +export default rabbitizer; +export const { + __version__, __version_info__, __author__, + Utils, config, Enum, Abi, InstrCategory, InstrId, InstrIdType, OperandType, AccessType, + RegGprO32, RegGprN32, RegCop1O32, RegCop1N32, RegCop1N64, TrinaryValue, + Instruction, LoPairingInfo, TrackedRegisterState, RegistersTracker, JrRegData, + RuntimeError, ValueError, IndexError, OverflowError, AssertionError, MemoryError, +} = rabbitizer; diff --git a/packages/romdev-rabbitizer/src/v1.14.3.js b/packages/romdev-rabbitizer/src/v1.14.3.js new file mode 100644 index 00000000..8fd39bc5 --- /dev/null +++ b/packages/romdev-rabbitizer/src/v1.14.3.js @@ -0,0 +1,14 @@ +// `import * as rabbitizer from "romdev-rabbitizer/1.14.3"`: the rabbitizer 1.14.3 +// module namespace, loaded synchronously at import (same object as +// loadRabbitizerSync("1.14.3")). +import { loadRabbitizerSync } from "./index.js"; + +const rabbitizer = loadRabbitizerSync("1.14.3"); +export default rabbitizer; +export const { + __version__, __version_info__, __author__, + Utils, config, Enum, Abi, InstrCategory, InstrId, InstrIdType, OperandType, AccessType, + RegGprO32, RegGprN32, RegCop1O32, RegCop1N32, RegCop1N64, TrinaryValue, + Instruction, LoPairingInfo, TrackedRegisterState, RegistersTracker, JrRegData, + RuntimeError, ValueError, IndexError, OverflowError, AssertionError, MemoryError, +} = rabbitizer; diff --git a/packages/romdev-rabbitizer/src/v1.16.2.js b/packages/romdev-rabbitizer/src/v1.16.2.js new file mode 100644 index 00000000..642993e4 --- /dev/null +++ b/packages/romdev-rabbitizer/src/v1.16.2.js @@ -0,0 +1,14 @@ +// `import * as rabbitizer from "romdev-rabbitizer/1.16.2"`: the rabbitizer 1.16.2 +// module namespace, loaded synchronously at import (same object as +// loadRabbitizerSync("1.16.2")). +import { loadRabbitizerSync } from "./index.js"; + +const rabbitizer = loadRabbitizerSync("1.16.2"); +export default rabbitizer; +export const { + __version__, __version_info__, __author__, + Utils, config, Enum, Abi, InstrCategory, InstrId, InstrIdType, OperandType, AccessType, + RegGprO32, RegGprN32, RegCop1O32, RegCop1N32, RegCop1N64, TrinaryValue, + Instruction, LoPairingInfo, TrackedRegisterState, RegistersTracker, JrRegData, + RuntimeError, ValueError, IndexError, OverflowError, AssertionError, MemoryError, +} = rabbitizer; diff --git a/packages/romdev-rabbitizer/test/binding.test.mjs b/packages/romdev-rabbitizer/test/binding.test.mjs new file mode 100644 index 00000000..19dcef28 --- /dev/null +++ b/packages/romdev-rabbitizer/test/binding.test.mjs @@ -0,0 +1,357 @@ +// romdev-rabbitizer binding tests. No ROM needed: the disassembly strings are +// upstream rabbitizer's own expected outputs (tests/python/disasm_test.py and +// tests/c/instruction_checks/plain_disassembly.c, MIT, Decompollaborate). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { VERSIONS, DEFAULT_VERSION, loadRabbitizer, loadRabbitizerSync } from "../src/index.js"; + +// wasm/ is gitignored: a dev box builds it (packages/romdevtools/scripts/ +// build-rabbitizer.sh) and CI fills it from the published npm tarball +// (scripts/fetch-payloads.mjs). Without it every test skips with this reason +// instead of failing on ENOENT, the contract romdevtools' test-rom.js set. +const absent = VERSIONS.map((v) => `wasm/rabbitizer-${v}.wasm`).filter((f) => !existsSync(fileURLToPath(new URL(`../${f}`, import.meta.url)))); +const WASM_SKIP = absent.length ? `romdev-rabbitizer payload absent (${absent.join(", ")}): gitignored WASM, built by packages/romdevtools/scripts/build-rabbitizer.sh or filled from npm by scripts/fetch-payloads.mjs` : false; +const r1162 = WASM_SKIP ? null : await import("romdev-rabbitizer/1.16.2"); + +// [word, immOverride, expected] with default config and gnuMode on. +const PLAIN = [ + [0x3C088001, null, "lui $t0, 0x8001"], + [0x25080E60, null, "addiu $t0, $t0, 0xE60"], + [0x3C090002, null, "lui $t1, 0x2"], + [0x25298DE0, null, "addiu $t1, $t1, -0x7220"], + [0xAD000000, null, "sw $zero, 0x0($t0)"], + [0xAD000004, null, "sw $zero, 0x4($t0)"], + [0x21080008, null, "addi $t0, $t0, 0x8"], + [0x2129FFF8, null, "addi $t1, $t1, -0x8"], + [0x1520FFFB, null, "bnez $t1, . + 4 + (-0x5 << 2)"], + [0x00000000, null, "nop"], + [0x3C0A8000, null, "lui $t2, 0x8000"], + [0x254A0494, null, "addiu $t2, $t2, 0x494"], + [0x3C1D8002, null, "lui $sp, 0x8002"], + [0x01400008, null, "jr $t2"], + [0x27BDF8C0, null, "addiu $sp, $sp, -0x740"], + [0x3C018001, null, "lui $at, 0x8001"], + [0x03E00008, null, "jr $ra"], + [0xAC24E190, null, "sw $a0, -0x1E70($at)"], + [0x3C018001, "%hi(D_8000E190)", "lui $at, %hi(D_8000E190)"], + [0xAC24E190, "%lo(D_8000E190)", "sw $a0, %lo(D_8000E190)($at)"], + [0x0C001F24, null, "jal func_80007C90"], + [0x0C001F24, "some_func", "jal some_func"], + [0x8F99805C, null, "lw $t9, -0x7FA4($gp)"], + [0x8F99805C, "%call16(strcmp)", "lw $t9, %call16(strcmp)($gp)"], + [0x8F858028, null, "lw $a1, -0x7FD8($gp)"], + [0x8F858028, "%got(STR_10007C90)", "lw $a1, %got(STR_10007C90)($gp)"], + [0x00435022, null, "sub $t2, $v0, $v1"], + [0x00025022, null, "neg $t2, $v0"], + [0x00E41823, null, "subu $v1, $a3, $a0"], + [0x00041823, null, "negu $v1, $a0"], + [0x42000010, null, "rfe"], + [0x44444444, null, ".word 0x44444444 # cfc1 $a0, $8 # 00000444 "], + [0x77777777, null, ".word 0x77777777 # INVALID $k1, $s7, 0x7777 # 00000000 "], + [0xEEEEEEEE, null, ".word 0xEEEEEEEE # INVALID $s7, $t6, -0x1112 # 00000000 "], +]; + +const CONFIG_DEFAULTS = { + regNames_namedRegisters: true, + regNames_userFpcCsr: true, + regNames_vr4300Cop0NamedRegisters: true, + regNames_vr4300RspCop0NamedRegisters: true, + regNames_r4000AllegrexVfpuControlNamedRegisters: false, + pseudos_enablePseudos: true, + pseudos_pseudoBeqz: true, + pseudos_pseudoBnez: true, + pseudos_pseudoB: true, + pseudos_pseudoMove: true, + pseudos_pseudoNot: true, + pseudos_pseudoNeg: true, + pseudos_pseudoNegu: true, + pseudos_pseudoBal: true, + toolchainTweaks_treatJAsUnconditionalBranch: true, + toolchainTweaks_sn64DivFix: false, + toolchainTweaks_gnuMode: true, + misc_opcodeLJust: 11, + misc_unknownInstrComment: true, + misc_omit0XOnSmallImm: false, + misc_upperCaseImm: true, + misc_expandJalr: false, +}; + +// Runs fn with config fields temporarily set, restoring them afterwards. +function withConfig(rab, fields, fn) { + const saved = {}; + for (const k of Object.keys(fields)) saved[k] = rab.config[k]; + try { + Object.assign(rab.config, fields); + return fn(); + } finally { + Object.assign(rab.config, saved); + } +} + +test("loader: every shipped version loads, reports its version, defaults to the newest", { skip: WASM_SKIP }, async () => { + assert.deepEqual(VERSIONS, ["1.16.2", "1.14.3", "1.13.0"]); + assert.equal(DEFAULT_VERSION, "1.16.2"); + for (const v of VERSIONS) { + const rab = loadRabbitizerSync(v); + assert.equal(rab.__version__, v); + assert.deepEqual([...rab.__version_info__], v.split(".").map(Number)); + assert.equal(rab.__author__, "Decompollaborate"); + assert.equal(await loadRabbitizer(v), rab, "one shared namespace per version"); + } + assert.equal(await loadRabbitizer(), loadRabbitizerSync("1.16.2")); + assert.equal(r1162.default, loadRabbitizerSync("1.16.2")); + assert.equal(r1162.Instruction, loadRabbitizerSync("1.16.2").Instruction); + assert.throws(() => loadRabbitizerSync("0.0.1"), /unknown rabbitizer version/); +}); + +for (const v of VERSIONS) { + test(`${v}: upstream expected disassembly (plain CPU)`, { skip: WASM_SKIP }, () => { + const rab = loadRabbitizerSync(v); + for (const [word, imm, expected] of PLAIN) { + const instr = new rab.Instruction(word); + assert.equal(instr.disassemble(imm), expected, `word 0x${word.toString(16)}`); + if (imm === null) assert.equal(String(instr), expected); + } + }); + + test(`${v}: config defaults, setters change the output, unknown fields are rejected`, { skip: WASM_SKIP }, () => { + const rab = loadRabbitizerSync(v); + for (const [k, want] of Object.entries(CONFIG_DEFAULTS)) assert.equal(rab.config[k], want, k); + assert.equal(rab.config.regNames_gprAbiNames, rab.Abi.O32); + assert.equal(rab.config.regNames_fprAbiNames, rab.Abi.NUMERIC); + + const addiu = new rab.Instruction(0x27BDFFE8); + withConfig(rab, { misc_opcodeLJust: 10 }, () => assert.equal(addiu.disassemble(), "addiu $sp, $sp, -0x18")); + assert.equal(addiu.disassemble(null, -1), "addiu $sp, $sp, -0x18"); + withConfig(rab, { regNames_namedRegisters: false }, () => assert.equal(addiu.disassemble(), "addiu $29, $29, -0x18")); + withConfig(rab, { regNames_gprAbiNames: rab.Abi.N32 }, () => { + assert.equal(addiu.rs, rab.RegGprN32.sp); + assert.equal(new rab.Instruction(0x3C088001).rt, rab.RegGprN32.a4); + }); + // Pseudo-instruction selection happens when the word is decoded. + assert.equal(new rab.Instruction(0x00801025).disassemble(), "move $v0, $a0"); + withConfig(rab, { pseudos_pseudoMove: false }, () => { + assert.equal(new rab.Instruction(0x00801025).disassemble(), "or $v0, $a0, $zero"); + }); + + assert.throws(() => { rab.config.regNames_gprAbiNames = rab.InstrCategory.CPU; }, { name: "ValueError" }); + assert.throws(() => { rab.config.regNames_gprAbiNames = "o32"; }, TypeError); + assert.throws(() => { rab.config.misc_opcodeLJust = "11"; }, TypeError); + assert.throws(() => { rab.config.noSuchField = true; }, TypeError); + assert.equal(rab.config.misc_opcodeLJust, 11); + }); + + test(`${v}: enums are shared singletons with Python names and values`, { skip: WASM_SKIP }, () => { + const rab = loadRabbitizerSync(v); + const a = new rab.Instruction(0x27BDFFE8); + const b = new rab.Instruction(0x27A40010); + assert.equal(a.uniqueId, rab.InstrId.cpu_addiu); + assert.equal(a.uniqueId, b.uniqueId); + assert.ok(a.uniqueId instanceof rab.Enum); + assert.equal(a.uniqueId.name, "cpu_addiu"); + assert.equal(typeof a.uniqueId.value, "number"); + assert.equal(String(a.uniqueId), ``); + const map = new Map([[rab.InstrId.cpu_addiu, "x"]]); + assert.equal(map.get(b.uniqueId), "x"); + assert.equal(a.rs, rab.RegGprO32.sp); + assert.equal(b.rt, rab.RegGprO32.a0); + assert.equal(a.instrIdType, rab.InstrIdType.CPU_NORMAL); + assert.equal(a.getAccessType(), rab.AccessType.INVALID); + assert.equal(new rab.Instruction(0x8FBF0014).getAccessType(), rab.AccessType.WORD); + assert.equal(rab.Abi.fromStr("n32"), rab.Abi.N32); + assert.equal(rab.Abi.fromStr(null), rab.Abi.O32); + assert.equal(rab.Abi.fromStr("numeric"), rab.Abi.NUMERIC); + assert.equal(rab.InstrCategory.fromStr("R5900"), rab.InstrCategory.R5900); + assert.equal(rab.InstrCategory.fromStr("bogus"), null); + assert.equal(rab.InstrCategory.fromStr(null), null); + // Identity equals Python's (type, value) equality: no two members of one + // enum type share a value, apart from InstrId's two MAX sentinels. + for (const type of ["Abi", "InstrCategory", "InstrId", "InstrIdType", "OperandType", "AccessType", + "RegGprO32", "RegGprN32", "RegCop1O32", "RegCop1N32", "RegCop1N64", "TrinaryValue"]) { + const seen = new Map(); + for (const m of Object.values(rab[type])) { + if (!(m instanceof rab.Enum)) continue; + assert.equal(m.enumType, type); + if (seen.has(m.value)) assert.deepEqual([type, [seen.get(m.value), m.name].sort()], ["InstrId", ["ALL_MAX", "r5900_MAX"]]); + seen.set(m.value, m.name); + } + assert.ok(seen.size > 1, type); + } + }); + + test(`${v}: Instruction methods and Python-shaped errors`, { skip: WASM_SKIP }, () => { + const rab = loadRabbitizerSync(v); + const lui = new rab.Instruction(0x3C088001, 0x80000400); + assert.equal(lui.getRaw(), 0x3C088001); + assert.equal(lui.vram, 0x80000400); + lui.vram = 0x80001000; + assert.equal(lui.vram, 0x80001000); + assert.equal(lui.getImmediate(), 0x8001); + assert.equal(lui.getProcessedImmediate(), 0x8001); + assert.equal(lui.getOpcodeName(), "lui"); + assert.equal(lui.canBeHi(), true); + assert.equal(lui.getDestinationGpr(), rab.RegGprO32.t0); + assert.equal(lui.hasOperandAlias(rab.OperandType.cpu_immediate), true); + assert.equal(lui.hasOperand(rab.OperandType.cpu_rs), false); + assert.throws(() => lui.rs, { name: "RuntimeError", message: "'lui' instruction does not reference register 'rs'" }); + assert.throws(() => lui.getBranchOffset(), { name: "RuntimeError", message: "'lui' instruction does not have an 'branch label' field" }); + assert.throws(() => lui.getInstrIndexAsVram(), { name: "RuntimeError", message: "'lui' instruction does not have an 'jump label' field" }); + assert.throws(() => lui.getBranchVramGeneric(), { name: "RuntimeError", message: "'lui' instruction does not not perform a branch or a jump." }); + assert.throws(() => lui.hasOperand(rab.InstrId.cpu_nop), { name: "ValueError" }); + assert.throws(() => lui.hasOperand(3), TypeError); + assert.throws(() => new rab.Instruction(0, 0, rab.Abi.O32), { name: "ValueError" }); + assert.throws(() => new rab.Instruction("x"), TypeError); + assert.throws(() => lui.disassemble(5), TypeError); + + const addu = new rab.Instruction(0x00851021); // addu $v0, $a0, $a1 + assert.throws(() => addu.getProcessedImmediate(), { name: "RuntimeError", message: "'addu' instruction does not have an 'immediate' field" }); + assert.equal(addu.modifiesRd(), true); + assert.equal(addu.readsRs(), true); + assert.equal(addu.sameOpcode(new rab.Instruction(0x00A41821)), true); + assert.equal(addu.sameOpcodeButDifferentArguments(new rab.Instruction(0x00A41821)), true); + assert.throws(() => addu.sameOpcode({}), TypeError); + + const sw = new rab.Instruction(0xAFBF0014); + assert.equal(sw.getDestinationGpr(), null); + assert.equal(sw.doesStore(), true); + assert.equal(sw.getProcessedImmediate(), 0x14); + assert.equal(new rab.Instruction(0x2129FFF8).getProcessedImmediate(), -8); + + const bnez = new rab.Instruction(0x1520FFFB, 0x80000420); // bnez $t1, -0x5 words + assert.equal(bnez.isBranch(), true); + assert.equal(bnez.hasDelaySlot(), true); + assert.equal(bnez.getBranchOffset(), -0x10); + assert.equal(bnez.getBranchOffsetGeneric(), -0x10); + assert.equal(bnez.getBranchVramGeneric(), 0x80000410); + assert.equal(bnez.getGenericBranchOffset(0x80000420), -0x10); + + const jal = new rab.Instruction(0x0C001F24, 0x80000400); + assert.equal(jal.isFunctionCall(), true); + assert.equal(jal.doesLink(), true); + assert.equal(jal.getInstrIndexAsVram(), 0x80007C90); + assert.equal(jal.getBranchVramGeneric(), 0x80007C90); + + const jr = new rab.Instruction(0x03E00008); + assert.equal(jr.isReturn(), true); + assert.equal(jr.isJrRa(), true); + assert.equal(new rab.Instruction(0x01400008).isJumptableJump(), true); + assert.equal(new rab.Instruction(0).isNop(), true); + assert.equal(new rab.Instruction(0).isValid(), true); + assert.equal(new rab.Instruction(0x77777777).isValid(), false); + + const fadd = new rab.Instruction(0x46062100); // add.s $f4, $f4, $f6 + assert.equal(fadd.fd, rab.RegCop1O32.ft0); + withConfig(rab, { regNames_fprAbiNames: rab.Abi.NUMERIC }, () => { + assert.equal(fadd.fd.enumType, "RegCop1O32"); + assert.equal(fadd.disassemble(), "add.s $f4, $f4, $f6"); + }); + assert.equal(fadd.isFloat(), true); + + assert.equal(lui.inHandwrittenFunction, false); + lui.inHandwrittenFunction = true; + assert.equal(lui.inHandwrittenFunction, true); + assert.throws(() => { lui.inHandwrittenFunction = 1; }, TypeError); + + assert.equal(lui.flag_r5900DisasmAsData, rab.TrinaryValue.NONE); + lui.flag_r5900UseDollar = rab.TrinaryValue.TRUE; + assert.equal(lui.flag_r5900UseDollar, rab.TrinaryValue.TRUE); + assert.throws(() => { lui.flag_r5900UseDollar = rab.Abi.O32; }, { name: "ValueError" }); + assert.equal("flag_r5900ProdgSnAsInvertedRegs" in lui, v === "1.16.2"); + + const cat = new rab.Instruction(0x4A180001, 0, rab.InstrCategory.R3000GTE); + assert.equal(cat.getOpcodeName().toLowerCase(), "rtps"); + + const blank = new rab.Instruction(0x27BDFFE8); + blank.blankOut(); + assert.equal(blank.getRaw() & 0xFC000000, 0x24000000); + assert.equal(blank.uniqueId, rab.InstrId.cpu_addiu); + }); + + test(`${v}: RegistersTracker pairs a lui with its lo`, { skip: WASM_SKIP }, () => { + const rab = loadRabbitizerSync(v); + const lui = new rab.Instruction(0x3C018001, 0x80000400); // lui $at, 0x8001 + const lo = new rab.Instruction(0x2424E190, 0x80000404); // addiu $a0, $at, -0x1E70 + const lw = new rab.Instruction(0x8C820000, 0x80000408); // lw $v0, 0x0($a0) + const tracker = new rab.RegistersTracker(); + assert.equal(tracker.__getitem__(1).hasLuiValue, false); + tracker.processLui(lui, 0x0); + const st = tracker.getItem(1); + assert.equal(st.registerNum, 1); + assert.equal(st.hasLuiValue, true); + assert.equal(st.luiOffset, 0); + assert.equal(st.value, 0x80010000); + assert.throws(() => { st.value = 1; }, TypeError); + assert.throws(() => tracker.__getitem__(32), { name: "IndexError", message: "Index must be a value between 0 and 31" }); + + const info = tracker.preprocessLoAndGetInfo(lo, 0x4); + assert.ok(info instanceof rab.LoPairingInfo); + assert.equal(info.shouldProcess, true); + assert.equal(info.instrOffset, 0); + assert.equal(info.value, 0x80010000); + assert.equal(info.isGpRel, false); + assert.deepEqual(tracker.getLuiOffsetForLo(lo, 0x4), [0, false, true]); + assert.equal(tracker.getAddressIfCanSetType(lw, 0x8), null); + tracker.processLo(lo, 0x8000E190, 0x4); + assert.equal(tracker.getItem(4).hasLoValue, true); + assert.equal(tracker.getItem(4).value, 0x8000E190); + assert.equal(tracker.hasLoButNoHi(lo), false); + assert.equal(tracker.getAddressIfCanSetType(lw, 0x8), 0x8000E190); + + const copy = new rab.RegistersTracker(tracker); + assert.equal(copy.getItem(4).hasLoValue, true); + assert.equal(copy.getItem(4).value, 0x8000E190); + assert.throws(() => new rab.RegistersTracker({}), TypeError); + + const jr = new rab.Instruction(0x00200008); // jr $at + const jrData = tracker.getJrRegData(jr); + assert.ok(jrData instanceof rab.JrRegData); + assert.equal(typeof jrData.hasInfo(), "boolean"); + const info2 = tracker.getJrInfo(jr); + assert.ok(info2 === null || (Array.isArray(info2) && info2.length === 2)); + assert.equal(new rab.RegistersTracker().getLuiOffsetForConstant(new rab.Instruction(0x34210001)), null); + + const fresh = new rab.LoPairingInfo(); + assert.equal(fresh.shouldProcess, false); + fresh.shouldProcess = true; + assert.equal(fresh.shouldProcess, true); + assert.throws(() => { fresh.isGpGot = 1; }, TypeError); + assert.equal(new rab.JrRegData().hasInfo(), false); + assert.equal(new rab.TrackedRegisterState(5).registerNum, 5); + tracker.free(); + tracker.free(); + }); + + test(`${v}: Utils`, { skip: WASM_SKIP }, () => { + const rab = loadRabbitizerSync(v); + assert.equal(rab.Utils.from2Complement(0xFFFF, 16), -1); + assert.equal(rab.Utils.from2Complement(0x7FFF, 16), 0x7FFF); + assert.equal(rab.Utils.escapeString('a"b\\c\n\t'), 'a\\"b\\\\c\\n\\t'); + assert.equal(rab.Utils.escapeString("あい"), "あい"); + assert.equal(rab.Utils.escapeString(""), ""); + assert.equal(rab.Utils.floatRepr_32From16(0x3C00), 0x3F800000); + }); +} + +test("instructions keep their own struct: interleaved use, mutation and long immOverrides", { skip: WASM_SKIP }, () => { + const rab = loadRabbitizerSync(DEFAULT_VERSION); + const a = new rab.Instruction(0x3C018001, 0x80000400); + const b = new rab.Instruction(0x0C001F24, 0x80000404); + assert.equal(a.disassemble(), "lui $at, 0x8001"); + assert.equal(b.disassemble(), "jal func_80007C90"); + b.vram = 0x80001000; + a.blankOut(); + assert.equal(b.vram, 0x80001000); + assert.equal(a.vram, 0x80000400); + assert.equal(b.getInstrIndexAsVram(), 0x80007C90); + const long = "sym_" + "x".repeat(20000); + assert.equal(b.disassemble(long), "jal " + long); + assert.equal(new rab.Instruction(0x3C018001).disassemble("%hi(\u30b7\u30f3)"), "lui $at, %hi(\u30b7\u30f3)"); + let n = 0; + for (let i = 0; i < 200000; i++) { + const instr = new rab.Instruction((0x24000000 | i) >>> 0, 0x80000000 + i * 4); + n += instr.disassemble().length; + } + assert.ok(n > 200000 * 20); +}); diff --git a/packages/romdev-rabbitizer/test/upstream-entries.mjs b/packages/romdev-rabbitizer/test/upstream-entries.mjs new file mode 100644 index 00000000..542ff600 --- /dev/null +++ b/packages/romdev-rabbitizer/test/upstream-entries.mjs @@ -0,0 +1,51 @@ +#!/usr/bin/env node +// Runs upstream rabbitizer's instruction_checks test tables (dumped to JSON +// lines by scripts/build-rabbitizer.sh --test) through the JS binding: +// Instruction(word, 0, category).disassemble(immOverride) must equal the +// expected string, with config.toolchainTweaks_gnuMode set per entry exactly +// as upstream's check_expected_output() does. +// +// usage: node test/upstream-entries.mjs +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { loadRabbitizerSync } from "../src/index.js"; + +const [version, dir] = process.argv.slice(2); +if (!version || !dir) { + console.error("usage: upstream-entries.mjs "); + process.exit(2); +} + +const rab = loadRabbitizerSync(version); +const categories = Object.values(rab.InstrCategory).filter((v) => v instanceof rab.Enum); +const byValue = new Map(categories.map((c) => [c.value, c])); + +let total = 0; +let failed = 0; +const files = readdirSync(dir).filter((f) => f.endsWith(".jsonl")).sort(); +if (files.length === 0) { + console.error(`no .jsonl files in ${dir}`); + process.exit(1); +} +for (const f of files) { + const lines = readFileSync(join(dir, f), "utf8").split("\n").filter(Boolean); + let fileFailed = 0; + for (const line of lines) { + const e = JSON.parse(line); + total++; + rab.config.toolchainTweaks_gnuMode = e.gnuMode; + const instr = new rab.Instruction(e.word, 0, byValue.get(e.category)); + const got = instr.disassemble(e.immOverride); + if (e.expected === null || got !== e.expected) { + fileFailed++; + if (fileFailed <= 5) { + console.error(` ${f}: word 0x${e.word.toString(16).padStart(8, "0")} expected ${JSON.stringify(e.expected)} got ${JSON.stringify(got)}`); + } + } + } + rab.config.toolchainTweaks_gnuMode = true; + failed += fileFailed; + console.log(` ${fileFailed === 0 ? "PASS" : "FAIL"} ${f}: ${lines.length - fileFailed}/${lines.length}`); +} +console.log(` rabbitizer ${version} via JS binding: ${total - failed}/${total} upstream entries identical`); +if (total === 0 || failed !== 0) process.exit(1); diff --git a/packages/romdev-spimdisasm/LICENSE b/packages/romdev-spimdisasm/LICENSE new file mode 100644 index 00000000..6e694d61 --- /dev/null +++ b/packages/romdev-spimdisasm/LICENSE @@ -0,0 +1,76 @@ +MIT License + +Copyright (c) 2022 Decompollaborate + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +-------------------------------------------------------------------------------- +The CPython-derived tables and algorithms in src/py/ (see NOTICE) are +licensed under the Python Software Foundation License Version 2. Text +from CPython v3.13.1 LICENSE: + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001-2024 Python Software Foundation; All Rights Reserved" +are retained in Python alone or in any derivative version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + diff --git a/packages/romdev-spimdisasm/NOTICE b/packages/romdev-spimdisasm/NOTICE new file mode 100644 index 00000000..6f52e669 --- /dev/null +++ b/packages/romdev-spimdisasm/NOTICE @@ -0,0 +1,41 @@ +romdev-spimdisasm +================= + +This package is a JavaScript port of spimdisasm, the MIPS disassembler used by +splat, made for romdev. + +Components and attribution +-------------------------- + +1. spimdisasm + https://github.com/Decompollaborate/spimdisasm + Copyright (c) 2022 Decompollaborate. + Licensed under the MIT License (LICENSE). + src/common/, src/mips/ and src/elf32/ are module-by-module translations of + the spimdisasm Python package. The port reproduces these releases, + selected at runtime with configureVersion(): + 1.42.4 4b5d4c68eeb9f9eae14b3bb713971433ae2c3c43 (base) + 1.39.3 c4737d9266fe626c130823b3c21c60f1209f39fa + 1.35.0 cc2104b561c6b4468441862de7dec7140fad052f + The command line frontends (disasmdis, rspDisasm, elfObjDisasm, + singleFileDisasm, frontendCommon) and the argparse wiring are not ported. + +2. CPython codec tables and algorithms (src/py/cjk-tables-jp.js, + src/py/codecs.js, test/data/cjk-encmap-jp.js) + https://github.com/python/cpython + The Japanese decode maps are generated by scripts/gen-cjk-tables.mjs from + CPython 3.13 Modules/cjkcodecs/mappings_jp.h; the decoders follow + Modules/cjkcodecs/_codecs_jp.c and multibytecodec.c. The float formatting + (src/py/pyfloat.js) and set iteration order (src/py/pyset.js) follow + CPython's Python/pystrtod.c, Objects/floatobject.c and Objects/setobject.c. + Copyright (c) 2001 Python Software Foundation; All Rights Reserved. + Licensed under the Python Software Foundation License Version 2 (PSF-2.0). + +3. rabbitizer + Not contained in this package: romdev-spimdisasm depends on the separate + romdev-rabbitizer package (MIT, Decompollaborate), and activates the + rabbitizer release paired with the selected spimdisasm release + (1.42.4 with 1.16.2, 1.39.3 with 1.14.3, 1.35.0 with 1.13.0). + +4. romdev port (src/, scripts/, test/) + Copyright (c) Luis Montes. Licensed under the MIT License. diff --git a/packages/romdev-spimdisasm/README.md b/packages/romdev-spimdisasm/README.md new file mode 100644 index 00000000..83a59d81 --- /dev/null +++ b/packages/romdev-spimdisasm/README.md @@ -0,0 +1,61 @@ +# romdev-spimdisasm + +A plain JavaScript (ESM) port of +[spimdisasm](https://github.com/Decompollaborate/spimdisasm), the MIPS +disassembler splat uses to turn N64 and PS1 binaries into assembly and data +files. It reproduces the output of three spimdisasm releases byte for byte, +selected at run time. No Python is needed. + +It is part of [romdev](https://github.com/monteslu/romdev). + +## Upstream and license + +- Upstream: spimdisasm (Decompollaborate), https://github.com/Decompollaborate/spimdisasm +- Reproduced releases: + + | spimdisasm | commit | rabbitizer used | + |---|---|---| + | 1.42.4 (base) | `4b5d4c68eeb9f9eae14b3bb713971433ae2c3c43` | 1.16.2 | + | 1.39.3 | `c4737d9266fe626c130823b3c21c60f1209f39fa` | 1.14.3 | + | 1.35.0 | `cc2104b561c6b4468441862de7dec7140fad052f` | 1.13.0 | + +- License: MIT (spimdisasm and the port). The Japanese codec tables, float + formatting and set iteration order follow CPython (PSF-2.0, Copyright (c) + 2001 Python Software Foundation). See `LICENSE` and `NOTICE`. +- `src/common/`, `src/mips/` and `src/elf32/` translate the Python package + module by module. The command-line frontends (`disasmdis`, `rspDisasm`, + `elfObjDisasm`, `singleFileDisasm`) are not ported. + +## How romdev uses it + +[`romdev-splat`](https://www.npmjs.com/package/romdev-splat) loads it as its +disassembler backend. romdevtools' `decomp` tool runs splat when it sets up or +imports an N64 or PS1 decomp project (`decomp({op:'setup'})`, +`decomp({op:'import'})`), with the spimdisasm version the project pins. + +## API + +```js +import * as spimdisasm from "romdev-spimdisasm"; + +spimdisasm.configureVersion("1.39.3"); // before building any Context or section +const { common, mips, elf32 } = spimdisasm; +``` + +The module mirrors the Python package layout: the `common`, `mips` and `elf32` +namespaces keep upstream's class, function and attribute names. +`configureVersion(v)` (alias `setVersion`) selects the release to reproduce and +activates the paired rabbitizer; `getVersion()`, `__version__`, +`SUPPORTED_VERSIONS`, `DEFAULT_VERSION` and `RABBITIZER_VERSION_FOR` describe +the selection. `setRabbitizer` lets a caller supply its own rabbitizer +namespace. Exports: `.` only. + +## Requirements + +Node >= 24, ESM only. Depends on +[`romdev-rabbitizer`](https://www.npmjs.com/package/romdev-rabbitizer). No +Python, no native code. + +## Versions + +romdev-spimdisasm 0.1.0 reproduces spimdisasm 1.42.4, 1.39.3 and 1.35.0. diff --git a/packages/romdev-spimdisasm/package.json b/packages/romdev-spimdisasm/package.json new file mode 100644 index 00000000..ba9869bd --- /dev/null +++ b/packages/romdev-spimdisasm/package.json @@ -0,0 +1,41 @@ +{ + "name": "romdev-spimdisasm", + "version": "0.1.0", + "description": "spimdisasm (MIPS disassembler used by splat) ported to plain JavaScript ESM, for romdev. Reproduces spimdisasm 1.42.4, 1.39.3 and 1.35.0 output byte for byte, selectable at runtime.", + "type": "module", + "main": "src/index.js", + "exports": { + ".": "./src/index.js", + "./package.json": "./package.json" + }, + "files": [ + "src", + "LICENSE", + "NOTICE" + ], + "scripts": { + "test": "node --test --test-concurrency=4 'test/**/*.test.mjs'" + }, + "engines": { + "node": ">=24" + }, + "license": "MIT AND PSF-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/monteslu/romdev.git", + "directory": "packages/romdev-spimdisasm" + }, + "homepage": "https://github.com/monteslu/romdev#readme", + "bugs": { + "url": "https://github.com/monteslu/romdev/issues" + }, + "author": "Luis Montes", + "dependencies": { + "romdev-rabbitizer": "0.1.0" + }, + "upstream": { + "url": "https://github.com/Decompollaborate/spimdisasm", + "license": "MIT", + "versions": ["1.42.4", "1.39.3", "1.35.0"] + } +} diff --git a/packages/romdev-spimdisasm/scripts/gen-cjk-tables.mjs b/packages/romdev-spimdisasm/scripts/gen-cjk-tables.mjs new file mode 100644 index 00000000..c58a6959 --- /dev/null +++ b/packages/romdev-spimdisasm/scripts/gen-cjk-tables.mjs @@ -0,0 +1,110 @@ +#!/usr/bin/env node +// Generates src/py/cjk-tables-jp.js (decode maps used by src/py/codecs.js) +// and test/data/cjk-encmap-jp.js (encode maps, used only by the structural +// invariant tests) from CPython's Modules/cjkcodecs/mappings_jp.h. +// +// Usage: node scripts/gen-cjk-tables.mjs [path/to/mappings_jp.h] [cpythonTag] +// +// The output is deterministic: same input file -> byte-identical output. + +import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createHash } from "node:crypto"; + +const here = dirname(fileURLToPath(import.meta.url)); +const pkgRoot = join(here, ".."); + +const srcPath = process.argv[2]; +if (!srcPath) { console.error("usage: node scripts/gen-cjk-tables.mjs [cpythonTag]"); process.exit(2); } +const tag = process.argv[3] ?? "3.13"; + +const text = readFileSync(srcPath, "latin1"); +const sha1 = createHash("sha1").update(readFileSync(srcPath)).digest("hex"); + +const SYM = { U: 0xfffe, N: 0xffff, M: 0xfffe, D: 0xfffd }; + +/** Parse `static const __[N] = { ... };` into a number array. */ +function parseFlat(name) { + const re = new RegExp(`static const \\w+ __${name}\\[(\\d+)\\] = \\{([^}]*)\\};`); + const m = re.exec(text); + if (!m) throw new Error(`array __${name} not found`); + const declared = Number(m[1]); + const vals = m[2].split(",").map((s) => s.trim()).filter((s) => s !== "").map((s) => { + if (s in SYM) return SYM[s]; + const v = Number(s); + if (!Number.isInteger(v) || v < 0 || v > 0xffff) throw new Error(`bad value ${s} in ${name}`); + return v; + }); + if (vals.length !== declared) throw new Error(`${name}: parsed ${vals.length} != declared ${declared}`); + return vals; +} + +/** Parse `static const struct [256] = {...};` into [offset,bottom,top] or null per slot. */ +function parseIndex(name) { + const re = new RegExp(`static const struct \\w+ ${name}\\[256\\] = \\{([\\s\\S]*?)\\};`); + const m = re.exec(text); + if (!m) throw new Error(`index ${name} not found`); + const body = m[1].replace(/\s+/g, ""); + const out = []; + const entryRe = /\{([^{}]*)\}/g; + let e; + while ((e = entryRe.exec(body)) !== null) { + const parts = e[1].split(","); + if (parts.length !== 3) throw new Error(`bad entry ${e[1]} in ${name}`); + if (parts[0] === "0") { + out.push(null); + } else { + const pm = /^__(\w+)\+(\d+)$/.exec(parts[0]); + if (!pm) throw new Error(`bad pointer ${parts[0]} in ${name}`); + out.push([Number(pm[2]), Number(parts[1]), Number(parts[2])]); + } + } + if (out.length !== 256) throw new Error(`${name}: ${out.length} entries`); + return out; +} + +function b64u16(vals) { + const buf = Buffer.alloc(vals.length * 2); + vals.forEach((v, i) => buf.writeUInt16LE(v, i * 2)); + return buf.toString("base64"); +} + +function emitTable(name) { + const flat = parseFlat(name); + const idx = parseIndex(name); + // Sanity: every index slice lies inside the flat array. + for (const ent of idx) { + if (ent && ent[0] + (ent[2] - ent[1]) >= flat.length) throw new Error(`${name}: index out of range`); + } + return { name, length: flat.length, data: b64u16(flat), index: idx }; +} + +function fmtTable(t) { + const idx = "[" + t.index.map((e) => (e ? `[${e.join(",")}]` : "null")).join(",") + "]"; + const lines = []; + for (let i = 0; i < t.data.length; i += 100) lines.push(JSON.stringify(t.data.slice(i, i + 100))); + return `export const ${t.name} = {\n length: ${t.length},\n index: ${idx},\n data:\n ${lines.join(" +\n ")},\n};\n`; +} + +const header = (what) => `// GENERATED by scripts/gen-cjk-tables.mjs - DO NOT EDIT. +// ${what} +// Source: CPython ${tag} Modules/cjkcodecs/mappings_jp.h (sha1 ${sha1}), +// itself generated by CPython's Tools/unicode/genmap_japanese.py. +// https://github.com/python/cpython/blob/${tag}/Modules/cjkcodecs/mappings_jp.h +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved. +// Licensed under the Python Software Foundation License Version 2 (PSF-2.0). +// +// Format: data is a base64 little-endian Uint16 array (the C __ array, +// with U=0xFFFE, N=0xFFFF, D=0xFFFD); index[lead] is null or +// [offset, bottom, top] exactly like the C struct index array. +`; + +const dec = ["jisx0208_decmap", "jisx0212_decmap", "cp932ext_decmap"].map(emitTable); +const enc = ["jisxcommon_encmap", "cp932ext_encmap"].map(emitTable); + +mkdirSync(join(pkgRoot, "src/py"), { recursive: true }); +mkdirSync(join(pkgRoot, "test/data"), { recursive: true }); +writeFileSync(join(pkgRoot, "src/py/cjk-tables-jp.js"), header("Japanese decode maps (JIS X 0208, JIS X 0212, CP932 extensions).") + "\n" + dec.map(fmtTable).join("\n")); +writeFileSync(join(pkgRoot, "test/data/cjk-encmap-jp.js"), header("Japanese encode maps, used only by the structural invariant tests.") + "\n" + enc.map(fmtTable).join("\n")); +console.log(dec.concat(enc).map((t) => `${t.name}: ${t.length}`).join("\n")); diff --git a/packages/romdev-spimdisasm/src/common/CompilerConfig.js b/packages/romdev-spimdisasm/src/common/CompilerConfig.js new file mode 100644 index 00000000..60cbf674 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/CompilerConfig.js @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/CompilerConfig.py + +import { createEnum } from "../py/pyutils.js"; +import { atLeast, onVersionChange } from "../version.js"; + +/** Dataclass CompilerProperties. Positional args follow the Python field order. */ +export class CompilerProperties { + constructor( + name, + hasLateRodata = false, + prevAlign_double = 3, + prevAlign_jumptable = null, + prevAlign_string = 2, + prevAlign_function = null, + pairMultipleHiToSameLow = true, + allowRdataMigration = false, + bigAddendWorkaroundForMigratedFunctions = true, + sectionAlign_text = null, + sectionAlign_rodata = null, + ) { + this.name = name; + this.hasLateRodata = hasLateRodata; + this.prevAlign_double = prevAlign_double; + this.prevAlign_jumptable = prevAlign_jumptable; + this.prevAlign_string = prevAlign_string; + this.prevAlign_function = prevAlign_function; + this.pairMultipleHiToSameLow = pairMultipleHiToSameLow; + this.allowRdataMigration = allowRdataMigration; + this.bigAddendWorkaroundForMigratedFunctions = bigAddendWorkaroundForMigratedFunctions; + this.sectionAlign_text = sectionAlign_text; + this.sectionAlign_rodata = sectionAlign_rodata; + } + + /** Keyword-style constructor helper: CompilerProperties.of("GCC", {prevAlign_jumptable: 3}) */ + static of(name, kw = {}) { + const p = new CompilerProperties(name); + Object.assign(p, kw); + return p; + } +} + +// Per-version property tables (keyword arguments as in the Python source). +function compilerKwargs() { + const defaultDouble = atLeast("1.39.0") ? 3 : null; + return { + GCC: { prevAlign_double: defaultDouble, prevAlign_jumptable: 3 }, + IDO: { prevAlign_double: defaultDouble, hasLateRodata: true, pairMultipleHiToSameLow: false, bigAddendWorkaroundForMigratedFunctions: false, sectionAlign_text: 4, sectionAlign_rodata: 4 }, + KMC: { prevAlign_double: defaultDouble, prevAlign_jumptable: 3, sectionAlign_text: 4, sectionAlign_rodata: 4 }, + SN64: { prevAlign_double: 3, prevAlign_jumptable: 3, allowRdataMigration: true, sectionAlign_text: 4, sectionAlign_rodata: 4 }, + EGCS: { prevAlign_double: defaultDouble, prevAlign_jumptable: 3, sectionAlign_text: 4, sectionAlign_rodata: 4 }, + PSYQ: { prevAlign_double: 3, prevAlign_jumptable: 3, allowRdataMigration: true }, + MWCCPS2: atLeast("1.42.0") + ? { prevAlign_double: defaultDouble, prevAlign_jumptable: 4, bigAddendWorkaroundForMigratedFunctions: false } + : { prevAlign_double: defaultDouble, prevAlign_jumptable: 4 }, + EEGCC: { prevAlign_double: defaultDouble, prevAlign_jumptable: 3, prevAlign_string: 3, prevAlign_function: 3 }, + }; +} + +const COMPILER_NAMES = ["GCC", "IDO", "KMC", "SN64", "EGCS", "PSYQ", "MWCCPS2", "EEGCC"]; + +const initialKw = compilerKwargs(); + +export const Compiler = createEnum( + "Compiler", + COMPILER_NAMES.map((n) => [n, CompilerProperties.of(n, initialKw[n])]), + {}, + { + fromStr(value) { + return compilerOptions.has(value) ? compilerOptions.get(value) : null; + }, + }, +); + +/** dict[str, Compiler] */ +export const compilerOptions = new Map(COMPILER_NAMES.map((n) => [n, Compiler[n]])); + +function resetCompilerProperties() { + const kw = compilerKwargs(); + for (const n of COMPILER_NAMES) { + const fresh = CompilerProperties.of(n, kw[n]); + Object.assign(Compiler[n].value, fresh); + } +} + +onVersionChange(resetCompilerProperties); diff --git a/packages/romdev-spimdisasm/src/common/Context.js b/packages/romdev-spimdisasm/src/common/Context.js new file mode 100644 index 00000000..aaa50fb1 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/Context.js @@ -0,0 +1,275 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/Context.py (the argparse parts are not ported). + +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +import * as Utils from "./Utils.js"; +import { SymbolsSegment } from "./SymbolsSegment.js"; +import { GpAccessContainer, GotEntry } from "./GpAccesses.js"; +import { RelocationInfo, RelocType } from "./Relocation.js"; +import { hexU, pyStrip } from "../py/pyutils.js"; +import { atLeast } from "../version.js"; + +export class AddressRange { + constructor(start, end) { + this.start = start; + this.end = end; + } + + isInRange(address) { + return this.start <= address && address < this.end; + } + + decreaseStart(address) { + this.start = Math.min(this.start, address); + } + + increaseEnd(address) { + this.end = Math.max(this.end, address); + } + + toString() { + return `AddressRange(0x${hexU(this.start, 8)}, 0x${hexU(this.end, 8)})`; + } +} + +export class SymbolsRanges { + constructor(start, end) { + this.mainAddressRange = new AddressRange(start, end); + this.specialRanges = []; + } + + isInRange(address) { + if (this.mainAddressRange.isInRange(address)) return true; + for (const spRange of this.specialRanges) if (spRange.isInRange(address)) return true; + return false; + } + + decreaseStart(address) { + this.mainAddressRange.decreaseStart(address); + } + + increaseEnd(address) { + this.mainAddressRange.increaseEnd(address); + } + + addSpecialRange(start, end) { + if (end <= start) return null; + const addrRange = new AddressRange(start, end); + this.specialRanges.push(addrRange); + return addrRange; + } + + toString() { + let ret = `MainRange: ${this.mainAddressRange}\n`; + this.specialRanges.forEach((spRange, i) => { + ret += ` ${i}'th special: ${spRange}\n`; + }); + return ret; + } +} + +/** A minimal text sink compatible with Python's TextIO.write for saveContextToFile. */ +class StringSink { + constructor() { + this.parts = []; + } + write(s) { + this.parts.push(s); + } + toString() { + return this.parts.join(""); + } +} + +export class Context { + static N64DefaultBanned = new Set([ + 0x7fffffe0, // osInvalICache + 0x7ffffff0, // osInvalDCache, osWritebackDCache, osWritebackDCacheAll + 0x7fffffff, + 0x80000010, + 0x80000020, + ]); + + constructor() { + // Arbitrary initial range + this.globalSegment = new SymbolsSegment(this, 0x0, 0x1000, 0x80000000, 0x80001000, null); + // For symbols that we don't know where they come from + this.unknownSegment = new SymbolsSegment(this, null, null, 0x00000000, 0xffffffff, null); + if (atLeast("1.39.0")) this.unknownSegment._isTheUnknownSegment = true; + else this._isTheUnknownSegment = true; + + /** Outer key is overlay type, inner key is the vrom of the overlay's segment */ + this.overlaySegments = new Map(); + + this.absoluteSegment = new SymbolsSegment(this, null, null, 0x00000000, 0xffffffff, null); + this.absoluteSegment._isAbsoluteSegment = true; + + this.totalVramRange = new SymbolsRanges(this.globalSegment.vramStart, this.globalSegment.vramEnd); + this._defaultVramRanges = true; + + // Stuff that looks like pointers, but the disassembler shouldn't count it as a pointer + this.bannedSymbols = new Set(); + this.bannedRangedSymbols = []; + + /** key: vrom address */ + this.globalRelocationOverrides = new Map(); + + this.gpAccesses = new GpAccessContainer(); + } + + changeGlobalSegmentRanges(vromStart, vromEnd, vramStart, vramEnd) { + if (vromStart === vromEnd) Utils.eprint(`Warning: globalSegment's will has its vromStart equal to the vromEnd (0x${hexU(vromStart)})`); + if (vramStart === vramEnd) Utils.eprint(`Warning: globalSegment's will has its vramStart equal to the vramEnd (0x${hexU(vramStart)})`); + this.globalSegment.changeRanges(vromStart, vromEnd, vramStart, vramEnd); + if (this._defaultVramRanges) { + this.totalVramRange.mainAddressRange.start = vramStart; + this.totalVramRange.mainAddressRange.end = vramEnd; + this._defaultVramRanges = false; + } + this.totalVramRange.decreaseStart(vramStart); + this.totalVramRange.increaseEnd(vramEnd); + } + + addOverlaySegment(overlayCategory, segmentVromStart, segmentVromEnd, segmentVramStart, segmentVramEnd, name = null) { + if (!this.overlaySegments.has(overlayCategory)) this.overlaySegments.set(overlayCategory, new Map()); + const segment = new SymbolsSegment(this, segmentVromStart, segmentVromEnd, segmentVramStart, segmentVramEnd, overlayCategory, atLeast("1.42.0") ? name : null); + this.overlaySegments.get(overlayCategory).set(segmentVromStart, segment); + + if (this._defaultVramRanges) { + this.totalVramRange.mainAddressRange.start = segmentVramStart; + this.totalVramRange.mainAddressRange.end = segmentVramEnd; + this._defaultVramRanges = false; + } + this.totalVramRange.decreaseStart(segmentVramStart); + this.totalVramRange.increaseEnd(segmentVramEnd); + + return segment; + } + + isInTotalVramRange(address) { + return this.totalVramRange.isInRange(address); + } + + addSpecialVramRange(start, end) { + return this.totalVramRange.addSpecialRange(start, end); + } + + setupGotTable(pltGot, table) { + this.gpAccesses.setupGotTable(pltGot, table); + + for (const gotEntry of this.gpAccesses.got.iterGlobals()) { + const contextSym = this.globalSegment.addSymbol(gotEntry.value()); + contextSym.isUserDeclared = true; + contextSym.isGotGlobal = true; + } + } + + /** @deprecated prefer setupGotTable() instead. */ + initGotTable(pltGot, localsTable, globalsTable) { + const table = []; + for (const x of localsTable) table.push(new GotEntry(x, false)); + for (const x of globalsTable) table.push(new GotEntry(x, true)); + this.setupGotTable(pltGot, table); + } + + addSmallSection(address, size) { + this.gpAccesses.addSmallSection(address, size); + } + + fillDefaultBannedSymbols() { + for (const x of Context.N64DefaultBanned) this.bannedSymbols.add(x); + } + + isAddressInGlobalRange(address) { + return this.totalVramRange.isInRange(address); + } + + addBannedSymbol(address) { + this.bannedSymbols.add(address); + } + + addBannedSymbolRange(rangeStart, rangeEnd) { + this.bannedRangedSymbols.push(new AddressRange(rangeStart, rangeEnd)); + } + + addBannedSymbolRangeBySize(rangeStart, size) { + this.bannedRangedSymbols.push(new AddressRange(rangeStart, rangeStart + size)); + } + + isAddressBanned(address) { + if (this.bannedSymbols.has(address)) return true; + for (const ranged of this.bannedRangedSymbols) if (ranged.isInRange(address)) return true; + return false; + } + + addGlobalReloc(vromAddres, relocType, symbol, addend = 0) { + const reloc = new RelocationInfo(relocType, symbol, addend, null, true); + this.globalRelocationOverrides.set(vromAddres, reloc); + return reloc; + } + + readSplatRelocAddrs(filepath) { + if (!existsSync(String(filepath))) { + Utils.eprintQuietless(`reloc_addrs file '${filepath}' not found.`); + return; + } + + const getRequired = (pairs, key, line) => { + const value = pairs.has(key) ? pairs.get(key) : null; + if (value === null) Utils.panic(`\nError parsing reloc_addrs file '${filepath}'.\n Missing key '${key}'.\n While parsing line '${line}'`); + return value; + }; + + const text = readFileSync(String(filepath), "utf8"); + const lines = text.split(/\r\n|\r|\n/); + if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop(); + for (let line of lines) { + line = pyStrip(line); + const pairs = Utils.parseColonSeparatedPairLine(line); + + const romStr = getRequired(pairs, "rom", line); + const rom = Utils.intFromStr(romStr); + if (rom === null) Utils.panic(`\nInvalid value '${romStr}' for attribute 'rom'.\n While parsing line '${line}'`); + + const relocStr = getRequired(pairs, "reloc", line); + const reloc = RelocType.fromStr(relocStr); + if (reloc === null) Utils.panic(`\nInvalid value '${relocStr}' for attribute 'reloc'.\n While parsing line '${line}'`); + + const symbol = getRequired(pairs, "symbol", line); + + const addend = Utils.getMaybeIntFromMaybeStr(pairs.has("addend") ? pairs.get("addend") : null) || 0; + + this.addGlobalReloc(rom, reloc, symbol, addend); + } + } + + saveContextToFile(contextPath) { + contextPath = String(contextPath); + const parsed = path.parse(contextPath); + const stem = parsed.name; + const suffix = parsed.ext; + const withName = (n) => path.join(parsed.dir, n); + + let sink = new StringSink(); + this.globalSegment.saveContextToFile(sink); + writeFileSync(contextPath, sink.toString()); + + const unknownPath = withName(`${stem}_unksegment${suffix}`); + sink = new StringSink(); + this.unknownSegment.saveContextToFile(sink); + writeFileSync(unknownPath, sink.toString()); + + for (const [overlayCategory, segmentsPerVrom] of this.overlaySegments) { + for (const [segmentVrom, overlaySegment] of segmentsPerVrom) { + const ovlPath = atLeast("1.42.0") + ? withName(`${stem}_${overlayCategory}_${overlaySegment.name === null ? "None" : overlaySegment.name}_${hexU(segmentVrom, 6)}${suffix}`) + : withName(`${stem}_${overlayCategory}_${hexU(segmentVrom, 6)}${suffix}`); + sink = new StringSink(); + overlaySegment.saveContextToFile(sink); + writeFileSync(ovlPath, sink.toString()); + } + } + } +} diff --git a/packages/romdev-spimdisasm/src/common/ContextSymbols.js b/packages/romdev-spimdisasm/src/common/ContextSymbols.js new file mode 100644 index 00000000..928e16c6 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/ContextSymbols.js @@ -0,0 +1,749 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/ContextSymbols.py + +import { rabbitizer } from "../rabbitizer.js"; +import { GlobalConfig } from "./GlobalConfig.js"; +import { FileSectionType } from "./FileSectionType.js"; +import { SortedDict } from "./SortedDict.js"; +import * as Utils from "./Utils.js"; +import { createEnum, hexU, pyStr, anyPySpace, enumValue } from "../py/pyutils.js"; +import { atLeast, onVersionChange } from "../version.js"; +import { newSymbolSet } from "./symset.js"; + +export const SymbolSpecialType = createEnum( + "SymbolSpecialType", + [ + ["function", 1], + ["branchlabel", 2], + ["jumptable", 3], + ["jumptablelabel", 4], + ["hardwarereg", 5], + ["constant", 6], + ["gccexcepttable", 7], + ["gccexcepttablelabel", 8], + ], + { + isTargetLabel() { + return this === SymbolSpecialType.branchlabel || this === SymbolSpecialType.jumptablelabel || this === SymbolSpecialType.gccexcepttablelabel; + }, + toStr() { + return "@" + this.name; + }, + }, + { + fromStr(symTypeStr) { + switch (symTypeStr) { + case "@function": return SymbolSpecialType.function; + case "@branchlabel": return SymbolSpecialType.branchlabel; + case "@jumptable": return SymbolSpecialType.jumptable; + case "@jumptablelabel": return SymbolSpecialType.jumptablelabel; + case "@hardwarereg": return SymbolSpecialType.hardwarereg; + case "@constant": return SymbolSpecialType.constant; + case "@gccexcepttable": return SymbolSpecialType.gccexcepttable; + case "@gccexcepttablelabel": return SymbolSpecialType.gccexcepttablelabel; + default: return null; + } + }, + }, +); + +export function isSymbolSpecialType(x) { + return x !== null && typeof x === "object" && x.__enumName === "SymbolSpecialType"; +} + +export class AccessTypeInfo { + constructor(size, typeSigned, typeUnsigned, typeNameAliases = new Set()) { + this.size = size; + this.typeSigned = typeSigned; + this.typeUnsigned = typeUnsigned; + this.typeNameAliases = typeNameAliases; + } + + typeMatchesAccess(typename) { + if (typename === null || typename === undefined) return false; + if (typename === this.typeSigned) return true; + if (typename === this.typeUnsigned) return true; + return typeof typename === "string" && this.typeNameAliases.has(typename); + } + + getAllTypes() { + const types = new Set(); + if (this.typeSigned !== null) types.add(this.typeSigned); + if (this.typeUnsigned !== null) types.add(this.typeUnsigned); + for (const t of this.typeNameAliases) types.add(t); + return types; + } +} + +// Ordered like the Python dict literal. +const ACCESS_KIND_TABLE = [ + ["BYTE", new AccessTypeInfo(1, "s8", "u8", new Set(["vs8", "vu8"]))], + ["SHORT", new AccessTypeInfo(2, "s16", "u16", new Set(["vs16", "vu16"]))], + // Ignore signed WORD since it tends to not give a proper type + ["WORD", new AccessTypeInfo(4, null, "u32", new Set(["s32", "vs32", "vu32"]))], + ["DOUBLEWORD", new AccessTypeInfo(8, "s64", "u64", new Set(["vs64", "vu64"]))], + ["QUADWORD", new AccessTypeInfo(16, null, null)], + ["FLOAT", new AccessTypeInfo(4, "f32", null, new Set(["Vec3f"]))], + ["DOUBLEFLOAT", new AccessTypeInfo(8, "f64", null)], + ["WORD_LEFT", new AccessTypeInfo(null, null, null)], + ["WORD_RIGHT", new AccessTypeInfo(null, null, null)], + ["DOUBLEWORD_LEFT", new AccessTypeInfo(null, null, null)], + ["DOUBLEWORD_RIGHT", new AccessTypeInfo(null, null, null)], +]; + +const ACCESS_KIND_BY_NAME = new Map(ACCESS_KIND_TABLE); + +let _gAccessKinds = null; +let _accessByValue = null; + +/** dict[rabbitizer.AccessType, AccessTypeInfo], built lazily (needs rabbitizer). */ +export function getAccessKinds() { + if (_gAccessKinds === null) { + _gAccessKinds = new Map(); + _accessByValue = new Map(); + for (const [name, info] of ACCESS_KIND_TABLE) { + const e = rabbitizer.AccessType[name]; + _gAccessKinds.set(e, info); + _accessByValue.set(enumValue(e), info); + } + } + return _gAccessKinds; +} + +onVersionChange(() => { + _gAccessKinds = null; + _accessByValue = null; +}); + +/** gAccessKinds[accessType] */ +export function accessKindInfo(accessType) { + getAccessKinds(); + const info = _accessByValue.get(enumValue(accessType)); + if (info === undefined) throw new Error(`KeyError: ${accessType}`); + return info; +} + +function accessKindByName(name) { + return ACCESS_KIND_BY_NAME.get(name); +} + +function isAccessType(accessType, name) { + if (accessType === null || accessType === undefined) return false; + return enumValue(accessType) === enumValue(rabbitizer.AccessType[name]); +} + +export const gKnownTypes = new Set(["asciz", "char", "char*", "String", "Char"]); +for (const [, kind] of ACCESS_KIND_TABLE) for (const t of kind.getAllTypes()) gKnownTypes.add(t); + +/** ContextSymbol.__eq__ : same address and vromAddress. */ +export function symEq(a, b) { + if (a === b) return true; + if (a === null || a === undefined || b === null || b === undefined) return false; + if (!(a instanceof ContextSymbol) || !(b instanceof ContextSymbol)) return false; + return a.address === b.address && (a.vromAddress ?? null) === (b.vromAddress ?? null); +} + +export class ContextSymbol { + constructor(address, segment = null) { + this.address = address; + this.segment = segment; + this.name = null; + this.nameEnd = null; + this.userDeclaredSize = null; + this.autodetectedSize = null; + this.userDeclaredType = null; + this.autodetectedType = null; + + this.accessType = null; + this.unsignedAccessType = null; + + this.vromAddress = null; + + this.sectionType = FileSectionType.Unknown; + + this.isDefined = false; + this.isUserDeclared = false; + this.isAutogenerated = false; + + this.isMaybeString = false; + this.failedStringDecoding = false; + this._ranStringCheck = false; + + this.isMaybePascalString = false; + this.failedPascalStringDecoding = false; + this._ranPascalStringCheck = false; + + this.referenceCounter = 0; + this.referenceFunctions = newSymbolSet(); + this.referenceSymbols = newSymbolSet(); + + this.parentFunction = null; + this.branchLabels = new SortedDict(); + this.jumpTables = new SortedDict(); + + this.parentFileName = null; + this.inFileOffset = null; + + this.overlayCategory = null; + + this.nameGetCallback = null; + + this.unknownSegment = false; + + this.isGot = false; + this.isGotGlobal = false; + this.isGotLocal = false; + this.gotIndex = null; + + this.accessedAsGpRel = false; + + this._isStatic = false; + + this.isAutoCreatedPad = false; + this.autoCreatedPadMainSymbol = null; + + this.firstLoAccess = null; + + this.isElfNotype = false; + + this.forceMigration = false; + this.forceNotMigration = false; + this.functionOwnerForMigration = null; + + this.allowedToReferenceAddends = false; + this.notAllowedToReferenceAddends = false; + + this.allowedToReferenceConstants = false; + this.notAllowedToReferenceConstants = false; + + this.allowedToReferenceSymbols = true; + this.allowedToBeReferenced = true; + + this.isAutocreatedSymFromOtherSizedSym = false; + + this.isMips1Double = false; + + this.visibility = null; + + this.alignmentShift = null; + + this.useNonMatchingLabel = true; + } + + get vram() { + return this.address; + } + + /** @deprecated */ + get size() { + return this.userDeclaredSize; + } + set size(value) { + this.userDeclaredSize = value; + } + + /** @deprecated */ + get type() { + return this.getTypeSpecial(); + } + set type(value) { + this.setTypeSpecial(value, this.isAutogenerated); + } + + hasNoType() { + const currentType = this.getTypeSpecial(); + return (currentType === null || currentType === "") && this.accessType === null; + } + + hasOnlyAutodetectedType() { + if (this.userDeclaredType !== null && this.userDeclaredType !== "") return false; + return (this.autodetectedType !== null && this.autodetectedType !== "") || this.accessType !== null; + } + + isTrustableFunction(rsp = false) { + if (this.unknownSegment) return false; + if (this.isGotLocal) return false; + if (this.isAutocreatedSymFromOtherSizedSym) return true; + + const currentType = this.getTypeSpecial(); + + if (GlobalConfig.TRUST_USER_FUNCTIONS && this.isUserDeclared) { + if (currentType === SymbolSpecialType.branchlabel) return false; + return true; + } + + if (GlobalConfig.TRUST_JAL_FUNCTIONS && this.isAutogenerated && currentType === SymbolSpecialType.function) return true; + + if (rsp) return true; + + return false; + } + + isByte() { + if (!GlobalConfig.USE_DOT_BYTE) return false; + const currentType = this.getTypeSpecial(); + if (accessKindByName("BYTE").typeMatchesAccess(currentType)) return true; + if (currentType !== null) return false; + return isAccessType(this.accessType, "BYTE"); + } + + isShort() { + if (!GlobalConfig.USE_DOT_SHORT) return false; + const currentType = this.getTypeSpecial(); + if (accessKindByName("SHORT").typeMatchesAccess(currentType)) return true; + if (currentType !== null) return false; + return isAccessType(this.accessType, "SHORT"); + } + + isString() { + if (this.failedStringDecoding) return false; + + const currentType = this.getTypeSpecial(); + + let stringGuesserLevel; + if (this.sectionType === FileSectionType.Rodata) stringGuesserLevel = GlobalConfig.RODATA_STRING_GUESSER_LEVEL; + else stringGuesserLevel = GlobalConfig.DATA_STRING_GUESSER_LEVEL; + + if (currentType === "char" || currentType === "char*" || currentType === "asciz") return true; + if (!this.isMaybeString) return false; + + if (stringGuesserLevel < 1) return false; + + if (this.hasNoType()) return true; + + if (this.hasOnlyAutodetectedType()) { + if (stringGuesserLevel >= 4) return true; + } + return false; + } + + isPascalString() { + if (this.failedPascalStringDecoding) return false; + + const currentType = this.getTypeSpecial(); + + let stringGuesserLevel; + if (this.sectionType === FileSectionType.Rodata) stringGuesserLevel = GlobalConfig.PASCAL_RODATA_STRING_GUESSER_LEVEL; + else stringGuesserLevel = GlobalConfig.PASCAL_DATA_STRING_GUESSER_LEVEL; + + if (currentType === "String" || currentType === "Char") return true; + if (!this.isMaybePascalString) return false; + + if (stringGuesserLevel < 1) return false; + + if (this.hasNoType()) return true; + + if (this.hasOnlyAutodetectedType()) { + if (stringGuesserLevel >= 4) return true; + } + return false; + } + + isFloat() { + if (this.vram % 4 !== 0) return false; + const currentType = this.getTypeSpecial(); + if (accessKindByName("FLOAT").typeMatchesAccess(currentType)) return true; + if (currentType !== null) return false; + return isAccessType(this.accessType, "FLOAT"); + } + + isDouble() { + if (this.vram % 8 !== 0) return false; + const currentType = this.getTypeSpecial(); + if (accessKindByName("DOUBLEFLOAT").typeMatchesAccess(currentType)) return true; + if (currentType !== null) return false; + return isAccessType(this.accessType, "DOUBLEFLOAT"); + } + + isJumpTable() { + return this.getTypeSpecial() === SymbolSpecialType.jumptable; + } + + isGccExceptTable() { + return this.getTypeSpecial() === SymbolSpecialType.gccexcepttable; + } + + isStatic() { + const currentType = this.getTypeSpecial(); + if (currentType === SymbolSpecialType.jumptablelabel) return false; + if (this._isStatic) return true; + if (atLeast("1.42.0") && this.nameGetCallback !== null) return false; + if (this.name === null) return false; + return this.name.startsWith("."); + } + + isLateRodata() { + if (!GlobalConfig.COMPILER.value.hasLateRodata) return false; + return this.isJumpTable() || this.isFloat() || this.isDouble(); + } + + notPointerByType() { + if (this.isByte()) return true; + if (this.isShort()) return true; + if (this.isFloat()) return true; + if (this.isDouble()) return true; + if (this.isString()) return true; + if (this.isPascalString()) return true; + return false; + } + + hasUserDeclaredSize() { + return this.userDeclaredSize !== null; + } + + _defaultName_suffix() { + let suffix = ""; + if (this.overlayCategory !== null) { + suffix = "_"; + if (this.vromAddress !== null) suffix += hexU(this.vromAddress, 6); + } + if (GlobalConfig.CUSTOM_SUFFIX) suffix += GlobalConfig.CUSTOM_SUFFIX; + return suffix; + } + + _defaultName_uniqueIdentifier(symType) { + if (GlobalConfig.SEQUENTIAL_LABEL_NAMES && this.parentFunction !== null) { + if (symType === SymbolSpecialType.branchlabel || symType === SymbolSpecialType.jumptablelabel) { + const index = this.parentFunction.branchLabels.index(this.vram); + if (index !== null) return `${this.parentFunction.getName()}_${index + 1}`; + } else if (symType === SymbolSpecialType.jumptable) { + const index = this.parentFunction.jumpTables.index(this.vram); + if (index !== null) return `${this.parentFunction.getName()}_${index + 1}`; + } + } + + if (GlobalConfig.AUTOGENERATED_NAMES_BASED_ON_FILE_NAME) { + if (this.parentFileName !== null && this.inFileOffset !== null && symType !== SymbolSpecialType.function) { + const sectionName = this.sectionType.toStr().replaceAll(".", "_"); + return `${this.parentFileName}${sectionName}_${hexU(this.inFileOffset, 6)}`; + } + } + + const suffix = this._defaultName_suffix(); + + if (GlobalConfig.LEGACY_SYM_ADDR_ZERO_PADDING) return `${hexU(this.address, 6)}${suffix}`; + return `${hexU(this.address, 8)}${suffix}`; + } + + _defaultName_sectionPrefix(symType) { + if ( + symType === SymbolSpecialType.function || + symType === SymbolSpecialType.branchlabel || + symType === SymbolSpecialType.jumptablelabel || + symType === SymbolSpecialType.jumptable || + symType === SymbolSpecialType.gccexcepttable || + symType === SymbolSpecialType.gccexcepttablelabel + ) { + return ""; + } + + if (GlobalConfig.AUTOGENERATED_NAMES_BASED_ON_SECTION_TYPE) { + if (this.sectionType === FileSectionType.Rodata) return "RO_"; + else if (this.sectionType === FileSectionType.Bss) return "B_"; + else if (this.sectionType === FileSectionType.Text) return "T_"; + else if (this.sectionType === FileSectionType.Reloc) return "REL_"; + if (this.sectionType === FileSectionType.GccExceptTable) return "EHTBL_"; + } + return "D_"; + } + + _defaultName_typePrefix(symType) { + if (symType === SymbolSpecialType.function) return "func_"; + if (symType === SymbolSpecialType.branchlabel || symType === SymbolSpecialType.jumptablelabel) return ".L"; + if (symType === SymbolSpecialType.jumptable) return "jtbl_"; + if (symType === SymbolSpecialType.gccexcepttable) return "ehtbl_"; + if (symType === SymbolSpecialType.gccexcepttablelabel) return "$LEH_"; + + if (GlobalConfig.AUTOGENERATED_NAMES_BASED_ON_DATA_TYPE) { + if (this.isFloat()) return "FLT_"; + else if (this.isDouble()) return "DBL_"; + else if (this.isString()) return "STR_"; + else if (this.isPascalString()) return "PSTR_"; + } + return ""; + } + + getDefaultName() { + const currentType = this.getTypeSpecial(); + const uniqueIdentifier = this._defaultName_uniqueIdentifier(currentType); + const sectionPrefix = this._defaultName_sectionPrefix(currentType); + const typePrefix = this._defaultName_typePrefix(currentType); + return `${sectionPrefix}${typePrefix}${uniqueIdentifier}`; + } + + getNameUnquoted() { + let name; + if (this.nameGetCallback !== null) name = this.nameGetCallback(this); + else if (this.name === null) name = this.getDefaultName(); + else name = this.name; + return name; + } + + getName() { + const name = this.getNameUnquoted(); + if (name.includes("@") || name.includes("<") || name.includes("\\") || name.includes("-") || name.includes("+") || (atLeast("1.42.0") && anyPySpace(name))) { + return `"${name}"`; + } + return name; + } + + setNameIfUnset(name) { + if (this.name === null) { + this.name = name; + return true; + } + return false; + } + + setNameGetCallback(callback) { + this.nameGetCallback = callback; + } + + setNameGetCallbackIfUnset(callback) { + if (this.nameGetCallback === null) this.nameGetCallback = callback; + } + + getNameEnd() { + return this.nameEnd; + } + + getSize() { + if (this.userDeclaredSize !== null) return this.userDeclaredSize; + if (this.autodetectedSize !== null) return this.autodetectedSize; + + const currentType = this.getTypeSpecial(); + + // Infer size based on user-declared type + if (currentType !== null && !isSymbolSpecialType(currentType)) { + for (const [, info] of ACCESS_KIND_TABLE) { + if (info.typeMatchesAccess(currentType)) { + const size = info.size; + if (size !== null) return size; + break; + } + } + } + + // Infer size based on instruction access type + if (this.accessType !== null) { + const size = accessKindInfo(this.accessType).size; + if (size !== null) return size; + } + + // Infer size based on symbol's address alignment + if (this.vram % 4 === 0) return 4; + if (this.vram % 2 === 0) return 2; + return 1; + } + + getVrom() { + if (this.vromAddress === null) return 0; + return this.vromAddress; + } + + setSizeIfUnset(size) { + if (size <= 0) return false; + if (this.userDeclaredSize === null) { + this.userDeclaredSize = size; + return true; + } + return false; + } + + getTypeSpecial() { + if (this.userDeclaredType !== null) return this.userDeclaredType; + return this.autodetectedType; + } + + getType() { + const currentType = this.getTypeSpecial(); + if (currentType === null) { + if (this.accessType !== null && this.unsignedAccessType !== null) { + const typeInfo = accessKindInfo(this.accessType); + const t = this.unsignedAccessType ? typeInfo.typeUnsigned : typeInfo.typeSigned; + if (t !== null) return t; + } + return ""; + } + if (isSymbolSpecialType(currentType)) return currentType.toStr(); + return currentType; + } + + setTypeSpecial(newType, isAutogenerated) { + if (newType === undefined) newType = null; + if (isAutogenerated) this.autodetectedType = newType; + else this.userDeclaredType = newType; + } + + setTypeIfUnset(newType, isAutogenerated) { + if (this.hasNoType()) { + this.setTypeSpecial(newType, isAutogenerated); + return true; + } + return false; + } + + setAccessTypeIfUnset(accessType, unsignedMemoryAccess) { + if (this.accessType === null && this.unsignedAccessType === null) { + this.accessType = accessType; + this.unsignedAccessType = unsignedMemoryAccess; + return true; + } + return false; + } + + setFirstLoAccessIfUnset(loOffset) { + if (this.firstLoAccess === null) this.firstLoAccess = loOffset; + } + + getSymbolPlusOffset(address) { + if (this.address === address) return this.getName(); + if (this.address > address) return `${this.getName()} - 0x${hexU(this.address - address)}`; + return `${this.getName()} + 0x${hexU(address - this.address)}`; + } + + getLabelMacro(isInMiddleLabel = false) { + if (!GlobalConfig.ASM_USE_SYMBOL_LABEL) return null; + let label = ""; + if (GlobalConfig.ASM_COMMENT) { + if (this.isStatic()) label += `/* static variable */${GlobalConfig.LINE_ENDS}`; + if (this.isAutogeneratedPad()) { + let mainSymbolInfo = ""; + if (this.autoCreatedPadMainSymbol !== null) mainSymbolInfo = ` (generated by the size of ${this.autoCreatedPadMainSymbol.getName()})`; + label += `/* Automatically generated and unreferenced pad${mainSymbolInfo} */${GlobalConfig.LINE_ENDS}`; + } + } + + const currentType = this.getTypeSpecial(); + if (currentType === SymbolSpecialType.jumptablelabel) label += GlobalConfig.ASM_JTBL_LABEL; + else if (currentType === SymbolSpecialType.gccexcepttablelabel) label += GlobalConfig.ASM_EHTBL_LABEL; + else if (typeof currentType === "string" && gKnownTypes.has(currentType)) label += GlobalConfig.ASM_DATA_LABEL; + else if (this.sectionType === FileSectionType.Text) { + if (isInMiddleLabel) label += GlobalConfig.ASM_TEXT_ALT_LABEL; + else label += GlobalConfig.ASM_TEXT_LABEL; + } else label += GlobalConfig.ASM_DATA_LABEL; + return label; + } + + isAutogeneratedPad() { + return this.isAutoCreatedPad && this.referenceCounter === 0 && this.isAutogenerated; + } + + getReferenceeSymbols() { + if (!GlobalConfig.ASM_COMMENT || !GlobalConfig.ASM_REFERENCEE_SYMBOLS) return ""; + + if (this.referenceFunctions.size) { + let output = "/* Functions referencing this symbol:"; + for (const sym of this.referenceFunctions) output += ` ${sym.getName()}`; + return `${output} */${GlobalConfig.LINE_ENDS}`; + } + + if (this.referenceSymbols.size) { + let output = "/* Symbols referencing this symbol:"; + for (const sym of this.referenceSymbols) output += ` ${sym.getName()}`; + return `${output} */${GlobalConfig.LINE_ENDS}`; + } + return ""; + } + + getAlignment() { + if (this.alignmentShift !== null) return 2 ** this.alignmentShift; + return null; + } + + setAlignment(alignment) { + if (alignment <= 0) { + Utils.eprint(` +Warning: Tried to set an alignment of \`${alignment}\` to symbol \`${this.getName()}\` (\`0x${hexU(this.vram, 8)}\`), but the given alignment is negative. +This alignment will be discarded. +`); + return; + } + // Calculate the alignment shift value: (alignment & -alignment).bit_length() - 1 + let low = alignment; + let alignmentShift = 0; + while (low % 2 === 0) { + low /= 2; + alignmentShift++; + } + if (2 ** alignmentShift !== alignment) { + Utils.eprint(` +Warning: Tried to set an alignment of \`${alignment}\` to symbol \`${this.getName()}\` (\`0x${hexU(this.vram, 8)}\`), but the given alignment isn't a power of two. +This alignment will be discarded. +`); + return; + } + const div = 2 ** alignmentShift; + const alignedVram = Math.floor(this.vram / div) * div; + if (alignedVram !== this.vram) { + Utils.eprint(` +Warning: Tried to set an alignment of \`${alignment}\` to symbol \`${this.getName()}\` (\`0x${hexU(this.vram, 8)}\`), but the given alignment does not match the alignment the symbol currently has. +This alignment will be discarded. +`); + return; + } + this.alignmentShift = alignmentShift; + } + + static getCsvHeader() { + let output = "address,name,getName,getNameEnd,"; + output += "userDeclaredType,autodetectedType,getType,"; + output += "accessType,"; + output += "userDeclaredSize,"; + output += "autodetectedSize,"; + output += "getSize,getVrom,sectionType,"; + output += "isDefined,isUserDeclared,isAutogenerated,"; + output += "isMaybeString,failedStringDecoding,isMaybePascalString,failedPascalStringDecoding,"; + output += "referenceCounter,"; + output += "parentFunction,"; + output += "parentFileName,"; + output += "inFileOffset,"; + output += "overlayCategory,unknownSegment,"; + output += "isGot,isGotGlobal,isGotLocal,gotIndex,accessedAsGpRel,"; + output += "firstLoAccess,isAutogeneratedPad,autoCreatedPadMainSymbol,isElfNotype,"; + output += "isAutocreatedSymFromOtherSizedSym,isMips1Double,visibility"; + return output; + } + + toCsv() { + let output = `0x${hexU(this.address, 8)},${pyStr(this.name)},${this.getName()},${pyStr(this.getNameEnd())},`; + + output += `${pyStr(this.userDeclaredType)},${pyStr(this.autodetectedType)},${this.getType()},`; + + if (this.accessType === null) output += "None,"; + else output += `${this.accessType.name},`; + + if (this.userDeclaredSize === null) output += "None,"; + else output += `0x${hexU(this.userDeclaredSize)},`; + if (this.autodetectedSize === null) output += "None,"; + else output += `0x${hexU(this.autodetectedSize)},`; + + output += `0x${hexU(this.getSize())},0x${hexU(this.getVrom())},${this.sectionType.toStr()},`; + output += `${pyStr(this.isDefined)},${pyStr(this.isUserDeclared)},${pyStr(this.isAutogenerated)},`; + output += `${pyStr(this.isMaybeString)},${pyStr(this.failedStringDecoding)},${pyStr(this.isMaybePascalString)},${pyStr(this.failedPascalStringDecoding)},`; + output += `${this.referenceCounter},`; + + if (this.parentFunction !== null) output += `${this.parentFunction.getName()},`; + else output += "None,"; + if (this.parentFileName !== null) output += `${this.parentFileName},`; + else output += "None,"; + if (this.inFileOffset !== null) output += `${this.inFileOffset},`; + else output += "None,"; + + output += `${pyStr(this.overlayCategory)},${pyStr(this.unknownSegment)},`; + output += `${pyStr(this.isGot)},${pyStr(this.isGotGlobal)},${pyStr(this.isGotLocal)},${pyStr(this.gotIndex)},${pyStr(this.accessedAsGpRel)},`; + let autoCreatedPadMainSymbolName = ""; + if (this.autoCreatedPadMainSymbol !== null) autoCreatedPadMainSymbolName = this.autoCreatedPadMainSymbol.getName(); + output += `${pyStr(this.firstLoAccess)},${pyStr(this.isAutogeneratedPad())},${autoCreatedPadMainSymbolName},${pyStr(this.isElfNotype)},`; + output += `${pyStr(this.isAutocreatedSymFromOtherSizedSym)},${pyStr(this.isMips1Double)},${pyStr(this.visibility)}`; + return output; + } + + equals(other) { + return symEq(this, other); + } + + toString() { + return `0x${hexU(this.address, 8)} ${pyStr(this.name)} (${this.getName()})`; + } +} diff --git a/packages/romdev-spimdisasm/src/common/ElementBase.js b/packages/romdev-spimdisasm/src/common/ElementBase.js new file mode 100644 index 00000000..947276a0 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/ElementBase.js @@ -0,0 +1,469 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/ElementBase.py +// +// Python keyword-only parameters are positional here, in declaration order. + +import { GlobalConfig } from "./GlobalConfig.js"; +import { FileSectionType } from "./FileSectionType.js"; +import { atLeast, versionString } from "../version.js"; + +const alwaysTrue = () => true; + +export class ElementBase { + /** + * @param context Context + * @param vromStart The VROM address of this element + * @param vromEnd The end of this element's VROM address + * @param inFileOffset The offset of this element relative to the start of its file + * @param vram The VRAM address of this element + * @param name The name of this element + * @param words A list of words (4 bytes) corresponding to this element + * @param sectionType The section type this element corresponds to + */ + constructor(context, vromStart, vromEnd, inFileOffset, vram, name, words, sectionType, segmentVromStart, overlayCategory) { + this.context = context; + this.vromStart = vromStart; + this.vromEnd = vromEnd; + this.inFileOffset = inFileOffset; + this.vram = vram; + this.name = name; + this.words = words; + this.sectionType = sectionType; + this.customSectionName = null; + + /** Added to the first column of the disassembled line comment */ + this.commentOffset = 0; + + /** The index of the current element inside its parent or null if unknown */ + this.index = null; + + /** For elements that are contained in other elements, like symbols inside of sections */ + this.parent = null; + + this.overlayCategory = overlayCategory ?? null; + this.segmentVromStart = segmentVromStart; + + this._ownSegmentReference = null; + } + + /** The amount of words this element has */ + get sizew() { + return this.words.length; + } + + /** The end of this element's VRAM */ + get vramEnd() { + return this.vram + this.sizew * 4; + } + + setVram(vram) { + this.vram = vram; + } + + setCommentOffset(commentOffset) { + this.commentOffset = commentOffset; + } + + getName() { + return this.name; + } + + getVromOffset(localOffset) { + return this.vromStart + localOffset; + } + + getVromOffsetNone(localOffset) { + if (this.sectionType === FileSectionType.Bss) return null; + return this.getVromOffset(localOffset); + } + + getVramOffset(localOffset) { + return this.vram + localOffset; + } + + containsVram(vram) { + if (vram < this.vram) return false; + if (vram >= this.vramEnd) return false; + return true; + } + + getLabelFromSymbol(sym, symName) { + if (sym !== null && sym !== undefined) { + let label = sym.getLabelMacro(false); + if (label === null) return ""; + label += ` ${symName || sym.getName()}`; + if (sym.visibility !== null && sym.visibility !== "global") label += `, ${sym.visibility}`; + if (GlobalConfig.GLABEL_ASM_COUNT) { + if (this.index !== null) label += ` # ${this.index}`; + } + label += GlobalConfig.LINE_ENDS; + return label; + } + return ""; + } + + /** Scans the words of this element, gathering as much info as possible. */ + analyze() {} + + getSpimdisasmVersionString() { + if (!GlobalConfig.ASM_COMMENT || !GlobalConfig.ASM_GENERATED_BY) return ""; + return `/* Generated by spimdisasm ${versionString()} */${GlobalConfig.LINE_ENDS}${GlobalConfig.LINE_ENDS}`; + } + + /** Produces a disassembly of this element. */ + disassemble(_migrate = false, _useGlobalLabel = true) { + return ""; + } + + getSegment() { + if (atLeast("1.42.0")) { + if (this._ownSegmentReference !== null) return this._ownSegmentReference; + + if (this.overlayCategory !== null) { + const segmentsPerVrom = this.context.overlaySegments.get(this.overlayCategory); + if (segmentsPerVrom !== undefined) { + const overlaySegment = segmentsPerVrom.get(this.segmentVromStart); + if (overlaySegment !== undefined) { + if (overlaySegment.isVromInRange(this.vromStart)) { + if (this._ownSegmentReference === null) this._ownSegmentReference = overlaySegment; + return overlaySegment; + } + } + } + } + + if (this.context.globalSegment.isVromInRange(this.vromStart)) { + if (this._ownSegmentReference === null) this._ownSegmentReference = this.context.globalSegment; + return this.context.globalSegment; + } + + return this.context.unknownSegment; + } + + // spimdisasm < 1.42 + if (this.overlayCategory !== null) { + const segmentsPerVrom = this.context.overlaySegments.get(this.overlayCategory); + if (segmentsPerVrom !== undefined) { + const overlaySegment = segmentsPerVrom.get(this.segmentVromStart); + if (overlaySegment !== undefined) { + if (this._ownSegmentReference === null) { + if (overlaySegment.isVromInRange(this.vromStart)) this._ownSegmentReference = overlaySegment; + } + return overlaySegment; + } + } + } + + if (this._ownSegmentReference === null) { + if (this.context.globalSegment.isVromInRange(this.vromStart)) this._ownSegmentReference = this.context.globalSegment; + } + return this.context.globalSegment; + } + + getSegmentForVram(vram) { + const v142 = atLeast("1.42.0"); + if (this._ownSegmentReference === null) { + if (this.context.globalSegment.isVromInRange(this.vromStart)) this._ownSegmentReference = this.context.globalSegment; + } + if (this.context.globalSegment.isVramInRange(vram)) return this.context.globalSegment; + + if (v142 && this.overlayCategory === null) { + // The owned segment is the global segment + const prioritizedSegment = this._findPrioritizedSegment(vram, this.context.globalSegment); + if (prioritizedSegment !== null) return prioritizedSegment; + } + + if (this.overlayCategory !== null) { + const segmentsPerVrom = this.context.overlaySegments.get(this.overlayCategory); + if (segmentsPerVrom !== undefined) { + const overlaySegment = segmentsPerVrom.get(this.segmentVromStart); + if (overlaySegment !== undefined) { + if (this._ownSegmentReference === null) { + if (overlaySegment.isVromInRange(this.vromStart)) this._ownSegmentReference = overlaySegment; + } + if (overlaySegment.isVramInRange(vram)) return overlaySegment; + + if (v142) { + const prioritizedSegment = this._findPrioritizedSegment(vram, overlaySegment); + if (prioritizedSegment !== null) return prioritizedSegment; + } + } + } + } + + return this.context.unknownSegment; + } + + getSegmentForVrom(vrom) { + if (this._ownSegmentReference === null) { + if (this.context.globalSegment.isVromInRange(this.vromStart)) this._ownSegmentReference = this.context.globalSegment; + } + if (this.context.globalSegment.isVromInRange(vrom)) return this.context.globalSegment; + + if (this.overlayCategory !== null) { + const segmentsPerVrom = this.context.overlaySegments.get(this.overlayCategory); + if (segmentsPerVrom !== undefined) { + const overlaySegment = segmentsPerVrom.get(this.segmentVromStart); + if (overlaySegment !== undefined) { + if (this._ownSegmentReference === null) { + if (overlaySegment.isVromInRange(this.vromStart)) this._ownSegmentReference = overlaySegment; + } + if (overlaySegment.isVromInRange(vrom)) return overlaySegment; + } + } + + // If the vrom was not part of that segment, then check for every other overlay category + for (const [overlayCategory, segmentsPerVrom2] of this.context.overlaySegments) { + if (this.overlayCategory !== overlayCategory) { + for (const [segmentVrom, overlaySegment] of segmentsPerVrom2) { + if (vrom < segmentVrom) continue; + if (overlaySegment.isVromInRange(vrom)) return overlaySegment; + } + } + } + } + + return this.context.unknownSegment; + } + + /** + * Searches symbol or a symbol with an addend if `tryPlusOffset` is True. + * Python keyword-only parameters, positional here: + * (vramAddress, vromAddress=None, tryPlusOffset=True, checkUpperLimit=True, checkGlobalSegment=True, allowOutsideIfVramIsInside=True) + */ + getSymbol(vramAddress, vromAddress = null, tryPlusOffset = true, checkUpperLimit = true, checkGlobalSegment = true, allowOutsideIfVramIsInside = true) { + const v142 = atLeast("1.42.0"); + let contextSym; + + if (v142) { + contextSym = this.context.absoluteSegment.getSymbol(vramAddress, tryPlusOffset, true); + if (contextSym !== null) return contextSym; + } + + if (vromAddress !== null && vromAddress !== undefined) { + return this.getSegmentForVrom(vromAddress).getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + } + + if (this.overlayCategory === null || checkGlobalSegment) { + contextSym = this.context.globalSegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (contextSym !== null) return contextSym; + + if (v142 && this.overlayCategory === null) { + // This is the owned segment + contextSym = this._findInPrioritizedSegments(this.context.globalSegment, vramAddress, alwaysTrue, tryPlusOffset, checkUpperLimit); + if (contextSym !== null) return contextSym; + } + } + + if (this.overlayCategory !== null) { + const segmentsPerVrom = this.context.overlaySegments.get(this.overlayCategory); + if (segmentsPerVrom !== undefined) { + const overlaySegment = segmentsPerVrom.get(this.segmentVromStart); + if (overlaySegment !== undefined) { + if (v142) { + let inRange = false; + if (overlaySegment.isVramInRange(vramAddress)) { + contextSym = overlaySegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (contextSym !== null) return contextSym; + inRange = true; + } + + contextSym = this._findInPrioritizedSegments(overlaySegment, vramAddress, alwaysTrue, tryPlusOffset, checkUpperLimit); + if (contextSym !== null) return contextSym; + + if (inRange && !allowOutsideIfVramIsInside) return null; + } else { + contextSym = overlaySegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (contextSym !== null) return contextSym; + } + } + } + + // If the vram was not part of that segment, then check for every other overlay category + for (const [overlayCategory, segmentsPerVrom2] of this.context.overlaySegments) { + if (this.overlayCategory !== overlayCategory) { + for (const overlaySegment of segmentsPerVrom2.values()) { + if (!overlaySegment.isVramInRange(vramAddress)) continue; + contextSym = overlaySegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (contextSym !== null) return contextSym; + } + } + } + } + + if (!checkGlobalSegment) return null; + + if (!GlobalConfig.ALLOW_UNKSEGMENT) return null; + contextSym = this.context.unknownSegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (this._ownSegmentReference !== null) { + if (contextSym !== null && contextSym.vromAddress !== null) { + if (!this._ownSegmentReference.isVromInRange(contextSym.getVrom())) return null; + } + } + return contextSym; + } + + /** (vramAddress, symValidation, tryPlusOffset=True, checkUpperLimit=True) */ + getSymbolFromAnySegment(vramAddress, symValidation, tryPlusOffset = true, checkUpperLimit = true) { + const v142 = atLeast("1.42.0"); + let contextSym; + if (v142) { + contextSym = this.context.absoluteSegment.getSymbol(vramAddress, tryPlusOffset, true); + if (contextSym !== null && symValidation(contextSym)) return contextSym; + } + + contextSym = this.context.globalSegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (contextSym !== null && symValidation(contextSym)) return contextSym; + + if (v142 && this.overlayCategory === null) { + contextSym = this._findInPrioritizedSegments(this.context.globalSegment, vramAddress, symValidation, tryPlusOffset, checkUpperLimit); + if (contextSym !== null) return contextSym; + } + + if (this.overlayCategory !== null) { + const segmentsPerVrom = this.context.overlaySegments.get(this.overlayCategory); + if (segmentsPerVrom !== undefined) { + const overlaySegment = segmentsPerVrom.get(this.segmentVromStart); + if (overlaySegment !== undefined) { + contextSym = overlaySegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (contextSym !== null && symValidation(contextSym)) return contextSym; + + if (v142) { + contextSym = this._findInPrioritizedSegments(overlaySegment, vramAddress, symValidation, tryPlusOffset, checkUpperLimit); + if (contextSym !== null) return contextSym; + } + } + } + + for (const [overlayCategory, segmentsPerVrom2] of this.context.overlaySegments) { + if (this.overlayCategory !== overlayCategory) { + for (const overlaySegment of segmentsPerVrom2.values()) { + if (!overlaySegment.isVramInRange(vramAddress)) continue; + contextSym = overlaySegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (contextSym !== null && symValidation(contextSym)) return contextSym; + } + } + } + } + + if (!GlobalConfig.ALLOW_UNKSEGMENT) return null; + contextSym = this.context.unknownSegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (this._ownSegmentReference !== null) { + if (contextSym !== null && contextSym.vromAddress !== null) { + if (!this._ownSegmentReference.isVromInRange(contextSym.getVrom())) return null; + } + } + if (contextSym !== null && symValidation(contextSym)) return contextSym; + return null; + } + + _findInPrioritizedSegments(overlaySegment, vramAddress, symValidation, tryPlusOffset, checkUpperLimit) { + for (const prioritizedOverlay of overlaySegment.getPrioritizedSegments()) { + for (const segmentsPerVrom of this.context.overlaySegments.values()) { + for (const otherOverlaySegment of segmentsPerVrom.values()) { + if (otherOverlaySegment.name === prioritizedOverlay && otherOverlaySegment.isVramInRange(vramAddress)) { + const contextSym = otherOverlaySegment.getSymbol(vramAddress, tryPlusOffset, checkUpperLimit); + if (contextSym !== null && symValidation(contextSym)) return contextSym; + } + } + } + } + return null; + } + + _findPrioritizedSegment(vram, ownedSegment) { + for (const prioritizedSegmentName of ownedSegment.prioritizedSegments) { + for (const segmentsPerRom of this.context.overlaySegments.values()) { + for (const segment of segmentsPerRom.values()) { + if (segment.name === prioritizedSegmentName && segment.isVramInRange(vram)) return segment; + } + } + } + return null; + } + + /** (vromAddress, tryPlusOffset=True, checkUpperLimit=True) */ + getSymbolByVrom(vromAddress, tryPlusOffset = true, checkUpperLimit = true) { + const segment = this.getSegmentForVrom(vromAddress); + const vram = segment.vromToVram(vromAddress); + if (vram === null) return null; + return segment.getSymbol(vram, tryPlusOffset, checkUpperLimit); + } + + getSymbolsRange(addressStart, addressEnd) { + const segment = this.getSegmentForVram(addressStart); + return segment.getSymbolsRange(addressStart, addressEnd); + } + + getConstant(constantValue) { + const segment = this.getSegment(); + return segment.getConstant(constantValue); + } + + _segmentFor(vramAddress, symbolVrom) { + if (symbolVrom !== null && symbolVrom !== undefined) return this.getSegmentForVrom(symbolVrom); + return this.getSegmentForVram(vramAddress); + } + + /** (vramAddress, sectionType=Unknown, isAutogenerated=False, symbolVrom=None, allowAddendInstead=False) */ + addSymbol(vramAddress, sectionType = FileSectionType.Unknown, isAutogenerated = false, symbolVrom = null, allowAddendInstead = false) { + const segment = this._segmentFor(vramAddress, symbolVrom); + return segment.addSymbol(vramAddress, sectionType, isAutogenerated, symbolVrom ?? null, allowAddendInstead); + } + + /** (vramAddress, isAutogenerated=False, symbolVrom=None) */ + addFunction(vramAddress, isAutogenerated = false, symbolVrom = null) { + return this._segmentFor(vramAddress, symbolVrom).addFunction(vramAddress, isAutogenerated, symbolVrom ?? null); + } + + addBranchLabel(vramAddress, isAutogenerated = false, symbolVrom = null) { + return this._segmentFor(vramAddress, symbolVrom).addBranchLabel(vramAddress, isAutogenerated, symbolVrom ?? null); + } + + addJumpTable(vramAddress, isAutogenerated = false, symbolVrom = null) { + return this._segmentFor(vramAddress, symbolVrom).addJumpTable(vramAddress, isAutogenerated, symbolVrom ?? null); + } + + addJumpTableLabel(vramAddress, isAutogenerated = false, symbolVrom = null) { + return this._segmentFor(vramAddress, symbolVrom).addJumpTableLabel(vramAddress, isAutogenerated, symbolVrom ?? null); + } + + addGccExceptTable(vramAddress, isAutogenerated = false, symbolVrom = null) { + return this._segmentFor(vramAddress, symbolVrom).addGccExceptTable(vramAddress, isAutogenerated, symbolVrom ?? null); + } + + addGccExceptTableLabel(vramAddress, isAutogenerated = false, symbolVrom = null) { + return this._segmentFor(vramAddress, symbolVrom).addGccExceptTableLabel(vramAddress, isAutogenerated, symbolVrom ?? null); + } + + /** (vramAddress, symbolVrom=None) */ + removeSymbol(vramAddress, symbolVrom = null) { + return this._segmentFor(vramAddress, symbolVrom).removeSymbol(vramAddress); + } + + /** (constantValue, name, isAutogenerated=False) */ + addConstant(constantValue, name, isAutogenerated = false) { + const segment = this.getSegment(); + return segment.addConstant(constantValue, name, isAutogenerated); + } + + addPointerInDataReference(pointer) { + const segment = this.getSegmentForVram(pointer); + segment.addPointerInDataReference(pointer); + } + + popPointerInDataReference(pointer) { + const segment = this.getSegmentForVram(pointer); + return segment.popPointerInDataReference(pointer); + } + + getAndPopPointerInDataReferencesRange(low, high) { + const segment = this.getSegmentForVram(low); + return segment.getAndPopPointerInDataReferencesRange(low, high); + } + + getSectionName() { + if (this.customSectionName !== null) return this.customSectionName; + return this.sectionType.toSectionName(); + } +} diff --git a/packages/romdev-spimdisasm/src/common/FileSectionType.js b/packages/romdev-spimdisasm/src/common/FileSectionType.js new file mode 100644 index 00000000..636d1e28 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/FileSectionType.js @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/FileSectionType.py + +import { createEnum } from "../py/pyutils.js"; + +let gNameToSectionType; +let gSmallNameToSectionType; + +export const FileSectionType = createEnum( + "FileSectionType", + [ + ["Dummy", -4], + ["End", -3], + ["Unknown", -2], + ["Invalid", -1], + ["Text", 1], + ["Data", 2], + ["Rodata", 3], + ["Bss", 4], + ["Reloc", 5], + ["GccExceptTable", 6], + ], + { + toStr() { + switch (this.name) { + case "Text": return ".text"; + case "Data": return ".data"; + case "Rodata": return ".rodata"; + case "Bss": return ".bss"; + case "Reloc": return ".reloc"; + case "GccExceptTable": return ".gcc_except_table"; + default: return ""; + } + }, + toCapitalizedStr() { + switch (this.name) { + case "Text": return "Text"; + case "Data": return "Data"; + case "Rodata": return "RoData"; + case "Bss": return "Bss"; + case "Reloc": return "Reloc"; + case "GccExceptTable": return "GccExceptTable"; + default: return ""; + } + }, + toSectionName() { + switch (this.name) { + case "Text": return ".text"; + case "Data": return ".data"; + case "Rodata": return ".rodata"; + case "Bss": return ".bss"; + case "Reloc": return ".ovl"; + case "GccExceptTable": return ".gcc_except_table"; + default: return ""; + } + }, + }, + { + fromId(sectionId) { + const m = FileSectionType.fromValueOrNull(sectionId); + return m === null ? FileSectionType.Invalid : m; + }, + fromStr(x) { + return gNameToSectionType.has(x) ? gNameToSectionType.get(x) : FileSectionType.Invalid; + }, + fromSmallStr(x) { + return gSmallNameToSectionType.has(x) ? gSmallNameToSectionType.get(x) : FileSectionType.Invalid; + }, + }, +); + +gNameToSectionType = new Map([ + [".text", FileSectionType.Text], + [".data", FileSectionType.Data], + [".rodata", FileSectionType.Rodata], + [".rdata", FileSectionType.Rodata], + [".bss", FileSectionType.Bss], + [".ovl", FileSectionType.Reloc], + [".reloc", FileSectionType.Reloc], + [".gcc_except_table", FileSectionType.GccExceptTable], + [".end", FileSectionType.End], + [".dummy", FileSectionType.Dummy], +]); +gSmallNameToSectionType = new Map([ + [".sdata", FileSectionType.Data], + [".srodata", FileSectionType.Rodata], + [".srdata", FileSectionType.Rodata], + [".sbss", FileSectionType.Bss], +]); + +export const FileSections_ListBasic = Object.freeze([FileSectionType.Text, FileSectionType.Data, FileSectionType.Rodata, FileSectionType.Bss]); +export const FileSections_ListAll = Object.freeze([ + FileSectionType.Text, + FileSectionType.Data, + FileSectionType.Rodata, + FileSectionType.Bss, + FileSectionType.Reloc, + FileSectionType.GccExceptTable, +]); diff --git a/packages/romdev-spimdisasm/src/common/FileSplitFormat.js b/packages/romdev-spimdisasm/src/common/FileSplitFormat.js new file mode 100644 index 00000000..14ee7c3f --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/FileSplitFormat.js @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/FileSplitFormat.py + +import * as Utils from "./Utils.js"; +import { FileSectionType } from "./FileSectionType.js"; +import { hexU, pyInt } from "../py/pyutils.js"; + +export class FileSplitEntry { + constructor(offset, vram, fileName, section, nextOffset, isHandwritten, isRsp) { + this.offset = offset; + this.vram = vram; + this.fileName = fileName; + this.section = section; + this.nextOffset = nextOffset; + this.isHandwritten = isHandwritten; + this.isRsp = isRsp; + } +} + +export class FileSplitFormat { + constructor(csvPath = null) { + this.splits = []; + if (csvPath !== null && csvPath !== undefined) this.readCsvFile(csvPath); + } + + get length() { + return this.splits.length; + } + + *[Symbol.iterator]() { + let section = FileSectionType.Invalid; + + for (let i = 0; i < this.splits.length; i++) { + const row = this.splits[i]; + if (row.length !== 3) throw new Error(`ValueError: expected 3 values, got ${row.length}`); + let [offsetStr, vramStr, fileName] = row; + + let isHandwritten = false; + let isRsp = false; + offsetStr = offsetStr.toUpperCase(); + if (offsetStr.at(-1) === "H") { + isHandwritten = true; + offsetStr = offsetStr.slice(0, -1); + } else if (offsetStr.at(-1) === "R") { + isRsp = true; + offsetStr = offsetStr.slice(0, -1); + } + + const possibleSection = FileSectionType.fromStr(fileName); + if (possibleSection !== FileSectionType.Invalid) { + if (possibleSection === FileSectionType.End) break; + section = possibleSection; + continue; + } + + const vram = pyInt(vramStr, 16); + const offset = pyInt(offsetStr, 16); + let nextOffset = 0xffffff; + if (i + 1 < this.splits.length) { + let nextOffsetStr; + if (this.splits[i + 1][2] === ".end") nextOffsetStr = this.splits[i + 1][0]; + else if (this.splits[i + 1][2].startsWith(".")) nextOffsetStr = this.splits[i + 2][0]; + else nextOffsetStr = this.splits[i + 1][0]; + const last = nextOffsetStr.toUpperCase().at(-1); + if (last === "H" || last === "R") nextOffsetStr = nextOffsetStr.slice(0, -1); + nextOffset = pyInt(nextOffsetStr, 16); + } + + yield new FileSplitEntry(offset, vram, fileName, section, nextOffset, isHandwritten, isRsp); + } + } + + readCsvFile(csvPath) { + this.splits = Utils.readCsv(csvPath); + this.splits = this.splits.filter((x) => x.length > 0); + } + + append(element) { + if (element instanceof FileSplitEntry) { + let offset = hexU(element.offset); + if (element.isRsp) offset += "R"; + else if (element.isHandwritten) offset += "H"; + + const vram = hexU(element.vram); + const fileName = element.fileName; + + if (element.section !== FileSectionType.Invalid) { + const section = element.section.toStr(); + this.splits.push(["offset", "vram", section]); + } + + this.splits.push([offset, vram, fileName]); + } else if (Array.isArray(element)) { + if (element.length !== 3) throw new TypeError(); + for (const x of element) if (typeof x !== "string") throw new TypeError(); + this.splits.push(element); + } else { + throw new TypeError(); + } + } + + appendEndSection(offset, vram) { + this.splits.push([hexU(offset), hexU(vram), ".end"]); + } +} diff --git a/packages/romdev-spimdisasm/src/common/GlobalConfig.js b/packages/romdev-spimdisasm/src/common/GlobalConfig.js new file mode 100644 index 00000000..ba4c76c9 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/GlobalConfig.js @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/GlobalConfig.py (the argparse parts are not ported). + +import { createEnum, pyInt } from "../py/pyutils.js"; +import { Compiler } from "./CompilerConfig.js"; +import { atLeast, onVersionChange } from "../version.js"; + +export const InputEndian = createEnum( + "InputEndian", + [ + ["BIG", "big"], + ["LITTLE", "little"], + ["MIDDLE", "middle"], + ], + { + toFormatString() { + if (this === InputEndian.BIG) return ">"; + if (this === InputEndian.LITTLE) return "<"; + throw new Error(`No struct format string available for : ${this}`); + }, + }, + { + fromStr(value) { + if (value === "little") return InputEndian.LITTLE; + if (value === "middle") return InputEndian.MIDDLE; + return InputEndian.BIG; + }, + }, +); + +export const Abi = createEnum( + "Abi", + [ + ["O32", "O32"], + ["N32", "N32"], + ["O64", "O64"], + ["N64", "N64"], + ["EABI32", "EABI32"], + ["EABI64", "EABI64"], + ], + {}, + { + fromStr(value) { + const m = Abi.fromValueOrNull(value); + return m === null ? Abi.O32 : m; + }, + }, +); + +export const archLevelOptions = new Set(["MIPS1", "MIPS2", "MIPS3", "MIPS4", "MIPS5", "MIPS32", "MIPS64", "MIPS32R2", "MIPS64R2"]); + +export const ArchLevel = createEnum( + "ArchLevel", + [ + ["MIPS1", 1], + ["MIPS2", 2], + ["MIPS3", 3], + ["MIPS4", 4], + ["MIPS5", 5], + ["MIPS32", 6], + ["MIPS64", 7], + ["MIPS32R2", 8], + ["MIPS64R2", 9], + ], + {}, + { + fromValue(value) { + return ArchLevel.fromValueOrNull(value); + }, + }, +); + +export const InputFileType = createEnum("InputFileType", [ + ["BINARY", "binary"], + ["ELF", "elf"], +]); + +function defaultFields() { + const v139 = atLeast("1.39.0"); + const f = { + DISASSEMBLE_UNKNOWN_INSTRUCTIONS: false, + PRODUCE_SYMBOLS_PLUS_OFFSET: true, + TRUST_USER_FUNCTIONS: true, + TRUST_JAL_FUNCTIONS: true, + RODATA_STRING_ENCODING: "EUC-JP", + DATA_STRING_ENCODING: "ASCII", + RODATA_STRING_GUESSER_LEVEL: 1, + DATA_STRING_GUESSER_LEVEL: 2, + PASCAL_RODATA_STRING_GUESSER_LEVEL: 0, + PASCAL_DATA_STRING_GUESSER_LEVEL: 0, + ALLOW_MIGRATING_CONST_VARIABLES: false, + AUTOGENERATED_NAMES_BASED_ON_SECTION_TYPE: true, + AUTOGENERATED_NAMES_BASED_ON_DATA_TYPE: true, + AUTOGENERATED_NAMES_BASED_ON_FILE_NAME: false, + SEQUENTIAL_LABEL_NAMES: false, + LEGACY_SYM_ADDR_ZERO_PADDING: false, + CUSTOM_SUFFIX: "", + COMPILER: Compiler.IDO, + SYMBOL_ALIGNMENT_REQUIRES_ALIGNED_SECTION: false, + DETECT_REDUNDANT_FUNCTION_END: false, + ENDIAN: InputEndian.BIG, + ENDIAN_DATA: null, + ENDIAN_RODATA: null, + ABI: Abi.O32, + ARCHLEVEL: ArchLevel.MIPS3, + INPUT_FILE_TYPE: InputFileType.BINARY, + GP_VALUE: null, + PIC: false, + EMIT_CPLOAD: true, + EMIT_INLINE_RELOC: false, + SYMBOL_FINDER_FILTER_LOW_ADDRESSES: true, + SYMBOL_FINDER_FILTER_ADDRESSES_ADDR_LOW: 0x80000000, + SYMBOL_FINDER_FILTER_HIGH_ADDRESSES: true, + SYMBOL_FINDER_FILTER_ADDRESSES_ADDR_HIGH: 0xc0000000, + SYMBOL_FINDER_FILTERED_ADDRESSES_AS_CONSTANTS: true, + SYMBOL_FINDER_FILTERED_ADDRESSES_AS_HILO: false, + ALLOW_UNKSEGMENT: true, + ALLOW_ALL_ADDENDS_ON_DATA: true, + ALLOW_ALL_CONSTANTS_ON_DATA: true, + ASM_COMMENT: true, + ASM_COMMENT_OFFSET_WIDTH: 6, + GLABEL_ASM_COUNT: true, + ASM_REFERENCEE_SYMBOLS: false, + ASM_INDENTATION: 4, + ASM_INDENTATION_LABELS: 2, + ASM_TEXT_LABEL: "glabel", + ASM_TEXT_ALT_LABEL: v139 ? "alabel" : "glabel", + ASM_JTBL_LABEL: "jlabel", + ASM_DATA_LABEL: "dlabel", + ASM_EHTBL_LABEL: "ehlabel", + ASM_USE_SYMBOL_LABEL: true, + ASM_TEXT_ENT_LABEL: "", + ASM_TEXT_END_LABEL: v139 ? "endlabel" : "", + ASM_TEXT_FUNC_AS_LABEL: false, + ASM_DATA_SYM_AS_LABEL: false, + ASM_EMIT_SIZE_DIRECTIVE: !v139, + ASM_USE_PRELUDE: true, + ASM_PRELUDE_USE_INCLUDES: true, + ASM_PRELUDE_USE_INSTRUCTION_DIRECTIVES: true, + ASM_PRELUDE_USE_SECTION_START: true, + ASM_GENERATED_BY: true, + ASM_GLOBALIZE_TEXT_LABELS_REFERENCED_BY_NON_JUMPTABLE: false, + PRINT_NEW_FILE_BOUNDARIES: false, + USE_DOT_BYTE: true, + USE_DOT_SHORT: true, + LINE_ENDS: "\n", + PANIC_RANGE_CHECK: false, + CREATE_DATA_PADS: true, + CREATE_RODATA_PADS: false, + QUIET: false, + VERBOSE: false, + PRINT_FUNCTION_ANALYSIS_DEBUG_INFO: false, + PRINT_SYMBOL_FINDER_DEBUG_INFO: false, + PRINT_UNPAIRED_LUIS_DEBUG_INFO: false, + REMOVE_POINTERS: false, + IGNORE_BRANCHES: false, + IGNORE_WORD_LIST: new Set(), + WRITE_BINARY: false, + }; + if (v139) { + // Added in 1.36-1.39 + f.ASM_NM_LABEL = "nonmatching"; + f.ASM_DATA_END_LABEL = "enddlabel"; + f.ASM_EMIT_ALIGN_BRANCH_LABELS = false; + } + if (atLeast("1.42.0")) { + f.CREATE_BSS_PADS = true; + } + return f; +} + +export class GlobalConfigType { + constructor() { + Object.assign(this, defaultFields()); + } + + /** @deprecated */ + get STRING_GUESSER() { + return this.RODATA_STRING_GUESSER_LEVEL > 0; + } + set STRING_GUESSER(value) { + if (value) { + if (this.RODATA_STRING_GUESSER_LEVEL <= 0) this.RODATA_STRING_GUESSER_LEVEL = 1; + } else { + this.RODATA_STRING_GUESSER_LEVEL = 0; + } + } + + /** @deprecated */ + get AGGRESSIVE_STRING_GUESSER() { + return this.RODATA_STRING_GUESSER_LEVEL > 1; + } + set AGGRESSIVE_STRING_GUESSER(value) { + if (value) { + this.RODATA_STRING_GUESSER_LEVEL = 9; + } else if (this.RODATA_STRING_GUESSER_LEVEL >= 0) { + this.RODATA_STRING_GUESSER_LEVEL = 1; + } + } + + /** Reset every field to the defaults of the configured spimdisasm version. */ + resetToDefaults() { + for (const k of Object.keys(this)) delete this[k]; + Object.assign(this, defaultFields()); + } + + /** + * Allows changing the global configuration by setting a SPIMDISASM_SETTINGNAME + * environment variable, e.g. SPIMDISASM_EMIT_CPLOAD=False + */ + processEnvironmentVariables(env = typeof process !== "undefined" ? process.env : {}) { + const attrs = new Set([...Object.keys(this), "STRING_GUESSER", "AGGRESSIVE_STRING_GUESSER"]); + for (const attr of [...attrs].sort()) { + const currentValue = this[attr]; + const key = `SPIMDISASM_${attr}`; + if (!(key in env)) continue; + let environmentValue = env[key]; + if (environmentValue === currentValue) continue; + if (typeof currentValue === "boolean") { + const up = environmentValue.toUpperCase(); + if (up === "TRUE") environmentValue = true; + else if (up === "FALSE") environmentValue = false; + else if (environmentValue === "0") environmentValue = false; + else environmentValue = environmentValue.length > 0; + } else if (currentValue !== null && typeof currentValue === "object" && currentValue.__enumName === "Compiler") { + const newComp = Compiler.fromStr(environmentValue); + if (newComp === null) { + console.error(`Unrecognized compiler setting from environment 'SPIMDISASM_${attr.toUpperCase()}=${environmentValue}'.`); + continue; + } + environmentValue = newComp; + } else if (currentValue !== null && typeof currentValue === "object" && currentValue.__enumName === "InputEndian") { + environmentValue = InputEndian.fromStr(environmentValue); + } else if (currentValue !== null && typeof currentValue === "object" && currentValue.__enumName === "Abi") { + environmentValue = Abi.fromStr(environmentValue); + } else if (currentValue !== null && typeof currentValue === "object" && currentValue.__enumName === "ArchLevel") { + const value = ArchLevel.fromValue(pyInt(environmentValue, 10)); + environmentValue = value !== null ? value : currentValue; + } else if (typeof currentValue === "number") { + environmentValue = pyInt(environmentValue, 16); + } + this[attr] = environmentValue; + } + } +} + +export const GlobalConfig = new GlobalConfigType(); +GlobalConfig.processEnvironmentVariables(); + +onVersionChange(() => { + GlobalConfig.resetToDefaults(); + GlobalConfig.processEnvironmentVariables(); +}); diff --git a/packages/romdev-spimdisasm/src/common/GpAccesses.js b/packages/romdev-spimdisasm/src/common/GpAccesses.js new file mode 100644 index 00000000..541eb8a3 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/GpAccesses.js @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/GpAccesses.py + +import * as Utils from "./Utils.js"; +import { SortedDict } from "./SortedDict.js"; +import { hexU } from "../py/pyutils.js"; + +export class GotEntry { + constructor(value, isGlobal) { + this._value = value; + this._isGlobal = isGlobal; + } + + value() { + return this._value; + } + + isGlobal() { + return this._isGlobal; + } +} + +export class GlobalOffsetTable { + constructor() { + this._table = []; + this._tableAddress = null; + } + + setupTable(pltGot, table) { + this._tableAddress = pltGot; + this._table = [...table]; + } + + /** @deprecated Prefer setupTable() instead. */ + initTables(pltGot, localsTable, globalsTable) { + const table = []; + for (const x of localsTable) table.push(new GotEntry(x, false)); + for (const x of globalsTable) table.push(new GotEntry(x, true)); + this.setupTable(pltGot, table); + } + + tableAddress() { + return this._tableAddress; + } + + *iterGlobals() { + for (const entry of this._table) if (entry._isGlobal) yield entry; + } + + *iterLocals() { + for (const entry of this._table) if (!entry._isGlobal) yield entry; + } + + _getGotEntry(address) { + if (this._tableAddress === null) return null; + + const index = Math.floor((address - this._tableAddress) / 4); + + if (index < 0) { + Utils.eprint(`Warning: %got address 0x${hexU(address)} not found on local or global table (negative index)`); + Utils.eprint(` index: ${index}, len(table):${this._table.length}`); + return null; + } + + if (index >= this._table.length) { + Utils.eprint(`Warning: %got address 0x${hexU(address)} not found on local or global table (out of range)`); + Utils.eprint(` index: ${index}, len(table): ${this._table.length}`); + return null; + } + return this._table[index]; + } +} + +export class SmallSection { + constructor(address, size) { + this.address = address; + this.size = size; + } + + isInRange(address) { + return this.address <= address && address < this.address + this.size; + } +} + +export class GpAccess { + constructor(address, isGotLocal = false, isGotGlobal = false, isSmallSection = false) { + this.address = address; + this.isGotLocal = isGotLocal; + this.isGotGlobal = isGotGlobal; + this.isSmallSection = isSmallSection; + } + + get isGot() { + return this.isGotLocal || this.isGotGlobal; + } +} + +export class GpAccessContainer { + constructor() { + this.got = new GlobalOffsetTable(); + this.smallSections = new SortedDict(); + } + + addSmallSection(address, size) { + this.smallSections.set(address, new SmallSection(address, size)); + } + + setupGotTable(tableAddress, table) { + this.got.setupTable(tableAddress, table); + this.addSmallSection(tableAddress, table.length * 4); + } + + /** @deprecated Prefer setupGotTable() instead */ + initGotTable(tableAddress, localsTable, globalsTable) { + const table = []; + for (const x of localsTable) table.push(new GotEntry(x, false)); + for (const x of globalsTable) table.push(new GotEntry(x, true)); + this.setupGotTable(tableAddress, table); + } + + requestAddress(address) { + const small = this.smallSections.getKeyRight(address); + if (small === null) { + Utils.eprint(`Warning: No section found for $gp access at address 0x${hexU(address, 8)}`); + return null; + } + + const [sectionAddr, sectionData] = small; + + if (sectionAddr !== this.got._tableAddress) { + if (!sectionData.isInRange(address)) { + Utils.eprint(`Warning: No section found for $gp access at address 0x${hexU(address, 8)}`); + return null; + } + + // small section + const access = new GpAccess(address); + access.isSmallSection = true; + return access; + } + + // got + const gotEntry = this.got._getGotEntry(address); + if (gotEntry === null) return null; + + const access = new GpAccess(gotEntry._value); + access.isGotGlobal = gotEntry._isGlobal; + access.isGotLocal = !gotEntry._isGlobal; + + return access; + } +} diff --git a/packages/romdev-spimdisasm/src/common/OrderedEnum.js b/packages/romdev-spimdisasm/src/common/OrderedEnum.js new file mode 100644 index 00000000..b7e34bd1 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/OrderedEnum.js @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/OrderedEnum.py +// +// Python's OrderedEnum adds rich comparisons between members of the same enum. +// JS enums created with createEnum are compared through these helpers. + +export const OrderedEnum = Object.freeze({ + ge: (a, b) => a.value >= b.value, + gt: (a, b) => a.value > b.value, + le: (a, b) => a.value <= b.value, + lt: (a, b) => a.value < b.value, +}); diff --git a/packages/romdev-spimdisasm/src/common/Relocation.js b/packages/romdev-spimdisasm/src/common/Relocation.js new file mode 100644 index 00000000..3d9fee8c --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/Relocation.js @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/Relocation.py + +import { createEnum, hexU } from "../py/pyutils.js"; +import { ContextSymbol } from "./ContextSymbols.js"; +import { GlobalConfig } from "./GlobalConfig.js"; + +let _percentRel; +let _wordRel; +let _operationRel; + +export const RelocType = createEnum( + "RelocType", + [ + ["MIPS_NONE", 0], + ["MIPS_16", 1], + ["MIPS_32", 2], + ["MIPS_REL32", 3], + ["MIPS_26", 4], + ["MIPS_HI16", 5], + ["MIPS_LO16", 6], + ["MIPS_GPREL16", 7], + ["MIPS_LITERAL", 8], + ["MIPS_GOT16", 9], + ["MIPS_PC16", 10], + ["MIPS_CALL16", 11], + ["MIPS_GPREL32", 12], + ["MIPS_GOT_HI16", 22], + ["MIPS_GOT_LO16", 23], + ["MIPS_CALL_HI16", 30], + ["MIPS_CALL_LO16", 31], + ["CUSTOM_CONSTANT_HI", -1], + ["CUSTOM_CONSTANT_LO", -2], + ], + { + getPercentRel() { + return _percentRel.has(this) ? _percentRel.get(this) : null; + }, + getWordRel() { + return _wordRel.has(this) ? _wordRel.get(this) : null; + }, + }, + { + fromValue(value) { + return RelocType.fromValueOrNull(value); + }, + fromStr(value) { + value = value.toUpperCase(); + for (const m of RelocType.members) if (m.name === value) return m; + return null; + }, + }, +); + +_percentRel = new Map([ + [RelocType.MIPS_HI16, "%hi"], + [RelocType.MIPS_LO16, "%lo"], + [RelocType.MIPS_GPREL16, "%gp_rel"], + [RelocType.MIPS_GOT16, "%got"], + [RelocType.MIPS_CALL16, "%call16"], + [RelocType.MIPS_GOT_HI16, "%got_hi"], + [RelocType.MIPS_GOT_LO16, "%got_lo"], + [RelocType.MIPS_CALL_HI16, "%call_hi"], + [RelocType.MIPS_CALL_LO16, "%call_lo"], +]); + +_wordRel = new Map([ + [RelocType.MIPS_32, ".word"], + [RelocType.MIPS_GPREL32, ".gpword"], +]); + +_operationRel = new Map([ + [RelocType.CUSTOM_CONSTANT_HI, ">> 16"], + [RelocType.CUSTOM_CONSTANT_LO, "& 0xFFFF"], +]); + +export class RelocationStaticReference { + constructor(sectionType, sectionVram) { + this.sectionType = sectionType; + this.sectionVram = sectionVram; + } +} + +export class RelocationInfo { + constructor(relocType, symbol, addend = 0, staticReference = null, globalReloc = false) { + this.relocType = relocType; + this.symbol = symbol; + this.addend = addend; + this.staticReference = staticReference; + this.globalReloc = globalReloc; + } + + getName(isSplittedSymbol = false) { + let name; + if (this.symbol instanceof ContextSymbol) name = this.symbol.getName(); + else name = this.symbol; + + if (this.addend === 0) return name; + + if (GlobalConfig.COMPILER.value.bigAddendWorkaroundForMigratedFunctions && isSplittedSymbol) { + if (this.relocType === RelocType.MIPS_LO16) { + if (this.addend < -0x8000) return `${name} - (0x${hexU(-this.addend)} & 0xFFFF)`; + if (this.addend > 0x7fff) return `${name} + (0x${hexU(this.addend)} & 0xFFFF)`; + } + } + + if (this.addend < 0) return `${name} - 0x${hexU(-this.addend)}`; + return `${name} + 0x${hexU(this.addend)}`; + } + + getNameWithReloc(isSplittedSymbol = false, ignoredRelocs = null) { + if (ignoredRelocs === null || ignoredRelocs === undefined) ignoredRelocs = new Set(); + const name = this.getName(isSplittedSymbol); + + const percentRel = this.relocType.getPercentRel(); + if (percentRel !== null) { + if (ignoredRelocs.has(this.relocType)) return `(${name})`; + return `${percentRel}(${name})`; + } + + const wordRel = this.relocType.getWordRel(); + if (wordRel !== null) return `${wordRel} ${name}`; + + const operationRel = _operationRel.has(this.relocType) ? _operationRel.get(this.relocType) : null; + if (operationRel !== null) return `(${name} ${operationRel})`; + + return name; + } + + getInlineStr(isSplittedSymbol = false) { + let output = ` # ${this.relocType.name} '${this.getName(isSplittedSymbol)}'`; + if (this.staticReference !== null) output += " (static)"; + if (this.globalReloc) output += " (global reloc)"; + output += `${GlobalConfig.LINE_ENDS}`; + return output; + } + + isRelocNone() { + return this.relocType === RelocType.MIPS_NONE; + } +} diff --git a/packages/romdev-spimdisasm/src/common/SortedDict.js b/packages/romdev-spimdisasm/src/common/SortedDict.js new file mode 100644 index 00000000..9c02028b --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/SortedDict.js @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/SortedDict.py + +function bisectLeft(a, x) { + let lo = 0; + let hi = a.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (a[mid] < x) lo = mid + 1; + else hi = mid; + } + return lo; +} + +function bisectRight(a, x) { + let lo = 0; + let hi = a.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (x < a[mid]) hi = mid; + else lo = mid + 1; + } + return lo; +} + +export class SortedDict { + constructor(other = null) { + this.map = new Map(); + this.sortedKeys = []; + if (other !== null && other !== undefined) { + const entries = other instanceof Map || other instanceof SortedDict ? other.entries() : Object.entries(other); + for (const [key, value] of entries) this.add(key, value); + } + } + + add(key, value) { + if (!this.map.has(key)) { + // Avoid adding the key twice if it is already on the map (bisect.insort == insort_right) + this.sortedKeys.splice(bisectRight(this.sortedKeys, key), 0, key); + } + this.map.set(key, value); + } + + remove(key) { + if (!this.map.has(key)) throw new Error(`KeyError: ${key}`); + this.map.delete(key); + const idx = bisectLeft(this.sortedKeys, key); + this.sortedKeys.splice(idx, 1); + } + + /** Pair with the greatest key <= key (or < key when not inclusive), or null. */ + getKeyRight(key, inclusive = true) { + const index = inclusive ? bisectRight(this.sortedKeys, key) : bisectLeft(this.sortedKeys, key); + if (index === 0) return null; + const currentKey = this.sortedKeys[index - 1]; + return [currentKey, this.map.get(currentKey)]; + } + + /** Pair with the smallest key >= key (or > key when not inclusive), or null. */ + getKeyLeft(key, inclusive = true) { + const index = inclusive ? bisectLeft(this.sortedKeys, key) : bisectRight(this.sortedKeys, key); + if (index === this.sortedKeys.length) return null; + const k = this.sortedKeys[index]; + return [k, this.map.get(k)]; + } + + *getRange(startKey, endKey, startInclusive = true, endInclusive = false) { + const keyIndexStart = startInclusive ? bisectLeft(this.sortedKeys, startKey) : bisectRight(this.sortedKeys, startKey); + const keyIndexEnd = endInclusive ? bisectRight(this.sortedKeys, endKey) : bisectLeft(this.sortedKeys, endKey); + for (let index = keyIndexStart; index < keyIndexEnd; index++) { + const key = this.sortedKeys[index]; + yield [key, this.map.get(key)]; + } + } + + /** Like getRange but removes each pair. Iterates in descending order. */ + *getRangeAndPop(startKey, endKey, startInclusive = true, endInclusive = false) { + const keyIndexStart = startInclusive ? bisectLeft(this.sortedKeys, startKey) : bisectRight(this.sortedKeys, startKey); + const keyIndexEnd = endInclusive ? bisectRight(this.sortedKeys, endKey) : bisectLeft(this.sortedKeys, endKey); + for (let index = keyIndexEnd - 1; index > keyIndexStart - 1; index--) { + const key = this.sortedKeys[index]; + const value = this.map.get(key); + this.remove(key); + yield [key, value]; + } + } + + index(key) { + if (!this.map.has(key)) return null; + return bisectLeft(this.sortedKeys, key); + } + + // Mapping protocol + get(key, dflt = null) { + return this.map.has(key) ? this.map.get(key) : dflt; + } + + getItem(key) { + if (!this.map.has(key)) throw new Error(`KeyError: ${key}`); + return this.map.get(key); + } + + set(key, value) { + this.add(key, value); + return this; + } + + delete(key) { + if (!this.map.has(key)) return false; + this.remove(key); + return true; + } + + has(key) { + return this.map.has(key); + } + + /** MutableMapping.pop(key, default) */ + pop(key, ...dflt) { + if (this.map.has(key)) { + const v = this.map.get(key); + this.remove(key); + return v; + } + if (dflt.length > 0) return dflt[0]; + throw new Error(`KeyError: ${key}`); + } + + get size() { + return this.map.size; + } + + get length() { + return this.map.size; + } + + *keys() { + yield* this.sortedKeys.slice(); + } + + *values() { + for (const k of this.sortedKeys.slice()) yield this.map.get(k); + } + + *items() { + for (const k of this.sortedKeys.slice()) yield [k, this.map.get(k)]; + } + + entries() { + return this.items(); + } + + [Symbol.iterator]() { + return this.keys(); + } + + toString() { + const parts = []; + for (const [k, v] of this.items()) parts.push(`${k}: ${v}`); + return `SortedDict({${parts.join(", ")}})`; + } +} diff --git a/packages/romdev-spimdisasm/src/common/SymbolsSegment.js b/packages/romdev-spimdisasm/src/common/SymbolsSegment.js new file mode 100644 index 00000000..63a457ae --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/SymbolsSegment.js @@ -0,0 +1,650 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/SymbolsSegment.py + +import { existsSync, readFileSync } from "node:fs"; + +import * as Utils from "./Utils.js"; +import { SortedDict } from "./SortedDict.js"; +import { GlobalConfig } from "./GlobalConfig.js"; +import { FileSectionType } from "./FileSectionType.js"; +import { SymbolSpecialType, ContextSymbol } from "./ContextSymbols.js"; +import { hexU, pyInt, pyStr, pyStrip, pyStripChars } from "../py/pyutils.js"; +import { atLeast } from "../version.js"; + +function assert(cond, msg = "") { + if (!cond) throw new Error(`AssertionError${msg ? ": " + msg : ""}`); +} + +/** Split text into lines the way iterating a text file does (keeps line ends). */ +function fileLines(text) { + const out = []; + let start = 0; + for (let i = 0; i < text.length; i++) { + if (text[i] === "\n") { + out.push(text.slice(start, i + 1)); + start = i + 1; + } else if (text[i] === "\r") { + const end = text[i + 1] === "\n" ? i + 2 : i + 1; + out.push(text.slice(start, i) + "\n"); + start = end; + i = end - 1; + } + } + if (start < text.length) out.push(text.slice(start)); + return out; +} + +export class SymbolsSegment { + constructor(context, vromStart, vromEnd, vramStart, vramEnd, overlayCategory = null, name = null) { + assert(vramStart < vramEnd); + if (vromStart !== null && vromStart !== undefined && vromEnd !== null && vromEnd !== undefined) { + assert(vromStart <= vromEnd, `0x${hexU(vromStart, 6)} <= 0x${hexU(vromEnd, 6)}`); + } + + this.name = name ?? null; + this.vromStart = vromStart ?? null; + this.vromEnd = vromEnd ?? null; + + this.vramStart = vramStart; + this.vramEnd = vramEnd; + + this.context = context; + + this.overlayCategory = overlayCategory ?? null; + + this.prioritizedSegments = []; + + this.symbols = new SortedDict(); + + /** dict[int, ContextSymbol] */ + this.constants = new Map(); + + /** Stuff that looks like pointers, found referenced by data */ + this.newPointersInData = new SortedDict(); + + this._isTheUnknownSegment = false; + this._isAbsoluteSegment = false; + } + + addPrioritizedSegment(segmentName) { + this.prioritizedSegments.push(segmentName); + } + + /** @deprecated prefer addPrioritizedSegment */ + addPrioritisedSegment(segmentName) { + this.addPrioritizedSegment(segmentName); + } + + get vromSize() { + if (this.vromStart === null) return null; + if (this.vromEnd === null) return null; + return this.vromEnd - this.vromStart; + } + + get vramSize() { + return this.vramEnd - this.vramStart; + } + + isVromInRange(vrom) { + if (this.vromStart === null) return false; + if (this.vromEnd === null) return false; + return this.vromStart <= vrom && vrom < this.vromEnd; + } + + isVramInRange(vram) { + return this.vramStart <= vram && vram < this.vramEnd; + } + + changeRanges(vromStart, vromEnd, vramStart, vramEnd) { + assert(vromStart <= vromEnd, `0x${hexU(vromStart, 6)} <= 0x${hexU(vromEnd, 6)}`); + assert(vramStart <= vramEnd, `0x${hexU(vramStart, 8)} <= 0x${hexU(vramEnd, 8)}`); + + this.vromStart = vromStart; + this.vromEnd = vromEnd; + + this.vramStart = vramStart; + this.vramEnd = vramEnd; + } + + vromToVram(vrom) { + if (this.vromStart === null) return null; + return vrom - this.vromStart + this.vramStart; + } + + addSymbol(address, sectionType = FileSectionType.Unknown, isAutogenerated = false, vromAddress = null, allowAddendInstead = false) { + let contextSym = this.getSymbol(address, allowAddendInstead, true); + if (contextSym === null) { + contextSym = new ContextSymbol(address, this); + contextSym.isAutogenerated = isAutogenerated; + contextSym.sectionType = sectionType; + contextSym.overlayCategory = this.overlayCategory; + this.symbols.set(address, contextSym); + } + + if (contextSym.sectionType === FileSectionType.Unknown) contextSym.sectionType = sectionType; + + if (contextSym.vromAddress === null && vromAddress !== null && vromAddress !== undefined) contextSym.vromAddress = vromAddress; + + if (this.vromStart === null || this.vromEnd === null || this._isTheUnknownSegment) contextSym.unknownSegment = true; + + return contextSym; + } + + addFunction(address, isAutogenerated = false, vromAddress = null) { + const contextSym = this.addSymbol(address, FileSectionType.Text, isAutogenerated, vromAddress); + if (contextSym.getTypeSpecial() !== SymbolSpecialType.jumptablelabel) contextSym.setTypeSpecial(SymbolSpecialType.function, isAutogenerated); + contextSym.sectionType = FileSectionType.Text; + return contextSym; + } + + addBranchLabel(address, isAutogenerated = false, vromAddress = null) { + const contextSym = this.addSymbol(address, FileSectionType.Text, isAutogenerated, vromAddress); + const currentType = contextSym.getTypeSpecial(); + if (currentType !== SymbolSpecialType.jumptablelabel && currentType !== SymbolSpecialType.function) { + contextSym.setTypeSpecial(SymbolSpecialType.branchlabel, isAutogenerated); + } + return contextSym; + } + + addJumpTable(address, isAutogenerated = false, vromAddress = null) { + const contextSym = this.addSymbol(address, FileSectionType.Rodata, isAutogenerated, vromAddress, versionAllowsJtblAddend()); + if (contextSym.getTypeSpecial() !== SymbolSpecialType.function) contextSym.setTypeSpecial(SymbolSpecialType.jumptable, isAutogenerated); + return contextSym; + } + + addJumpTableLabel(address, isAutogenerated = false, vromAddress = null) { + const contextSym = this.addSymbol(address, FileSectionType.Text, isAutogenerated, vromAddress); + contextSym.setTypeSpecial(SymbolSpecialType.jumptablelabel, isAutogenerated); + contextSym.sectionType = FileSectionType.Text; + return contextSym; + } + + addGccExceptTable(address, isAutogenerated = false, vromAddress = null) { + const contextSym = this.addSymbol(address, FileSectionType.GccExceptTable, isAutogenerated, vromAddress); + contextSym.setTypeSpecial(SymbolSpecialType.gccexcepttable, isAutogenerated); + return contextSym; + } + + addGccExceptTableLabel(address, isAutogenerated = false, vromAddress = null) { + const contextSym = this.addSymbol(address, FileSectionType.Text, isAutogenerated, vromAddress); + contextSym.setTypeSpecial(SymbolSpecialType.gccexcepttablelabel, isAutogenerated); + contextSym.sectionType = FileSectionType.Text; + return contextSym; + } + + removeSymbol(address) { + if (!this.symbols.has(address)) return; + this.symbols.remove(address); + } + + addConstant(constantValue, name, isAutogenerated = false) { + if (!this.constants.has(constantValue)) { + const contextSym = new ContextSymbol(constantValue, this); + contextSym.name = name; + contextSym.setTypeSpecial(SymbolSpecialType.constant, isAutogenerated); + this.constants.set(constantValue, contextSym); + return contextSym; + } + return this.constants.get(constantValue); + } + + /** Searches symbol or a symbol with an addend if `tryPlusOffset` is True */ + getSymbol(address, tryPlusOffset = true, checkUpperLimit = true) { + if (GlobalConfig.PRODUCE_SYMBOLS_PLUS_OFFSET && tryPlusOffset) { + const pair = this.symbols.getKeyRight(address, true); + if (pair === null) return null; + + const [symVram, contextSym] = pair; + if (checkUpperLimit && address >= symVram + contextSym.getSize()) return null; + return contextSym; + } + + return this.symbols.get(address, null); + } + + getSymbolsRange(addressStart, addressEnd) { + return this.symbols.getRange(addressStart, addressEnd, true, false); + } + + getConstant(constantValue) { + return this.constants.has(constantValue) ? this.constants.get(constantValue) : null; + } + + addPointerInDataReference(pointer) { + this.newPointersInData.set(pointer, pointer); + } + + popPointerInDataReference(pointer) { + return this.newPointersInData.pop(pointer, null); + } + + *getAndPopPointerInDataReferencesRange(low, high) { + for (const [key] of this.newPointersInData.getRangeAndPop(low, high, true, false)) yield key; + } + + getPrioritizedSegments() { + return this.prioritizedSegments; + } + + getPrioritisedSegments() { + return this.getPrioritizedSegments(); + } + + /** f: object with a write(str) method */ + saveContextToFile(f) { + f.write(`category,${ContextSymbol.getCsvHeader()}\n`); + for (const address of this.symbols) f.write(`symbol,${this.symbols.getItem(address).toCsv()}\n`); + for (const constant of this.constants.values()) f.write(`constants,${constant.toCsv()}\n`); + for (const address of this.newPointersInData) f.write(`new_pointer_in_data,0x${hexU(address, 8)}\n`); + } + + static N64LibultraSyms = new Map([ + [0x800001a0, ["leoBootID", "u32", 0x4]], + [0x80000300, ["osTvType", "u32", 0x4]], + [0x80000304, ["osRomType", "u32", 0x4]], + [0x80000308, ["osRomBase", "u32", 0x4]], + [0x8000030c, ["osResetType", "u32", 0x4]], + [0x80000310, ["osCicId", "u32", 0x4]], + [0x80000314, ["osVersion", "u32", 0x4]], + [0x80000318, ["osMemSize", "u32", 0x4]], + [0x8000031c, ["osAppNMIBuffer", "u8", 0x40]], + ]); + + static iQueLibultraSyms = new Map([ + [0x8000035c, ["__osBbEepromAddress", "u32", 0x4]], + [0x80000360, ["__osBbEepromSize", "u32", 0x4]], + [0x80000364, ["__osBbFlashAddress", "u32", 0x4]], + [0x80000368, ["__osBbFlashSize", "u32", 0x4]], + [0x8000036c, ["__osBbSramAddress", "u32", 0x4]], + [0x80000370, ["__osBbSramSize", "u32", 0x4]], + [0x80000374, ["__osBbPakAddress", "u32", 0x4 * 4]], + [0x80000384, ["__osBbPakSize", "u32", 0x4]], + [0x80000388, ["__osBbIsBb", "u32", 0x4]], + [0x8000038c, ["__osBbHackFlags", "u32", 0x4]], + [0x80000390, ["__osBbStashMagic", "u32", 0x4]], + [0x80000394, ["__osBbPakBindings", "s32", 0x4 * 4]], + [0x800003a4, ["__osBbStateName", "char", 0x10]], + [0x800003b4, ["__osBbStateDirty", "u32", 0x4]], + [0x800003b8, ["__osBbAuxDataLimit", "u32", 0x4]], + ]); + + /** N64 OS hardware registers (insertion order of the Python dict literal; duplicate keys collapsed as Python does). */ + static N64HardwareRegs = new Map([ + // Signal Processor Registers + [0xa4040000, "SP_MEM_ADDR_REG"], + [0xa4040004, "SP_DRAM_ADDR_REG"], + [0xa4040008, "SP_RD_LEN_REG"], + [0xa404000c, "SP_WR_LEN_REG"], + [0xa4040010, "SP_STATUS_REG"], + [0xa4040014, "SP_DMA_FULL_REG"], + [0xa4040018, "SP_DMA_BUSY_REG"], + [0xa404001c, "SP_SEMAPHORE_REG"], + [0xa4080000, "SP_PC"], + // Display Processor Command Registers / Rasterizer Interface + [0xa4100000, "DPC_START_REG"], + [0xa4100004, "DPC_END_REG"], + [0xa4100008, "DPC_CURRENT_REG"], + [0xa410000c, "DPC_STATUS_REG"], + [0xa4100010, "DPC_CLOCK_REG"], + [0xa4100014, "DPC_BUFBUSY_REG"], + [0xa4100018, "DPC_PIPEBUSY_REG"], + [0xa410001c, "DPC_TMEM_REG"], + // Display Processor Span Registers + [0xa4200000, "DPS_TBIST_REG"], + [0xa4200004, "DPS_TEST_MODE_REG"], + [0xa4200008, "DPS_BUFTEST_ADDR_REG"], + [0xa420000c, "DPS_BUFTEST_DATA_REG"], + // MIPS Interface Registers + [0xa4300000, "MI_MODE_REG"], + [0xa4300004, "MI_VERSION_REG"], + [0xa4300008, "MI_INTR_REG"], + [0xa430000c, "MI_INTR_MASK_REG"], + [0xa4300010, "D_A4300010"], + [0xa4300014, "MI_SK_EXCEPTION_REG"], + [0xa4300018, "MI_SK_WATCHDOG_TIMER"], + [0xa4300028, "D_A4300028"], + [0xa430002c, "MI_RANDOM_BIT"], + [0xa4300030, "D_A4300030"], + [0xa4300038, "MI_HW_INTR_REG"], + [0xa430003c, "MI_HW_INTR_MASK_REG"], + // Video Interface Registers + [0xa4400000, "VI_STATUS_REG"], + [0xa4400004, "VI_DRAM_ADDR_REG"], + [0xa4400008, "VI_WIDTH_REG"], + [0xa440000c, "VI_INTR_REG"], + [0xa4400010, "VI_CURRENT_REG"], + [0xa4400014, "VI_BURST_REG"], + [0xa4400018, "VI_V_SYNC_REG"], + [0xa440001c, "VI_H_SYNC_REG"], + [0xa4400020, "VI_LEAP_REG"], + [0xa4400024, "VI_H_START_REG"], + [0xa4400028, "VI_V_START_REG"], + [0xa440002c, "VI_V_BURST_REG"], + [0xa4400030, "VI_X_SCALE_REG"], + [0xa4400034, "VI_Y_SCALE_REG"], + // Audio Interface Registers + [0xa4500000, "AI_DRAM_ADDR_REG"], + [0xa4500004, "AI_LEN_REG"], + [0xa4500008, "AI_CONTROL_REG"], + [0xa450000c, "AI_STATUS_REG"], + [0xa4500010, "AI_DACRATE_REG"], + [0xa4500014, "AI_BITRATE_REG"], + // Peripheral/Parallel Interface Registers + [0xa4600000, "PI_DRAM_ADDR_REG"], + [0xa4600004, "PI_CART_ADDR_REG"], + [0xa4600008, "PI_RD_LEN_REG"], + [0xa460000c, "PI_WR_LEN_REG"], + [0xa4600010, "PI_STATUS_REG"], + [0xa4600014, "PI_BSD_DOM1_LAT_REG"], + [0xa4600018, "PI_BSD_DOM1_PWD_REG"], + [0xa460001c, "PI_BSD_DOM1_PGS_REG"], + [0xa4600020, "PI_BSD_DOM1_RLS_REG"], + [0xa4600024, "PI_BSD_DOM2_LAT_REG"], + [0xa4600028, "PI_BSD_DOM2_LWD_REG"], + [0xa460002c, "PI_BSD_DOM2_PGS_REG"], + [0xa4600030, "PI_BSD_DOM2_RLS_REG"], + [0xa4600038, "PI_CARD_STATUS_REG"], + [0xa4600040, "PI_ATB_NEXT_CONFIG"], + [0xa4600044, "D_A4600044"], + [0xa4600048, "PI_CARD_CNT_REG"], + [0xa460004c, "PI_CARD_CONFIG_REG"], + [0xa4600050, "PI_AES_CNT"], + [0xa4600054, "PI_ALLOWED_IO"], + [0xa4600058, "PI_EX_RD_LEN_REG"], + [0xa460005c, "PI_EX_WR_LEN_REG"], + [0xa4600060, "PI_MISC_REG"], + [0xa4600064, "D_A4600064"], + [0xa4600070, "PI_CARD_BLK_OFFSET_REG"], + [0xa4610000, "PI_EX_DMA_BUF"], + [0xa4610420, "PI_AES_EXPANDED_KEY"], + [0xa46104d0, "PI_AES_IV"], + [0xa4610500, "PI_ATB_ENTRY"], + [0xa4620000, "D_A4620000"], + [0xa46e0000, "PI_RDB_REQ_HI_REG"], + [0xa46e0002, "PI_RDB_REQ_LO_REG"], + [0xa46e0004, "D_A46E0004"], + [0xa46e0400, "D_A46E0400"], + [0xa46e0402, "D_A46E0402"], + [0xa46e8000, "PI_RDB_STATUS_REG"], + // RDRAM Interface Registers + [0xa4700000, "RI_MODE_REG"], + [0xa4700004, "RI_CONFIG_REG"], + [0xa4700008, "RI_CURRENT_LOAD_REG"], + [0xa470000c, "RI_SELECT_REG"], + [0xa4700010, "RI_REFRESH_REG"], + [0xa4700014, "RI_LATENCY_REG"], + [0xa4700018, "RI_RERROR_REG"], + [0xa470001c, "RI_WERROR_REG"], + // Serial Interface Registers + [0xa4800000, "SI_DRAM_ADDR_REG"], + [0xa4800004, "SI_PIF_ADDR_RD64B_REG"], + [0xa4800008, "D_A4800008"], + [0xa480000c, "D_A480000C"], + [0xa4800010, "SI_PIF_ADDR_WR64B_REG"], + [0xa4800014, "D_A4800014"], + [0xa4800018, "SI_STATUS_REG"], + [0xa480001c, "D_A480001C"], + [0xa4900000, "D_A4900000"], + [0xa4940010, "USB0_STATUS_REG"], + [0xa4a00000, "D_A4A00000"], + [0xa4a40010, "USB1_STATUS_REG"], + // libleo (64DD) address range + [0xa5000508, "LEO_CMD"], + [0xa5000510, "LEO_BM_CTL"], + [0xa5000518, "LEO_SEQ_CTL"], + [0xa5000000, "LEO_C2_BUFF"], + [0xa5000400, "LEO_SECTOR_BUFF"], + [0xa5000500, "LEO_DATA"], + [0xa5000504, "LEO_MISC_REG"], + [0xa500050c, "LEO_CUR_TK"], + [0xa5000514, "LEO_ERR_SECTOR"], + [0xa500051c, "LEO_CUR_SECTOR"], + [0xa5000520, "LEO_HARD_RESET"], + [0xa5000524, "LEO_C1_S0"], + [0xa5000528, "LEO_HOST_SECBYTE"], + [0xa500052c, "LEO_C1_S2"], + [0xa5000530, "LEO_SEC_BYTE"], + [0xa5000534, "LEO_C1_S4"], + [0xa5000538, "LEO_C1_S6"], + [0xa500053c, "LEO_CUR_ADDR"], + [0xa5000540, "LEO_ID_REG"], + [0xa5000544, "LEO_TEST_REG"], + [0xa5000548, "LEO_TEST_PIN_SEL"], + [0xa5000580, "LEO_RAM_ADDR"], + ]); + + static iQueHardwareReg = new Map(); + + fillLibultraSymbols() { + let lowestVram = 0xffffffff; + let highestVram = 0x00000000; + for (const [vram, [name, type, size]] of SymbolsSegment.N64LibultraSyms) { + const contextSym = this.addSymbol(vram); + contextSym.name = name; + contextSym.setTypeSpecial(type, false); + contextSym.userDeclaredSize = size; + contextSym.isDefined = true; + contextSym.isUserDeclared = true; + highestVram = Math.max(highestVram, vram); + lowestVram = Math.min(lowestVram, vram); + } + this.context.totalVramRange.addSpecialRange(lowestVram, highestVram); + } + + fillIQueSymbols() { + let lowestVram = 0xffffffff; + let highestVram = 0x00000000; + for (const [vram, [name, type, size]] of SymbolsSegment.iQueLibultraSyms) { + const contextSym = this.addSymbol(vram); + contextSym.name = name; + contextSym.setTypeSpecial(type, false); + contextSym.userDeclaredSize = size; + contextSym.isDefined = true; + contextSym.isUserDeclared = true; + highestVram = Math.max(highestVram, vram); + lowestVram = Math.min(lowestVram, vram); + } + this.context.totalVramRange.addSpecialRange(lowestVram, highestVram); + } + + fillHardwareRegs(useRealNames = false) { + let lowestVram = 0xffffffff; + let highestVram = 0x00000000; + for (let [vram, name] of SymbolsSegment.N64HardwareRegs) { + // spimdisasm < 1.36 declared LEO_STATUS/LEO_BM_STATUS/LEO_SEQ_STATUS as duplicate keys, overriding the values + if (!atLeast("1.39.0") && LEGACY_LEO_NAMES.has(vram)) name = LEGACY_LEO_NAMES.get(vram); + let nameToUse = null; + if (useRealNames) nameToUse = name; + let contextSym = this.addSymbol(vram); + contextSym.name = nameToUse; + contextSym.setTypeSpecial(SymbolSpecialType.hardwarereg, false); + contextSym.userDeclaredSize = 4; + contextSym.isDefined = true; + contextSym.isUserDeclared = true; + + if (useRealNames) { + contextSym = this.addConstant(vram, name, false); + contextSym.setTypeSpecial(SymbolSpecialType.hardwarereg, false); + contextSym.userDeclaredSize = 4; + contextSym.isDefined = true; + contextSym.isUserDeclared = true; + } + highestVram = Math.max(highestVram, vram); + lowestVram = Math.min(lowestVram, vram); + } + this.context.totalVramRange.addSpecialRange(lowestVram, highestVram); + } + + readVariablesCsv(filepath) { + if (!existsSync(String(filepath))) return; + + const variablesFile = Utils.readCsv(filepath); + for (const row of variablesFile) { + if (row.length === 0) continue; + if (row.length !== 4) throw new Error(`ValueError: expected 4 values, got ${row.length}`); + let [vramStr, varName, varType, varSizeStr] = row; + if (vramStr === "-") continue; + + const vram = pyInt(vramStr, 16); + let varSize = null; + if (varSizeStr !== "" && varSizeStr !== "-") { + varSize = pyInt(varSizeStr, 16); + if (varSize === 0) varSize = null; + } + if (varType === "" || varType === "-") varType = null; + + const specialType = SymbolSpecialType.fromStr(varType); + let contextSym; + if (specialType !== null) { + varType = specialType; + if (specialType === SymbolSpecialType.function) contextSym = this.addFunction(vram); + else if (specialType === SymbolSpecialType.branchlabel) contextSym = this.addBranchLabel(vram); + else if (specialType === SymbolSpecialType.jumptable) contextSym = this.addJumpTable(vram); + else if (specialType === SymbolSpecialType.jumptablelabel) contextSym = this.addJumpTableLabel(vram); + else contextSym = this.addSymbol(vram); + } else { + contextSym = this.addSymbol(vram); + } + + contextSym.name = varName; + contextSym.setTypeSpecial(varType, false); + contextSym.userDeclaredSize = varSize; + contextSym.isUserDeclared = true; + } + } + + readFunctionsCsv(filepath) { + if (!existsSync(String(filepath))) return; + + const functionsFile = Utils.readCsv(filepath); + for (const row of functionsFile) { + if (row.length === 0) continue; + if (row.length !== 2) throw new Error(`ValueError: expected 2 values, got ${row.length}`); + const [vramStr, funcName] = row; + if (vramStr === "-") continue; + + const vram = pyInt(vramStr, 16); + const contextSym = this.addFunction(vram); + contextSym.name = funcName; + contextSym.isUserDeclared = true; + } + } + + readConstantsCsv(filepath) { + if (!existsSync(String(filepath))) return; + + const constantsFile = Utils.readCsv(filepath); + for (const row of constantsFile) { + if (row.length === 0) continue; + if (row.length !== 2) throw new Error(`ValueError: expected 2 values, got ${row.length}`); + const [constantValueStr, constantName] = row; + if (constantValueStr === "-") continue; + + const constantValue = pyInt(constantValueStr, 16); + const contextSym = this.addConstant(constantValue, constantName); + contextSym.isUserDeclared = true; + } + } + + readSplatSymbolAddrs(filepath) { + if (!existsSync(String(filepath))) { + if (atLeast("1.39.0")) Utils.eprintQuietless(`symbol_addrs file '${filepath}' not found.`); + return; + } + + const text = readFileSync(String(filepath), "utf8"); + for (const line of fileLines(text)) { + let [info, ...extra] = pyStrip(line).split("//"); + const colonSeparatedPairs = extra.join("//"); + + info = pyStripChars(pyStrip(info), ";"); + + if (!info.includes("=")) continue; + + const parts = info.split("="); + if (parts.length !== 2) throw new Error(`ValueError: too many values to unpack (expected 2)`); + let [name, addressStr] = parts; + const address = pyInt(pyStrip(addressStr), 0); + name = pyStrip(name); + + const pairs = Utils.parseColonSeparatedPairLine(colonSeparatedPairs); + const get = (k) => (pairs.has(k) ? pairs.get(k) : null); + + const symSize = Utils.getMaybeIntFromMaybeStr(get("size")); + + if (Utils.getMaybeBooleyFromMaybeStr(get("ignore"))) { + if (symSize !== null && symSize > 0) this.context.addBannedSymbolRangeBySize(address, symSize); + else this.context.addBannedSymbol(address); + continue; + } + + const symType = get("type"); + const rom = Utils.getMaybeIntFromMaybeStr(get("rom")); + let contextSym; + if (symType === "func") contextSym = this.addFunction(address, false, rom); + else if (symType === "jtbl") contextSym = this.addJumpTable(address, false, rom); + else if (symType === "jtbl_label") contextSym = this.addJumpTableLabel(address, false, rom); + else if (symType === "label") contextSym = this.addBranchLabel(address, false, rom); + else { + contextSym = this.addSymbol(address, undefined, false, rom); + if (symType !== null) contextSym.setTypeSpecial(symType, false); + } + + contextSym.name = name; + contextSym.isUserDeclared = true; + contextSym.nameEnd = get("name_end"); + contextSym.userDeclaredSize = Utils.getMaybeIntFromMaybeStr(get("size")); + + const defined = Utils.getMaybeBooleyFromMaybeStr(get("defined")); + if (defined !== null) contextSym.isDefined = defined; + + const forceMigration = Utils.getMaybeBooleyFromMaybeStr(get("force_migration")); + if (forceMigration !== null) contextSym.forceMigration = forceMigration; + const forceNotMigration = Utils.getMaybeBooleyFromMaybeStr(get("force_not_migration")); + if (forceNotMigration !== null) contextSym.forceNotMigration = forceNotMigration; + contextSym.functionOwnerForMigration = get("function_owner"); + + const allowAddend = Utils.getMaybeBooleyFromMaybeStr(get("allow_addend")); + if (allowAddend !== null) contextSym.allowedToReferenceAddends = allowAddend; + const dontAllowAddend = Utils.getMaybeBooleyFromMaybeStr(get("dont_allow_addend")); + if (dontAllowAddend !== null) contextSym.notAllowedToReferenceAddends = dontAllowAddend; + + const allowReference = Utils.getMaybeBooleyFromMaybeStr(get("allow_reference")); + if (allowReference !== null) contextSym.allowedToReferenceSymbols = allowReference; + + const allowBeReferenced = Utils.getMaybeBooleyFromMaybeStr(get("allow_be_referenced")); + if (allowBeReferenced !== null) contextSym.allowedToBeReferenced = allowBeReferenced; + + contextSym.visibility = get("visibility"); + + const align = get("align"); + if (align !== null) contextSym.setAlignment(pyInt(align, 0)); + + if (versionHasNonMatchingPerSym()) { + const useNonMatchingLabel = Utils.getMaybeBooleyFromMaybeStr(get("use_non_matching_label")); + if (useNonMatchingLabel !== null) contextSym.useNonMatchingLabel = useNonMatchingLabel; + } + } + } + + toString() { + const vromStart = this.vromStart !== null ? `0x${hexU(this.vromStart)}` : "None"; + const vromEnd = this.vromEnd !== null ? `0x${hexU(this.vromEnd)}` : "None"; + const prio = `[${this.prioritizedSegments.map((s) => `'${s}'`).join(", ")}]`; + return `SymbolsSegment`; + } +} + +const LEGACY_LEO_NAMES = new Map([ + [0xa5000508, "LEO_STATUS"], + [0xa5000510, "LEO_BM_STATUS"], + [0xa5000518, "LEO_SEQ_STATUS"], +]); + +function versionAllowsJtblAddend() { + return atLeast("1.39.0"); +} + +function versionHasNonMatchingPerSym() { + return atLeast("1.42.0"); +} diff --git a/packages/romdev-spimdisasm/src/common/Utils.js b/packages/romdev-spimdisasm/src/common/Utils.js new file mode 100644 index 00000000..75823382 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/Utils.js @@ -0,0 +1,517 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/Utils.py (argparse helpers are not ported). + +import { createHash } from "node:crypto"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; + +import { GlobalConfig, InputEndian } from "./GlobalConfig.js"; +import { rabbitizer } from "../rabbitizer.js"; +import { pyDecode, UnicodeDecodeError } from "../py/codecs.js"; +import { wordToFloat as pyWordToFloat, qwordToDouble as pyQwordToDouble } from "../py/pyfloat.js"; +import { hexU, pyInt, pyStrip, splitWs, ValueError } from "../py/pyutils.js"; +import { atLeast } from "../version.js"; + +function fmtArgs(args) { + return args.map((a) => (typeof a === "string" ? a : String(a))).join(" "); +} + +export function eprint(...args) { + process.stderr.write(fmtArgs(args) + "\n"); +} + +export class SystemExit extends Error { + constructor(code) { + super(`SystemExit(${code})`); + this.name = "SystemExit"; + this.code = code; + } +} + +export function panic(...args) { + eprint(...args); + throw new SystemExit(1); +} + +export function printQuietless(...args) { + if (!GlobalConfig.QUIET) process.stdout.write(fmtArgs(args) + "\n"); +} + +export function eprintQuietless(...args) { + if (!GlobalConfig.QUIET) { + if (atLeast("1.39.0")) process.stdout.write(fmtArgs(args) + "\n"); + else process.stderr.write(fmtArgs(args) + "\n"); + } +} + +export function epprintQuietless(...args) { + return eprintQuietless(...args); +} + +export function printVerbose(...args) { + if (!GlobalConfig.QUIET && GlobalConfig.VERBOSE) process.stdout.write(fmtArgs(args) + "\n"); +} + +export function eprintVerbose(...args) { + if (!GlobalConfig.QUIET && GlobalConfig.VERBOSE) eprint(...args); +} + +export function isStdoutRedirected() { + return !process.stdout.isTTY; +} + +/** Returns the md5 hash of a bytes */ +export function getStrHash(byteArray) { + return createHash("md5").update(byteArray).digest("hex"); +} + +export function writeBytesToFile(filepath, arrayOfBytes) { + writeFileSync(String(filepath), arrayOfBytes); +} + +/** @deprecated */ +export const writeBytearrayToFile = writeBytesToFile; + +export function readFileAsBytearray(filepath) { + if (!existsSync(String(filepath))) return new Uint8Array(0); + return new Uint8Array(readFileSync(String(filepath))); +} + +export function readFile(filepath) { + const text = readFileSync(String(filepath), "utf8"); + return splitLinesKeepEnds(text).map((x) => pyStrip(x)); +} + +function splitLinesKeepEnds(text) { + // file.readlines() semantics with universal newlines + const out = []; + let cur = ""; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (c === "\r") { + cur += "\n"; + if (text[i + 1] === "\n") i++; + out.push(cur); + cur = ""; + } else if (c === "\n") { + cur += c; + out.push(cur); + cur = ""; + } else { + cur += c; + } + } + if (cur.length > 0) out.push(cur); + return out; +} + +export function removeExtraWhitespace(line) { + return splitWs(line).join(" "); +} + +function toU8(b) { + if (b instanceof Uint8Array) return b; + if (Array.isArray(b)) return Uint8Array.from(b); + if (b && b.buffer instanceof ArrayBuffer) return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); + return new Uint8Array(b); +} + +export function endianessBytesToWords(endian, arrayOfBytes, offset = 0, offsetEnd = null) { + let bytes = toU8(arrayOfBytes); + const totalBytesCount = bytes.length; + if (totalBytesCount === 0) return []; + + let bytesCount = totalBytesCount; + let offsetEndHex = "None"; + if (offsetEnd !== null && offsetEnd !== undefined && offsetEnd > 0) { + bytesCount = offsetEnd; + offsetEndHex = hexU(offsetEnd); + } + bytesCount -= offset; + + if (!(bytesCount >= 0)) throw new Error(`AssertionError: ${hexU(offset)}, ${offsetEndHex}, ${hexU(bytesCount)}, ${hexU(totalBytesCount)}`); + if (!(offset + bytesCount <= totalBytesCount)) throw new Error(`AssertionError: ${hexU(offset)}, ${offsetEndHex}, ${hexU(bytesCount)}, ${hexU(totalBytesCount)}`); + + if (endian === InputEndian.MIDDLE) { + // Convert middle endian to big endian + const halfwords = Math.floor(bytesCount / 2); + const newBytes = new Uint8Array(bytes); + for (let h = 0; h < halfwords; h++) { + const p = offset + h * 2; + newBytes[p] = bytes[p + 1]; + newBytes[p + 1] = bytes[p]; + } + bytes = newBytes; + } + + const words = Math.floor(bytesCount / 4); + const out = new Array(words); + const little = endian === InputEndian.LITTLE; + for (let i = 0; i < words; i++) { + const p = offset + i * 4; + if (little) out[i] = (bytes[p] | (bytes[p + 1] << 8) | (bytes[p + 2] << 16) | (bytes[p + 3] << 24)) >>> 0; + else out[i] = ((bytes[p] << 24) | (bytes[p + 1] << 16) | (bytes[p + 2] << 8) | bytes[p + 3]) >>> 0; + } + return out; +} + +export function bytesToWords(arrayOfBytes, offset = 0, offsetEnd = null) { + return endianessBytesToWords(GlobalConfig.ENDIAN, arrayOfBytes, offset, offsetEnd); +} + +/** @deprecated */ +export const bytesToBEWords = bytesToWords; + +export function endianessWordsToBytes(endian, wordsList) { + if (endian === InputEndian.MIDDLE) { + throw new Error("BufferError: TODO: wordsToBytesEndianess: GlobalConfig.ENDIAN == InputEndian.MIDDLE"); + } + const out = new Uint8Array(wordsList.length * 4); + const little = endian === InputEndian.LITTLE; + for (let i = 0; i < wordsList.length; i++) { + const w = wordsList[i]; + if (!(Number.isInteger(w) && w >= 0 && w <= 0xffffffff)) { + throw new Error("struct.error: 'I' format requires 0 <= number <= 4294967295"); + } + const p = i * 4; + if (little) { + out[p] = w & 0xff; + out[p + 1] = (w >>> 8) & 0xff; + out[p + 2] = (w >>> 16) & 0xff; + out[p + 3] = (w >>> 24) & 0xff; + } else { + out[p] = (w >>> 24) & 0xff; + out[p + 1] = (w >>> 16) & 0xff; + out[p + 2] = (w >>> 8) & 0xff; + out[p + 3] = w & 0xff; + } + } + return out; +} + +export function wordsToBytes(wordsList) { + return endianessWordsToBytes(GlobalConfig.ENDIAN, wordsList); +} + +/** @deprecated */ +export const beWordsToBytes = wordsToBytes; + +export function wordToFloat(word) { + return pyWordToFloat(word); +} + +export function qwordToDouble(qword) { + return pyQwordToDouble(BigInt(qword)); +} + +export function wordToCurrenEndian(word) { + if (GlobalConfig.ENDIAN === InputEndian.BIG) return word; + if (GlobalConfig.ENDIAN === InputEndian.LITTLE) { + return (((word & 0xff) << 24) | (((word >>> 8) & 0xff) << 16) | (((word >>> 16) & 0xff) << 8) | ((word >>> 24) & 0xff)) >>> 0; + } + // MIDDLE + const hi = (word >>> 16) & 0xffff; + const lo = word & 0xffff; + const swap = (h) => ((h & 0xff) << 8) | ((h >>> 8) & 0xff); + return ((swap(hi) << 16) | swap(lo)) >>> 0; +} + +export function qwordToCurrenEndian(word) { + word = BigInt(word); + if (GlobalConfig.ENDIAN === InputEndian.BIG) return word; + if (GlobalConfig.ENDIAN === InputEndian.LITTLE) { + let r = 0n; + for (let i = 0n; i < 8n; i++) r |= ((word >> (i * 8n)) & 0xffn) << ((7n - i) * 8n); + return r; + } + // MIDDLE + const swap = (h) => ((h & 0xffn) << 8n) | ((h >> 8n) & 0xffn); + const a = swap((word >> 48n) & 0xffffn); + const b = swap((word >> 32n) & 0xffffn); + const c = swap((word >> 16n) & 0xffffn); + const d = swap(word & 0xffffn); + return (a << 48n) | (b << 32n) | (c << 16n) | d; +} + +/** Python csv.reader over lines with '#' comments stripped. */ +export function readCsv(filepath) { + const text = readFileSync(String(filepath), "utf8"); + const lines = splitLinesKeepEnds(text); + const processedLines = lines.map((x) => pyStrip(x.split("#")[0])); + const data = []; + for (const line of processedLines) data.push(parseCsvLine(line)); + return data; +} + +/** Minimal csv.reader (default dialect) for a single line without newlines. */ +export function parseCsvLine(line) { + if (line.length === 0) return []; + const row = []; + let field = ""; + let inQuotes = false; + let quotedField = false; + for (let i = 0; i < line.length; i++) { + const c = line[i]; + if (inQuotes) { + if (c === '"') { + if (line[i + 1] === '"') { + field += '"'; + i++; + } else { + inQuotes = false; + } + } else { + field += c; + } + } else if (c === '"' && field.length === 0 && !quotedField) { + inQuotes = true; + quotedField = true; + } else if (c === ",") { + row.push(field); + field = ""; + quotedField = false; + } else { + field += c; + } + } + row.push(field); + return row; +} + +export function parseColonSeparatedPairLine(line) { + const pairs = new Map(); + // Allow // and # comments + if (atLeast("1.39.0")) line = pyStrip(line.split("//")[0]); + else line = pyStrip(line.split("//")[0].split("#")[0]); + + for (const info of line.split(" ")) { + if (!info.includes(":")) continue; + const [key, ...vals] = info.split(":"); + pairs.set(key, vals.join(":")); + } + return pairs; +} + +export function getMaybeIntFromMaybeStr(number, base = 0) { + if (number === null || number === undefined) return null; + return pyInt(number, base); +} + +export function intFromStr(number, base = 0) { + try { + return pyInt(number, base); + } catch (e) { + if (e instanceof ValueError) return null; + throw e; + } +} + +export const TRUEY_VALS = ["true", "on", "yes", "y"]; +export const FALSEY_VALS = ["false", "off", "no", "n"]; + +export function getMaybeBooleyFromMaybeStr(booley) { + if (booley === null || booley === undefined) return null; + if (TRUEY_VALS.includes(booley)) return true; + if (FALSEY_VALS.includes(booley)) return false; + return null; +} + +// Escape characters that are unlikely to be used +const bannedEscapeCharactersBase = [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0b, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, + 0x1c, 0x1d, 0x1e, 0x1f, +]; + +/** Set of banned characters for the configured version (0x7F was added in 1.36). */ +export const bannedEscapeCharacters = new Set([...bannedEscapeCharactersBase, 0x7f]); +const bannedEscapeCharacters135 = new Set(bannedEscapeCharactersBase); + +function isBanned(c) { + return atLeast("1.39.0") ? bannedEscapeCharacters.has(c) : bannedEscapeCharacters135.has(c); +} + +export const escapeCharactersSpecialCases = new Set([0x1a, 0x1b, 0x8c, 0x8d]); + +function tryDecode(bytes, encoding) { + try { + return { ok: true, value: pyDecode(bytes, encoding) }; + } catch (e) { + if (e instanceof UnicodeDecodeError) return { ok: false }; + throw e; + } +} + +function hex2(c) { + return `\\x${hexU(c, 2)}`; +} + +export function decodeBytesToStrings(buf, offset, stringEncoding, terminator = 0) { + buf = toU8(buf); + const result = []; + let dst = []; + let i = 0; + while (offset + i < buf.length && buf[offset + i] !== terminator) { + const char = buf[offset + i]; + if (isBanned(char)) return [[], -10]; + + let validNonAsciiSequence = false; + if (char > 0x7f) { + dst.push(char); + if (tryDecode(Uint8Array.from(dst), stringEncoding).ok) { + validNonAsciiSequence = true; + } else if (offset + i + 1 < buf.length) { + const nextChar = buf[offset + i + 1]; + if (nextChar !== 0x5c) { + dst.push(nextChar); + if (tryDecode(Uint8Array.from(dst), stringEncoding).ok) validNonAsciiSequence = true; + dst.pop(); + } + } + dst.pop(); + + if (!validNonAsciiSequence && offset + i + 1 < buf.length) { + const nextChar = buf[offset + i + 1]; + if (nextChar === 0x5c) { + if (dst.length > 0) { + const d = tryDecode(Uint8Array.from(dst), stringEncoding); + if (!d.ok) return [[], -60]; + result.push(rabbitizer.Utils.escapeString(d.value)); + dst = []; + } + result.push(hex2(char)); + result.push(hex2(nextChar)); + i += 2; + continue; + } + } + } + + if (!validNonAsciiSequence && escapeCharactersSpecialCases.has(char)) { + if (dst.length > 0) { + const d = tryDecode(Uint8Array.from(dst), stringEncoding); + if (!d.ok) return [[], -70]; + result.push(rabbitizer.Utils.escapeString(d.value)); + dst = []; + } + result.push(hex2(char)); + } else { + dst.push(char); + } + i += 1; + } + + if (offset + i >= buf.length) { + // Reached the end of the buffer without finding an 0 + return [[], -80]; + } + + if (dst.length > 0) { + const d = tryDecode(Uint8Array.from(dst), stringEncoding); + if (!d.ok) return [[], -90]; + result.push(rabbitizer.Utils.escapeString(d.value)); + } + + // To be a valid aligned string, the next word-aligned bytes needs to be zero + let checkStartOffset = offset + i; + const checkEndOffset = Math.min((checkStartOffset & ~3) + 4, buf.length); + while (checkStartOffset < checkEndOffset) { + if (buf[checkStartOffset] !== terminator) return [[], -100]; + checkStartOffset += 1; + } + + return [result, i]; +} + +export function decodeBytesToPascalStrings(buf, offset, stringEncoding, terminator = 0x20) { + buf = toU8(buf); + const result = []; + let dst = []; + let i = 0; + while (offset + i < buf.length) { + if (buf[offset + i] === terminator) { + if (offset + i + 1 < buf.length && buf[offset + i + 1] === terminator) { + // Require at least 2 terminators next to each other to actually consider the string has ended + break; + } + } + const char = buf[offset + i]; + if (isBanned(char)) { + return [[], -1]; + } else if (escapeCharactersSpecialCases.has(char)) { + if (dst.length > 0) { + const d = tryDecode(Uint8Array.from(dst), stringEncoding); + if (!d.ok) return [[], -1]; + result.push(rabbitizer.Utils.escapeString(d.value)); + dst = []; + } + result.push(hex2(char)); + } else { + dst.push(char); + } + i += 1; + } + + if (offset + i >= buf.length) { + return [[], -1]; + } + + // To be a valid aligned string, the next word-aligned bytes needs to be the terminator value + let checkStartOffset = offset + i; + const checkEndOffset = Math.min((checkStartOffset & ~3) + 4, buf.length); + while (checkStartOffset < checkEndOffset) { + if (buf[checkStartOffset] !== terminator) return [[], -1]; + dst.push(buf[checkStartOffset]); + checkStartOffset += 1; + i += 1; + } + + while (offset + i < buf.length) { + // Check in chunks of 4 bytes for the terminator value + let j = 0; + let onlyTerminator = true; + while (j < 4 && offset + i + j < buf.length) { + const char = buf[offset + i + j]; + if (char !== terminator) { + onlyTerminator = false; + break; + } + j += 1; + } + if (!onlyTerminator) break; + dst.push(terminator, terminator, terminator, terminator); + i += 4; + } + + if (dst.length > 0) { + const d = tryDecode(Uint8Array.from(dst), stringEncoding); + if (!d.ok) return [[], -1]; + result.push(rabbitizer.Utils.escapeString(d.value)); + } + + return [result, i]; +} + +/** @deprecated */ +export function decodeString(buf, offset, stringEncoding) { + buf = toU8(buf); + const result = []; + let dst = []; + let i = 0; + while (offset + i < buf.length && buf[offset + i] !== 0) { + const char = buf[offset + i]; + if (isBanned(char)) { + throw new Error("RuntimeError"); + } else if (escapeCharactersSpecialCases.has(char)) { + if (dst.length > 0) { + result.push(rabbitizer.Utils.escapeString(pyDecode(Uint8Array.from(dst), stringEncoding))); + dst = []; + } + result.push(hex2(char)); + } else { + dst.push(char); + } + i += 1; + } + if (offset + i > buf.length) throw new Error("RuntimeError: Reached the end of the buffer without finding an 0"); + if (dst.length > 0) result.push(rabbitizer.Utils.escapeString(pyDecode(Uint8Array.from(dst), stringEncoding))); + return [result, i]; +} diff --git a/packages/romdev-spimdisasm/src/common/index.js b/packages/romdev-spimdisasm/src/common/index.js new file mode 100644 index 00000000..b8b5f63e --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/index.js @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/common/__init__.py + +import * as Utils from "./Utils.js"; + +export { Utils }; + +export { SortedDict } from "./SortedDict.js"; +export { CompilerProperties, Compiler, compilerOptions } from "./CompilerConfig.js"; +export { GlobalConfig, GlobalConfigType, InputEndian, Abi, ArchLevel, InputFileType, archLevelOptions } from "./GlobalConfig.js"; +export { FileSectionType, FileSections_ListBasic, FileSections_ListAll } from "./FileSectionType.js"; +export { SymbolSpecialType, ContextSymbol, gKnownTypes, getAccessKinds, AccessTypeInfo, symEq } from "./ContextSymbols.js"; +export { SymbolsSegment } from "./SymbolsSegment.js"; +export { Context, AddressRange, SymbolsRanges } from "./Context.js"; +export { FileSplitFormat, FileSplitEntry } from "./FileSplitFormat.js"; +export { ElementBase } from "./ElementBase.js"; +export { GotEntry, GlobalOffsetTable, GpAccessContainer, GpAccess, SmallSection } from "./GpAccesses.js"; +export { OrderedEnum } from "./OrderedEnum.js"; +export { RelocType, RelocationInfo, RelocationStaticReference } from "./Relocation.js"; diff --git a/packages/romdev-spimdisasm/src/common/symset.js b/packages/romdev-spimdisasm/src/common/symset.js new file mode 100644 index 00000000..ed1af2f2 --- /dev/null +++ b/packages/romdev-spimdisasm/src/common/symset.js @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT +// Python set emulation for spimdisasm's sets. +// +// spimdisasm keeps `set[int]` and `set[ContextSymbol]` collections. Some of them +// are iterated by callers (splat iterates `referencedVrams`), so their iteration +// order must match CPython's hash-table order. PySet reproduces that order. + +import { PySet, pyHashTuple, pyHashInt } from "../py/pyset.js"; + +export { PySet }; + +/** New Python-ordered set of ints. */ +export function newIntSet(iterable) { + return new PySet(iterable); +} + +function symHash(sym) { + return pyHashTuple([sym.address, sym.vromAddress === undefined ? null : sym.vromAddress]); +} + +function symEqForSet(a, b) { + return a === b || (a.address === b.address && (a.vromAddress ?? null) === (b.vromAddress ?? null)); +} + +/** New Python-ordered set of ContextSymbol (hash/eq on (address, vromAddress)). */ +export function newSymbolSet(iterable) { + return new PySet(iterable, { hash: symHash, eq: symEqForSet }); +} + +export { pyHashInt }; diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32Constants.js b/packages/romdev-spimdisasm/src/elf32/Elf32Constants.js new file mode 100644 index 00000000..7aba101f --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32Constants.js @@ -0,0 +1,290 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32Constants.py + +import { createEnum } from "../py/pyutils.js"; +import { withAliases, enumFromValue } from "./_util.js"; + +// a.k.a. EI +const FileClass = createEnum("FileClass", [ + ["CLASSNONE", 0], // Invalid class + ["CLASS32", 1], // 32-bit objects + ["CLASS64", 2], // 64-bit objects + ["CLASSNUM", 3], +]); + +const DataEncoding = createEnum("DataEncoding", [ + ["DATANONE", 0], // Invalid data encoding + ["DATA2LSB", 1], // 2's complement, little endian + ["DATA2MSB", 2], // 2's complement, big endian + ["DATANUM", 3], +]); + +const OsAbi = withAliases( + createEnum("OsAbi", [ + ["NONE", 0], // UNIX System V ABI + ["HPUX", 1], + ["NETBSD", 2], + ["GNU", 3], + ["SOLARIS", 6], + ["AIX", 7], + ["IRIX", 8], + ["FREEBSD", 9], + ["TRU64", 10], + ["MODESTO", 11], + ["OPENBSD", 12], + ["ARM_AEABI", 64], + ["ARM", 97], + ["STANDALONE", 255], + ]), + { SYSV: "NONE", LINUX: "GNU" }, +); + +export const Elf32HeaderIdentifier = Object.freeze({ FileClass, DataEncoding, OsAbi }); + +// ET (object file type) +export const Elf32ObjectFileType = createEnum("Elf32ObjectFileType", [ + ["NONE", 0], + ["REL", 1], + ["EXEC", 2], + ["DYN", 3], + ["CORE", 4], + ["NUM", 5], +]); + +const HEADER_FLAG_ENTRIES = [ + ["NOREORDER", 0x00000001], + ["PIC", 0x00000002], + ["CPIC", 0x00000004], + ["XGOT", 0x00000008], + ["F_64BIT_WHIRL", 0x00000010], + ["ABI2", 0x00000020], + ["ABI_ON32", 0x00000040], + ["_32BITSMODE", 0x00000100], + ["FP64", 0x00000200], + ["NAN2008", 0x00000400], + // ABI + ["O32", 0x00001000], + ["O64", 0x00002000], + ["EABI32", 0x00003000], + ["EABI64", 0x00004000], + // CPU + ["CPU", 0x00ff0000], + ["_3900", 0x00810000], + ["_4010", 0x00820000], + ["_4100", 0x00830000], + ["_4650", 0x00850000], + ["_4120", 0x00870000], + ["_4111", 0x00880000], + ["SB1", 0x008a0000], + ["OCTEON", 0x008b0000], + ["XLR", 0x008c0000], + ["OCTEON2", 0x008d0000], + ["OCTEON3", 0x008e0000], + ["_5400", 0x00910000], + ["_5900", 0x00920000], + ["IAMR2", 0x00930000], + ["_5500", 0x00980000], + ["_9000", 0x00990000], + ["LS2E", 0x00a00000], + ["LS2F", 0x00a10000], + ["GS464", 0x00a20000], + ["GS464E", 0x00a30000], + ["GS264E", 0x00a40000], + // arch level + ["ARCH", 0xf0000000], + ["ARCH_1", 0x00000000], + ["ARCH_2", 0x10000000], + ["ARCH_3", 0x20000000], + ["ARCH_4", 0x30000000], + ["ARCH_5", 0x40000000], + ["ARCH_32", 0x50000000], + ["ARCH_64", 0x60000000], + ["ARCH_32R2", 0x70000000], + ["ARCH_64R2", 0x80000000], +]; + +const CPU_NAMES = ["_3900", "_4010", "_4100", "_4650", "_4120", "_4111", "SB1", "OCTEON", "XLR", "OCTEON2", "OCTEON3", "_5400", "_5900", "IAMR2", "_5500", "_9000", "LS2E", "LS2F", "GS464", "GS464E", "GS264E"]; +const ARCH_NAMES = ["ARCH_1", "ARCH_2", "ARCH_3", "ARCH_4", "ARCH_5", "ARCH_32", "ARCH_64", "ARCH_32R2", "ARCH_64R2"]; +const SIMPLE_FLAG_NAMES = ["NOREORDER", "PIC", "CPIC", "XGOT", "F_64BIT_WHIRL", "ABI2", "ABI_ON32", "_32BITSMODE", "FP64", "NAN2008", "O32", "O64", "EABI32", "EABI64"]; + +// Legal values for e_flags field of Elf32_Ehdr +export const Elf32HeaderFlag = createEnum("Elf32HeaderFlag", HEADER_FLAG_ENTRIES, {}, { + /** Returns [parsedFlags, remainingUnknownFlags] */ + parseFlags(rawFlags) { + rawFlags >>>= 0; + const parsedFlags = []; + + for (const n of SIMPLE_FLAG_NAMES) { + const flagEnum = Elf32HeaderFlag[n]; + if ((rawFlags & flagEnum.value) >>> 0) { + parsedFlags.push(flagEnum); + rawFlags = (rawFlags & ~flagEnum.value) >>> 0; + } + } + + const cpu = (rawFlags & Elf32HeaderFlag.CPU.value) >>> 0; + rawFlags = (rawFlags & ~Elf32HeaderFlag.CPU.value) >>> 0; + const cpuName = CPU_NAMES.find((n) => Elf32HeaderFlag[n].value === cpu); + if (cpuName !== undefined) parsedFlags.push(Elf32HeaderFlag[cpuName]); + else rawFlags = (rawFlags | cpu) >>> 0; + + const archLevel = (rawFlags & Elf32HeaderFlag.ARCH.value) >>> 0; + rawFlags = (rawFlags & ~Elf32HeaderFlag.ARCH.value) >>> 0; + const archName = ARCH_NAMES.find((n) => Elf32HeaderFlag[n].value === archLevel); + if (archName !== undefined) parsedFlags.push(Elf32HeaderFlag[archName]); + else rawFlags = (rawFlags | archLevel) >>> 0; + + return [parsedFlags, rawFlags]; + }, +}); + +// a.k.a. SHT (section header type) +export const Elf32SectionHeaderType = createEnum( + "Elf32SectionHeaderType", + [ + ["NULL", 0], + ["PROGBITS", 1], + ["SYMTAB", 2], + ["STRTAB", 3], + ["RELA", 4], + ["HASH", 5], + ["DYNAMIC", 6], + ["NOTE", 7], + ["NOBITS", 8], + ["REL", 9], + ["DYNSYM", 11], + ["MIPS_LIBLIST", 0x70000000], + ["MIPS_MSYM", 0x70000001], + ["MIPS_CONFLICT", 0x70000002], + ["MIPS_GPTAB", 0x70000003], + ["MIPS_DEBUG", 0x70000005], + ["MIPS_REGINFO", 0x70000006], + ["MIPS_OPTIONS", 0x7000000d], + ["MIPS_SYMBOL_LIB", 0x70000020], + ["MIPS_ABIFLAGS", 0x7000002a], + ], + {}, + { + fromValue(value) { + return enumFromValue(Elf32SectionHeaderType, value); + }, + }, +); + +const SECTION_FLAG_NAMES = ["WRITE", "ALLOC", "EXECINSTR", "MERGE", "STRINGS", "INFO_LINK", "LINK_ORDER", "OS_NONCONFORMING", "GROUP", "TLS", "COMPRESSED", "EXCLUDE"]; + +// Values for section header, sh_flags field. +export const Elf32SectionHeaderFlag = createEnum( + "Elf32SectionHeaderFlag", + [ + ["WRITE", 0x00000001], + ["ALLOC", 0x00000002], + ["EXECINSTR", 0x00000004], + ["MERGE", 0x00000010], + ["STRINGS", 0x00000020], + ["INFO_LINK", 0x00000040], + ["LINK_ORDER", 0x00000080], + ["OS_NONCONFORMING", 0x00000100], + ["GROUP", 0x00000200], + ["TLS", 0x00000400], + ["COMPRESSED", 0x00000800], + ["EXCLUDE", 0x80000000], + ], + {}, + { + /** Returns [parsedFlags, remainingUnknownFlags] */ + parseFlags(rawFlags) { + rawFlags >>>= 0; + const parsedFlags = []; + for (const n of SECTION_FLAG_NAMES) { + const flagEnum = Elf32SectionHeaderFlag[n]; + if ((rawFlags & flagEnum.value) >>> 0) { + parsedFlags.push(flagEnum); + rawFlags = (rawFlags & ~flagEnum.value) >>> 0; + } + } + return [parsedFlags, rawFlags]; + }, + }, +); + +// a.k.a. STT (symbol table type) +export const Elf32SymbolTableType = createEnum("Elf32SymbolTableType", [ + ["NOTYPE", 0], + ["OBJECT", 1], + ["FUNC", 2], + ["SECTION", 3], + ["FILE", 4], + ["COMMON", 5], + ["TLS", 6], + ["NUM", 7], +]); + +// a.k.a. STB (symbol table binding) +export const Elf32SymbolTableBinding = createEnum( + "Elf32SymbolTableBinding", + [ + ["LOCAL", 0], + ["GLOBAL", 1], + ["WEAK", 2], + ["LOOS", 10], + ["HIOS", 12], + ["LOPROC", 13], + ["HIPROC", 14], + ], + {}, + { + fromValue(value) { + return enumFromValue(Elf32SymbolTableBinding, value); + }, + }, +); + +// Symbol visibility specification encoded in the st_other field. +export const Elf32SymbolVisibility = createEnum( + "Elf32SymbolVisibility", + [ + ["DEFAULT", 0], + ["INTERNAL", 1], + ["HIDDEN", 2], + ["PROTECTED", 3], + ["PLT", 8], + ["SC_ALIGN_UNUSED", 0xff], + ], + {}, + { + fromValue(value) { + return enumFromValue(Elf32SymbolVisibility, value); + }, + }, +); + +// a.k.a. SHN (section header number) +export const Elf32SectionHeaderNumber = createEnum( + "Elf32SectionHeaderNumber", + [ + ["UNDEF", 0], + ["ABS", 0xfff1], + ["COMMON", 0xfff2], + ["MIPS_ACOMMON", 0xff00], + ["MIPS_TEXT", 0xff01], + ["MIPS_DATA", 0xff02], + ["MIPS_SCOMMON", 0xff03], + ["MIPS_SUNDEFINED", 0xff04], + ], + {}, + { + fromValue(value) { + return enumFromValue(Elf32SectionHeaderNumber, value); + }, + }, +); + +// a.k.a. DT +export const Elf32DynamicTable = createEnum("Elf32DynamicTable", [ + ["NULL", 0], // Marks end of dynamic section + ["PLTGOT", 3], // Processor defined value + ["MIPS_LOCAL_GOTNO", 0x7000000a], // Number of local GOT entries + ["MIPS_SYMTABNO", 0x70000011], // Number of DYNSYM entries + ["MIPS_GOTSYM", 0x70000013], // First GOT entry in DYNSYM +]); diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32Dyns.js b/packages/romdev-spimdisasm/src/elf32/Elf32Dyns.js new file mode 100644 index 00000000..0a2603f2 --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32Dyns.js @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32Dyns.py + +import { Elf32DynamicTable } from "./Elf32Constants.js"; +import { unpackFrom, endianFmt, dataclassRepr } from "./_util.js"; + +// a.k.a. Dyn +export class Elf32DynEntry { + /** tag: dynamic entry type, val: integer value */ + constructor(tag, val) { + this.tag = tag; + this.val = val; + } + + /** Address value */ + get ptr() { + return this.val; + } + + static fromBytearray(array_of_bytes, offset = 0) { + return new Elf32DynEntry(...unpackFrom(endianFmt() + "II", array_of_bytes, offset)); + } + + static structSize() { + return 0x08; + } + + __repr__() { + return dataclassRepr("Elf32DynEntry", this, ["tag", "val"]); + } + + toString() { + return this.__repr__(); + } +} + +export class Elf32Dyns { + constructor(array_of_bytes, offset, rawSize) { + this.dyns = []; + this.offset = offset; + this.rawSize = rawSize; + + this.pltGot = null; + this.localGotNo = null; + this.symTabNo = null; + this.gotSym = null; + + const n = Math.floor(rawSize / Elf32DynEntry.structSize()); + for (let i = 0; i < n; i++) { + const entry = Elf32DynEntry.fromBytearray(array_of_bytes, offset + i * Elf32DynEntry.structSize()); + this.dyns.push(entry); + + if (entry.tag === Elf32DynamicTable.PLTGOT.value) this.pltGot = entry.val; + else if (entry.tag === Elf32DynamicTable.MIPS_LOCAL_GOTNO.value) this.localGotNo = entry.val; + else if (entry.tag === Elf32DynamicTable.MIPS_SYMTABNO.value) this.symTabNo = entry.val; + else if (entry.tag === Elf32DynamicTable.MIPS_GOTSYM.value) this.gotSym = entry.val; + } + } + + /** Python __getitem__ */ + get(key) { + let idx = key; + if (idx < 0) idx += this.dyns.length; + if (idx < 0 || idx >= this.dyns.length) throw Object.assign(new Error("list index out of range"), { name: "IndexError" }); + return this.dyns[idx]; + } + + getItem(key) { + return this.get(key); + } + + [Symbol.iterator]() { + return this.dyns[Symbol.iterator](); + } + + getGpValue() { + if (this.pltGot === null) return null; + return this.pltGot + 0x7ff0; + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32File.js b/packages/romdev-spimdisasm/src/elf32/Elf32File.js new file mode 100644 index 00000000..cec335f1 --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32File.js @@ -0,0 +1,589 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32File.py + +import { GlobalConfig, InputEndian, Abi, ArchLevel } from "../common/GlobalConfig.js"; +import { FileSectionType } from "../common/FileSectionType.js"; +import { RelocType } from "../common/Relocation.js"; +import * as Utils from "../common/Utils.js"; +import { hexU } from "../py/pyutils.js"; +import { atLeast } from "../version.js"; +import { + Elf32HeaderIdentifier, + Elf32ObjectFileType, + Elf32HeaderFlag, + Elf32SectionHeaderType, + Elf32SectionHeaderFlag, + Elf32SymbolTableType, + Elf32SymbolTableBinding, + Elf32SymbolVisibility, + Elf32SectionHeaderNumber, +} from "./Elf32Constants.js"; +import { Elf32Dyns } from "./Elf32Dyns.js"; +import { Elf32GlobalOffsetTable } from "./Elf32GlobalOffsetTable.js"; +import { Elf32Header } from "./Elf32Header.js"; +import { Elf32RegInfo } from "./Elf32RegInfo.js"; +import { Elf32SectionHeaders } from "./Elf32SectionHeaders.js"; +import { Elf32StringTable } from "./Elf32StringTable.js"; +import { Elf32Syms } from "./Elf32Syms.js"; +import { Elf32Rels } from "./Elf32Rels.js"; +import { enumCall, enumRepr } from "./_util.js"; + +function out(s = "", end = "\n") { + process.stdout.write(s + end); +} + +const ljust = (s, w) => String(s).padEnd(w); +const rjust = (s, w) => String(s).padStart(w); + +/** Python format spec "> X": right aligned, space sign, uppercase hex. */ +function spaceSignHex(n, w) { + return (" " + hexU(n)).padStart(w); +} + +/** Python str.isprintable() for a single code point in 0..255 */ +function isPrintableLatin1(c) { + if (c < 0x20) return false; + if (c >= 0x7f && c <= 0xa0) return false; + if (c === 0xad) return false; + return true; +} + +function pyFlagList(flags) { + return `[${flags.map(enumRepr).join(", ")}]`; +} + +export class Elf32File { + constructor(array_of_bytes) { + this.header = Elf32Header.fromBytearray(array_of_bytes); + + const dataEncoding = this.header.ident.getDataEncoding(); + if (dataEncoding === Elf32HeaderIdentifier.DataEncoding.DATA2MSB) GlobalConfig.ENDIAN = InputEndian.BIG; + else if (dataEncoding === Elf32HeaderIdentifier.DataEncoding.DATA2LSB) GlobalConfig.ENDIAN = InputEndian.LITTLE; + + const [elfFlags, unknownElfFlags] = Elf32HeaderFlag.parseFlags(this.header.flags); + this.elfFlags = elfFlags; + this.unknownElfFlags = unknownElfFlags; + + this.strtab = null; + this.symtab = null; + + this.dynamic = null; + this.dynstr = null; + this.dynsym = null; + + /** @deprecated Map */ + this.progbits = new Map(); + /** @deprecated */ + this.nobits = null; + + /** @deprecated */ + this.progbitsSmall = new Map(); + /** @deprecated */ + this.nobitsSmall = null; + + /** @deprecated Map */ + this.rel = new Map(); + + this.progbitsExecute = new Map(); + this.progbitsWrite = new Map(); + this.progbitsNoWrite = new Map(); + + this.nobitsPerName = new Map(); + + this.smallSections = new Map(); + + this.relPerName = new Map(); + + this.reginfo = null; + + this.sectionHeaders = new Elf32SectionHeaders(array_of_bytes, this.header.shoff, this.header.shnum); + + const shstrtabSectionEntry = this.sectionHeaders.sections.at(this.header.shstrndx); + if (shstrtabSectionEntry === undefined) throw Object.assign(new Error("list index out of range"), { name: "IndexError" }); + this.shstrtab = new Elf32StringTable(array_of_bytes, shstrtabSectionEntry.offset, shstrtabSectionEntry.size); + + this.got = null; + + for (const entry of this.sectionHeaders.sections) { + const sectionEntryName = this.shstrtab.get(entry.name); + + const callback = Elf32File._sectionProcessorCallbacks.get(entry.type); + if (callback !== undefined) callback.call(this, array_of_bytes, entry, sectionEntryName); + else if (GlobalConfig.VERBOSE) Utils.eprint("Unknown section header type found:", sectionEntryName, entry, "\n"); + } + + if (this.got !== null && this.dynamic !== null && this.dynsym !== null) this.got.initTables(this.dynamic, this.dynsym); + } + + handleHeaderIdent() { + if (this.header.ident.getVersion() !== 1) { + Utils.eprint(`Warning: Elf version '${this.header.ident.getVersion()}' when version '1' was expected.`); + } + } + + handleFlags() { + const has = (f) => this.elfFlags.includes(f); + const warnUnhandled = (name) => { + Utils.eprint(`Warning: Elf with ${name} flag.`); + Utils.eprint("\t This flag is currently not handled in any way, please report this"); + }; + + if (this.unknownElfFlags !== 0) Utils.eprint(`Warning: Elf header has unknown flags: 0x${hexU(this.unknownElfFlags)}`); + + if (has(Elf32HeaderFlag.PIC) || has(Elf32HeaderFlag.CPIC)) GlobalConfig.PIC = true; + + if (has(Elf32HeaderFlag.XGOT)) warnUnhandled("XGOT"); + if (has(Elf32HeaderFlag.F_64BIT_WHIRL)) warnUnhandled("F_64BIT_WHIRL"); + if (has(Elf32HeaderFlag.ABI_ON32)) warnUnhandled("ABI_ON32"); + if (has(Elf32HeaderFlag._32BITSMODE)) warnUnhandled("32BITSMODE"); + if (has(Elf32HeaderFlag.FP64)) warnUnhandled("FP64"); + if (has(Elf32HeaderFlag.NAN2008)) warnUnhandled("NAN2008"); + + if (has(Elf32HeaderFlag.ABI2) && has(Elf32HeaderFlag.O64)) { + Utils.eprint("Warning: Elf compiled using N64 ABI. Support is in experimental state"); + // spimdisasm 1.35.x set N32 here + GlobalConfig.ABI = atLeast("1.39.0") ? Abi.N64 : Abi.N32; + } else if (has(Elf32HeaderFlag.ABI2)) { + Utils.eprint("Warning: Elf compiled using N32 ABI. Support is in experimental state"); + GlobalConfig.ABI = Abi.N32; + } else if (has(Elf32HeaderFlag.O64)) { + Utils.eprint("Warning: Elf compiled using O64 ABI. Support is in experimental state"); + GlobalConfig.ABI = Abi.O64; + } + + if (has(Elf32HeaderFlag.EABI32)) { + Utils.eprint("Warning: Elf compiled using EABI32 ABI. Support is in experimental state"); + GlobalConfig.ABI = Abi.EABI32; + } + + if (has(Elf32HeaderFlag.EABI64)) { + Utils.eprint("Warning: Elf compiled using EABI64 ABI. Support is in experimental state"); + GlobalConfig.ABI = Abi.EABI64; + } + + // Python builds this from a set intersection; the name order follows set + // iteration, which for these few enum members is not reproducible without + // their object hashes. Only the warning text depends on it. + const unkArchLevel = [Elf32HeaderFlag.ARCH_5, Elf32HeaderFlag.ARCH_32, Elf32HeaderFlag.ARCH_64, Elf32HeaderFlag.ARCH_32R2, Elf32HeaderFlag.ARCH_64R2].filter(has); + if (unkArchLevel.length > 0) { + const unkArchLevelNames = `[${unkArchLevel.map((x) => `'${x.name}'`).join(", ")}]`; + Utils.eprint(`Warning: Elf uses not supported architecture level: ${unkArchLevelNames}`); + Utils.eprint("\t This means this elf probably uses an unknown instruction set"); + } + + if (has(Elf32HeaderFlag.ARCH_1)) GlobalConfig.ARCHLEVEL = ArchLevel.MIPS1; + else if (has(Elf32HeaderFlag.ARCH_2)) GlobalConfig.ARCHLEVEL = ArchLevel.MIPS2; + else if (has(Elf32HeaderFlag.ARCH_3)) GlobalConfig.ARCHLEVEL = ArchLevel.MIPS3; + else if (has(Elf32HeaderFlag.ARCH_4)) GlobalConfig.ARCHLEVEL = ArchLevel.MIPS4; + else if (has(Elf32HeaderFlag.ARCH_5)) { + // spimdisasm 1.42.x maps ARCH_5 to MIPS4 (earlier releases used MIPS5) + GlobalConfig.ARCHLEVEL = atLeast("1.42.0") ? ArchLevel.MIPS4 : ArchLevel.MIPS5; + } else if (has(Elf32HeaderFlag.ARCH_32)) GlobalConfig.ARCHLEVEL = ArchLevel.MIPS32; + else if (has(Elf32HeaderFlag.ARCH_64)) GlobalConfig.ARCHLEVEL = ArchLevel.MIPS64; + else if (has(Elf32HeaderFlag.ARCH_32R2)) GlobalConfig.ARCHLEVEL = ArchLevel.MIPS32R2; + else if (has(Elf32HeaderFlag.ARCH_64R2)) GlobalConfig.ARCHLEVEL = ArchLevel.MIPS64R2; + } + + _processSection_NULL(_array_of_bytes, _entry, _sectionEntryName) {} + + _processSection_PROGBITS(array_of_bytes, entry, sectionEntryName) { + const fileSecType = FileSectionType.fromStr(sectionEntryName); + const smallFileSecType = FileSectionType.fromSmallStr(sectionEntryName); + const [flags, unknownFlags] = Elf32SectionHeaderFlag.parseFlags(entry.flags); + + if (fileSecType !== FileSectionType.Invalid) { + this.progbits.set(fileSecType, entry); + if (fileSecType === FileSectionType.Text) this.sectionHeaders.mipsText = entry; + else if (fileSecType === FileSectionType.Data) this.sectionHeaders.mipsData = entry; + } else if (smallFileSecType !== FileSectionType.Invalid) { + this.progbitsSmall.set(smallFileSecType, entry); + } else if (sectionEntryName === ".got") { + this.got = new Elf32GlobalOffsetTable(array_of_bytes, entry.offset, entry.size); + } else if (sectionEntryName === ".interp" || sectionEntryName === ".MIPS.stubs" || sectionEntryName === ".init") { + Utils.printVerbose(`Unhandled PROGBITS found: '${sectionEntryName}'`); + } else if (GlobalConfig.VERBOSE) { + Utils.eprint(`Unhandled PROGBITS found: '${sectionEntryName}'`, entry, "\n"); + } + + if (smallFileSecType !== FileSectionType.Invalid) this.smallSections.set(sectionEntryName, entry); + + if (sectionEntryName === ".got") { + this.got = new Elf32GlobalOffsetTable(array_of_bytes, entry.offset, entry.size); + } else if (flags.includes(Elf32SectionHeaderFlag.EXECINSTR) && sectionEntryName !== ".vutext") { + this.progbitsExecute.set(sectionEntryName, entry); + } else if (sectionEntryName === ".rodata" || sectionEntryName === ".rdata") { + // Some compilers set the Write flag on .rodata sections + this.progbitsNoWrite.set(sectionEntryName, entry); + } else if (flags.includes(Elf32SectionHeaderFlag.WRITE)) { + this.progbitsWrite.set(sectionEntryName, entry); + } else if (flags.includes(Elf32SectionHeaderFlag.ALLOC)) { + this.progbitsNoWrite.set(sectionEntryName, entry); + } else if (flags.includes(Elf32SectionHeaderFlag.STRINGS)) { + this.progbitsNoWrite.set(sectionEntryName, entry); + } else if (sectionEntryName === ".comment") { + // Usually strings specifying the compiler used to build + } else if (sectionEntryName === ".pdr") { + // Debugging section + } else if (!GlobalConfig.QUIET) { + Utils.eprint(`Unhandled PROGBITS found: '${sectionEntryName}', flags: ${pyFlagList(flags)}, unknownFlags: ${unknownFlags}\n`); + } + } + + _processSection_SYMTAB(array_of_bytes, entry, sectionEntryName) { + if (sectionEntryName === ".symtab") this.symtab = new Elf32Syms(array_of_bytes, entry.offset, entry.size); + else if (GlobalConfig.VERBOSE) Utils.eprint("Unhandled SYMTAB found: ", sectionEntryName, entry, "\n"); + } + + _processSection_STRTAB(array_of_bytes, entry, sectionEntryName) { + if (sectionEntryName === ".strtab") this.strtab = new Elf32StringTable(array_of_bytes, entry.offset, entry.size); + else if (sectionEntryName === ".dynstr") this.dynstr = new Elf32StringTable(array_of_bytes, entry.offset, entry.size); + else if (sectionEntryName === ".shstrtab") { + // nothing + } else if (GlobalConfig.VERBOSE) Utils.eprint("Unhandled STRTAB found: ", sectionEntryName, entry, "\n"); + } + + _processSection_RELA(_array_of_bytes, _entry, _sectionEntryName) {} + + _processSection_HASH(_array_of_bytes, _entry, _sectionEntryName) {} + + _processSection_DYNAMIC(array_of_bytes, entry, sectionEntryName) { + if (sectionEntryName === ".dynamic") this.dynamic = new Elf32Dyns(array_of_bytes, entry.offset, entry.size); + else if (GlobalConfig.VERBOSE) Utils.eprint("Unhandled DYNAMIC found: ", sectionEntryName, entry, "\n"); + } + + _processSection_NOTE(_array_of_bytes, _entry, _sectionEntryName) {} + + _processSection_NOBITS(array_of_bytes, entry, sectionEntryName) { + if (sectionEntryName === ".bss") this.nobits = entry; + // Upstream uses `if` here (not elif), so .bss also reaches the verbose branch. + if (sectionEntryName === ".sbss") this.nobitsSmall = entry; + else if (GlobalConfig.VERBOSE) Utils.eprint("Unhandled NOBITS found: ", sectionEntryName, entry, "\n"); + + const smallFileSecType = FileSectionType.fromSmallStr(sectionEntryName); + if (smallFileSecType !== FileSectionType.Invalid) this.smallSections.set(sectionEntryName, entry); + + this.nobitsPerName.set(sectionEntryName, entry); + } + + _processSection_REL(array_of_bytes, entry, sectionEntryName) { + const sectName = sectionEntryName.slice(4); + + if (sectionEntryName.startsWith(".rel")) { + const fileSecType = FileSectionType.fromStr(sectName); + if (fileSecType !== FileSectionType.Invalid) this.rel.set(fileSecType, new Elf32Rels(sectionEntryName, array_of_bytes, entry.offset, entry.size)); + else if (GlobalConfig.VERBOSE) Utils.eprint("Unhandled REL subsection found: ", sectionEntryName, entry, "\n"); + } else if (GlobalConfig.VERBOSE) { + Utils.eprint("Unhandled REL found: ", sectionEntryName, entry, "\n"); + } + + if (sectionEntryName.startsWith(".rel")) this.relPerName.set(sectName, new Elf32Rels(sectionEntryName, array_of_bytes, entry.offset, entry.size)); + else Utils.eprint("Unhandled REL found: ", sectionEntryName, entry, "\n"); + } + + _processSection_DYNSYM(array_of_bytes, entry, sectionEntryName) { + if (sectionEntryName === ".dynsym") this.dynsym = new Elf32Syms(array_of_bytes, entry.offset, entry.size); + else if (GlobalConfig.VERBOSE) Utils.eprint("Unhandled DYNSYM found: ", sectionEntryName, entry, "\n"); + } + + _processSection_MIPS_LIBLIST(_array_of_bytes, _entry, _sectionEntryName) {} + _processSection_MIPS_MSYM(_array_of_bytes, _entry, _sectionEntryName) {} + _processSection_MIPS_CONFLICT(_array_of_bytes, _entry, _sectionEntryName) {} + _processSection_MIPS_GPTAB(_array_of_bytes, _entry, _sectionEntryName) {} + _processSection_MIPS_DEBUG(_array_of_bytes, _entry, _sectionEntryName) {} + + _processSection_MIPS_REGINFO(array_of_bytes, entry, sectionEntryName) { + if (sectionEntryName === ".reginfo") this.reginfo = Elf32RegInfo.fromBytearray(array_of_bytes, entry.offset); + else if (GlobalConfig.VERBOSE) Utils.eprint("Unhandled MIPS_REGINFO found: ", sectionEntryName, entry, "\n"); + } + + _processSection_MIPS_OPTIONS(_array_of_bytes, _entry, _sectionEntryName) {} + _processSection_MIPS_SYMBOL_LIB(_array_of_bytes, _entry, _sectionEntryName) {} + _processSection_MIPS_ABIFLAGS(_array_of_bytes, _entry, _sectionEntryName) {} + + static _sectionProcessorCallbacks = new Map([ + [Elf32SectionHeaderType.NULL.value, Elf32File.prototype._processSection_NULL], + [Elf32SectionHeaderType.PROGBITS.value, Elf32File.prototype._processSection_PROGBITS], + [Elf32SectionHeaderType.SYMTAB.value, Elf32File.prototype._processSection_SYMTAB], + [Elf32SectionHeaderType.STRTAB.value, Elf32File.prototype._processSection_STRTAB], + [Elf32SectionHeaderType.HASH.value, Elf32File.prototype._processSection_HASH], + [Elf32SectionHeaderType.DYNAMIC.value, Elf32File.prototype._processSection_DYNAMIC], + [Elf32SectionHeaderType.NOBITS.value, Elf32File.prototype._processSection_NOBITS], + [Elf32SectionHeaderType.REL.value, Elf32File.prototype._processSection_REL], + [Elf32SectionHeaderType.DYNSYM.value, Elf32File.prototype._processSection_DYNSYM], + [Elf32SectionHeaderType.MIPS_LIBLIST.value, Elf32File.prototype._processSection_MIPS_LIBLIST], + [Elf32SectionHeaderType.MIPS_MSYM.value, Elf32File.prototype._processSection_MIPS_MSYM], + [Elf32SectionHeaderType.MIPS_CONFLICT.value, Elf32File.prototype._processSection_MIPS_CONFLICT], + [Elf32SectionHeaderType.MIPS_GPTAB.value, Elf32File.prototype._processSection_MIPS_GPTAB], + [Elf32SectionHeaderType.MIPS_DEBUG.value, Elf32File.prototype._processSection_MIPS_DEBUG], + [Elf32SectionHeaderType.MIPS_REGINFO.value, Elf32File.prototype._processSection_MIPS_REGINFO], + [Elf32SectionHeaderType.MIPS_OPTIONS.value, Elf32File.prototype._processSection_MIPS_OPTIONS], + [Elf32SectionHeaderType.MIPS_SYMBOL_LIB.value, Elf32File.prototype._processSection_MIPS_SYMBOL_LIB], + [Elf32SectionHeaderType.MIPS_ABIFLAGS.value, Elf32File.prototype._processSection_MIPS_ABIFLAGS], + ]); + + readelf_fileHeader() { + out("ELF Header:"); + out(" Magic: ", ""); + for (const magic of this.header.ident.ident) out(` ${hexU(magic, 2)}`, ""); + out("\n ", ""); + for (const magic of this.header.ident.ident) { + let character = String.fromCharCode(magic); + if (!isPrintableLatin1(magic)) character = hexU(magic, 2); + out(` ${rjust(character, 2)}`, ""); + } + out(); + + out(` ${ljust("Class:", 34)} ${this.header.ident.getFileClass().name.replace("CLASS", "ELF")}`); + + out(` ${ljust("Data:", 34)} `, ""); + const dataEncoding = this.header.ident.getDataEncoding(); + if (dataEncoding === Elf32HeaderIdentifier.DataEncoding.DATANONE) out("Invalid data encoding"); + else if (dataEncoding === Elf32HeaderIdentifier.DataEncoding.DATA2LSB) out("2's complement, little endian"); + else if (dataEncoding === Elf32HeaderIdentifier.DataEncoding.DATA2MSB) out("2's complement, big endian"); + else out(dataEncoding.name); + + out(` ${ljust("Version:", 34)} `, ""); + const version = this.header.ident.getVersion(); + out(`${version}` + (version === 1 ? " (current)" : "")); + + out(` ${ljust("OS/ABI:", 34)} `, ""); + const osAbi = this.header.ident.getOsAbi(); + if (osAbi === Elf32HeaderIdentifier.OsAbi.NONE) out("UNIX - System V"); + else if (osAbi === Elf32HeaderIdentifier.OsAbi.IRIX) out("SGI Irix"); + else out(osAbi.name); + + out(` ${ljust("ABI Version:", 34)} ${this.header.ident.getAbiVersion()}`); + + out(` ${ljust("Type:", 34)} `, ""); + const filetype = Elf32ObjectFileType.fromValueOrNull(this.header.type); + if (filetype !== null) { + out(`${filetype.name}`, ""); + if (filetype === Elf32ObjectFileType.NONE) out(" (No file type)"); + else if (filetype === Elf32ObjectFileType.REL) out(" (Relocatable file)"); + else if (filetype === Elf32ObjectFileType.EXEC) out(" (Executable file)"); + else if (filetype === Elf32ObjectFileType.DYN) out(" (Shared object file)"); + else if (filetype === Elf32ObjectFileType.CORE) out(" (Core file)"); + else out(" (Unknown)"); + } else { + out(`0x${hexU(this.header.type, 4)}`, ""); + if (this.header.type >= 0xfe00 && this.header.type <= 0xfeff) out(" (OS-specific)"); + if (this.header.type >= 0xff00 && this.header.type <= 0xffff) out(" (Processor-specific)"); + else out(" (Unknown)"); + } + + out(` ${ljust("Machine:", 34)} ${this.header.machine}`); + out(` ${ljust("Version:", 34)} 0x${hexU(this.header.version)}`); + out(` ${ljust("Entry point address:", 34)} 0x${hexU(this.header.entry, 8)}`); + out(` ${ljust("Start of program headers:", 34)} 0x${hexU(this.header.phoff)} (bytes into file)`); + out(` ${ljust("Start of section headers:", 34)} 0x${hexU(this.header.shoff)} (bytes into file)`); + + out(` ${ljust("Flags:", 34)} 0x${hexU(this.header.flags)}`, ""); + for (const flag of this.elfFlags) { + let printableFlagName = flag.name.toLowerCase().replaceAll("arch_", "mips"); + if (printableFlagName.length > 0 && printableFlagName[0] === "_") printableFlagName = printableFlagName.slice(1); + out(`, ${printableFlagName}`, ""); + } + if (this.unknownElfFlags !== 0) out(`, 0x${hexU(this.unknownElfFlags, 8)}`, ""); + out(); + + out(` ${ljust("Size of this header:", 34)} 0x${hexU(this.header.ehsize)} (bytes)`); + out(` ${ljust("Size of program headers:", 34)} 0x${hexU(this.header.phentsize)} (bytes)`); + out(` ${ljust("Number of program headers:", 34)} ${this.header.phnum}`); + out(` ${ljust("Size of section headers:", 34)} 0x${hexU(this.header.shentsize)} (bytes)`); + out(` ${ljust("Number of section headers:", 34)} ${this.header.shnum}`); + out(` ${ljust("Section header string table index:", 34)} ${this.header.shstrndx}`); + out(); + } + + readelf_sectionHeaders() { + const flagsKeys = new Map([ + [Elf32SectionHeaderFlag.WRITE, "W"], + [Elf32SectionHeaderFlag.ALLOC, "A"], + [Elf32SectionHeaderFlag.EXECINSTR, "X"], + [Elf32SectionHeaderFlag.MERGE, "M"], + [Elf32SectionHeaderFlag.STRINGS, "S"], + [Elf32SectionHeaderFlag.INFO_LINK, "I"], + [Elf32SectionHeaderFlag.LINK_ORDER, "L"], + [Elf32SectionHeaderFlag.OS_NONCONFORMING, "O"], + [Elf32SectionHeaderFlag.GROUP, "G"], + [Elf32SectionHeaderFlag.TLS, "T"], + [Elf32SectionHeaderFlag.COMPRESSED, "C"], + [Elf32SectionHeaderFlag.EXCLUDE, "E"], + ]); + + out(`There are ${this.sectionHeaders.length} section headers, starting at offset 0x${hexU(this.sectionHeaders.shoff)}:`); + out(); + out("Section Headers:"); + + let largestSectionHeaderName = 17; + for (const header of this.sectionHeaders) { + const name = this.shstrtab.get(header.name); + largestSectionHeaderName = Math.max(largestSectionHeaderName, name.length); + } + + out(` [${rjust("Nr", 2)}] ${ljust("Name", largestSectionHeaderName)} ${ljust("Type", 15)} ${ljust("Addr", 8)} ${ljust("Off", 6)} ${ljust("Size", 6)} ES Flg Lk Inf Al`); + + let i = 0; + for (const header of this.sectionHeaders) { + const name = this.shstrtab.get(header.name); + + const headerType = Elf32SectionHeaderType.fromValue(header.type); + let headerTypeStr = `<0x${hexU(header.type)}>`; + if (headerType !== null) headerTypeStr = headerType.name; + + let [flags, unknownFlags] = Elf32SectionHeaderFlag.parseFlags(header.flags); + let flagsStr = ""; + for (const flag of flags) flagsStr += flagsKeys.get(flag); + + if ((unknownFlags & 0x0ff00000) >>> 0) flagsStr += "o"; + unknownFlags = (unknownFlags & ~0x0ff00000) >>> 0; + if ((unknownFlags & 0xf0000000) >>> 0) flagsStr += "p"; + unknownFlags = (unknownFlags & ~0xf0000000) >>> 0; + + out( + ` [${rjust(i, 2)}] ${ljust(name, largestSectionHeaderName)} ${ljust(headerTypeStr, 15)} ${hexU(header.addr, 8)} ${hexU(header.offset, 6)} ${hexU(header.size, 6)} ${hexU(header.entsize, 2)} ${rjust(flagsStr, 3)} ${spaceSignHex(header.link, 2)} ${spaceSignHex(header.info, 3)} ${rjust(hexU(header.addralign), 2)}`, + ); + if (unknownFlags) out(`Warning unknown flags: 0x${hexU(unknownFlags)}`); + i++; + } + + out("Key to Flags:"); + out(" W (write), A (alloc), X (execute), M (merge), S (strings), I (info),"); + out(" L (link order), O (extra OS processing required), G (group), T (TLS),"); + out(" C (compressed), x (unknown), o (OS specific), E (exclude),"); + out(" D (mbind), p (processor specific)"); + out(); + } + + _readelf_symbol_table(symbolTable, stringTable) { + let symbolTableName = ""; + for (const header of this.sectionHeaders) { + if (header.offset === symbolTable.offset) symbolTableName = this.shstrtab.get(header.name); + } + + out(`Symbol table '${symbolTableName}' contains ${symbolTable.symbols.length} entries:`); + out(` ${rjust("Num", 5)}: ${rjust("Value", 8)} ${rjust("Size", 5)} ${ljust("Type", 7)} ${ljust("Bind", 6)} ${ljust("Vis", 9)} ${rjust("Ndx", 15)} Name`); + + symbolTable.symbols.forEach((sym, i) => { + const entryType = enumCall(Elf32SymbolTableType, sym.stType); + + let bind = String(sym.stBind); + const stBind = Elf32SymbolTableBinding.fromValue(sym.stBind); + if (stBind !== null) bind = stBind.name; + + let visibility = `0x${hexU(sym.other)}`; + const stOther = Elf32SymbolVisibility.fromValue(sym.other); + if (stOther !== null) visibility = stOther.name; + + let ndx = `0x${hexU(sym.shndx)}`; + const shndx = Elf32SectionHeaderNumber.fromValue(sym.shndx); + if (shndx !== null) { + ndx = shndx.name; + } else if (entryType === Elf32SymbolTableType.OBJECT || entryType === Elf32SymbolTableType.FUNC) { + // spimdisasm-extension: instead of a number we use the section name if available + const section = this.sectionHeaders.get(sym.shndx); + if (section !== null) ndx = this.shstrtab.get(section.name); + } + + let symName = ""; + if (stringTable !== null) symName = stringTable.get(sym.name); + if (symName === "") { + if (entryType === Elf32SymbolTableType.SECTION) { + const section = this.sectionHeaders.get(sym.shndx); + if (section !== null) symName = this.shstrtab.get(section.name); + } + } + + out(` ${rjust(i, 5)}: ${hexU(sym.value, 8)} ${rjust(hexU(sym.size), 5)} ${ljust(entryType.name, 7)} ${ljust(bind, 6)} ${ljust(visibility, 9)} ${rjust(ndx, 15)} ${symName}`); + }); + + out(); + } + + readelf_syms() { + if (this.symtab === null) return; + this._readelf_symbol_table(this.symtab, this.strtab); + } + + readelf_dyn_syms() { + if (this.dynsym === null) return; + this._readelf_symbol_table(this.dynsym, this.dynstr); + } + + readelf_relocs() { + for (const relSection of this.rel.values()) { + out(`Relocation section '${relSection.sectionName}' at offset 0x${hexU(relSection.offset)} contains ${relSection.relocations.length} entries:`); + out(` ${ljust("Offset", 8)} ${ljust("Info", 8)} ${ljust("Type", 12)} ${rjust("Sym.Value", 9)} Sym.Name`); + let sym; + for (const rel of relSection.relocations) { + let relType = String(rel.rType); + const rType = RelocType.fromValue(rel.rType); + if (rType !== null) relType = rType.name; + + let symValue = ""; + let symName = ""; + if (this.symtab !== null) { + sym = this.symtab.get(rel.rSym); + symValue = hexU(sym.value, 8); + if (this.strtab !== null) symName = this.strtab.get(sym.name); + } + if (symName === "") { + if (sym === undefined) throw Object.assign(new Error("cannot access local variable 'sym' where it is not associated with a value"), { name: "UnboundLocalError" }); + const section = this.sectionHeaders.get(sym.shndx); + if (section !== null) symName = this.shstrtab.get(section.name); + } + + out(` ${hexU(rel.offset, 8)} ${hexU(rel.info, 8)} ${ljust(relType, 12)} ${rjust(symValue, 9)} ${symName}`); + } + out(); + } + out(); + } + + readelf_displayGot() { + const accessStrOf = (access) => (access < 0 ? `-0x${hexU(-access)}` : `0x${hexU(access)}`); + + out("Primary GOT:"); + let gpValue = 0x7ff0; + let entryAddress = 0; + if (this.dynamic !== null && this.dynamic.pltGot !== null) { + gpValue = this.dynamic.getGpValue() || 0; + if (GlobalConfig.GP_VALUE !== null) gpValue = GlobalConfig.GP_VALUE; + entryAddress = this.dynamic.pltGot; + out(` Canonical gp value: ${hexU(gpValue)}`); + out(); + } + + if (this.got !== null) { + out(" Reserved entries:"); + out(` Address ${rjust("Access", 12)} Initial Purpose`); + if (this.got.localsTable.length === 0) throw Object.assign(new Error("list index out of range"), { name: "IndexError" }); + out(` ${rjust(hexU(entryAddress), 8)} ${ljust(accessStrOf(entryAddress - gpValue), 5)}($gp) ${hexU(this.got.localsTable[0], 8)} Lazy resolver`); + entryAddress += 4; + out(); + + out(" Local entries:"); + out(` Address ${rjust("Access", 12)} Initial`); + for (const x of this.got.localsTable.slice(1)) { + out(` ${rjust(hexU(entryAddress), 8)} ${ljust(accessStrOf(entryAddress - gpValue), 5)}($gp) ${hexU(x, 8)}`); + entryAddress += 4; + } + out(); + + out(" Global entries:"); + out(` ${rjust("Address", 8)} ${rjust("Access", 12)} Initial Sym.Val. Type ${ljust("Ndx", 12)} Name`); + for (const gotEntry of this.got.globalsTable) { + const entryType = enumCall(Elf32SymbolTableType, gotEntry.symEntry.stType); + let ndx = `0x${hexU(gotEntry.symEntry.shndx)}`; + const shndx = Elf32SectionHeaderNumber.fromValue(gotEntry.symEntry.shndx); + if (shndx !== null) ndx = shndx.name; + let symName = ""; + if (this.dynstr !== null) symName = this.dynstr.get(gotEntry.symEntry.name); + out(` ${rjust(hexU(entryAddress), 8)} ${ljust(accessStrOf(entryAddress - gpValue), 5)}($gp) ${hexU(gotEntry.getAddress(), 8)} ${hexU(gotEntry.symEntry.value, 8)} ${ljust(entryType.name, 7)} ${ljust(ndx, 12)} ${symName}`); + entryAddress += 4; + } + out(); + } + out(); + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32GlobalOffsetTable.js b/packages/romdev-spimdisasm/src/elf32/Elf32GlobalOffsetTable.js new file mode 100644 index 00000000..36786919 --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32GlobalOffsetTable.js @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32GlobalOffsetTable.py + +import { Elf32SectionHeaderNumber } from "./Elf32Constants.js"; +import { unpackFrom, endianFmt } from "./_util.js"; + +export class GotEntry { + constructor(symEntry, initial = null) { + this.symEntry = symEntry; + this.initial = initial; + } + + getAddress() { + if (this.initial !== null) return this.initial; + return this.symEntry.value; + } +} + +export class Elf32GlobalOffsetTable { + constructor(array_of_bytes, offset, rawSize) { + this.offset = offset; + this.rawSize = rawSize; + + this.entries = unpackFrom(endianFmt() + `${Math.floor(rawSize / 4)}I`, array_of_bytes, offset); + + this.localsTable = []; + this.globalsTable = []; + } + + /** Python __getitem__ */ + get(key) { + let idx = key; + if (idx < 0) idx += this.entries.length; + if (idx < 0 || idx >= this.entries.length) throw Object.assign(new Error("list index out of range"), { name: "IndexError" }); + return this.entries[idx]; + } + + getItem(key) { + return this.get(key); + } + + get length() { + return this.entries.length; + } + + initTables(dynamic, dynsym) { + if (dynamic.gotSym === null || dynamic.localGotNo === null) return; + + for (let i = 0; i < dynamic.localGotNo; i++) this.localsTable.push(this.get(i)); + + for (let i = dynamic.gotSym; i < dynsym.length; i++) { + const symEntry = dynsym.get(i); + const gotEntry = new GotEntry(symEntry); + + if (symEntry.shndx === Elf32SectionHeaderNumber.UNDEF.value || symEntry.shndx === Elf32SectionHeaderNumber.COMMON.value) { + const gotIndex = dynamic.localGotNo + (i - dynamic.gotSym); + gotEntry.initial = this.get(gotIndex); + } + + this.globalsTable.push(gotEntry); + } + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32Header.js b/packages/romdev-spimdisasm/src/elf32/Elf32Header.js new file mode 100644 index 00000000..bc82c796 --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32Header.js @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32Header.py + +import { Elf32HeaderIdentifier } from "./Elf32Constants.js"; +import { unpackFrom, enumCall, dataclassRepr } from "./_util.js"; + +export class Elf32Identifier { + /** ident: 16 bytes as a list of ints */ + constructor(ident) { + this.ident = ident; + } + + checkMagic() { + if (this.ident[0] !== 0x7f) return false; + if (this.ident[1] !== 0x45) return false; // 'E' + if (this.ident[2] !== 0x4c) return false; // 'L' + if (this.ident[3] !== 0x46) return false; // 'F' + return true; + } + + getFileClass() { + return enumCall(Elf32HeaderIdentifier.FileClass, this.ident[4]); + } + + getDataEncoding() { + return enumCall(Elf32HeaderIdentifier.DataEncoding, this.ident[5]); + } + + getVersion() { + return this.ident[6]; + } + + getOsAbi() { + return enumCall(Elf32HeaderIdentifier.OsAbi, this.ident[7]); + } + + getAbiVersion() { + return this.ident[8]; + } + + // should always return 0 + getPad() { + return this.ident[9]; + } + + static fromBytearray(array_of_bytes, offset = 0) { + const ident = unpackFrom(">16B", array_of_bytes, 0 + offset); + const identifier = new Elf32Identifier(ident); + + if (!identifier.checkMagic()) throw Object.assign(new Error("Not an ELF file: wrong magic"), { name: "RuntimeError" }); + + if (identifier.getFileClass() !== Elf32HeaderIdentifier.FileClass.CLASS32) { + throw Object.assign(new Error(`Unsupported ELF file class: ${identifier.getFileClass()} (expected CLASS32)`), { name: "RuntimeError" }); + } + + if (identifier.getPad() !== 0) throw new Error("AssertionError"); + + return identifier; + } + + static structSize() { + return 0x10; + } + + __repr__() { + return dataclassRepr("Elf32Identifier", this, ["ident"]); + } + + toString() { + return this.__repr__(); + } +} + +const HEADER_FIELDS = ["ident", "type", "machine", "version", "entry", "phoff", "shoff", "flags", "ehsize", "phentsize", "phnum", "shentsize", "shnum", "shstrndx"]; + +// a.k.a. Ehdr (elf header) +export class Elf32Header { + constructor(ident, type, machine, version, entry, phoff, shoff, flags, ehsize, phentsize, phnum, shentsize, shnum, shstrndx) { + this.ident = ident; + this.type = type; + this.machine = machine; + this.version = version; + this.entry = entry; + this.phoff = phoff; + this.shoff = shoff; + this.flags = flags; + this.ehsize = ehsize; + this.phentsize = phentsize; + this.phnum = phnum; + this.shentsize = shentsize; + this.shnum = shnum; + this.shstrndx = shstrndx; + } + + static fromBytearray(array_of_bytes, offset = 0) { + const identifier = Elf32Identifier.fromBytearray(array_of_bytes, offset); + + const dataEncoding = identifier.getDataEncoding(); + let endianFormat; + if (dataEncoding === Elf32HeaderIdentifier.DataEncoding.DATA2MSB) endianFormat = ">"; + else if (dataEncoding === Elf32HeaderIdentifier.DataEncoding.DATA2LSB) endianFormat = "<"; + else throw Object.assign(new Error(`Unsupported ELF data encoding: ${dataEncoding}`), { name: "RuntimeError" }); + + const unpacked = unpackFrom(endianFormat + "HHIIIIIHHHHHH", array_of_bytes, Elf32Identifier.structSize() + offset); + return new Elf32Header(identifier, ...unpacked); + } + + static structSize() { + return 0x34; + } + + __repr__() { + return dataclassRepr("Elf32Header", this, HEADER_FIELDS); + } + + toString() { + return this.__repr__(); + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32RegInfo.js b/packages/romdev-spimdisasm/src/elf32/Elf32RegInfo.js new file mode 100644 index 00000000..11ec470d --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32RegInfo.js @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32RegInfo.py + +import { unpackFrom, endianFmt, dataclassRepr } from "./_util.js"; + +export class Elf32RegInfo { + /** gprmask: uint32, cprmask: uint32[4], gpValue: int32 */ + constructor(gprmask, cprmask, gpValue) { + this.gprmask = gprmask; + this.cprmask = cprmask; + this.gpValue = gpValue; + } + + static fromBytearray(array_of_bytes, offset = 0) { + const gpr = unpackFrom(endianFmt() + "I", array_of_bytes, 0 + offset)[0]; + const cpr = unpackFrom(endianFmt() + "4I", array_of_bytes, 4 + offset); + const gp = unpackFrom(endianFmt() + "i", array_of_bytes, 0x14 + offset)[0]; + return new Elf32RegInfo(gpr, cpr, gp); + } + + __repr__() { + return dataclassRepr("Elf32RegInfo", this, ["gprmask", "cprmask", "gpValue"]); + } + + toString() { + return this.__repr__(); + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32Rels.js b/packages/romdev-spimdisasm/src/elf32/Elf32Rels.js new file mode 100644 index 00000000..c40bbf86 --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32Rels.js @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32Rels.py + +import { unpackFrom, endianFmt, dataclassRepr } from "./_util.js"; + +export class Elf32RelEntry { + constructor(offset, info) { + this.offset = offset; + this.info = info; + } + + get rSym() { + return this.info >>> 8; + } + + get rType() { + return this.info & 0xff; + } + + static fromBytearray(array_of_bytes, offset = 0) { + return new Elf32RelEntry(...unpackFrom(endianFmt() + "II", array_of_bytes, offset)); + } + + __repr__() { + return dataclassRepr("Elf32RelEntry", this, ["offset", "info"]); + } + + toString() { + return this.__repr__(); + } +} + +export class Elf32Rels { + constructor(sectionName, array_of_bytes, offset, rawSize) { + this.sectionName = sectionName; + this.relocations = []; + this.offset = offset; + this.rawSize = rawSize; + + const n = Math.floor(rawSize / 0x08); + for (let i = 0; i < n; i++) this.relocations.push(Elf32RelEntry.fromBytearray(array_of_bytes, offset + i * 0x08)); + } + + [Symbol.iterator]() { + return this.relocations[Symbol.iterator](); + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32SectionHeaders.js b/packages/romdev-spimdisasm/src/elf32/Elf32SectionHeaders.js new file mode 100644 index 00000000..891ec99c --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32SectionHeaders.js @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32SectionHeaders.py +// +// Python `headers[key]` is `headers.get(key)` here (same None cases and the +// same IndexError when key == len(headers)). + +import * as Utils from "../common/Utils.js"; +import { Elf32SectionHeaderNumber } from "./Elf32Constants.js"; +import { unpackFrom, endianFmt, dataclassRepr } from "./_util.js"; + +const FIELDS = ["name", "type", "flags", "addr", "offset", "size", "link", "info", "addralign", "entsize"]; + +// a.k.a. Shdr (section header) +export class Elf32SectionHeaderEntry { + constructor(name, type, flags, addr, offset, size, link, info, addralign, entsize) { + this.name = name; + this.type = type; + this.flags = flags; + this.addr = addr; + this.offset = offset; + this.size = size; + this.link = link; + this.info = info; + this.addralign = addralign; + this.entsize = entsize; + } + + static fromBytearray(array_of_bytes, offset = 0) { + const unpacked = unpackFrom(endianFmt() + "10I", array_of_bytes, offset); + return new Elf32SectionHeaderEntry(...unpacked); + } + + __repr__() { + return dataclassRepr("Elf32SectionHeaderEntry", this, FIELDS); + } + + toString() { + return this.__repr__(); + } +} + +export class Elf32SectionHeaders { + constructor(array_of_bytes, shoff, shnum) { + this.sections = []; + this.shoff = shoff; + this.shnum = shnum; + + this.mipsText = null; + this.mipsData = null; + + for (let i = 0; i < shnum; i++) { + this.sections.push(Elf32SectionHeaderEntry.fromBytearray(array_of_bytes, shoff + i * 0x28)); + } + } + + /** Python __getitem__ */ + get(key) { + if (key === Elf32SectionHeaderNumber.UNDEF.value) return null; + if (key === Elf32SectionHeaderNumber.COMMON.value) { + Utils.eprint("Warning: Elf32SectionHeaderNumber.COMMON not implemented\n"); + return null; + } + if (key === Elf32SectionHeaderNumber.MIPS_ACOMMON.value) { + Utils.eprint("Warning: Elf32SectionHeaderNumber.MIPS_ACOMMON not implemented\n"); + return null; + } + if (key === Elf32SectionHeaderNumber.MIPS_TEXT.value) return this.mipsText; + if (key === Elf32SectionHeaderNumber.MIPS_DATA.value) return this.mipsData; + if (key === Elf32SectionHeaderNumber.MIPS_SCOMMON.value) { + Utils.eprint("Warning: Elf32SectionHeaderNumber.MIPS_SCOMMON not implemented\n"); + return null; + } + if (key === Elf32SectionHeaderNumber.MIPS_SUNDEFINED.value) { + Utils.eprint("Warning: Elf32SectionHeaderNumber.MIPS_SUNDEFINED not implemented\n"); + return null; + } + if (key > this.sections.length) return null; + let idx = key; + if (idx < 0) idx += this.sections.length; + if (idx < 0 || idx >= this.sections.length) throw Object.assign(new Error("list index out of range"), { name: "IndexError" }); + return this.sections[idx]; + } + + getItem(key) { + return this.get(key); + } + + [Symbol.iterator]() { + return this.sections[Symbol.iterator](); + } + + get length() { + return this.sections.length; + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32StringTable.js b/packages/romdev-spimdisasm/src/elf32/Elf32StringTable.js new file mode 100644 index 00000000..86958440 --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32StringTable.js @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32StringTable.py +// +// Python `strtab[key]` is `strtab.get(key)` here. + +import { decodeUtf8 } from "./_util.js"; + +const encoder = new TextEncoder(); + +// a.k.a. strtab (string table) +export class Elf32StringTable { + constructor(array_of_bytes, offset, rawsize) { + this.strings = array_of_bytes.slice(offset, offset + rawsize); + this.offset = offset; + this.rawsize = rawsize; + } + + /** Python __getitem__: NUL-terminated UTF-8 string starting at `key`. */ + get(key) { + let i = key; + if (i < 0) i += this.strings.length; + const start = i; + for (;;) { + if (i < 0 || i >= this.strings.length) throw Object.assign(new Error("index out of range"), { name: "IndexError" }); + if (this.strings[i] === 0) break; + i += 1; + } + return decodeUtf8(this.strings.subarray(start, i)); + } + + getItem(key) { + return this.get(key); + } + + *[Symbol.iterator]() { + let i = 0; + while (i < this.rawsize) { + const string = this.get(i); + yield string; + i += encoder.encode(string).length + 1; + } + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/Elf32Syms.js b/packages/romdev-spimdisasm/src/elf32/Elf32Syms.js new file mode 100644 index 00000000..184b6b30 --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/Elf32Syms.js @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/Elf32Syms.py + +import { unpackFrom, endianFmt, dataclassRepr } from "./_util.js"; + +const FIELDS = ["name", "value", "size", "info", "other", "shndx"]; + +// a.k.a. Sym (symbol) +export class Elf32SymEntry { + constructor(name, value, size, info, other, shndx) { + this.name = name; + this.value = value; + this.size = size; + this.info = info; + this.other = other; + this.shndx = shndx; + } + + get stBind() { + return this.info >> 4; + } + + get stType() { + return this.info & 0xf; + } + + static fromBytearray(array_of_bytes, offset = 0) { + return new Elf32SymEntry(...unpackFrom(endianFmt() + "IIIBBH", array_of_bytes, offset)); + } + + static structSize() { + return 0x10; + } + + __repr__() { + return dataclassRepr("Elf32SymEntry", this, FIELDS); + } + + toString() { + return this.__repr__(); + } +} + +export class Elf32Syms { + constructor(array_of_bytes, offset, rawSize) { + this.symbols = []; + this.offset = offset; + this.rawSize = rawSize; + + const n = Math.floor(rawSize / Elf32SymEntry.structSize()); + for (let i = 0; i < n; i++) this.symbols.push(Elf32SymEntry.fromBytearray(array_of_bytes, offset + i * Elf32SymEntry.structSize())); + } + + /** Python __getitem__ */ + get(key) { + let idx = key; + if (idx < 0) idx += this.symbols.length; + if (idx < 0 || idx >= this.symbols.length) throw Object.assign(new Error("list index out of range"), { name: "IndexError" }); + return this.symbols[idx]; + } + + getItem(key) { + return this.get(key); + } + + [Symbol.iterator]() { + return this.symbols[Symbol.iterator](); + } + + get length() { + return this.symbols.length; + } +} diff --git a/packages/romdev-spimdisasm/src/elf32/_util.js b/packages/romdev-spimdisasm/src/elf32/_util.js new file mode 100644 index 00000000..d8e391ca --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/_util.js @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: MIT +// Internal helpers for the elf32 port (struct unpacking, Python enum calls). + +import { GlobalConfig, InputEndian } from "../common/GlobalConfig.js"; +import { ValueError } from "../py/pyutils.js"; + +export class StructError extends Error { + constructor(msg) { + super(msg); + this.name = "struct.error"; + } +} + +/** struct.unpack_from for the codes used by the elf32 modules (B H I i). */ +export function unpackFrom(fmt, bytes, offset = 0) { + let little; + let spec = fmt; + if (spec[0] === "<") little = true; + else if (spec[0] === ">") little = false; + else throw new Error(`unsupported struct format '${fmt}'`); + spec = spec.slice(1); + const codes = []; + for (const m of spec.matchAll(/(\d*)([BHIi])/g)) { + const n = m[1] === "" ? 1 : Number.parseInt(m[1], 10); + for (let i = 0; i < n; i++) codes.push(m[2]); + } + const sizes = { B: 1, H: 2, I: 4, i: 4 }; + const total = codes.reduce((a, c) => a + sizes[c], 0); + if (offset < 0 || offset + total > bytes.length) { + throw new StructError(`unpack_from requires a buffer of at least ${offset + total} bytes for unpacking ${total} bytes at offset ${offset} (actual buffer size is ${bytes.length})`); + } + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const out = []; + let p = offset; + for (const c of codes) { + if (c === "B") out.push(dv.getUint8(p)); + else if (c === "H") out.push(dv.getUint16(p, little)); + else if (c === "I") out.push(dv.getUint32(p, little)); + else out.push(dv.getInt32(p, little)); + p += sizes[c]; + } + return out; +} + +/** GlobalConfig.ENDIAN.toFormatString() */ +export function endianFmt() { + return GlobalConfig.ENDIAN.toFormatString(); +} + +export { InputEndian }; + +/** Python `EnumClass(value)`: member or ValueError. */ +export function enumCall(E, value) { + const m = E.fromValueOrNull(value); + if (m === null) throw new ValueError(`${value} is not a valid ${E.__name}`); + return m; +} + +/** Python `EnumClass.fromValue(value)`: member or null. */ +export function enumFromValue(E, value) { + return E.fromValueOrNull(value); +} + +/** + * Add Python enum aliases (e.g. SYSV = NONE). Aliases resolve to the same + * member object; iteration and `members` keep only canonical members. + */ +export function withAliases(E, aliases) { + const out = Object.create(E); + for (const [alias, target] of Object.entries(aliases)) { + Object.defineProperty(out, alias, { value: E[target], enumerable: true }); + } + return Object.freeze(out); +} + +/** Python repr of an Enum member: */ +export function enumRepr(m) { + return `<${m.__enumName}.${m.name}: ${m.value}>`; +} + +/** Python `bytes.decode()` (strict UTF-8). */ +const utf8 = new TextDecoder("utf-8", { fatal: true }); +export function decodeUtf8(bytes) { + try { + return utf8.decode(bytes); + } catch { + const e = new Error("UnicodeDecodeError: 'utf-8' codec can't decode bytes"); + e.name = "UnicodeDecodeError"; + throw e; + } +} + +/** Python str(list_of_ints) / repr of a dataclass field value. */ +export function pyReprValue(v) { + if (v === null || v === undefined) return "None"; + if (Array.isArray(v)) return `[${v.map(pyReprValue).join(", ")}]`; + if (typeof v === "string") return `'${v}'`; + if (v === true) return "True"; + if (v === false) return "False"; + if (typeof v === "object" && typeof v.__repr__ === "function") return v.__repr__(); + return String(v); +} + +/** dataclass-style repr: Cls(a=1, b=2) */ +export function dataclassRepr(name, obj, fields) { + return `${name}(${fields.map((f) => `${f}=${pyReprValue(obj[f])}`).join(", ")})`; +} diff --git a/packages/romdev-spimdisasm/src/elf32/index.js b/packages/romdev-spimdisasm/src/elf32/index.js new file mode 100644 index 00000000..a4bc3290 --- /dev/null +++ b/packages/romdev-spimdisasm/src/elf32/index.js @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/elf32/__init__.py + +import * as Elf32Constants from "./Elf32Constants.js"; + +// Python exposes the submodule too (`from spimdisasm.elf32 import Elf32Constants`). +export { Elf32Constants }; + +export { + Elf32HeaderIdentifier, + Elf32ObjectFileType, + Elf32HeaderFlag, + Elf32SectionHeaderType, + Elf32SectionHeaderFlag, + Elf32SymbolTableType, + Elf32SymbolTableBinding, + Elf32SymbolVisibility, + Elf32SectionHeaderNumber, + Elf32DynamicTable, +} from "./Elf32Constants.js"; +export { Elf32Dyns, Elf32DynEntry } from "./Elf32Dyns.js"; +export { Elf32GlobalOffsetTable } from "./Elf32GlobalOffsetTable.js"; +export { Elf32Header } from "./Elf32Header.js"; +export { Elf32RegInfo } from "./Elf32RegInfo.js"; +export { Elf32SectionHeaders, Elf32SectionHeaderEntry } from "./Elf32SectionHeaders.js"; +export { Elf32StringTable } from "./Elf32StringTable.js"; +export { Elf32Syms, Elf32SymEntry } from "./Elf32Syms.js"; +export { Elf32Rels, Elf32RelEntry } from "./Elf32Rels.js"; + +export { Elf32File } from "./Elf32File.js"; + +// To avoid breaking backwards compatibility +export { RelocType as Elf32Relocs } from "../common/Relocation.js"; diff --git a/packages/romdev-spimdisasm/src/index.js b/packages/romdev-spimdisasm/src/index.js new file mode 100644 index 00000000..da7e4594 --- /dev/null +++ b/packages/romdev-spimdisasm/src/index.js @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: MIT +// romdev-spimdisasm: JavaScript port of spimdisasm (Decompollaborate, MIT). +// +// Mirrors the Python package layout: `common`, `mips`, `elf32` namespaces with +// the same class/function/attribute names. Select the upstream release to +// reproduce with configureVersion() before building any Context/section. + +import * as common from "./common/index.js"; +import * as mips from "./mips/index.js"; +import * as elf32 from "./elf32/index.js"; +import { setVersion as setVersionInternal, versionString, versionInfo, SUPPORTED_VERSIONS, RABBITIZER_VERSION_FOR, DEFAULT_VERSION } from "./version.js"; +import { rabbitizer, getRabbitizer, setRabbitizer, hasRabbitizer } from "./rabbitizer.js"; + +export { common, mips, elf32 }; +export { SUPPORTED_VERSIONS, RABBITIZER_VERSION_FOR, DEFAULT_VERSION, rabbitizer, setRabbitizer, getRabbitizer, hasRabbitizer }; + +export const __author__ = "Decompollaborate"; + +/** Live binding: the configured spimdisasm version string, e.g. "1.42.4". */ +export let __version__ = versionString(); +/** Live binding: the configured spimdisasm version as [major, minor, patch]. */ +export let __version_info__ = versionInfo(); + +/** + * Select which upstream spimdisasm release to reproduce ("1.42.4", "1.39.3", + * "1.35.0"). Resets GlobalConfig and the compiler properties to that release's + * defaults, so call it before configuring anything else. Also asks the loaded + * rabbitizer module to switch to the paired rabbitizer release when it + * supports that. + */ +export function configureVersion(version) { + setVersionInternal(version); + __version__ = versionString(); + __version_info__ = versionInfo(); + + return { spimdisasm: __version__, rabbitizer: RABBITIZER_VERSION_FOR[__version__] }; +} + +// Alias of configureVersion (name the splat port probes for). +export { configureVersion as setVersion }; + +export function getVersion() { + return versionString(); +} diff --git a/packages/romdev-spimdisasm/src/mips/FilesHandlers.js b/packages/romdev-spimdisasm/src/mips/FilesHandlers.js new file mode 100644 index 00000000..152c6a0d --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/FilesHandlers.js @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/FilesHandlers.py + +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +import { rabbitizer } from "../rabbitizer.js"; +import { GlobalConfig } from "../common/GlobalConfig.js"; +import { FileSectionType } from "../common/FileSectionType.js"; +import * as Utils from "../common/Utils.js"; +import { hexU } from "../py/pyutils.js"; +import { SectionText } from "./sections/MipsSectionText.js"; +import { SectionData } from "./sections/MipsSectionData.js"; +import { SectionRodata } from "./sections/MipsSectionRodata.js"; +import { SectionBss } from "./sections/MipsSectionBss.js"; +import { SectionRelocZ64 } from "./sections/MipsSectionRelocZ64.js"; +import { FunctionRodataEntry } from "./FuncRodataEntry.js"; + +function byteLength(b) { + return b.length ?? b.byteLength; +} + +export function createSectionFromSplitEntry(splitEntry, array_of_bytes, context, vromStart = 0) { + const offsetStart = splitEntry.offset; + let offsetEnd = splitEntry.nextOffset; + + if (offsetEnd === 0xffffff) offsetEnd = byteLength(array_of_bytes); + + if (offsetStart >= 0 && offsetEnd >= 0) Utils.printVerbose(`Parsing offset range [${hexU(offsetStart, 2)}, ${hexU(offsetEnd, 2)}]`); + else if (offsetEnd >= 0) Utils.printVerbose(`Parsing until offset 0x${hexU(offsetEnd, 2)}`); + else if (offsetStart >= 0) Utils.printVerbose(`Parsing since offset 0x${hexU(offsetStart, 2)}`); + + const sectionStart = vromStart + offsetStart; + const sectionEnd = vromStart + offsetEnd; + + Utils.printVerbose(`Using VRAM ${hexU(splitEntry.vram, 8)}`); + const vram = splitEntry.vram; + + let f; + if (splitEntry.section === FileSectionType.Text) { + f = new SectionText(context, sectionStart, sectionEnd, vram, splitEntry.fileName, array_of_bytes, 0, null); + if (splitEntry.isRsp) f.instrCat = rabbitizer.InstrCategory.RSP; + } else if (splitEntry.section === FileSectionType.Data) { + f = new SectionData(context, sectionStart, sectionEnd, vram, splitEntry.fileName, array_of_bytes, 0, null); + } else if (splitEntry.section === FileSectionType.Rodata) { + f = new SectionRodata(context, sectionStart, sectionEnd, vram, splitEntry.fileName, array_of_bytes, 0, null); + } else if (splitEntry.section === FileSectionType.Bss) { + const bssVramEnd = splitEntry.vram + offsetEnd - offsetStart; + f = new SectionBss(context, sectionStart, sectionEnd, splitEntry.vram, bssVramEnd, splitEntry.fileName, 0, null); + } else if (splitEntry.section === FileSectionType.Reloc) { + f = new SectionRelocZ64(context, sectionStart, sectionEnd, vram, splitEntry.fileName, array_of_bytes, 0, null); + } else { + Utils.eprint("Error! Section not set!"); + throw new Utils.SystemExit(-1); + } + + f.isHandwritten = splitEntry.isHandwritten; + + return f; +} + +export function writeSection(p, fileSection) { + mkdirSync(path.dirname(String(p)), { recursive: true }); + fileSection.saveToFile(String(p)); + return p; +} + +/** @deprecated Use the static methods from FunctionRodataEntry instead */ +export function getRdataAndLateRodataForFunctionFromSection(func, rodataSection) { + const entry = FunctionRodataEntry.getEntryForFuncFromSection(func, rodataSection); + let lateRodataSize = 0; + for (const rodataSym of entry.lateRodataSyms) lateRodataSize += rodataSym.sizew; + return [entry.rodataSyms, entry.lateRodataSyms, lateRodataSize]; +} + +/** @deprecated Use the static methods from FunctionRodataEntry instead */ +export function getRdataAndLateRodataForFunction(func, rodataFileList) { + const entry = FunctionRodataEntry.getEntryForFuncFromPossibleRodataSections(func, rodataFileList); + let lateRodataSize = 0; + for (const rodataSym of entry.lateRodataSyms) lateRodataSize += rodataSym.sizew; + return [entry.rodataSyms, entry.lateRodataSyms, lateRodataSize]; +} + +/** @deprecated Use the static methods from FunctionRodataEntry instead */ +export function writeFunctionRodataToFile(f, func, rdataList, lateRodataList, _lateRodataSize = 0) { + const entry = new FunctionRodataEntry(func, rdataList, lateRodataList); + entry.writeToFile(f, false); +} + +function writeTextFile(p, producer) { + const parts = []; + producer({ write: (s) => parts.push(s) }); + writeFileSync(p, parts.join(""), "utf8"); +} + +/** @deprecated Use the static methods from FunctionRodataEntry instead */ +export function writeSplitedFunction(p, func, rodataFileList) { + mkdirSync(String(p), { recursive: true }); + const entry = FunctionRodataEntry.getEntryForFuncFromPossibleRodataSections(func, rodataFileList); + const funcPath = path.join(String(p), func.getName() + ".s"); + writeTextFile(funcPath, (f) => entry.writeToFile(f, true)); +} + +export function writeOtherRodata(p, rodataFileList) { + for (const rodataSection of rodataFileList) { + if (!(rodataSection instanceof SectionRodata)) throw new Error("AssertionError"); + + const rodataPath = path.join(String(p), rodataSection.name); + mkdirSync(rodataPath, { recursive: true }); + + for (const rodataSym of rodataSection.symbolList) { + if (rodataSym.shouldMigrate()) continue; + + const rodataSymbolPath = path.join(rodataPath, rodataSym.getName() + ".s"); + Utils.printVerbose(`Writing unmigrated rodata ${rodataSymbolPath}`); + + writeTextFile(rodataSymbolPath, (f) => { + f.write(".section .rodata" + GlobalConfig.LINE_ENDS); + f.write(rodataSym.disassemble(true)); + }); + } + } +} + +/** processedSegments: Map */ +export function writeMigratedFunctionsList(processedSegments, functionMigrationPath, name) { + const funcAndRodataOrderPath = path.join(String(functionMigrationPath), `${name}_migrated_functions.txt`); + + const rodataSymbols = []; + for (const section of processedSegments.get(FileSectionType.Rodata) ?? []) { + for (const sym of section.symbolList) rodataSymbols.push([sym, null]); + } + const rodataSymbolsVrams = new Set(rodataSymbols.map(([sym]) => sym.vram)); + + const funcs = []; + for (const section of processedSegments.get(FileSectionType.Text) ?? []) { + for (const func of section.symbolList) { + funcs.push(func); + + const referencedRodata = new Set(); + for (const v of func.instrAnalyzer.referencedVrams) if (rodataSymbolsVrams.has(v)) referencedRodata.add(v); + for (let i = 0; i < rodataSymbols.length; i++) { + if (referencedRodata.size === 0) break; + + const [rodataSym, funcReferencingThisSym] = rodataSymbols[i]; + + if (!referencedRodata.has(rodataSym.vram)) continue; + + referencedRodata.delete(rodataSym.vram); + + if (funcReferencingThisSym !== null) continue; + + rodataSymbols[i] = [rodataSym, func]; + } + } + } + + const resultingList = []; + const alreadyAddedFuncs = new Set(); + + let lastFunc = null; + for (const [rodataSym, funcReferencingThisSym] of rodataSymbols) { + if (funcReferencingThisSym === null) { + resultingList.push(rodataSym); + } else if (!alreadyAddedFuncs.has(funcReferencingThisSym)) { + alreadyAddedFuncs.add(funcReferencingThisSym); + lastFunc = funcReferencingThisSym; + + for (const func of funcs) { + if (func.vram >= funcReferencingThisSym.vram) break; + if (alreadyAddedFuncs.has(func)) continue; + + alreadyAddedFuncs.add(func); + resultingList.push(func); + } + resultingList.push(funcReferencingThisSym); + } + } + + if (lastFunc === null) { + resultingList.push(...funcs); + } else { + for (const func of funcs) { + if (func.vram <= lastFunc.vram) continue; + resultingList.push(func); + } + } + + writeFileSync(funcAndRodataOrderPath, resultingList.map((sym) => sym.getName() + "\n").join(""), "utf8"); +} diff --git a/packages/romdev-spimdisasm/src/mips/FuncRodataEntry.js b/packages/romdev-spimdisasm/src/mips/FuncRodataEntry.js new file mode 100644 index 00000000..6f426f7f --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/FuncRodataEntry.js @@ -0,0 +1,242 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/FuncRodataEntry.py + +import { GlobalConfig } from "../common/GlobalConfig.js"; +import { SectionRodata } from "./sections/MipsSectionRodata.js"; + +function assert(cond, msg = "") { + if (!cond) throw new Error(`AssertionError${msg !== "" ? ": " + msg : ""}`); +} + +/** + * Class to facilitate rodata migration. + * + * Dataclass fields (positional, same order as Python): + * (function=None, rodataSyms=[], lateRodataSyms=[], sectionText=".text", sectionRodata=".rodata", sectionLateRodata=".late_rodata") + */ +export class FunctionRodataEntry { + constructor(func = null, rodataSyms = null, lateRodataSyms = null, sectionText = ".text", sectionRodata = ".rodata", sectionLateRodata = ".late_rodata") { + this.function = func ?? null; + this.rodataSyms = rodataSyms ?? []; + this.lateRodataSyms = lateRodataSyms ?? []; + this.sectionText = sectionText; + this.sectionRodata = sectionRodata; + this.sectionLateRodata = sectionLateRodata; + } + + hasRodataSyms() { + return this.rodataSyms.length > 0 || this.lateRodataSyms.length > 0; + } + + *iterRodataSyms() { + yield* this.rodataSyms; + yield* this.lateRodataSyms; + } + + /** f: object with a write(str) method */ + writeToFile(f, writeFunction = true) { + // Disassemble the function first without writing it, since it may affect other symbols. + let disassembledFunction = null; + if (this.function !== null) disassembledFunction = this.function.disassemble(this.hasRodataSyms(), true, true); + + if (this.rodataSyms.length > 0) { + // Write the rdata + f.write(`.section ${this.sectionRodata}${GlobalConfig.LINE_ENDS}`); + for (const sym of this.rodataSyms) { + f.write(sym.disassemble(true, true, true)); + f.write(GlobalConfig.LINE_ENDS); + } + } + + if (this.lateRodataSyms.length > 0) { + assert(this.function !== null); + // Write the late_rodata + f.write(`.section ${this.sectionLateRodata}${GlobalConfig.LINE_ENDS}`); + + let lateRodataSize = 0; + for (const sym of this.lateRodataSyms) lateRodataSize += sym.sizew; + + if (lateRodataSize / this.function.instructions.length > 1 / 3) { + let align = 4; + const firstLateRodataVram = this.lateRodataSyms[0].vram; + if (firstLateRodataVram !== null && firstLateRodataVram % 8 === 0) align = 8; + f.write(`.late_rodata_alignment ${align}${GlobalConfig.LINE_ENDS}`); + } + for (const sym of this.lateRodataSyms) { + f.write(sym.disassemble(true, true, true)); + f.write(GlobalConfig.LINE_ENDS); + } + } + + if (disassembledFunction !== null) { + if (this.rodataSyms.length > 0 || this.lateRodataSyms.length > 0) f.write(`${GlobalConfig.LINE_ENDS}.section ${this.sectionText}${GlobalConfig.LINE_ENDS}`); + + if (writeFunction) { + // Write the function itself + f.write(disassembledFunction); + } + } + } + + getName() { + assert(this.function !== null || this.hasRodataSyms()); + + if (this.function !== null) return this.function.getName(); + + const rodataSymsLen = this.rodataSyms.length; + if (rodataSymsLen > 0) { + assert(rodataSymsLen === 1, String(rodataSymsLen)); + return this.rodataSyms[0].getName(); + } + + const lateRodataSyms = this.lateRodataSyms.length; + assert(lateRodataSyms === 1, String(lateRodataSyms)); + return this.lateRodataSyms[0].getName(); + } + + static _shouldMigrateRodataSymbolToFunction(rodataSym, intersection, funcName, already_migrated_syms) { + if (already_migrated_syms.has(rodataSym.vram)) return false; + + const functionOwner = rodataSym.contextSym.functionOwnerForMigration; + if (functionOwner !== null) { + // If a function owner was specified for this symbol then it is only + // allowed to be migrated to that function and none other + return functionOwner === funcName; + } + + if (!intersection.has(rodataSym.vram)) return false; + + if (!rodataSym.shouldMigrate()) return false; + + return true; + } + + static _updateMigrableSymbolsSets(rodataSym, intersection, funcName, migrableRodataSyms, maybeMigrableRodataSyms, rodataMigratedSomewhereElse, already_migrated_syms) { + if (rodataMigratedSomewhereElse) return rodataMigratedSomewhereElse; + + if (FunctionRodataEntry._shouldMigrateRodataSymbolToFunction(rodataSym, intersection, funcName, already_migrated_syms)) { + migrableRodataSyms.add(rodataSym.vram); + + for (const x of maybeMigrableRodataSyms) migrableRodataSyms.add(x); + maybeMigrableRodataSyms.clear(); + } else if (migrableRodataSyms.size > 0) { + if (rodataSym.contextSym.referenceSymbols.size > 0 || rodataSym.contextSym.referenceFunctions.size > 0) { + rodataMigratedSomewhereElse = true; + } else if (rodataSym.shouldMigrate()) { + if (already_migrated_syms.has(rodataSym.vram)) rodataMigratedSomewhereElse = true; + else maybeMigrableRodataSyms.add(rodataSym.vram); + } else { + rodataMigratedSomewhereElse = true; + } + } + + return rodataMigratedSomewhereElse; + } + + /** + * Pairs the given function to the migrable rodata symbols of the given rodata section. + */ + static getEntryForFuncFromSection(func, rodataSection, already_migrated_syms = null) { + if (already_migrated_syms === null || already_migrated_syms === undefined) already_migrated_syms = new Set(); + if (rodataSection === null || rodataSection === undefined) return new FunctionRodataEntry(func); + + const rodataList = []; + const lateRodataList = []; + + const intersection = new Set(); + for (const v of func.instrAnalyzer.referencedVrams) if (rodataSection.symbolsVRams.has(v)) intersection.add(v); + + const funcName = func.getName(); + + const migrableRodataSyms = new Set(); + const migrableLateRodataSyms = new Set(); + const maybeMigrableRodataSyms = new Set(); + const maybeMigrableLateRodataSyms = new Set(); + let rodataMigratedSomewhereElse = false; + let lateRodataMigratedSomewhereElse = false; + for (const rodataSym of rodataSection.symbolList) { + if (rodataMigratedSomewhereElse) { + if (!GlobalConfig.COMPILER.value.hasLateRodata) break; + if (lateRodataMigratedSomewhereElse) break; + } + + if (rodataSym.contextSym.isLateRodata()) { + lateRodataMigratedSomewhereElse = FunctionRodataEntry._updateMigrableSymbolsSets(rodataSym, intersection, funcName, migrableLateRodataSyms, maybeMigrableLateRodataSyms, lateRodataMigratedSomewhereElse, already_migrated_syms); + } else { + rodataMigratedSomewhereElse = FunctionRodataEntry._updateMigrableSymbolsSets(rodataSym, intersection, funcName, migrableRodataSyms, maybeMigrableRodataSyms, rodataMigratedSomewhereElse, already_migrated_syms); + } + } + + for (const rodataSym of rodataSection.symbolList) { + if (migrableLateRodataSyms.has(rodataSym.vram)) lateRodataList.push(rodataSym); + else if (migrableRodataSyms.has(rodataSym.vram)) rodataList.push(rodataSym); + } + + return new FunctionRodataEntry(func, rodataList, lateRodataList); + } + + /** Searches and try to pair migrable rodata symbols to the given function. */ + static getEntryForFuncFromPossibleRodataSections(func, rodataFileList) { + for (const rodataSection of rodataFileList) { + assert(rodataSection instanceof SectionRodata); + + const entry = FunctionRodataEntry.getEntryForFuncFromSection(func, rodataSection); + if (entry.hasRodataSyms()) return entry; + } + + return new FunctionRodataEntry(func); + } + + /** + * Return all functions to rodata symbols pairings from the given sections, + * preserving the original ordering of both sections. + */ + static getAllEntriesFromSections(textSection, rodataSection) { + const remainingRodataSymbols = rodataSection !== null && rodataSection !== undefined ? [...rodataSection.symbolList] : []; + let head = 0; + const handledSymbols = new Set(); + + const allEntries = []; + + const textSymbols = textSection !== null && textSection !== undefined ? textSection.symbolList : []; + for (const func of textSymbols) { + const entry = FunctionRodataEntry.getEntryForFuncFromSection(func, rodataSection ?? null, handledSymbols); + + for (const sym of entry.iterRodataSyms()) handledSymbols.add(sym.vram); + + // Preserve the order of rodata symbols by looking for symbols that has not been migrated yet + if (entry.rodataSyms.length > 0) { + const firstFuncRodataSym = entry.rodataSyms[0]; + + while (head < remainingRodataSymbols.length) { + const rodataSym = remainingRodataSymbols[head]; + + if (handledSymbols.has(rodataSym.vram)) { + // Drop migrated symbols + head += 1; + continue; + } + + if (rodataSym.vram >= firstFuncRodataSym.vram) { + // Take all the symbols up to symbols referenced by the current function + break; + } + + allEntries.push(new FunctionRodataEntry(null, [rodataSym])); + handledSymbols.add(rodataSym.vram); + head += 1; + } + } + + allEntries.push(entry); + } + + // Check if there's any rodata symbol remaining and add it to the list + for (let k = head; k < remainingRodataSymbols.length; k++) { + const rodataSym = remainingRodataSymbols[k]; + if (!handledSymbols.has(rodataSym.vram)) allEntries.push(new FunctionRodataEntry(null, [rodataSym])); + } + + return allEntries; + } +} diff --git a/packages/romdev-spimdisasm/src/mips/InstructionConfig.js b/packages/romdev-spimdisasm/src/mips/InstructionConfig.js new file mode 100644 index 00000000..1d78a6ff --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/InstructionConfig.js @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/InstructionConfig.py +// +// The upstream class only wires argparse options to rabbitizer.config. The CLI +// frontends are not ported, so parseArgs accepts a plain object with the same +// attribute names argparse would produce. + +import { rabbitizer } from "../rabbitizer.js"; +import { GlobalConfig, Abi } from "../common/GlobalConfig.js"; +import { pyInt } from "../py/pyutils.js"; + +export class InstructionConfig { + static addParametersToArgParse(_parser) { + throw new Error("InstructionConfig.addParametersToArgParse: argparse frontends are not ported"); + } + + static parseArgs(args) { + const has = (k) => args[k] !== null && args[k] !== undefined; + if (has("named_registers")) rabbitizer.config.regNames_namedRegisters = args.named_registers; + + if (GlobalConfig.ABI !== Abi.O32) { + rabbitizer.config.regNames_gprAbiNames = rabbitizer.Abi.fromStr(GlobalConfig.ABI.name); + rabbitizer.config.regNames_fprAbiNames = rabbitizer.Abi.fromStr(GlobalConfig.ABI.name); + } + + if (args.Mgpr_names) rabbitizer.config.regNames_gprAbiNames = rabbitizer.Abi.fromStr(args.Mgpr_names); + if (args.Mfpr_names) rabbitizer.config.regNames_fprAbiNames = rabbitizer.Abi.fromStr(args.Mfpr_names); + if (args.Mreg_names) { + rabbitizer.config.regNames_gprAbiNames = rabbitizer.Abi.fromStr(args.Mreg_names); + rabbitizer.config.regNames_fprAbiNames = rabbitizer.Abi.fromStr(args.Mreg_names); + } + + if (has("use_fpccsr")) rabbitizer.config.regNames_userFpcCsr = args.use_fpccsr; + if (has("cop0_named_registers")) rabbitizer.config.regNames_vr4300Cop0NamedRegisters = args.cop0_named_registers; + if (has("rsp_cop0_named_registers")) rabbitizer.config.regNames_vr4300RspCop0NamedRegisters = args.rsp_cop0_named_registers; + if (has("pseudo_instr")) rabbitizer.config.pseudos_enablePseudos = args.pseudo_instr; + if (has("j_branch")) rabbitizer.config.toolchainTweaks_treatJAsUnconditionalBranch = args.j_branch; + if (has("sn64_div_fix")) rabbitizer.config.toolchainTweaks_sn64DivFix = args.sn64_div_fix; + if (has("opcode_ljust")) rabbitizer.config.misc_opcodeLJust = pyInt(String(args.opcode_ljust), 0); + if (has("unk_instr_comment")) rabbitizer.config.misc_unknownInstrComment = args.unk_instr_comment; + } +} diff --git a/packages/romdev-spimdisasm/src/mips/MipsFileBase.js b/packages/romdev-spimdisasm/src/mips/MipsFileBase.js new file mode 100644 index 00000000..e49d231d --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/MipsFileBase.js @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/MipsFileBase.py + +import { writeFileSync } from "node:fs"; + +import { ElementBase } from "../common/ElementBase.js"; +import { GlobalConfig } from "../common/GlobalConfig.js"; +import { Context } from "../common/Context.js"; +import { FileSectionType } from "../common/FileSectionType.js"; +import * as Utils from "../common/Utils.js"; +import { newIntSet } from "../common/symset.js"; +import { hexU } from "../py/pyutils.js"; + +export class FileBase extends ElementBase { + constructor(context, vromStart, vromEnd, vram, filename, words, sectionType, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, 0, vram, filename, words, sectionType, segmentVromStart, overlayCategory); + + this.symbolList = []; + + this.pointersOffsets = newIntSet(); + + this.isHandwritten = false; + + this.fileBoundaries = []; + + /** addresses of symbols in this section */ + this.symbolsVRams = newIntSet(); + + this.bytes = Utils.wordsToBytes(this.words); + + /** In log2 */ + this.sectionAlignment = 4; + + this.sectionFlags = null; + } + + setCommentOffset(commentOffset) { + this.commentOffset = commentOffset; + for (const sym of this.symbolList) sym.setCommentOffset(this.commentOffset); + } + + getAsmPrelude_includes() { + let output = ""; + output += `.include "macro.inc"${GlobalConfig.LINE_ENDS}`; + output += GlobalConfig.LINE_ENDS; + return output; + } + + getAsmPrelude_instructionDirectives() { + return ""; + } + + getAsmPrelude_sectionStart() { + let output = ""; + + output += `.section ${this.getSectionName()}`; + if (this.sectionFlags !== null) output += `, "${this.sectionFlags}"`; + output += GlobalConfig.LINE_ENDS; + + output += GlobalConfig.LINE_ENDS; + if (this.sectionAlignment !== null) { + output += `.align ${this.sectionAlignment}${GlobalConfig.LINE_ENDS}`; + output += GlobalConfig.LINE_ENDS; + } + return output; + } + + getAsmPrelude() { + let output = ""; + if (GlobalConfig.ASM_PRELUDE_USE_INCLUDES) output += this.getAsmPrelude_includes(); + if (GlobalConfig.ASM_PRELUDE_USE_INSTRUCTION_DIRECTIVES) output += this.getAsmPrelude_instructionDirectives(); + if (GlobalConfig.ASM_PRELUDE_USE_SECTION_START) output += this.getAsmPrelude_sectionStart(); + return output; + } + + getHash() { + const buffer = Utils.wordsToBytes(this.words); + return Utils.getStrHash(buffer); + } + + printNewFileBoundaries() { + if (!GlobalConfig.PRINT_NEW_FILE_BOUNDARIES) return; + + if (this.fileBoundaries.length > 0) { + const out = []; + out.push(`File ${this.name}`); + out.push(`Section: ${this.sectionType.toStr()}`); + out.push(`Found ${this.symbolList.length} symbols.`); + out.push(`Found ${this.fileBoundaries.length} file boundaries.`); + out.push(" offset, size, vram, symbols"); + + const boundaries = [...this.fileBoundaries]; + boundaries.push(this.sizew * 4 + this.inFileOffset); + + for (let i = 0; i < boundaries.length - 1; i++) { + const start = boundaries[i]; + const end = boundaries[i + 1]; + + let symbolsInBoundary = 0; + for (const func of this.symbolList) { + const funcOffset = func.inFileOffset - this.inFileOffset; + if (start <= funcOffset && funcOffset < end) symbolsInBoundary += 1; + } + let fileVram = 0; + if (this.vram !== null) fileVram = start + this.vram; + out.push(` ${hexU(start + this.commentOffset, 6)}, ${hexU(end - start, 6)}, ${hexU(fileVram, 8)}, ${String(symbolsInBoundary).padStart(7)}`); + } + out.push(""); + process.stdout.write(out.join("\n") + "\n"); + } + } + + printAnalyzisResults() { + this.printNewFileBoundaries(); + } + + compareToFile(otherFile) { + const hashOne = this.getHash(); + const hashTwo = otherFile.getHash(); + + const result = { + equal: hashOne === hashTwo, + hash_one: hashOne, + hash_two: hashTwo, + size_one: this.sizew * 4, + size_two: otherFile.sizew * 4, + diff_bytes: 0, + diff_words: 0, + }; + + let diffBytes = 0; + let diffWords = 0; + + if (!result.equal) { + const minLen = Math.min(this.sizew, otherFile.sizew); + for (let i = 0; i < minLen; i++) { + for (let j = 0; j < 4; j++) { + if (((this.words[i] >>> (j * 8)) & 0xff) !== ((otherFile.words[i] >>> (j * 8)) & 0xff)) diffBytes += 1; + } + } + for (let i = 0; i < minLen; i++) { + if (this.words[i] !== otherFile.words[i]) diffWords += 1; + } + } + + result.diff_bytes = diffBytes; + result.diff_words = diffWords; + + return result; + } + + blankOutDifferences(_other) { + if (!GlobalConfig.REMOVE_POINTERS) return false; + return false; + } + + removePointers() { + if (!GlobalConfig.REMOVE_POINTERS) return false; + return false; + } + + disassemble(migrate = false, useGlobalLabel = true) { + let output = ""; + + if (!migrate) output += this.getSpimdisasmVersionString(); + + for (let i = 0; i < this.symbolList.length; i++) { + const sym = this.symbolList[i]; + output += sym.disassemble(migrate, useGlobalLabel, false); + if (i + 1 < this.symbolList.length) output += GlobalConfig.LINE_ENDS; + } + return output; + } + + /** f: object with a write(str) method */ + disassembleToFile(f) { + if (GlobalConfig.ASM_USE_PRELUDE) f.write(this.getAsmPrelude()); + f.write(this.disassemble()); + } + + saveToFile(filepath) { + if (this.symbolList.length === 0) return; + + if (filepath === "-") { + this.disassembleToFile({ write: (s) => process.stdout.write(s) }); + } else { + if (GlobalConfig.WRITE_BINARY) { + if (this.sizew > 0) { + const buffer = Utils.wordsToBytes(this.words); + Utils.writeBytesToFile(filepath + this.sectionType.toStr(), buffer); + } + } + const parts = []; + this.disassembleToFile({ write: (s) => parts.push(s) }); + writeFileSync(filepath + this.sectionType.toStr() + ".s", parts.join(""), "utf8"); + } + } +} + +export function createEmptyFile() { + return new FileBase(new Context(), 0, 0, 0, "", [], FileSectionType.Unknown, 0, null); +} diff --git a/packages/romdev-spimdisasm/src/mips/MipsFileSplits.js b/packages/romdev-spimdisasm/src/mips/MipsFileSplits.js new file mode 100644 index 00000000..664d61a3 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/MipsFileSplits.js @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/MipsFileSplits.py + +import { FileSectionType, FileSections_ListBasic, FileSections_ListAll } from "../common/FileSectionType.js"; +import { FileSplitEntry } from "../common/FileSplitFormat.js"; +import { GlobalConfig } from "../common/GlobalConfig.js"; +import * as Utils from "../common/Utils.js"; +import { FileBase, createEmptyFile } from "./MipsFileBase.js"; +import { SectionText } from "./sections/MipsSectionText.js"; +import * as FilesHandlers from "./FilesHandlers.js"; + +export class FileSplits extends FileBase { + constructor(context, vromStart, vromEnd, vram, filename, array_of_bytes, segmentVromStart, overlayCategory, splitsData = null, relocSection = null) { + super(context, vromStart, vromEnd, vram, filename, Utils.bytesToWords(array_of_bytes, vromStart, vromEnd), FileSectionType.Unknown, segmentVromStart, overlayCategory); + + this.sectionsDict = new Map([ + [FileSectionType.Text, new Map()], + [FileSectionType.Data, new Map()], + [FileSectionType.Rodata, new Map()], + [FileSectionType.Bss, new Map()], + [FileSectionType.Reloc, new Map()], + ]); + + this.splitsDataList = []; + + if (relocSection !== null && relocSection !== undefined) { + relocSection.parent = this; + if (!relocSection.differentSegment) { + let relocStart = relocSection.textSize + relocSection.dataSize + relocSection.rodataSize; + if (relocSection.differentSegment) relocStart += relocSection.bssSize; + relocSection.vram = this.vram + relocStart; + } + this.sectionsDict.get(FileSectionType.Reloc).set(filename, relocSection); + } + + if ((splitsData === null || splitsData === undefined) && (relocSection === null || relocSection === undefined)) { + this.sectionsDict.get(FileSectionType.Text).set(filename, new SectionText(context, vromStart, vromEnd, vram, filename, array_of_bytes, segmentVromStart, overlayCategory)); + } else if (splitsData !== null && splitsData !== undefined && splitsData.length > 0) { + for (const splitEntry of splitsData) this.splitsDataList.push(splitEntry); + } else if (relocSection !== null && relocSection !== undefined) { + let start = 0; + let end = 0; + for (let i = 0; i < FileSections_ListBasic.length; i++) { + const sectionType = FileSections_ListBasic[i]; + const sectionSize = relocSection.sectionSizes.get(sectionType); + + if (i !== 0) start += relocSection.sectionSizes.get(FileSections_ListBasic[i - 1]); + end += relocSection.sectionSizes.get(sectionType); + + if (sectionType === FileSectionType.Bss) { + // bss is after reloc when the relocation is on the same segment + if (!relocSection.differentSegment) { + start += relocSection.sizew * 4; + end += relocSection.sizew * 4; + } + } + + if (sectionSize === 0) continue; + + const v = this.vram + start; + const splitEntry = new FileSplitEntry(start, v, filename, sectionType, end, false, false); + this.splitsDataList.push(splitEntry); + } + } + + for (const splitEntry of this.splitsDataList) { + if (splitEntry.section === FileSectionType.Dummy) continue; + + const f = FilesHandlers.createSectionFromSplitEntry(splitEntry, array_of_bytes, context, vromStart); + f.parent = this; + f.setCommentOffset(splitEntry.offset); + + this.sectionsDict.get(splitEntry.section).set(splitEntry.fileName, f); + } + } + + get nFuncs() { + let nFuncs = 0; + for (const f of this.sectionsDict.get(FileSectionType.Text).values()) nFuncs += f.nFuncs; + return nFuncs; + } + + setVram(vram) { + super.setVram(vram); + for (const sectDict of this.sectionsDict.values()) for (const section of sectDict.values()) section.setVram(vram); + } + + getHash() { + const words = []; + for (const sectDict of this.sectionsDict.values()) for (const section of sectDict.values()) words.push(...section.words); + return Utils.getStrHash(Utils.wordsToBytes(words)); + } + + analyze() { + for (const relocSection of this.sectionsDict.get(FileSectionType.Reloc).values()) { + for (const entry of relocSection.entries) { + const sectionType = entry.getSectionType(); + if (entry.reloc === 0) continue; + for (const subFile of this.sectionsDict.get(sectionType).values()) subFile.pointersOffsets.add(entry.offset); + } + } + + for (const sectDict of this.sectionsDict.values()) for (const section of sectDict.values()) section.analyze(); + } + + compareToFile(other_file) { + if (other_file instanceof FileSplits) { + const filesections = new Map([ + [FileSectionType.Text, new Map()], + [FileSectionType.Data, new Map()], + [FileSectionType.Rodata, new Map()], + [FileSectionType.Bss, new Map()], + [FileSectionType.Reloc, new Map()], + ]); + + for (const sectionType of FileSections_ListAll) { + const mine = this.sectionsDict.get(sectionType) ?? new Map(); + const theirs = other_file.sectionsDict.get(sectionType) ?? new Map(); + if (!filesections.has(sectionType)) filesections.set(sectionType, new Map()); + const out = filesections.get(sectionType); + for (const [section_name, section] of mine) { + if (theirs.has(section_name)) out.set(section_name, section.compareToFile(theirs.get(section_name))); + else out.set(section_name, section.compareToFile(createEmptyFile())); + } + for (const [section_name, other_section] of theirs) { + if (mine.has(section_name)) { + const section = mine.get(section_name); + if (!out.has(section_name)) out.set(section_name, section.compareToFile(other_section)); + } else { + out.set(section_name, createEmptyFile().compareToFile(other_section)); + } + } + } + + return { filesections }; + } + + return super.compareToFile(other_file); + } + + blankOutDifferences(other_file) { + if (!GlobalConfig.REMOVE_POINTERS) return false; + if (!(other_file instanceof FileSplits)) return false; + + let was_updated = false; + for (const sectionType of FileSections_ListAll) { + const mine = this.sectionsDict.get(sectionType) ?? new Map(); + const theirs = other_file.sectionsDict.get(sectionType) ?? new Map(); + for (const [section_name, section] of mine) { + if (theirs.has(section_name)) was_updated = section.blankOutDifferences(theirs.get(section_name)) || was_updated; + } + for (const [section_name, other_section] of theirs) { + if (mine.has(section_name)) was_updated = mine.get(section_name).blankOutDifferences(other_section) || was_updated; + } + } + return was_updated; + } + + removePointers() { + if (!GlobalConfig.REMOVE_POINTERS) return false; + let was_updated = false; + for (const sectDict of this.sectionsDict.values()) for (const section of sectDict.values()) was_updated = section.removePointers() || was_updated; + return was_updated; + } + + saveToFile(filepath) { + for (const sectDict of this.sectionsDict.values()) { + for (let [name, section] of sectDict) { + if (name !== "" && !filepath.endsWith("/")) name = " " + name; + section.saveToFile(filepath + name); + } + } + } +} diff --git a/packages/romdev-spimdisasm/src/mips/index.js b/packages/romdev-spimdisasm/src/mips/index.js new file mode 100644 index 00000000..f122c5b8 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/index.js @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/__init__.py + +import * as sections from "./sections/index.js"; +import * as symbols from "./symbols/index.js"; +import * as FilesHandlers from "./FilesHandlers.js"; + +export { sections, symbols, FilesHandlers }; +export { FunctionRodataEntry } from "./FuncRodataEntry.js"; +export { InstructionConfig } from "./InstructionConfig.js"; +export { FileBase, createEmptyFile } from "./MipsFileBase.js"; +export { FileSplits } from "./MipsFileSplits.js"; diff --git a/packages/romdev-spimdisasm/src/mips/sections/MipsSectionBase.js b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionBase.js new file mode 100644 index 00000000..0e030bf5 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionBase.js @@ -0,0 +1,276 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/sections/MipsSectionBase.py + +import { FileBase } from "../MipsFileBase.js"; +import { GlobalConfig } from "../../common/GlobalConfig.js"; +import { FileSectionType } from "../../common/FileSectionType.js"; +import { SymbolSpecialType, symEq } from "../../common/ContextSymbols.js"; +import * as Utils from "../../common/Utils.js"; +import { atLeast } from "../../version.js"; + +export class SectionBase extends FileBase { + constructor(context, vromStart, vromEnd, vram, filename, words, sectionType, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, vram, filename, words, sectionType, segmentVromStart, overlayCategory); + + this.stringEncoding = GlobalConfig.DATA_STRING_ENCODING; + /** Allows to toggle string guessing at the section level. */ + this.enableStringGuessing = true; + + /** If not null, the autodetectedType of the symbols found on this section is set to this value. */ + this.typeForOwnedSymbols = null; + + /** If not null, the autodetectedSize of the symbols found on this section is set to this value. */ + this.sizeForOwnedSymbols = null; + } + + checkWordIsASymbolReference(word) { + if (!this.context.totalVramRange.isInRange(word)) return false; + if (this.context.isAddressBanned(word)) return false; + + const contextSym = this.getSymbol(word, null, true, false); + if (contextSym !== null) { + const symType = contextSym.getTypeSpecial(); + if ( + symType === SymbolSpecialType.function || + symType === SymbolSpecialType.branchlabel || + symType === SymbolSpecialType.jumptablelabel || + (atLeast("1.39.0") && symType === SymbolSpecialType.gccexcepttablelabel) + ) { + // Avoid generating extra symbols in the middle of functions + return false; + } + + if (word < contextSym.vram + contextSym.getSize()) { + // Avoid generating symbols in the middle of other symbols with known sizes + return false; + } + } + + this.addPointerInDataReference(word); + return true; + } + + processStaticRelocs() { + for (let i = 0; i < this.sizew; i++) { + const word = this.words[i]; + const vrom = this.getVromOffset(i * 4); + const relocInfo = this.context.globalRelocationOverrides.get(vrom); + if (relocInfo === undefined || relocInfo.staticReference === null) continue; + + const relocVram = relocInfo.staticReference.sectionVram + word; + const sectionType = relocInfo.staticReference.sectionType; + let contextSym; + if (this.sectionType === FileSectionType.Rodata && sectionType === FileSectionType.Text) { + contextSym = this.addJumpTableLabel(relocVram, true); + } else { + contextSym = this.addSymbol(relocVram, sectionType, true); + } + contextSym._isStatic = true; + } + } + + /** Check if the very start of the file has a symbol and create it if it doesn't exist yet */ + _checkAndCreateFirstSymbol() { + const currentVram = this.getVramOffset(0); + const currentVrom = this.getVromOffsetNone(0); + return this.addSymbol(currentVram, this.sectionType, true, currentVrom); + } + + _getOwnedSymbol(localOffset) { + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffsetNone(localOffset); + + const contextSym = this.getSymbol(currentVram, currentVrom, false); + if (contextSym === null) return null; + + if (this.typeForOwnedSymbols !== null) contextSym.autodetectedType = this.typeForOwnedSymbols; + if (this.sizeForOwnedSymbols !== null) contextSym.autodetectedSize = this.sizeForOwnedSymbols; + + if (this.sectionType !== FileSectionType.Bss) { + contextSym.isMaybeString = this._stringGuesser(contextSym, localOffset); + contextSym.isMaybePascalString = this._pascalStringGuesser(contextSym, localOffset); + } + + this._createAutoPadFromSymbol(localOffset, contextSym); + + return contextSym; + } + + _addOwnedSymbol(localOffset) { + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffsetNone(localOffset); + + const contextSym = this.addSymbol(currentVram, this.sectionType, true, currentVrom, true); + if (contextSym.vram !== currentVram) return null; + + if (this.typeForOwnedSymbols !== null) contextSym.autodetectedType = this.typeForOwnedSymbols; + if (this.sizeForOwnedSymbols !== null) contextSym.autodetectedSize = this.sizeForOwnedSymbols; + + if (this.sectionType !== FileSectionType.Bss) { + contextSym.isMaybeString = this._stringGuesser(contextSym, localOffset); + contextSym.isMaybePascalString = this._pascalStringGuesser(contextSym, localOffset); + } + + return contextSym; + } + + _addOwnedAutocreatedPad(localOffset) { + if (localOffset >= this.sizew * 4) return null; + + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffsetNone(localOffset); + + const extraContextSym = this.addSymbol(currentVram, this.sectionType, true, currentVrom); + extraContextSym.isAutoCreatedPad = true; + return extraContextSym; + } + + _createAutoPadFromSymbol(localOffset, contextSym) { + if (!contextSym.hasUserDeclaredSize()) { + if (this.sizeForOwnedSymbols !== null && this.sizeForOwnedSymbols > 0) return this._addOwnedAutocreatedPad(localOffset + this.sizeForOwnedSymbols); + } + + let createPads; + if (this.sectionType === FileSectionType.Data) createPads = GlobalConfig.CREATE_DATA_PADS; + else if (this.sectionType === FileSectionType.Rodata) createPads = GlobalConfig.CREATE_RODATA_PADS; + else createPads = false; + + if (createPads && contextSym.hasUserDeclaredSize()) { + const symDeclaredSize = contextSym.getSize(); + if (symDeclaredSize > 0) { + // Try to respect the user-declared size for this symbol + return this._addOwnedAutocreatedPad(localOffset + symDeclaredSize); + } + } + + return null; + } + + _stringGuesser(contextSym, localOffset) { + if (contextSym._ranStringCheck) return contextSym.isMaybeString; + + if (contextSym.isMaybeString || contextSym.isString()) return true; + + if (!this.enableStringGuessing) return false; + + let stringGuesserLevel; + if (this.sectionType === FileSectionType.Rodata) stringGuesserLevel = GlobalConfig.RODATA_STRING_GUESSER_LEVEL; + else stringGuesserLevel = GlobalConfig.DATA_STRING_GUESSER_LEVEL; + + if (stringGuesserLevel < 1) return false; + + if (contextSym.referenceCounter > 1) { + if (stringGuesserLevel < 2) return false; + } + + // This would mean the string is an empty string, which is not very likely + const w = this.words[Math.floor(localOffset / 4)]; + if (w === 0) { + if (stringGuesserLevel < 3) return false; + } + + if (contextSym.hasOnlyAutodetectedType()) { + if (stringGuesserLevel < 4) return false; + } + + if (atLeast("1.39.0")) { + // We don't want to decode as string if this is a pointer + const suspectedPtr = this.getSymbol(w); + if (suspectedPtr !== null) { + if (w === suspectedPtr.vram) return false; + const t = suspectedPtr.getTypeSpecial(); + if ( + t === SymbolSpecialType.function || + t === SymbolSpecialType.branchlabel || + t === SymbolSpecialType.jumptablelabel || + t === SymbolSpecialType.gccexcepttablelabel + ) { + // It is very unlikely for a symbol to be referencing the middle + // of a function, so we allow this to be a string. + } else { + return false; + } + } else if (w % 4 === 0 && this.containsVram(w) && w !== contextSym.vram) { + // Likely to be a pointer to a symbol in the current section. + return false; + } + } + + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffset(localOffset); + const [, rawStringSize] = Utils.decodeBytesToStrings(this.bytes, localOffset, this.stringEncoding); + if (rawStringSize < 0) { + // String can't be decoded + return false; + } + + // Check if there is already another symbol after the current one and before the end of the string, + // in which case we say this symbol should not be a string + const otherSym = this.getSymbol(currentVram + rawStringSize, currentVrom + rawStringSize, true, false, false); + if (!symEq(otherSym, contextSym)) return false; + + return true; + } + + _pascalStringGuesser(contextSym, localOffset) { + if (contextSym._ranPascalStringCheck) return contextSym.isMaybePascalString; + + if (contextSym.isMaybePascalString || contextSym.isPascalString()) return true; + + if (!this.enableStringGuessing) return false; + + let stringGuesserLevel; + if (this.sectionType === FileSectionType.Rodata) stringGuesserLevel = GlobalConfig.PASCAL_RODATA_STRING_GUESSER_LEVEL; + else stringGuesserLevel = GlobalConfig.PASCAL_DATA_STRING_GUESSER_LEVEL; + + if (stringGuesserLevel < 1) return false; + + if (contextSym.referenceCounter > 1) { + if (stringGuesserLevel < 2) return false; + } + + // This would mean the string is an empty string, which is not very likely + if (this.words[Math.floor(localOffset / 4)] === 0) { + if (stringGuesserLevel < 3) return false; + } + + if (contextSym.hasOnlyAutodetectedType()) { + if (stringGuesserLevel < 4) return false; + } + + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffset(localOffset); + const [, rawStringSize] = Utils.decodeBytesToPascalStrings(this.bytes, localOffset, this.stringEncoding, 0x20); + if (rawStringSize < 0) return false; + + const otherSym = this.getSymbol(currentVram + rawStringSize - 1, currentVrom + rawStringSize, true, false, false); + if (!symEq(otherSym, contextSym)) return false; + + return true; + } + + blankOutDifferences(other) { + if (!GlobalConfig.REMOVE_POINTERS) return false; + + let was_updated = false; + if (GlobalConfig.IGNORE_WORD_LIST.size > 0) { + const minLen = Math.min(this.sizew, other.sizew); + for (let i = 0; i < minLen; i++) { + for (const upperByte of GlobalConfig.IGNORE_WORD_LIST) { + const word = (upperByte * 0x1000000) >>> 0; + if (((this.words[i] >>> 24) & 0xff) === upperByte && ((other.words[i] >>> 24) & 0xff) === upperByte) { + this.words[i] = word; + other.words[i] = word; + was_updated = true; + } + } + } + } + + return was_updated; + } + + suspectedPaddingGarbage() { + return []; + } +} diff --git a/packages/romdev-spimdisasm/src/mips/sections/MipsSectionBss.js b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionBss.js new file mode 100644 index 00000000..fc59e833 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionBss.js @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/sections/MipsSectionBss.py + +import { GlobalConfig } from "../../common/GlobalConfig.js"; +import { FileSectionType } from "../../common/FileSectionType.js"; +import { hexU, sortedNumbers } from "../../py/pyutils.js"; +import { atLeast } from "../../version.js"; +import { SymbolBss } from "../symbols/MipsSymbolBss.js"; +import { SectionBase } from "./MipsSectionBase.js"; + +function assert(cond, msg = "") { + if (!cond) throw new Error(`AssertionError${msg ? ": " + msg : ""}`); +} + +export class SectionBss extends SectionBase { + constructor(context, vromStart, vromEnd, bssVramStart, bssVramEnd, filename, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, bssVramStart, filename, [], FileSectionType.Bss, segmentVromStart, overlayCategory); + + this.bssVramStart = bssVramStart; + this.bssVramEnd = bssVramEnd; + + this.vram = bssVramStart; + } + + get bssTotalSize() { + return this.bssVramEnd - this.bssVramStart; + } + + get sizew() { + if (this.bssVramEnd === undefined) return this.words.length; + return Math.floor(this.bssTotalSize / 4); + } + + setVram(vram) { + super.setVram(vram); + this.bssVramStart = vram; + // Same evaluation order as upstream: bssTotalSize already sees the new start + this.bssVramEnd = vram + this.bssTotalSize; + } + + analyze() { + this._checkAndCreateFirstSymbol(); + + // If something that could be a pointer found in data happens to be in + // the middle of this bss file's addresses space then consider it as a + // new bss variable + for (const ptr of this.getAndPopPointerInDataReferencesRange(this.bssVramStart, this.bssVramEnd)) { + // Check if the symbol already exists, in case the user has provided size + const contextSym = this.getSymbol(ptr, null, true); + if (contextSym === null) this.addSymbol(ptr, this.sectionType, true); + } + + const autoCreatedPads = new Set(); + const bssSymbolOffsets = new Set(); + const v142 = atLeast("1.42.0"); + for (const [symbolVram, contextSym] of this.getSymbolsRange(this.bssVramStart, this.bssVramEnd)) { + // Mark every known symbol that happens to be in this address space as defined + contextSym.sectionType = FileSectionType.Bss; + + assert(symbolVram >= this.bssVramStart); + assert(symbolVram < this.bssVramEnd); + bssSymbolOffsets.add(symbolVram - this.bssVramStart); + + if (v142) { + // If the bss/sbss has an explicit non-zero size then produce an extra symbol after it, + // so the generated symbol uses the user-declared size + if (GlobalConfig.CREATE_BSS_PADS && contextSym.hasUserDeclaredSize()) { + const contextSymSize = contextSym.getSize(); + if (contextSymSize > 0) { + const newSymbolVram = symbolVram + contextSymSize; + if (newSymbolVram !== this.bssVramEnd) { + assert(newSymbolVram >= this.bssVramStart); + assert(newSymbolVram < this.bssVramEnd, `${this.name}, symbolVram=${hexU(symbolVram, 8)}, newSymbolVram=${hexU(newSymbolVram, 8)}, self.bssVramEnd=${hexU(this.bssVramEnd, 8)}`); + const symOffset = symbolVram + contextSymSize - this.bssVramStart; + bssSymbolOffsets.add(symOffset); + autoCreatedPads.add(symOffset); + } + } + } + } else if (contextSym.hasUserDeclaredSize()) { + // If the bss has an explicit size then produce an extra symbol after it, so the generated bss symbol uses the user-declared size + const newSymbolVram = symbolVram + contextSym.getSize(); + if (newSymbolVram !== this.bssVramEnd) { + assert(newSymbolVram >= this.bssVramStart); + assert(newSymbolVram < this.bssVramEnd, `${this.name}, symbolVram=${hexU(symbolVram, 8)}, newSymbolVram=${hexU(newSymbolVram, 8)}, self.bssVramEnd=${hexU(this.bssVramEnd, 8)}`); + const symOffset = symbolVram + contextSym.getSize() - this.bssVramStart; + bssSymbolOffsets.add(symOffset); + autoCreatedPads.add(symOffset); + } + } + } + + const sortedOffsets = sortedNumbers(bssSymbolOffsets); + + let i = 0; + while (i < sortedOffsets.length) { + const symbolOffset = sortedOffsets[i]; + const symbolVram = this.bssVramStart + symbolOffset; + + // Calculate the space of the bss variable + let space = this.bssTotalSize - symbolOffset; + if (i + 1 < sortedOffsets.length) { + const nextSymbolOffset = sortedOffsets[i + 1]; + if (nextSymbolOffset <= this.bssTotalSize) space = nextSymbolOffset - symbolOffset; + } + + assert(space > 0); + + const vrom = this.getVromOffset(symbolOffset); + const vromEnd = vrom + space; + const sym = new SymbolBss(this.context, vrom, vromEnd, symbolOffset + this.inFileOffset, symbolVram, space, this.segmentVromStart, this.overlayCategory); + sym.parent = this; + sym.contextSym.autodetectedSize = space; + sym.setCommentOffset(this.commentOffset); + if (autoCreatedPads.has(symbolOffset)) sym.contextSym.isAutoCreatedPad = true; + sym.analyze(); + this.symbolList.push(sym); + + this.symbolsVRams.add(symbolVram); + + i += 1; + } + } +} diff --git a/packages/romdev-spimdisasm/src/mips/sections/MipsSectionData.js b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionData.js new file mode 100644 index 00000000..b91f189b --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionData.js @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/sections/MipsSectionData.py + +import { GlobalConfig } from "../../common/GlobalConfig.js"; +import { FileSectionType } from "../../common/FileSectionType.js"; +import { symEq } from "../../common/ContextSymbols.js"; +import * as Utils from "../../common/Utils.js"; +import { atLeast } from "../../version.js"; +import { SymbolData } from "../symbols/MipsSymbolData.js"; +import { SectionBase } from "./MipsSectionBase.js"; + +export class SectionData extends SectionBase { + constructor(context, vromStart, vromEnd, vram, filename, array_of_bytes, segmentVromStart, overlayCategory) { + let words; + if (GlobalConfig.ENDIAN_DATA !== null) words = Utils.endianessBytesToWords(GlobalConfig.ENDIAN_DATA, array_of_bytes, vromStart, vromEnd); + else words = Utils.bytesToWords(array_of_bytes, vromStart, vromEnd); + super(context, vromStart, vromEnd, vram, filename, words, FileSectionType.Data, segmentVromStart, overlayCategory); + } + + analyze() { + this._checkAndCreateFirstSymbol(); + + let symbolList = []; + let localOffset = 0; + const localOffsetsWithSymbols = new Set(); + + let needsFurtherAnalyzis = false; + + const v142 = atLeast("1.42.0"); + const ownedSegment = v142 ? this.getSegment() : null; + + for (const w of this.words) { + const currentVram = this.getVramOffset(localOffset); + + let contextSym = this._getOwnedSymbol(localOffset); + if (contextSym !== null) { + symbolList.push([localOffset, contextSym]); + localOffsetsWithSymbols.add(localOffset); + } else if (this.popPointerInDataReference(currentVram) !== null) { + contextSym = this._addOwnedSymbol(localOffset); + if (contextSym !== null) { + symbolList.push([localOffset, contextSym]); + localOffsetsWithSymbols.add(localOffset); + } + } + + if (v142) { + if (!this.context.isAddressBanned(w)) { + if (this.checkWordIsASymbolReference(w)) { + if (w < currentVram && this.containsVram(w)) { + // References a data symbol from this section and it is behind this current symbol + needsFurtherAnalyzis = true; + } + } + + if (!ownedSegment.isVramInRange(w)) { + const prioritizedSegment = this._findPrioritizedSegment(w, ownedSegment); + if (prioritizedSegment !== null) prioritizedSegment.addSymbol(w, undefined, true, null, true); + } + } + } else if (this.checkWordIsASymbolReference(w)) { + if (w < currentVram && this.containsVram(w)) needsFurtherAnalyzis = true; + } + + localOffset += 4; + } + + if (needsFurtherAnalyzis) { + localOffset = 0; + for (const _w of this.words) { + const currentVram = this.getVramOffset(localOffset); + + if (this.popPointerInDataReference(currentVram) !== null && !localOffsetsWithSymbols.has(localOffset)) { + const contextSym = this._addOwnedSymbol(localOffset); + if (contextSym !== null) { + symbolList.push([localOffset, contextSym]); + localOffsetsWithSymbols.add(localOffset); + } + } + + localOffset += 4; + } + + // Since we appended new symbols, this list is not sorted anymore + symbolList = sortPairs(symbolList); + } + + this.processStaticRelocs(); + + for (let i = 0; i < symbolList.length; i++) { + const [offset, contextSym] = symbolList[i]; + let words; + if (i + 1 === symbolList.length) { + words = this.words.slice(offset / 4); + } else { + const nextOffset = symbolList[i + 1][0]; + if (offset === nextOffset) continue; + words = this.words.slice(offset / 4, nextOffset / 4); + } + + const vrom = this.getVromOffset(offset); + const vromEnd = vrom + 4 * words.length; + const sym = new SymbolData(this.context, vrom, vromEnd, offset + this.inFileOffset, contextSym.vram, words, this.segmentVromStart, this.overlayCategory); + sym.parent = this; + sym.setCommentOffset(this.commentOffset); + sym.stringEncoding = this.stringEncoding; + sym.analyze(); + this.symbolList.push(sym); + + this.symbolsVRams.add(contextSym.vram); + } + } + + removePointers() { + if (!GlobalConfig.REMOVE_POINTERS) return false; + + let was_updated = false; + for (let i = 0; i < this.sizew; i++) { + const top_byte = (this.words[i] >>> 24) & 0xff; + if (top_byte === 0x80) { + this.words[i] = (top_byte << 24) >>> 0; + was_updated = true; + } + if ((top_byte & 0xf0) === 0x00 && (top_byte & 0x0f) !== 0x00) { + this.words[i] = (top_byte << 24) >>> 0; + was_updated = true; + } + } + return was_updated; + } +} + +/** + * list.sort() over (offset, ContextSymbol) tuples: offsets are unique in + * practice; equal offsets would make CPython compare ContextSymbols and raise. + */ +export function sortPairs(list) { + const out = list.map((p, i) => [p, i]); + out.sort((a, b) => { + if (a[0][0] !== b[0][0]) return a[0][0] < b[0][0] ? -1 : 1; + if (symEq(a[0][1], b[0][1])) return a[1] - b[1]; + throw new TypeError("'<' not supported between instances of 'ContextSymbol' and 'ContextSymbol'"); + }); + return out.map((x) => x[0]); +} diff --git a/packages/romdev-spimdisasm/src/mips/sections/MipsSectionGccExceptTable.js b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionGccExceptTable.js new file mode 100644 index 00000000..b78c86ba --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionGccExceptTable.js @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/sections/MipsSectionGccExceptTable.py + +import { rabbitizer } from "../../rabbitizer.js"; +import { GlobalConfig } from "../../common/GlobalConfig.js"; +import { FileSectionType } from "../../common/FileSectionType.js"; +import * as Utils from "../../common/Utils.js"; +import { SymbolGccExceptTable } from "../symbols/MipsSymbolGccExceptTable.js"; +import { SectionBase } from "./MipsSectionBase.js"; + +/** + * A `.gcc_except_table` section contains a single symbol that contains + * information to handle C++ exceptions known as the Error Handler Table. + */ +export class SectionGccExceptTable extends SectionBase { + constructor(context, vromStart, vromEnd, vram, filename, array_of_bytes, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, vram, filename, Utils.bytesToWords(array_of_bytes, vromStart, vromEnd), FileSectionType.GccExceptTable, segmentVromStart, overlayCategory); + } + + _analyze_processExceptTable(localOffset, w, contextSym, lastVramSymbol, exceptTableSym, firstExceptTableWord) { + if (contextSym !== null && contextSym.isGccExceptTable()) { + exceptTableSym = contextSym; + firstExceptTableWord = w; + } else if (exceptTableSym !== null) { + if (!this.pointersOffsets.has(localOffset)) { + if (w === 0xffffffff) { + // Except tables contain 2 negative ones at the end of the table. + } else if (w === 0) { + return [null, firstExceptTableWord]; + } else if (contextSym !== null) { + return [null, firstExceptTableWord]; + } else if (((w >>> 24) & 0xff) !== ((firstExceptTableWord >>> 24) & 0xff)) { + if (!(lastVramSymbol.isGccExceptTable() && lastVramSymbol.isGot && GlobalConfig.GP_VALUE !== null)) return [null, firstExceptTableWord]; + } + } + } else { + return [null, firstExceptTableWord]; + } + + // Generate the current label + if (w !== 0xffffffff && w !== 0) { + let labelAddr = w; + if (lastVramSymbol.isGot && GlobalConfig.GP_VALUE !== null) labelAddr = GlobalConfig.GP_VALUE + rabbitizer.Utils.from2Complement(w, 32); + const labelSym = this.addGccExceptTableLabel(labelAddr, true); + + if (labelSym.unknownSegment) return [null, firstExceptTableWord]; + + labelSym.referenceCounter += 1; + } + + return [exceptTableSym, firstExceptTableWord]; + } + + analyze() { + let lastVramSymbol = this._checkAndCreateFirstSymbol(); + let contextSym = null; + + // All symbols on this section are assumed to be except tables + this.addGccExceptTable(this.getVramOffset(0), true, this.getVromOffset(0)); + + const symbolList = []; + let localOffset = 0; + + let exceptTableSym = null; + let firstExceptTableWord = -1; + let negativeOneCounter = 0; + + for (const w of this.words) { + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffset(localOffset); + + if (w === 0) { + if (!lastVramSymbol.isAutoCreatedPad) { + const pad = this._addOwnedAutocreatedPad(localOffset); + if (pad !== null) lastVramSymbol = pad; + } + } + + if (negativeOneCounter >= 2 && w !== 0) { + // The except table ended + contextSym = this._addOwnedSymbol(localOffset); + if (contextSym !== null) { + lastVramSymbol = contextSym; + this.addGccExceptTable(currentVram, true, currentVrom); + } + negativeOneCounter = 0; + } else { + // Check if we have a symbol at this address, if not then use the last known one + contextSym = this.getSymbol(currentVram, currentVrom, false); + if (contextSym !== null) lastVramSymbol = contextSym; + } + + [exceptTableSym, firstExceptTableWord] = this._analyze_processExceptTable(localOffset, w, contextSym, lastVramSymbol, exceptTableSym, firstExceptTableWord); + + if (exceptTableSym === null) { + if (contextSym !== null || this.popPointerInDataReference(currentVram) !== null || (lastVramSymbol.isGccExceptTable() && w !== 0)) { + contextSym = this._addOwnedSymbol(localOffset); + if (contextSym !== null) lastVramSymbol = contextSym; + } + + this.checkWordIsASymbolReference(w); + } + + if (contextSym !== null) { + this.symbolsVRams.add(currentVram); + symbolList.push([localOffset, currentVram]); + + this._createAutoPadFromSymbol(localOffset, contextSym); + } + + if (w === 0xffffffff) negativeOneCounter += 1; + + localOffset += 4; + } + + for (let i = 0; i < symbolList.length; i++) { + const [offset, vram] = symbolList[i]; + let words; + if (i + 1 === symbolList.length) { + words = this.words.slice(offset / 4); + } else { + const nextOffset = symbolList[i + 1][0]; + words = this.words.slice(offset / 4, nextOffset / 4); + } + + const vrom = this.getVromOffset(offset); + const vromEnd = vrom + words.length * 4; + const sym = new SymbolGccExceptTable(this.context, vrom, vromEnd, offset + this.inFileOffset, vram, words, this.segmentVromStart, this.overlayCategory); + sym.parent = this; + sym.setCommentOffset(this.commentOffset); + sym.analyze(); + this.symbolList.push(sym); + } + + this.processStaticRelocs(); + } +} diff --git a/packages/romdev-spimdisasm/src/mips/sections/MipsSectionRelocZ64.js b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionRelocZ64.js new file mode 100644 index 00000000..da40ce55 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionRelocZ64.js @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/sections/MipsSectionRelocZ64.py +// Relocation format used by some N64 overlay-based engines. + +import path from "node:path"; + +import { FileSectionType, FileSections_ListBasic } from "../../common/FileSectionType.js"; +import { RelocType } from "../../common/Relocation.js"; +import * as Utils from "../../common/Utils.js"; +import { hexU } from "../../py/pyutils.js"; +import { SymbolData } from "../symbols/MipsSymbolData.js"; +import { SectionBase } from "./MipsSectionBase.js"; + +export class RelocEntry { + constructor(entry) { + this.sectionId = entry >>> 30; + this.relocType = (entry >>> 24) & 0x3f; + this.offset = entry & 0x00ffffff; + } + + get reloc() { + return ((this.sectionId << 30) | (this.relocType << 24) | this.offset) >>> 0; + } + + getSectionType() { + return FileSectionType.fromId(this.sectionId); + } + + getRelocType() { + return RelocType.fromValue(this.relocType); + } + + toString() { + const section = this.getSectionType().toStr(); + let relocName = "None"; + const reloc = this.getRelocType(); + if (reloc !== null) relocName = reloc.name; + return `${section} ${relocName} 0x${hexU(this.offset)}`; + } +} + +export class SectionRelocZ64 extends SectionBase { + constructor(context, vromStart, vromEnd, vram, filename, array_of_bytes, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, vram, filename, Utils.bytesToWords(array_of_bytes, vromStart, vromEnd), FileSectionType.Reloc, segmentVromStart, overlayCategory); + + this.seekup = this.words.at(-1); + + this.setCommentOffset(this.sizew * 4 - this.seekup); + + // Remove non reloc stuff + const n = Math.floor(-this.seekup / 4); + this.words = n === 0 ? this.words.slice(0) : this.words.slice(n); + + this.sectionSizes = new Map([ + [FileSectionType.Text, this.words[0]], + [FileSectionType.Data, this.words[1]], + [FileSectionType.Rodata, this.words[2]], + [FileSectionType.Bss, this.words[3]], + ]); + this.relocCount = this.words[4]; + + this.tail = this.words.slice(this.relocCount + 5, -1); + + this.entries = []; + for (const word of this.words.slice(5, this.relocCount + 5)) this.entries.push(new RelocEntry(word)); + + this.differentSegment = false; + + this.sectionFlags = "a"; + this.enableStringGuessing = false; + } + + get nRelocs() { + return this.entries.length; + } + + get textSize() { + return this.sectionSizes.get(FileSectionType.Text); + } + + get dataSize() { + return this.sectionSizes.get(FileSectionType.Data); + } + + get rodataSize() { + return this.sectionSizes.get(FileSectionType.Rodata); + } + + get bssSize() { + return this.sectionSizes.get(FileSectionType.Bss); + } + + _makeSym(localOffset, vromLen, words, name) { + const currentVram = this.getVramOffset(localOffset); + const vrom = this.getVromOffset(localOffset); + const vromEnd = vrom + vromLen; + const sym = new SymbolData(this.context, vrom, vromEnd, localOffset + this.inFileOffset, currentVram, words, this.segmentVromStart, this.overlayCategory); + sym.contextSym.name = name; + sym.contextSym.userDeclaredType = "s32"; + sym.contextSym.allowedToReferenceSymbols = false; + sym.contextSym.allowedToBeReferenced = false; + sym.parent = this; + sym.setCommentOffset(this.commentOffset); + return sym; + } + + analyze() { + // The name may be a path, so we take the name of the file and discard everything else + const relocName = path.parse(this.name).name; + + let localOffset = 0; + + let sym = this._makeSym(localOffset, 4 * 4, this.words.slice(0, 4), `${relocName}_OverlayInfo`); + sym.endOfLineComment = new Map(FileSections_ListBasic.map((sectName, i) => [i, ` /* _${relocName}Segment${sectName.toCapitalizedStr()}Size */`])); + sym.analyze(); + this.symbolList.push(sym); + localOffset += 4 * 4; + + sym = this._makeSym(localOffset, 4, [this.relocCount], `${relocName}_RelocCount`); + sym.analyze(); + this.symbolList.push(sym); + localOffset += 4; + + sym = this._makeSym(localOffset, 4 * this.entries.length, this.entries.map((r) => r.reloc), `${relocName}_OverlayRelocations`); + sym.endOfLineComment = new Map(this.entries.map((r, i) => [i, ` /* ${r.toString()} */`])); + sym.analyze(); + this.symbolList.push(sym); + localOffset += 4 * this.entries.length; + + if (this.tail.length > 0) { + sym = this._makeSym(localOffset, 4 * this.tail.length, this.tail, `${relocName}_Padding`); + sym.analyze(); + this.symbolList.push(sym); + localOffset += 4 * this.tail.length; + } + + sym = this._makeSym(localOffset, 4, [this.seekup], `${relocName}_OverlayInfoOffset`); + sym.analyze(); + this.symbolList.push(sym); + + for (const s of this.symbolList) { + if (s.vram !== null) this.symbolsVRams.add(s.vram); + } + } +} diff --git a/packages/romdev-spimdisasm/src/mips/sections/MipsSectionRodata.js b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionRodata.js new file mode 100644 index 00000000..808acbec --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionRodata.js @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/sections/MipsSectionRodata.py + +import { rabbitizer } from "../../rabbitizer.js"; +import { GlobalConfig } from "../../common/GlobalConfig.js"; +import { FileSectionType } from "../../common/FileSectionType.js"; +import * as Utils from "../../common/Utils.js"; +import { sortedNumbers } from "../../py/pyutils.js"; +import { atLeast } from "../../version.js"; +import { SymbolRodata } from "../symbols/MipsSymbolRodata.js"; +import { SectionBase } from "./MipsSectionBase.js"; +import { sortPairs } from "./MipsSectionData.js"; + +export class SectionRodata extends SectionBase { + constructor(context, vromStart, vromEnd, vram, filename, array_of_bytes, segmentVromStart, overlayCategory) { + let words; + if (GlobalConfig.ENDIAN_RODATA !== null) words = Utils.endianessBytesToWords(GlobalConfig.ENDIAN_RODATA, array_of_bytes, vromStart, vromEnd); + else words = Utils.bytesToWords(array_of_bytes, vromStart, vromEnd); + super(context, vromStart, vromEnd, vram, filename, words, FileSectionType.Rodata, segmentVromStart, overlayCategory); + + this.stringEncoding = GlobalConfig.RODATA_STRING_ENCODING; + } + + /** Returns [jumpTableSym|null, firstJumptableWord] */ + _analyze_processJumptable(localOffset, w, contextSym, lastVramSymbol, jumpTableSym, firstJumptableWord) { + if (contextSym !== null && contextSym.isJumpTable()) { + // New jumptable + jumpTableSym = contextSym; + firstJumptableWord = w; + } else if (jumpTableSym !== null) { + // The last symbol found was part of a jumptable, check if this word still is part of the jumptable + if (!this.pointersOffsets.has(localOffset)) { + if (w === 0) { + return [null, firstJumptableWord]; + } else if (contextSym !== null) { + return [null, firstJumptableWord]; + } else if (((w >>> 24) & 0xff) !== ((firstJumptableWord >>> 24) & 0xff)) { + if (!(lastVramSymbol.isJumpTable() && lastVramSymbol.isGot && GlobalConfig.GP_VALUE !== null)) return [null, firstJumptableWord]; + } + } + } else { + // No jumptable + return [null, firstJumptableWord]; + } + + // Generate the current label + let labelAddr; + let labelVrom; + if (lastVramSymbol.isGot && GlobalConfig.GP_VALUE !== null) { + labelAddr = GlobalConfig.GP_VALUE + rabbitizer.Utils.from2Complement(w, 32); + labelVrom = null; + } else { + labelAddr = w; + const maybeVrom = this.vromStart + labelAddr - this.vram; + const segment = this.getSegmentForVrom(this.segmentVromStart); + if (!segment._isTheUnknownSegment && segment.isVromInRange(maybeVrom)) labelVrom = maybeVrom; + else labelVrom = null; + } + const labelSym = this.addJumpTableLabel(labelAddr, true, labelVrom); + + if (labelSym.unknownSegment) return [null, firstJumptableWord]; + + labelSym.referenceCounter += 1; + if (jumpTableSym.parentFunction !== null) { + labelSym.parentFunction = jumpTableSym.parentFunction; + labelSym.parentFileName = jumpTableSym.parentFunction.parentFileName; + jumpTableSym.parentFunction.branchLabels.add(labelSym.vram, labelSym); + } + + return [jumpTableSym, firstJumptableWord]; + } + + analyze() { + let lastVramSymbol = this._checkAndCreateFirstSymbol(); + + let symbolList = []; + let localOffset = 0; + const localOffsetsWithSymbols = new Set(); + + let needsFurtherAnalyzis = false; + + let jumpTableSym = null; + let firstJumptableWord = -1; + + const v142 = atLeast("1.42.0"); + const ownedSegment = v142 ? this.getSegment() : null; + + for (const w of this.words) { + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffset(localOffset); + + // Check if we have a symbol at this address, if not then use the last known one + let contextSym = this.getSymbol(currentVram, currentVrom, false); + if (contextSym !== null) lastVramSymbol = contextSym; + + [jumpTableSym, firstJumptableWord] = this._analyze_processJumptable(localOffset, w, contextSym, lastVramSymbol, jumpTableSym, firstJumptableWord); + + if (jumpTableSym === null) { + if (contextSym !== null || this.popPointerInDataReference(currentVram) !== null || (lastVramSymbol.isJumpTable() && w !== 0)) { + contextSym = this._addOwnedSymbol(localOffset); + if (contextSym !== null) lastVramSymbol = contextSym; + } + + this.checkWordIsASymbolReference(w); + } + + if (contextSym !== null) { + symbolList.push([localOffset, contextSym]); + localOffsetsWithSymbols.add(localOffset); + + this._createAutoPadFromSymbol(localOffset, contextSym); + } else if (jumpTableSym === null && this.popPointerInDataReference(currentVram) !== null) { + contextSym = this._addOwnedSymbol(localOffset); + if (contextSym !== null) { + symbolList.push([localOffset, contextSym]); + localOffsetsWithSymbols.add(localOffset); + } + } + + if (!lastVramSymbol.notPointerByType()) { + if (v142) { + if (!this.context.isAddressBanned(w)) { + if (this.checkWordIsASymbolReference(w)) { + if (w < currentVram && this.containsVram(w)) needsFurtherAnalyzis = true; + } + + if (!ownedSegment.isVramInRange(w)) { + const prioritizedSegment = this._findPrioritizedSegment(w, ownedSegment); + if (prioritizedSegment !== null) prioritizedSegment.addSymbol(w, undefined, true, null, true); + } + } + } else if (this.checkWordIsASymbolReference(w)) { + if (w < currentVram && this.containsVram(w)) needsFurtherAnalyzis = true; + } + } + + localOffset += 4; + } + + if (needsFurtherAnalyzis) { + localOffset = 0; + for (const _w of this.words) { + const currentVram = this.getVramOffset(localOffset); + + if (this.popPointerInDataReference(currentVram) !== null && !localOffsetsWithSymbols.has(localOffset)) { + const contextSym = this._addOwnedSymbol(localOffset); + if (contextSym !== null) { + symbolList.push([localOffset, contextSym]); + localOffsetsWithSymbols.add(localOffset); + } + } + + localOffset += 4; + } + + // Since we appended new symbols, this list is not sorted anymore + symbolList = sortPairs(symbolList); + } + + let previousSymbolWasLateRodata = false; + let previousSymbolExtraPadding = 0; + const compiler = GlobalConfig.COMPILER.value; + const sectionAlign_rodata = compiler.sectionAlign_rodata; + const rodataAlignment = sectionAlign_rodata !== null ? 2 ** sectionAlign_rodata : null; + + for (let i = 0; i < symbolList.length; i++) { + const [offset, contextSym] = symbolList[i]; + let words; + if (i + 1 === symbolList.length) { + words = this.words.slice(offset / 4); + } else { + const nextOffset = symbolList[i + 1][0]; + words = this.words.slice(offset / 4, nextOffset / 4); + } + + const vrom = this.getVromOffset(offset); + const vromEnd = vrom + words.length * 4; + const sym = new SymbolRodata(this.context, vrom, vromEnd, offset + this.inFileOffset, contextSym.vram, words, this.segmentVromStart, this.overlayCategory); + sym.parent = this; + sym.setCommentOffset(this.commentOffset); + sym.stringEncoding = this.stringEncoding; + sym.analyze(); + this.symbolList.push(sym); + this.symbolsVRams.add(contextSym.vram); + + if (rodataAlignment !== null) { + // Section boundaries detection + if ((this.vromStart + sym.inFileOffset) % rodataAlignment === 0) { + if (previousSymbolWasLateRodata && !sym.contextSym.isLateRodata()) { + // late rodata followed by normal rodata implies a file split + this.fileBoundaries.push(sym.inFileOffset); + } else if (previousSymbolExtraPadding > 0) { + if (sym.isDouble(0)) { + // doubles require a bit extra of alignment + if (previousSymbolExtraPadding >= 2) this.fileBoundaries.push(sym.inFileOffset); + } else if (sym.isJumpTable()) { + if (compiler.prevAlign_jumptable !== null && compiler.prevAlign_jumptable >= 3) { + if (previousSymbolExtraPadding >= 2) this.fileBoundaries.push(sym.inFileOffset); + } + } else if (sym.isString()) { + if (compiler.prevAlign_string !== null && compiler.prevAlign_string >= 3) { + if (previousSymbolExtraPadding >= 2) this.fileBoundaries.push(sym.inFileOffset); + } + } else { + this.fileBoundaries.push(sym.inFileOffset); + } + } + } + + previousSymbolWasLateRodata = sym.contextSym.isLateRodata(); + previousSymbolExtraPadding = sym.countExtraPadding(); + } + } + + this.processStaticRelocs(); + + // Filter out repeated values and sort + this.fileBoundaries = sortedNumbers(new Set(this.fileBoundaries)); + } + + removePointers() { + if (!GlobalConfig.REMOVE_POINTERS) return false; + + let was_updated = super.removePointers(); + for (let i = 0; i < this.sizew; i++) { + const top_byte = (this.words[i] >>> 24) & 0xff; + if (top_byte === 0x80) { + this.words[i] = (top_byte << 24) >>> 0; + was_updated = true; + } + if ((top_byte & 0xf0) === 0x00 && (top_byte & 0x0f) !== 0x00) { + this.words[i] = (top_byte << 24) >>> 0; + was_updated = true; + } + } + return was_updated; + } +} diff --git a/packages/romdev-spimdisasm/src/mips/sections/MipsSectionText.js b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionText.js new file mode 100644 index 00000000..ce5ca1ad --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/sections/MipsSectionText.js @@ -0,0 +1,472 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/sections/MipsSectionText.py + +import { rabbitizer } from "../../rabbitizer.js"; +import { GlobalConfig, ArchLevel } from "../../common/GlobalConfig.js"; +import { Compiler } from "../../common/CompilerConfig.js"; +import { FileSectionType } from "../../common/FileSectionType.js"; +import * as Utils from "../../common/Utils.js"; +import { sortedNumbers } from "../../py/pyutils.js"; +import { SymbolFunction } from "../symbols/MipsSymbolFunction.js"; +import { sameRabbitizerEnum } from "../symbols/analysis/InstrAnalyzer.js"; +import { SectionBase } from "./MipsSectionBase.js"; + +export class SectionText extends SectionBase { + constructor(context, vromStart, vromEnd, vram, filename, array_of_bytes, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, vram, filename, Utils.bytesToWords(array_of_bytes, vromStart, vromEnd), FileSectionType.Text, segmentVromStart, overlayCategory); + + this.instrCat = rabbitizer.InstrCategory.CPU; + this.detectRedundantFunctionEnd = null; + /** Get rid of `%gp_rel` and `$gp` since old assemblers don't support `%gp_rel`. */ + this.gpRelHack = false; + + this.enableStringGuessing = false; + } + + get nFuncs() { + return this.symbolList.length; + } + + static wordListToInstructions(wordList, currentVram, instrCat) { + const instrsList = []; + for (const word of wordList) { + const instr = new rabbitizer.Instruction(word, 0, instrCat); + if (currentVram !== null && currentVram !== undefined) { + instr.vram = currentVram; + currentVram += 4; + } + instrsList.push(instr); + } + return instrsList; + } + + wordListToInstructions(wordList, currentVram, instrCat) { + return SectionText.wordListToInstructions(wordList, currentVram, instrCat); + } + + _isRsp() { + return sameRabbitizerEnum(this.instrCat, rabbitizer.InstrCategory.RSP); + } + + getAsmPrelude_instructionDirectives() { + let output = ""; + output += `/* assembler directives */${GlobalConfig.LINE_ENDS}`; + output += `.set noat /* allow manual use of $at */${GlobalConfig.LINE_ENDS}`; + output += `.set noreorder /* do not insert nops after branches */${GlobalConfig.LINE_ENDS}`; + if (GlobalConfig.ARCHLEVEL.value >= ArchLevel.MIPS3.value) output += `.set gp=64 /* allow use of 64-bit general purpose registers */${GlobalConfig.LINE_ENDS}`; + output += GlobalConfig.LINE_ENDS; + return output; + } + + tryDetectRedundantFunctionEnd() { + if (GlobalConfig.COMPILER !== Compiler.IDO) return false; + if (this.detectRedundantFunctionEnd === null || this.detectRedundantFunctionEnd === undefined) return GlobalConfig.DETECT_REDUNDANT_FUNCTION_END; + return this.detectRedundantFunctionEnd; + } + + _findFunctions_branchChecker(instructionOffset, instr, funcsStartsList, unimplementedInstructionsFuncList, farthestBranch, isLikelyHandwritten, isInstrImplemented) { + let haltFunctionSearching = false; + + if (instr.isJumpWithAddress()) { + // If this instruction is a jump and it is jumping to a function then + // don't treat it as a branch, it is probably actually being used as + // a jump + const targetVram = instr.getInstrIndexAsVram(); + const auxSym = this.getSymbol(targetVram, null, false, true, false); + + if (auxSym !== null && auxSym.isTrustableFunction(this._isRsp())) return [farthestBranch, haltFunctionSearching]; + } + + if (instr.doesLink()) { + // This is used more as a function call than as an actual branch + return [farthestBranch, haltFunctionSearching]; + } + + const branchOffset = instr.getBranchOffsetGeneric(); + // keep track of the farthest branch target + farthestBranch = Math.max(farthestBranch, branchOffset); + if (branchOffset < 0) { + if (branchOffset + instructionOffset < 0) { + // Whatever we are reading is not a valid instruction + if (!instr.isJump()) haltFunctionSearching = true; + } + // make sure to not branch outside of the current function + if (!isLikelyHandwritten && isInstrImplemented) { + let j = funcsStartsList.length - 1; + while (j >= 0) { + if (branchOffset + instructionOffset < 0) break; + const otherFuncStartOffset = funcsStartsList[j] * 4; + if (branchOffset + instructionOffset < otherFuncStartOffset) { + const vram = this.getVramOffset(otherFuncStartOffset); + const vromAddress = this.getVromOffset(otherFuncStartOffset); + const funcSymbol = this.getSymbol(vram, vromAddress, false, true, false); + if (funcSymbol !== null && funcSymbol.isTrustableFunction(this._isRsp())) { + j -= 1; + continue; + } + funcsStartsList.splice(j, 1); + // Python: del unimplementedInstructionsFuncList[j-1] (j-1 may be -1) + let k = j - 1; + if (k < 0) k += unimplementedInstructionsFuncList.length; + if (k < 0 || k >= unimplementedInstructionsFuncList.length) throw new Error("IndexError: list assignment index out of range"); + unimplementedInstructionsFuncList.splice(k, 1); + } else { + break; + } + j -= 1; + } + } + } + return [farthestBranch, haltFunctionSearching]; + } + + _findFunctions_checkFunctionHalted(instructionOffset, currentVrom, currentVram, currentInstructionStart) { + if (instructionOffset === currentInstructionStart) { + // Check if we have a function after the first instruction of the current function. + const funcSymbol = this.getSymbol(currentVram + 4, currentVrom + 4, false, true, false); + if (funcSymbol !== null && funcSymbol.isTrustableFunction(this._isRsp())) { + if (funcSymbol.vromAddress === null || currentVrom + 4 === funcSymbol.vromAddress) return true; + } + } + return false; + } + + _findFunctions_checkFunctionEnded(instructionOffset, instr, index, currentVrom, currentVram, currentFunctionSym, farthestBranch, currentInstructionStart, isLikelyHandwritten, instrsList, nInstr) { + let functionEnded = false; + let prevFuncHadUserDeclaredSize = false; + let functionHalted = false; + + // Try to find the end of the function + if (currentFunctionSym !== null && currentFunctionSym.userDeclaredSize !== null) { + // If the function has a size set by the user then only use that and ignore the other ways of determining function-ends + if (instructionOffset + 8 === currentInstructionStart + currentFunctionSym.getSize()) { + functionEnded = true; + prevFuncHadUserDeclaredSize = true; + } + } else if (this._findFunctions_checkFunctionHalted(instructionOffset, currentVrom, currentVram, currentInstructionStart)) { + functionEnded = true; + functionHalted = true; + } else { + const funcSymbol = this.getSymbol(currentVram + 8, currentVrom + 8, false, true, false); + // If there's another function after this then the current function has ended + if (funcSymbol !== null && funcSymbol.isTrustableFunction(this._isRsp())) { + if (funcSymbol.vromAddress === null || currentVrom + 8 === funcSymbol.vromAddress) functionEnded = true; + } + + if (!functionEnded && !(farthestBranch > 0) && instr.isJump()) { + if (instr.isReturn()) { + // Found a jr $ra and there are no branches outside of this function + if (this.tryDetectRedundantFunctionEnd()) { + let redundantPatternDetected = false; + if (index + 3 < nInstr) { + const instr1 = instrsList[index + 1]; + const instr2 = instrsList[index + 2]; + const instr3 = instrsList[index + 3]; + if (funcSymbol === null && instr1.isNop() && instr2.isReturn() && instr3.isNop()) redundantPatternDetected = true; + } + if (!redundantPatternDetected) functionEnded = true; + } else { + functionEnded = true; + } + } else if (instr.isJumptableJump()) { + // Usually jumptables, ignore + } else if (!instr.doesLink()) { + if (isLikelyHandwritten || this._isRsp()) { + functionEnded = true; + } else if (instr.isJumpWithAddress()) { + // tail-call optimization + if (!rabbitizer.config.toolchainTweaks_treatJAsUnconditionalBranch) { + functionEnded = true; + } else { + const targetVram = instr.getInstrIndexAsVram(); + const auxSym = this.getSymbol(targetVram, null, false, true, false); + if (auxSym !== null && auxSym.isTrustableFunction(this._isRsp())) functionEnded = true; + } + } + } + } + } + + return [functionEnded, prevFuncHadUserDeclaredSize, functionHalted]; + } + + _findFunctions(instrsList) { + const nInstr = instrsList.length; + + if (nInstr === 0) return [[0], [false]]; + + let functionEnded = false; + let functionHalted = false; + let farthestBranch = 0; + const funcsStartsList = [0]; + const unimplementedInstructionsFuncList = []; + + let instructionOffset = 0; + let currentInstructionStart = 0; + let currentFunctionSym = this.getSymbol(this.getVramOffset(instructionOffset), this.getVromOffset(instructionOffset), false, true, false); + + let isLikelyHandwritten = this.isHandwritten; + + let isInstrImplemented = true; + let index = 0; + + if (instrsList[0].isNop()) { + // Loop over until we find a instruction that isn't a nop + while (index < nInstr) { + if (currentFunctionSym !== null) break; + + const instr = instrsList[index]; + if (!instr.isNop()) break; + index += 1; + instructionOffset += 4; + + currentInstructionStart = instructionOffset; + currentFunctionSym = this.getSymbol(this.getVramOffset(instructionOffset), this.getVromOffset(instructionOffset), false, true, false); + } + + if (index !== 0) { + funcsStartsList.push(index); + unimplementedInstructionsFuncList.push(!isInstrImplemented); + } + } + + let prevFuncHadUserDeclaredSize = false; + + while (index < nInstr) { + let instr = instrsList[index]; + if (!instr.isImplemented() || !instr.isValid()) isInstrImplemented = false; + + if (functionEnded) { + functionEnded = false; + + isLikelyHandwritten = this.isHandwritten; + if (!functionHalted) { + index += 1; + instructionOffset += 4; + } + functionHalted = false; + + let auxSym = this.getSymbol(this.getVramOffset(instructionOffset), this.getVromOffset(instructionOffset), false, true, false); + + // Loop over until we find a instruction that isn't a nop + while (index < nInstr) { + if (auxSym !== null) break; + + instr = instrsList[index]; + if (!instr.isNop()) break; + index += 1; + instructionOffset += 4; + + auxSym = this.getSymbol(this.getVramOffset(instructionOffset), this.getVromOffset(instructionOffset), false, true, false); + } + + currentInstructionStart = instructionOffset; + currentFunctionSym = auxSym; + + funcsStartsList.push(index); + unimplementedInstructionsFuncList.push(!isInstrImplemented); + if (index >= nInstr) break; + if (prevFuncHadUserDeclaredSize) { + auxSym = this.addFunction(this.getVramOffset(instructionOffset), true, this.getVromOffset(instructionOffset)); + auxSym.isAutocreatedSymFromOtherSizedSym = true; + } + prevFuncHadUserDeclaredSize = false; + instr = instrsList[index]; + isInstrImplemented = instr.isImplemented() && instr.isValid(); + } + + const currentVram = this.getVramOffset(instructionOffset); + const currentVrom = this.getVromOffset(instructionOffset); + + if (!this._isRsp() && !isLikelyHandwritten) isLikelyHandwritten = instr.isLikelyHandwritten(); + + if (instr.isBranch() || instr.isUnconditionalBranch()) { + let haltFunctionSearching; + [farthestBranch, haltFunctionSearching] = this._findFunctions_branchChecker(instructionOffset, instr, funcsStartsList, unimplementedInstructionsFuncList, farthestBranch, isLikelyHandwritten, isInstrImplemented); + if (haltFunctionSearching) break; + } + + [functionEnded, prevFuncHadUserDeclaredSize, functionHalted] = this._findFunctions_checkFunctionEnded(instructionOffset, instr, index, currentVrom, currentVram, currentFunctionSym, farthestBranch, currentInstructionStart, isLikelyHandwritten, instrsList, nInstr); + + index += 1; + farthestBranch -= 4; + instructionOffset += 4; + } + + unimplementedInstructionsFuncList.push(!isInstrImplemented); + return [funcsStartsList, unimplementedInstructionsFuncList]; + } + + _findCalls(instrsList) { + // A simple pass to gather function calls. + for (const instr of instrsList) { + if (instr.doesLink()) { + if (instr.isJumpWithAddress() || instr.isBranch()) { + const funcVram = instr.getBranchVramGeneric(); + this.addFunction(funcVram, true); + } + } + } + } + + analyze() { + const instrsList = this.wordListToInstructions(this.words, this.getVramOffset(0), this.instrCat); + const nInstr = instrsList.length; + + this._findCalls(instrsList); + const [funcsStartsList, unimplementedInstructionsFuncList] = this._findFunctions(instrsList); + + let previousSymbolExtraPadding = 0; + const sectionAlign_text = GlobalConfig.COMPILER.value.sectionAlign_text; + const textAlignment = sectionAlign_text !== null ? 2 ** sectionAlign_text : null; + + const startsCount = funcsStartsList.length; + for (let startIndex = 0; startIndex < startsCount; startIndex++) { + const start = funcsStartsList[startIndex]; + const hasUnimplementedIntrs = unimplementedInstructionsFuncList[startIndex]; + let end = nInstr; + if (startIndex + 1 < startsCount) end = funcsStartsList[startIndex + 1]; + + if (start >= end) break; + + const localOffset = start * 4; + const vram = this.getVramOffset(localOffset); + + const vrom = this.getVromOffset(localOffset); + const vromEnd = vrom + (end - start) * 4; + + if (GlobalConfig.DISASSEMBLE_UNKNOWN_INSTRUCTIONS || !hasUnimplementedIntrs) this.addFunction(vram, true, vrom); + else this.addSymbol(vram, this.sectionType, true, vrom); + + this.symbolsVRams.add(vram); + + const func = new SymbolFunction(this.context, vrom, vromEnd, this.inFileOffset + localOffset, vram, instrsList.slice(start, end), this.segmentVromStart, this.overlayCategory); + func.setCommentOffset(this.commentOffset); + func.index = startIndex; + func.pointersOffsets.update(this.pointersOffsets); + func.hasUnimplementedIntrs = hasUnimplementedIntrs; + func.parent = this; + func.isRsp = this._isRsp(); + func.gpRelHack = this.gpRelHack; + func.analyze(); + this.symbolList.push(func); + + if (textAlignment !== null) { + // Section boundaries detection + if ((this.vromStart + func.inFileOffset) % textAlignment === 0 && previousSymbolExtraPadding > 0) { + this.fileBoundaries.push(func.inFileOffset); + } + previousSymbolExtraPadding = func.countExtraPadding(); + } + } + + // Filter out repeated values and sort + this.fileBoundaries = sortedNumbers(new Set(this.fileBoundaries)); + } + + compareToFile(other) { + const result = super.compareToFile(other); + if (other instanceof SectionText) { + result.text = { + diff_opcode: this.countDiffOpcodes(other), + same_opcode_same_args: this.countSameOpcodeButDifferentArguments(other), + }; + } + return result; + } + + countDiffOpcodes(other) { + let result = 0; + for (let i = 0; i < Math.min(this.nFuncs, other.nFuncs); i++) result += this.symbolList[i].countDiffOpcodes(other.symbolList[i]); + return result; + } + + countSameOpcodeButDifferentArguments(other) { + let result = 0; + for (let i = 0; i < Math.min(this.nFuncs, other.nFuncs); i++) result += this.symbolList[i].countSameOpcodeButDifferentArguments(other.symbolList[i]); + return result; + } + + blankOutDifferences(other_file) { + if (!GlobalConfig.REMOVE_POINTERS) return false; + if (!(other_file instanceof SectionText)) return false; + + let was_updated = false; + for (let i = 0; i < Math.min(this.nFuncs, other_file.nFuncs); i++) { + const func = this.symbolList[i]; + const other_func = other_file.symbolList[i]; + const func_updated = func.blankOutDifferences(other_func); + if (func_updated) { + let localOffset = func.inFileOffset - this.inFileOffset; + func.instructions.forEach((instr, wordOffset) => { + this.words[localOffset / 4 + wordOffset] = instr.getRaw(); + }); + localOffset = other_func.inFileOffset - other_file.inFileOffset; + other_func.instructions.forEach((instr, wordOffset) => { + other_file.words[localOffset / 4 + wordOffset] = instr.getRaw(); + }); + } + was_updated = func_updated || was_updated; + } + return was_updated; + } + + removePointers() { + if (!GlobalConfig.REMOVE_POINTERS) return false; + + let was_updated = false; + for (const func of this.symbolList) { + const func_updated = func.removePointers(); + if (func_updated) { + const localOffset = func.inFileOffset - this.inFileOffset; + func.instructions.forEach((instr, wordOffset) => { + this.words[localOffset / 4 + wordOffset] = instr.getRaw(); + }); + } + was_updated = func_updated || was_updated; + } + return was_updated; + } + + removeTrailingNops() { + let was_updated = false; + if (this.nFuncs > 0) { + const func = this.symbolList.at(-1); + func.removeTrailingNops(); + was_updated = true; + } + return was_updated; + } + + getGpRelHack() { + return this.gpRelHack; + } + + setGpRelHack(value) { + this.gpRelHack = value; + for (const func of this.symbolList) func.gpRelHack = value; + } + + suspectedPaddingGarbage() { + const garbage = []; + + const sectionAlign_text = GlobalConfig.COMPILER.value.sectionAlign_text; + const textAlignment = sectionAlign_text !== null ? 2 ** sectionAlign_text : null; + if (textAlignment === null) return garbage; + + for (const func of this.symbolList) { + if (func.sizew * 4 >= textAlignment) continue; + if ((func.vram + func.sizew * 4) % textAlignment !== 0) continue; + if (func.contextSym.referenceCounter !== 0) continue; + + if (func.sizew >= 2) { + const instr = func.instructions.at(-2); + if (instr.isJump() || instr.isBranch()) continue; + } + + garbage.push(func.inFileOffset + func.sizew * 4); + } + + return garbage; + } +} diff --git a/packages/romdev-spimdisasm/src/mips/sections/index.js b/packages/romdev-spimdisasm/src/mips/sections/index.js new file mode 100644 index 00000000..b25e1848 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/sections/index.js @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/sections/__init__.py + +export { SectionBase } from "./MipsSectionBase.js"; +export { SectionText } from "./MipsSectionText.js"; +export { SectionData } from "./MipsSectionData.js"; +export { SectionRodata } from "./MipsSectionRodata.js"; +export { SectionBss } from "./MipsSectionBss.js"; +export { SectionRelocZ64, RelocEntry } from "./MipsSectionRelocZ64.js"; +export { SectionGccExceptTable } from "./MipsSectionGccExceptTable.js"; diff --git a/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolBase.js b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolBase.js new file mode 100644 index 00000000..14e5dc42 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolBase.js @@ -0,0 +1,834 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/MipsSymbolBase.py + +import { rabbitizer } from "../../rabbitizer.js"; +import { ElementBase } from "../../common/ElementBase.js"; +import { GlobalConfig, InputEndian } from "../../common/GlobalConfig.js"; +import { FileSectionType } from "../../common/FileSectionType.js"; +import { SymbolSpecialType, isSymbolSpecialType } from "../../common/ContextSymbols.js"; +import * as Utils from "../../common/Utils.js"; +import { newIntSet } from "../../common/symset.js"; +import { formatG } from "../../py/pyfloat.js"; +import { hexU, pyStr } from "../../py/pyutils.js"; +import { atLeast } from "../../version.js"; + +export class SymbolBase extends ElementBase { + constructor(context, vromStart, vromEnd, inFileOffset, vram, words, sectionType, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, inFileOffset, vram, "", words, sectionType, segmentVromStart, overlayCategory); + + /** offset in words */ + this.endOfLineComment = new Map(); + + this.contextSym = this.addSymbol(this.vram, this.sectionType, true); + this.contextSym.vromAddress = this.vromStart; + this.contextSym.isDefined = true; + this.contextSym.sectionType = this.sectionType; + + this.stringEncoding = GlobalConfig.DATA_STRING_ENCODING; + + /** key: word offset */ + this.relocs = new Map(); + + /** Every referenced vram found */ + this.referencedVrams = newIntSet(); + + if (atLeast("1.42.0")) { + // Void the autodetected symbol type if it is a branch target, but the + // symbol isn't part of a text section. + if (this.sectionType !== FileSectionType.Text) { + const symType = this.contextSym.autodetectedType; + if (isSymbolSpecialType(symType)) { + if (symType.isTargetLabel()) this.contextSym.autodetectedType = null; + } + } + } + } + + getNameUnquoted() { + return this.contextSym.getNameUnquoted(); + } + + getName() { + return this.contextSym.getName(); + } + + getNameEnd() { + return this.contextSym.getNameEnd(); + } + + setNameIfUnset(name) { + this.contextSym.setNameIfUnset(name); + } + + setNameGetCallback(callback) { + this.contextSym.setNameGetCallback(callback); + } + + setNameGetCallbackIfUnset(callback) { + this.contextSym.setNameGetCallbackIfUnset(callback); + } + + canUseAddendsOnData() { + if (this.contextSym.notAllowedToReferenceAddends) return false; + if (GlobalConfig.ALLOW_ALL_ADDENDS_ON_DATA) return true; + return this.contextSym.allowedToReferenceAddends; + } + + canUseConstantsOnData() { + if (this.contextSym.notAllowedToReferenceConstants) return false; + if (GlobalConfig.ALLOW_ALL_CONSTANTS_ON_DATA) return true; + return this.contextSym.allowedToReferenceConstants; + } + + /** (localOffset, wordValue=None, isDouble=False, emitRomOffset=True); wordValue may be a bigint when isDouble */ + generateAsmLineComment(localOffset, wordValue = null, isDouble = false, emitRomOffset = true) { + const indentation = " ".repeat(GlobalConfig.ASM_INDENTATION); + + if (!GlobalConfig.ASM_COMMENT) return indentation; + + let offsetHex; + if (emitRomOffset) offsetHex = `${hexU(localOffset + this.inFileOffset + this.commentOffset, GlobalConfig.ASM_COMMENT_OFFSET_WIDTH)} `; + else offsetHex = ""; + + const currentVram = this.getVramOffset(localOffset); + const vramHex = hexU(currentVram, 8); + + let wordValueHex = ""; + if (wordValue !== null && wordValue !== undefined) { + if (isDouble) wordValueHex = `${hexU(Utils.qwordToCurrenEndian(wordValue), 16)} `; + else wordValueHex = `${hexU(Utils.wordToCurrenEndian(wordValue), 8)} `; + } + + return `${indentation}/* ${offsetHex}${vramHex} ${wordValueHex}*/`; + } + + generateBytesComment(rawData) { + if (!GlobalConfig.ASM_COMMENT) return ""; + + const indentation = " ".repeat(GlobalConfig.ASM_INDENTATION); + let comment = `${indentation}/* `; + for (const byte of rawData) comment += hexU(byte, 2); + comment += ` */${GlobalConfig.LINE_ENDS}`; + return comment; + } + + getSymbolAsmDeclaration(symName, useGlobalLabel = true) { + if (!useGlobalLabel) return `${symName}:` + GlobalConfig.LINE_ENDS; + + let output = ""; + output += this.getLabelFromSymbol(this.contextSym, symName); + if (this.sectionType === FileSectionType.Text) { + if (GlobalConfig.ASM_TEXT_ENT_LABEL) output += `${GlobalConfig.ASM_TEXT_ENT_LABEL} ${symName}${GlobalConfig.LINE_ENDS}`; + if (GlobalConfig.ASM_TEXT_FUNC_AS_LABEL) output += `${symName}:${GlobalConfig.LINE_ENDS}`; + } else if (GlobalConfig.ASM_DATA_SYM_AS_LABEL) { + output += `${symName}:${GlobalConfig.LINE_ENDS}`; + } + return output; + } + + getExtraLabelFromSymbol(contextSym) { + let label = ""; + if (contextSym !== null && contextSym !== undefined) { + label = GlobalConfig.LINE_ENDS; + const symLabel = contextSym.getLabelMacro(true); + if (symLabel !== null) { + const symName = contextSym.getName(); + if (atLeast("1.39.0")) label += this.getNonMatchingLabel(symName, null); + label += `${symLabel} ${symName}${GlobalConfig.LINE_ENDS}`; + if (GlobalConfig.ASM_DATA_SYM_AS_LABEL) label += `${symName}:` + GlobalConfig.LINE_ENDS; + } + } + return label; + } + + getReloc(wordOffset) { + let relocInfo = this.context.globalRelocationOverrides.get(this.getVromOffset(wordOffset)); + if (relocInfo === undefined) relocInfo = this.relocs.get(wordOffset); + return relocInfo === undefined ? null : relocInfo; + } + + relocToInlineStr(relocInfo, isSplittedSymbol = false) { + if (relocInfo === null || relocInfo === undefined) return ""; + return relocInfo.getInlineStr(isSplittedSymbol); + } + + getSizeDirective(symName) { + if (GlobalConfig.ASM_EMIT_SIZE_DIRECTIVE) return `.size ${symName}, . - ${symName}${GlobalConfig.LINE_ENDS}`; + return ""; + } + + getNonMatchingLabel(symName, symSize) { + if (!atLeast("1.39.0")) return ""; + const nmLabel = GlobalConfig.ASM_NM_LABEL; + const perSym = atLeast("1.42.0") ? this.contextSym.useNonMatchingLabel : true; + if (nmLabel && perSym) { + const out = `${nmLabel} ${symName}`; + let sizePart; + if (symSize !== null && symSize !== undefined) { + symSize = Math.max(symSize, 1); + sizePart = `, 0x${hexU(symSize)}`; + } else { + sizePart = ""; + } + // We need an empty line between the nonmatching marker and the actual + // label to avoid triggering the KMC compiler to emit an extra nop as + // part of the function. + return `${out}${sizePart}${GlobalConfig.LINE_ENDS}${GlobalConfig.LINE_ENDS}`; + } + return ""; + } + + isFunction() { + return false; + } + + isByte(_index) { + if (this.isString() || this.isPascalString()) return false; + return this.contextSym.isByte(); + } + + isShort(_index) { + return this.contextSym.isShort(); + } + + isString() { + if (this.contextSym.isPascalString()) return false; + return this.contextSym.isString(); + } + + isPascalString() { + if (this.contextSym.isString()) return false; + return this.contextSym.isPascalString(); + } + + isFloat(index) { + if (this.contextSym.isFloat()) { + if (index >= this.words.length) return false; + const word = this.words[index]; + // Filter out NaN and infinity + if ((word & 0x7f800000) !== 0x7f800000) return true; + } + return false; + } + + isDouble(index) { + if (index % 2 !== 0) return false; + + if (this.contextSym.isDouble()) { + if (index + 1 < this.words.length) { + const word0 = this.words[index]; + // Filter out NaN and infinity (only the upper word matters for the exponent mask) + if ((word0 & 0x7ff00000) !== 0x7ff00000) { + // Prevent accidentally losing symbols + const currentVram = this.getVramOffset(index * 4); + const currentVrom = this.getVromOffset(index * 4); + if (this.getSymbol(currentVram + 4, currentVrom, false) === null) return true; + } + } + } + return false; + } + + isJumpTable() { + return false; + } + + /** @deprecated */ + isRdata() { + return false; + } + + shouldMigrate() { + return false; + } + + analyze() { + this.contextSym.inFileOffset = this.inFileOffset; + if (this.parent !== null) this.contextSym.parentFileName = this.parent.getName(); + + const isWordSized = !this.contextSym.isByte() && !this.contextSym.isShort(); + + if (this.sectionType !== FileSectionType.Bss) { + for (let i = 0; i < this.sizew; i++) { + const localOffset = 4 * i; + for (let j = 0; j < 4; j++) { + if (i === 0 && j === 0) continue; + + // Possible symbols in the middle of words + const currentVram = this.getVramOffset(localOffset + j); + const currentVrom = this.getVromOffset(localOffset + j); + const contextSym = this.getSymbol(currentVram, currentVrom, false); + if (contextSym !== null) { + contextSym.vromAddress = this.getVromOffset(localOffset + j); + contextSym.isDefined = true; + contextSym.sectionType = this.sectionType; + contextSym.setTypeIfUnset(this.contextSym.getTypeSpecial(), this.contextSym.isAutogenerated); + contextSym.inFileOffset = this.inFileOffset + localOffset + j; + if (this.parent !== null) contextSym.parentFileName = this.parent.getName(); + } + } + + if (isWordSized) { + const word = this.words[i]; + const referencedSym = this.getSymbol(word, null, false); + if (referencedSym !== null) { + if (!referencedSym.isJumpTable()) referencedSym.referenceSymbols.add(this.contextSym); + this.referencedVrams.add(referencedSym.vram); + } + } + } + } + } + + getEndOfLineComment(wordIndex) { + if (!GlobalConfig.ASM_COMMENT) return ""; + return this.endOfLineComment.has(wordIndex) ? this.endOfLineComment.get(wordIndex) : ""; + } + + getJByteAsByte(i, j) { + const localOffset = 4 * i; + const w = this.words[i]; + + const dotType = ".byte"; + + let shiftValue = j * 8; + if (GlobalConfig.ENDIAN === InputEndian.BIG) shiftValue = 24 - shiftValue; + const subVal = (w >>> shiftValue) & 0xff; + const value = `0x${hexU(subVal, 2)}`; + + const comment = this.generateAsmLineComment(localOffset + j); + return `${comment} ${dotType} ${value}`; + } + + getJByteAsShort(i, j) { + const localOffset = 4 * i; + const w = this.words[i]; + + const dotType = ".short"; + + let shiftValue = j * 8; + if (GlobalConfig.ENDIAN === InputEndian.BIG) shiftValue = 16 - shiftValue; + // Python: (w & (0xFFFF << shiftValue)) >> shiftValue; for shift 24 (little endian j=3) the mask exceeds 32 bits. + const subVal = Number((BigInt(w) & (0xffffn << BigInt(shiftValue))) >> BigInt(shiftValue)); + const value = `0x${hexU(subVal, 4)}`; + + const comment = this.generateAsmLineComment(localOffset + j); + return `${comment} ${dotType} ${value}`; + } + + getNthWordAsBytesAndShorts(i, sym1, sym2, sym3, lastSymName, symSize = null) { + const v139 = atLeast("1.39.0"); + let output = ""; + + if (sym1 !== null || this.isByte(i) || (!this.isShort(i) && sym3 !== null)) { + output += this.getJByteAsByte(i, 0); + output += GlobalConfig.LINE_ENDS; + + if (v139) { + if (sym1 !== null || i * 4 + 1 === symSize) { + output += this._getSymEnd(lastSymName); + if (sym1 !== null) lastSymName = sym1.getName(); + } + } else if (sym1 !== null) { + output += this.getSizeDirective(lastSymName); + lastSymName = sym1.getName(); + } + + output += this.getExtraLabelFromSymbol(sym1); + output += this.getJByteAsByte(i, 1); + output += GlobalConfig.LINE_ENDS; + } else { + output += this.getJByteAsShort(i, 0); + output += GlobalConfig.LINE_ENDS; + } + + if (v139) { + if (sym2 !== null || i * 4 + 2 === symSize) { + output += this._getSymEnd(lastSymName); + if (sym2 !== null) lastSymName = sym2.getName(); + } + } else if (sym2 !== null) { + output += this.getSizeDirective(lastSymName); + lastSymName = sym2.getName(); + } + + output += this.getExtraLabelFromSymbol(sym2); + if (sym3 !== null || (sym2 !== null && sym2.isByte()) || (this.isByte(i) && (sym2 === null || !sym2.isShort()))) { + output += this.getJByteAsByte(i, 2); + output += GlobalConfig.LINE_ENDS; + + if (v139) { + if (sym3 !== null || i * 4 + 3 === symSize) { + output += this._getSymEnd(lastSymName); + if (sym3 !== null) lastSymName = sym3.getName(); + } + } else if (sym3 !== null) { + output += this.getSizeDirective(lastSymName); + lastSymName = sym3.getName(); + } + + output += this.getExtraLabelFromSymbol(sym3); + output += this.getJByteAsByte(i, 3); + output += GlobalConfig.LINE_ENDS; + } else { + output += this.getJByteAsShort(i, 2); + output += GlobalConfig.LINE_ENDS; + } + + return [output, 0]; + } + + _allowWordSymbolReference(symbolRef, word) { + if (symbolRef.isElfNotype) return false; + if (symbolRef.vram < 0) return false; + if (!this.contextSym.allowedToReferenceSymbols) return false; + if (!symbolRef.allowedToBeReferenced) return false; + + const symType = symbolRef.getTypeSpecial(); + if (isSymbolSpecialType(symType)) { + if (symType === SymbolSpecialType.function) { + if (word !== symbolRef.vram) return false; + } + if (symType === SymbolSpecialType.branchlabel) return false; + if (symType === SymbolSpecialType.jumptable) return false; + if (symType.isTargetLabel()) { + if (word !== symbolRef.vram) return false; + if (!this.contextSym.isJumpTable() && !this.contextSym.isGccExceptTable()) return false; + } + } + return true; + } + + getNthWordAsWords(i, relocInfo, canReferenceSymbolsWithAddends = false, canReferenceConstants = false, isSplittedSymbol = false) { + let output = ""; + const localOffset = 4 * i; + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffset(localOffset); + const w = this.words[i]; + + let dotType = ".word"; + + let label = ""; + if (i !== 0) label = this.getExtraLabelFromSymbol(this.getSymbol(currentVram, currentVrom, false)); + + let value = `0x${hexU(w, 8)}`; + + if (relocInfo === undefined) relocInfo = this.getReloc(localOffset); + const v142 = atLeast("1.42.0"); + + // .elf relocated symbol + if (relocInfo !== null) { + if (relocInfo.isRelocNone()) { + // If the reloc type is none then use the raw number instead + } else if (relocInfo.staticReference !== null) { + const relocVram = relocInfo.staticReference.sectionVram + w; + const contextSym = this.getSymbol(relocVram, null, true, false); + if (contextSym !== null) { + const wordRel = relocInfo.relocType.getWordRel(); + if (!v142) value = contextSym.getSymbolPlusOffset(relocVram); + if (wordRel !== null) { + dotType = wordRel; + if (v142) value = contextSym.getSymbolPlusOffset(relocVram); + } + } + } else { + if (!v142) value = relocInfo.getName(isSplittedSymbol); + const wordRel = relocInfo.relocType.getWordRel(); + if (wordRel !== null) { + dotType = wordRel; + if (v142) value = relocInfo.getName(isSplittedSymbol); + } + } + } else if (this.contextSym.isJumpTable()) { + let labelSym; + if (this.contextSym.isGot && GlobalConfig.GP_VALUE !== null) { + const labelAddr = GlobalConfig.GP_VALUE + rabbitizer.Utils.from2Complement(w, 32); + labelSym = this.getSymbol(labelAddr, null, false); + if (labelSym !== null) { + const labelType = labelSym.getTypeSpecial(); + if (labelType === SymbolSpecialType.jumptablelabel || labelType === SymbolSpecialType.function) dotType = ".gpword"; + } + } else { + labelSym = this.getSymbol(w, null, false); + } + + if (labelSym !== null) { + const labelType = labelSym.getTypeSpecial(); + if (labelType === SymbolSpecialType.jumptablelabel || labelType === SymbolSpecialType.function) { + // We check for function references too because this symbol may have gotten wrongly identified as a jumptable because of tail call optimizations. + value = labelSym.getName(); + } + } + } else { + // This word could be a reference to a symbol + if (!this.context.isAddressBanned(w)) { + const symbolRef = this.getSymbol(w, null, canReferenceSymbolsWithAddends); + if (symbolRef !== null && !this.context.isAddressBanned(symbolRef.vram)) { + if (this._allowWordSymbolReference(symbolRef, w)) value = symbolRef.getSymbolPlusOffset(w); + } else if (canReferenceConstants) { + const constant = this.getConstant(w); + if (constant !== null) value = constant.getName(); + } + } + } + + const comment = this.generateAsmLineComment(localOffset, w); + output += `${label}${comment} ${dotType} ${value}`; + output += this.getEndOfLineComment(i); + output += GlobalConfig.LINE_ENDS; + + return [output, 0]; + } + + getNthWordAsFloat(i) { + let output = ""; + const localOffset = 4 * i; + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffset(localOffset); + const w = this.words[i]; + + let label = ""; + if (i !== 0) label = this.getExtraLabelFromSymbol(this.getSymbol(currentVram, currentVrom, false)); + + const dotType = ".float"; + const floatValue = Utils.wordToFloat(w); + const value = formatG(floatValue, 10); + + const comment = this.generateAsmLineComment(localOffset, w); + output += `${label}${comment} ${dotType} ${value}`; + output += this.getEndOfLineComment(i); + output += GlobalConfig.LINE_ENDS; + + return [output, 0]; + } + + getNthWordAsDouble(i) { + let output = ""; + const localOffset = 4 * i; + const currentVram = this.getVramOffset(localOffset); + const currentVrom = this.getVromOffset(localOffset); + const w = this.words[i]; + + let label = ""; + if (i !== 0) label = this.getExtraLabelFromSymbol(this.getSymbol(currentVram, currentVrom, false)); + + const dotType = ".double"; + const otherHalf = this.words[i + 1]; + let doubleWord; + if (GlobalConfig.ENDIAN === InputEndian.LITTLE) doubleWord = (BigInt(otherHalf) << 32n) | BigInt(w); + else doubleWord = (BigInt(w) << 32n) | BigInt(otherHalf); + const doubleValue = Utils.qwordToDouble(doubleWord); + const value = formatG(doubleValue, 18); + + const comment = this.generateAsmLineComment(localOffset, doubleWord, true); + output += `${label}${comment} ${dotType} ${value}`; + output += this.getEndOfLineComment(i); + output += GlobalConfig.LINE_ENDS; + + return [output, 1]; + } + + /** Returns [result, skip, symSize] (the 1.35 variant never touches symSize). */ + getNthWordAsString(i, lastSymName = null, symSize = null) { + const localOffset = 4 * i; + + const buffer = Utils.wordsToBytes(this.words); + const [decodedStrings, rawStringSize] = Utils.decodeBytesToStrings(buffer, localOffset, this.stringEncoding); + if (rawStringSize < 0) return ["", -1, symSize]; + + const skip = Math.floor(rawStringSize / 4); + const comment = this.generateAsmLineComment(localOffset); + let result = `${comment} `; + + let commentPaddingNum = 22; + if (!GlobalConfig.ASM_COMMENT) commentPaddingNum = 1; + + if (rawStringSize === 0) decodedStrings.push(""); + for (const decodedValue of decodedStrings.slice(0, -1)) { + result += `.ascii "${decodedValue}"`; + result += GlobalConfig.LINE_ENDS + " ".repeat(commentPaddingNum); + } + result += `.asciz "${decodedStrings.at(-1)}"${GlobalConfig.LINE_ENDS}`; + + const alignedStrSize = (skip + 1) * 4; + const subBuffer = buffer.subarray(localOffset, localOffset + alignedStrSize); + result += this.generateBytesComment(subBuffer); + + if (atLeast("1.39.0")) { + if (symSize !== null && symSize > 0 && alignedStrSize >= symSize) { + // Users may use sizes that are not multiple of four, because + // strings may be smaller than a multiple of four and padded, which + // padding the user may not consider part of the size of the string. + result += this._getSymEnd(lastSymName); + // Make it -1 to to avoid emitting the enddlabel more than once + symSize = -1; + } + } + + return [result, skip, symSize]; + } + + getNthWordAsPascalString(i) { + const localOffset = 4 * i; + + const buffer = Utils.wordsToBytes(this.words); + const [decodedStrings, rawStringSize] = Utils.decodeBytesToPascalStrings(buffer, localOffset, this.stringEncoding, 0x20); + if (rawStringSize < 0) return ["", -1]; + + const skip = Math.floor((rawStringSize - 1) / 4); + const comment = this.generateAsmLineComment(localOffset); + let result = `${comment} `; + + let commentPaddingNum = 22; + if (!GlobalConfig.ASM_COMMENT) commentPaddingNum = 1; + + if (rawStringSize === 0) decodedStrings.push(""); + for (const decodedValue of decodedStrings.slice(0, -1)) { + result += `.ascii "${decodedValue}"`; + result += GlobalConfig.LINE_ENDS + " ".repeat(commentPaddingNum); + } + result += `.ascii "${decodedStrings.at(-1)}"${GlobalConfig.LINE_ENDS}`; + + const alignedStrSize = (skip + 1) * 4; + const subBuffer = buffer.subarray(localOffset, localOffset + alignedStrSize); + result += this.generateBytesComment(subBuffer); + + return [result, skip]; + } + + getNthWord(i, relocInfo, canReferenceSymbolsWithAddends = false, canReferenceConstants = false, isSplittedSymbol = false) { + return this.getNthWordAsWords(i, relocInfo, canReferenceSymbolsWithAddends, canReferenceConstants, isSplittedSymbol); + } + + /** Returns how many extra word paddings this symbol has */ + countExtraPadding() { + return 0; + } + + _getAlignDirectiveStr(shiftValue, i) { + const shiftedVal = 2 ** shiftValue; + + if (this.parent === null) return ""; + + if (GlobalConfig.SYMBOL_ALIGNMENT_REQUIRES_ALIGNED_SECTION) { + if (this.parent.vram % shiftedVal !== 0) return ""; + if (this.getVramOffset(i * 4) % shiftedVal !== 0) return ""; + } else { + const subRam = this.getVramOffset(i * 4) - this.parent.vram; + if (((subRam % shiftedVal) + shiftedVal) % shiftedVal !== 0) return ""; + } + + return `.align ${shiftValue}${GlobalConfig.LINE_ENDS}`; + } + + getPrevAlignDirective(i) { + const symAlignmentShift = this.contextSym.alignmentShift; + const compiler = GlobalConfig.COMPILER.value; + + if (symAlignmentShift !== null) { + return this._getAlignDirectiveStr(symAlignmentShift, i); + } else if (this.isDouble(i)) { + if (i === 0 || !atLeast("1.39.0")) { + const shiftValue = compiler.prevAlign_double; + if (shiftValue !== null) return this._getAlignDirectiveStr(shiftValue, i); + } + } else if (this.isJumpTable()) { + if (i === 0) { + const shiftValue = compiler.prevAlign_jumptable; + if (shiftValue !== null) return this._getAlignDirectiveStr(shiftValue, i); + } + } else if (this.isString() || this.isPascalString()) { + const shiftValue = compiler.prevAlign_string; + if (shiftValue !== null) return this._getAlignDirectiveStr(shiftValue, i); + } else if (this.isFunction()) { + const shiftValue = compiler.prevAlign_function; + if (shiftValue !== null) return this._getAlignDirectiveStr(shiftValue, i); + } + + return ""; + } + + getPostAlignDirective(i) { + if (this.isString() || this.isPascalString()) return this._getAlignDirectiveStr(2, i); + return ""; + } + + _getSymEnd(lastSymName) { + let output = ""; + if (GlobalConfig.ASM_DATA_END_LABEL) output += `${GlobalConfig.ASM_DATA_END_LABEL} ${lastSymName}${GlobalConfig.LINE_ENDS}`; + output += this.getSizeDirective(lastSymName); + return output; + } + + disassembleAsData(useGlobalLabel = true, isSplittedSymbol = false) { + if (!atLeast("1.39.0")) return this._disassembleAsData135(useGlobalLabel, isSplittedSymbol); + + let output = this.contextSym.getReferenceeSymbols(); + output += this.getPrevAlignDirective(0); + + const symName = this.getName(); + output += this.getNonMatchingLabel(symName, null); + output += this.getSymbolAsmDeclaration(symName, useGlobalLabel); + + let lastSymName = symName; + + const canReferenceSymbolsWithAddends = this.canUseAddendsOnData(); + const canReferenceConstants = this.canUseConstantsOnData(); + + let symSize = this.contextSym.userDeclaredSize; + + if (symSize !== null && symSize % 4 !== 0 && this.contextSym.userDeclaredType !== null) { + const warningMsg = ` +Warning: Symbol '${symName}' (0x${hexU(this.vram, 8)}) was given a size '0x${hexU(symSize)}' that is not a multiple of its given type '${pyStr(this.contextSym.userDeclaredType)}' +This may produce inconsistency issues like end labels not being emitted. +You are highly encouraged to fix it. +This may be changed to a hard error in the future. +`; + if (symSize % 2 !== 0) { + if (!this.isByte(0)) Utils.eprint(warningMsg); + } else if (!this.isByte(0) && !this.isShort(0)) { + Utils.eprint(warningMsg); + } + } + + let i = 0; + while (i < this.sizew) { + const currentVram = this.getVramOffset(i * 4); + const currentVrom = this.getVromOffset(i * 4); + const relocInfo = this.getReloc(i * 4); + + const sym1 = this.getSymbol(currentVram + 1, currentVrom, false, true, false); + const sym2 = this.getSymbol(currentVram + 2, currentVrom, false, true, false); + const sym3 = this.getSymbol(currentVram + 3, currentVrom, false, true, false); + + let data; + let skip; + if (relocInfo !== null) { + // If there is any user provided reloc info then we use that instead of anything else. + [data, skip] = this.getNthWord(i, relocInfo, canReferenceSymbolsWithAddends, canReferenceConstants, isSplittedSymbol); + } else if (sym1 !== null || sym2 !== null || sym3 !== null || this.isByte(i) || this.isShort(i)) { + // Check for symbols in the middle of this word + [data, skip] = this.getNthWordAsBytesAndShorts(i, sym1, sym2, sym3, lastSymName, symSize); + + if (sym3 !== null) lastSymName = sym3.getName(); + else if (sym2 !== null) lastSymName = sym2.getName(); + else if (sym1 !== null) lastSymName = sym1.getName(); + if (lastSymName !== symName) symSize = null; + } else if (this.isFloat(i)) { + [data, skip] = this.getNthWordAsFloat(i); + } else if (this.isDouble(i)) { + [data, skip] = this.getNthWordAsDouble(i); + } else if (this.isString()) { + [data, skip, symSize] = this.getNthWordAsString(i, lastSymName, symSize); + if (skip < 0) { + // Not a string + this.contextSym.failedStringDecoding = true; + [data, skip] = this.getNthWord(i, relocInfo, canReferenceSymbolsWithAddends, canReferenceConstants, isSplittedSymbol); + } + } else if (this.isPascalString()) { + [data, skip] = this.getNthWordAsPascalString(i); + if (skip < 0) { + // Not a string + this.contextSym.failedPascalStringDecoding = true; + [data, skip] = this.getNthWord(i, relocInfo, canReferenceSymbolsWithAddends, canReferenceConstants, isSplittedSymbol); + } + } else { + [data, skip] = this.getNthWord(i, relocInfo, canReferenceSymbolsWithAddends, canReferenceConstants, isSplittedSymbol); + } + + if (i !== 0) output += this.getPrevAlignDirective(i); + output += data; + if (GlobalConfig.EMIT_INLINE_RELOC) output += this.relocToInlineStr(relocInfo, isSplittedSymbol); + output += this.getPostAlignDirective(i); + + i += skip; + i += 1; + + if (i * 4 === symSize) output += this._getSymEnd(lastSymName); + } + + if (symSize === null || i * 4 < symSize) { + // Size was cleared up by some in-middle symbol, so we need to emit + // the end label for the last sym. + // Or the user specified a larger size than what the symbol symbol + // actually is. + output += this._getSymEnd(lastSymName); + } + + const nameEnd = this.getNameEnd(); + if (nameEnd !== null) output += this.getSymbolAsmDeclaration(nameEnd, useGlobalLabel); + + return output; + } + + /** spimdisasm 1.35.x variant of disassembleAsData */ + _disassembleAsData135(useGlobalLabel, isSplittedSymbol) { + let output = this.contextSym.getReferenceeSymbols(); + output += this.getPrevAlignDirective(0); + + const symName = this.getName(); + output += this.getSymbolAsmDeclaration(symName, useGlobalLabel); + + let lastSymName = symName; + + const canReferenceSymbolsWithAddends = this.canUseAddendsOnData(); + const canReferenceConstants = this.canUseConstantsOnData(); + + let i = 0; + while (i < this.sizew) { + const currentVram = this.getVramOffset(i * 4); + const currentVrom = this.getVromOffset(i * 4); + + const sym1 = this.getSymbol(currentVram + 1, currentVrom, false, true, false); + const sym2 = this.getSymbol(currentVram + 2, currentVrom, false, true, false); + const sym3 = this.getSymbol(currentVram + 3, currentVrom, false, true, false); + + let data; + let skip; + if (sym1 !== null || sym2 !== null || sym3 !== null || this.isByte(i) || this.isShort(i)) { + [data, skip] = this.getNthWordAsBytesAndShorts(i, sym1, sym2, sym3, lastSymName, null); + + if (sym3 !== null) lastSymName = sym3.getName(); + else if (sym2 !== null) lastSymName = sym2.getName(); + else if (sym1 !== null) lastSymName = sym1.getName(); + } else if (this.isFloat(i)) { + [data, skip] = this.getNthWordAsFloat(i); + } else if (this.isDouble(i)) { + [data, skip] = this.getNthWordAsDouble(i); + } else if (this.isString()) { + [data, skip] = this.getNthWordAsString(i); + if (skip < 0) { + this.contextSym.failedStringDecoding = true; + [data, skip] = this.getNthWord(i, this.getReloc(i * 4), canReferenceSymbolsWithAddends, canReferenceConstants, isSplittedSymbol); + } + } else if (this.isPascalString()) { + [data, skip] = this.getNthWordAsPascalString(i); + if (skip < 0) { + this.contextSym.failedPascalStringDecoding = true; + [data, skip] = this.getNthWord(i, this.getReloc(i * 4), canReferenceSymbolsWithAddends, canReferenceConstants, isSplittedSymbol); + } + } else { + [data, skip] = this.getNthWord(i, this.getReloc(i * 4), canReferenceSymbolsWithAddends, canReferenceConstants, isSplittedSymbol); + } + + if (i !== 0) output += this.getPrevAlignDirective(i); + output += data; + if (GlobalConfig.EMIT_INLINE_RELOC) output += this.relocToInlineStr(this.getReloc(i * 4), isSplittedSymbol); + output += this.getPostAlignDirective(i); + + i += skip; + i += 1; + } + + output += this.getSizeDirective(lastSymName); + + const nameEnd = this.getNameEnd(); + if (nameEnd !== null) output += this.getSymbolAsmDeclaration(nameEnd, useGlobalLabel); + + return output; + } + + disassemble(_migrate = false, useGlobalLabel = true, isSplittedSymbol = false) { + return this.disassembleAsData(useGlobalLabel, isSplittedSymbol); + } +} diff --git a/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolBss.js b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolBss.js new file mode 100644 index 00000000..dabb2281 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolBss.js @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/MipsSymbolBss.py + +import { FileSectionType } from "../../common/FileSectionType.js"; +import { GlobalConfig } from "../../common/GlobalConfig.js"; +import * as Utils from "../../common/Utils.js"; +import { hexU } from "../../py/pyutils.js"; +import { atLeast } from "../../version.js"; +import { SymbolBase } from "./MipsSymbolBase.js"; + +export class SymbolBss extends SymbolBase { + constructor(context, vromStart, vromEnd, inFileOffset, vram, spaceSize, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, inFileOffset, vram, [], FileSectionType.Bss, segmentVromStart, overlayCategory); + this.spaceSize = spaceSize; + } + + get sizew() { + return Math.floor(this.spaceSize / 4); + } + + analyze() { + super.analyze(); + + if (this.contextSym.hasUserDeclaredSize()) { + // Check user declared size matches the size that will be generated + const contextSymSize = this.contextSym.getSize(); + let sizeMismatch; + if (atLeast("1.42.0")) { + sizeMismatch = this.spaceSize < contextSymSize; + if (GlobalConfig.CREATE_BSS_PADS) sizeMismatch = this.spaceSize !== contextSymSize; + } else { + sizeMismatch = this.spaceSize !== contextSymSize; + } + if (sizeMismatch) { + const warningMessage = ` +Range check triggered: .bss symbol (name: ${this.getName()}, address: 0x${hexU(this.contextSym.vram, 8)}): + User declared size (0x${hexU(contextSymSize)}) does not match the .space that will be emitted (0x${hexU(this.spaceSize)}). + Try checking the size again or look for symbols which overlaps this region`; + if (GlobalConfig.PANIC_RANGE_CHECK) { + if (this.spaceSize !== contextSymSize) throw new Error(`AssertionError: ${warningMessage}`); + } else { + Utils.eprint(`\n${warningMessage}\n`); + } + } + } + } + + disassembleAsBss(useGlobalLabel = true) { + let output = this.contextSym.getReferenceeSymbols(); + output += this.getPrevAlignDirective(0); + + const symName = this.getName(); + + if (!atLeast("1.42.0")) { + output += this.getNonMatchingLabel(symName, this.spaceSize); + output += this.getSymbolAsmDeclaration(symName, useGlobalLabel); + output += this.generateAsmLineComment(0, null, false, false); + output += ` .space 0x${hexU(this.spaceSize, 2)}${GlobalConfig.LINE_ENDS}`; + } else { + let symSize = null; + if (!GlobalConfig.CREATE_BSS_PADS) { + symSize = this.contextSym.userDeclaredSize; + if (symSize !== null) { + if (symSize <= 0 || symSize > this.spaceSize) symSize = null; + } + } + + let spaceSize = this.spaceSize; + if (symSize !== null) spaceSize = symSize; + + output += this.getNonMatchingLabel(symName, spaceSize); + output += this.getSymbolAsmDeclaration(symName, useGlobalLabel); + output += this.generateAsmLineComment(0, null, false, false); + output += ` .space 0x${hexU(spaceSize, 2)}${GlobalConfig.LINE_ENDS}`; + + if (symSize !== null) output += this._getSymEnd(symName); + + if (spaceSize !== this.spaceSize) { + output += this.generateAsmLineComment(spaceSize, null, false, false); + output += ` .space 0x${hexU(this.spaceSize - spaceSize, 2)}${GlobalConfig.LINE_ENDS}`; + } + } + + const nameEnd = this.getNameEnd(); + if (nameEnd !== null) output += this.getSymbolAsmDeclaration(nameEnd, useGlobalLabel); + + return output; + } + + disassemble(_migrate = false, _useGlobalLabel = true, _isSplittedSymbol = false) { + return this.disassembleAsBss(); + } +} diff --git a/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolData.js b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolData.js new file mode 100644 index 00000000..8cee8080 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolData.js @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/MipsSymbolData.py + +import { FileSectionType } from "../../common/FileSectionType.js"; +import { GlobalConfig } from "../../common/GlobalConfig.js"; +import * as Utils from "../../common/Utils.js"; +import { hexU } from "../../py/pyutils.js"; +import { SymbolBase } from "./MipsSymbolBase.js"; + +export class SymbolData extends SymbolBase { + constructor(context, vromStart, vromEnd, inFileOffset, vram, words, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, inFileOffset, vram, words, FileSectionType.Data, segmentVromStart, overlayCategory); + } + + analyze() { + super.analyze(); + + if (this.contextSym.hasUserDeclaredSize()) { + // Check user declared size matches the size that will be generated + const contextSymSize = this.contextSym.getSize(); + const actualSize = this.sizew * 4; + if (actualSize < contextSymSize) { + const warningMessage = ` +Range check triggered: .data symbol (name: ${this.getName()}, address: 0x${hexU(this.contextSym.vram, 8)}): + User declared size (0x${hexU(contextSymSize)}) does not match the amount of bytes that will be emitted (0x${hexU(actualSize)}). + Try checking the size again or look for symbols which overlaps this region`; + if (GlobalConfig.PANIC_RANGE_CHECK) { + if (actualSize !== contextSymSize) throw new Error(`AssertionError: ${warningMessage}`); + } else { + Utils.eprint(`\n${warningMessage}\n`); + } + } + } + } +} diff --git a/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolFunction.js b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolFunction.js new file mode 100644 index 00000000..1da00729 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolFunction.js @@ -0,0 +1,985 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/MipsSymbolFunction.py + +import { rabbitizer } from "../../rabbitizer.js"; +import { GlobalConfig, Abi, InputFileType } from "../../common/GlobalConfig.js"; +import { SymbolSpecialType, isSymbolSpecialType } from "../../common/ContextSymbols.js"; +import { RelocType, RelocationInfo } from "../../common/Relocation.js"; +import * as Utils from "../../common/Utils.js"; +import { newIntSet } from "../../common/symset.js"; +import { hexU, enumValue } from "../../py/pyutils.js"; +import { atLeast } from "../../version.js"; +import { SymbolText } from "./MipsSymbolText.js"; +import { InstrAnalyzer, SymbolTypeInfoDict, isGpReg, sameRabbitizerEnum } from "./analysis/InstrAnalyzer.js"; + +function isAccess(accessType, name) { + return sameRabbitizerEnum(accessType, rabbitizer.AccessType[name]); +} + +export class SymbolFunction extends SymbolText { + constructor(context, vromStart, vromEnd, inFileOffset, vram, instrsList, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, inFileOffset, vram, [], segmentVromStart, overlayCategory); + this.instructions = [...instrsList]; + + this.instrAnalyzer = new InstrAnalyzer(this.vram, context); + + /** set[tuple[int, bool]] (membership only) */ + this.branchesTaken = new Set(); + + this.pointersOffsets = newIntSet(); + this.pointersRemoved = false; + + this.hasUnimplementedIntrs = false; + this.isRsp = false; + this.isLikelyHandwritten = false; + this.gpRelHack = false; + } + + get nInstr() { + return this.instructions.length; + } + + get sizew() { + return this.instructions === undefined ? this.words.length : this.nInstr; + } + + isFunction() { + return true; + } + + _lookAheadSymbolFinder(instr, prevInstr, instructionOffset, trackedRegistersOriginal, prev_is_likely) { + if (!prevInstr.isBranch() && !prevInstr.isUnconditionalBranch()) return; + + const currentVram = this.getVramOffset(instructionOffset); + + const prevInstrOffset = instructionOffset - 4; + const branchOffset = prevInstr.getBranchOffsetGeneric(); + let branch = prevInstrOffset + branchOffset; + + if (branch < 0) { + // Avoid jumping outside of the function + return; + } + + const regsTracker = new rabbitizer.RegistersTracker(trackedRegistersOriginal); + + this.instrAnalyzer.processInstr(regsTracker, instr, instructionOffset, currentVram, null); + + const key = `${instructionOffset}|${prev_is_likely ? 1 : 0}`; + if (this.branchesTaken.has(key)) return; + this.branchesTaken.add(key); + + const sizew = this.instructions.length * 4; + while (branch < sizew) { + const prevTargetInstr = this.instructions.at(Math.floor(branch / 4) - 1); + const targetInstr = this.instructions[Math.floor(branch / 4)]; + + this.instrAnalyzer.processInstr(regsTracker, targetInstr, branch, this.getVramOffset(branch), prevTargetInstr); + + this._lookAheadSymbolFinder(targetInstr, prevTargetInstr, branch, regsTracker, prev_is_likely || prevTargetInstr.isBranchLikely()); + + if (prevTargetInstr.isUnconditionalBranch()) { + // Since we took the branch on the previous _lookAheadSymbolFinder + // call then we don't have anything else to process here. + return; + } + if (prevTargetInstr.isJump() && !prevTargetInstr.doesLink()) { + // Technically this is another form of unconditional branching. + return; + } + + this.instrAnalyzer.processPrevFuncCall(regsTracker, targetInstr, prevTargetInstr); + branch += 4; + } + } + + _runInstructionAnalyzer() { + let regsTracker = new rabbitizer.RegistersTracker(); + + const sizew = this.instructions.length * 4; + + let instructionOffset = 0; + if (instructionOffset < sizew) { + // First process the first instruction. We do this separately because the first one doesn't have a prev instruction. + const currentVram = this.getVramOffset(instructionOffset); + const instr = this.instructions[instructionOffset / 4]; + + if (instr.isLikelyHandwritten() && !this.isRsp) { + this.isLikelyHandwritten = true; + this.endOfLineComment.set(instructionOffset / 4, " /* handwritten instruction */"); + } + + if (!GlobalConfig.DISASSEMBLE_UNKNOWN_INSTRUCTIONS && !instr.isImplemented()) { + // Abort analysis + this.hasUnimplementedIntrs = true; + return; + } + + this.instrAnalyzer.processInstr(regsTracker, instr, instructionOffset, currentVram, null); + instructionOffset += 4; + } + + while (instructionOffset < sizew) { + const currentVram = this.getVramOffset(instructionOffset); + const prevInstr = this.instructions[instructionOffset / 4 - 1]; + const instr = this.instructions[instructionOffset / 4]; + + this.instrAnalyzer.printAnalisisDebugInfo_IterInfo(regsTracker, instr, currentVram); + + if (instr.isLikelyHandwritten() && !this.isRsp) { + this.isLikelyHandwritten = true; + this.endOfLineComment.set(instructionOffset / 4, " /* handwritten instruction */"); + } + + if (!GlobalConfig.DISASSEMBLE_UNKNOWN_INSTRUCTIONS && !instr.isImplemented()) { + // Abort analysis + this.hasUnimplementedIntrs = true; + return; + } + + if (!prevInstr.isBranchLikely() && !prevInstr.isUnconditionalBranch()) { + this.instrAnalyzer.processInstr(regsTracker, instr, instructionOffset, currentVram, prevInstr); + } + + // look-ahead symbol finder + this._lookAheadSymbolFinder(instr, prevInstr, instructionOffset, regsTracker, prevInstr.isBranchLikely()); + + if (prevInstr.isJumpWithAddress() && !prevInstr.doesLink()) { + const targetVram = prevInstr.getBranchVramGeneric(); + if (targetVram < this.vram || targetVram >= this.vramEnd) { + // Function is jumping outside the current function, so the state of + // the registers is garbage to the rest of the function. + regsTracker = new rabbitizer.RegistersTracker(); + } + } + + this.instrAnalyzer.processPrevFuncCall(regsTracker, instr, prevInstr, currentVram); + + if (prevInstr.isUnconditionalBranch() || (prevInstr.isJumpWithAddress() && !prevInstr.doesLink()) || prevInstr.isReturn()) { + // Execution diverges here, so it doesn't make sense to keep the current state. + regsTracker = new rabbitizer.RegistersTracker(); + } + + instructionOffset += 4; + } + + this.instrAnalyzer.printSymbolFinderDebugInfo_UnpairedLuis(); + } + + _processElfRelocSymbols() { + if (this.context.globalRelocationOverrides.size === 0) return; + if (GlobalConfig.INPUT_FILE_TYPE !== InputFileType.ELF) return; + + let instructionOffset = 0; + let vrom = this.vromStart; + for (const instr of this.instructions) { + const relocInfo = this.context.globalRelocationOverrides.get(vrom); + if (relocInfo !== undefined) { + if (relocInfo.relocType === RelocType.MIPS_26) { + if (relocInfo.staticReference !== null) { + const targetVram = instr.getInstrIndexAsVram() + relocInfo.staticReference.sectionVram; + if (instr.doesLink()) { + // Function call + relocInfo.symbol = this.addFunction(targetVram, true); + } else { + relocInfo.symbol = this.addBranchLabel(targetVram, true); + } + relocInfo.symbol._isStatic = true; + } + } else { + const offsetAddend = this.instrAnalyzer.symbolInstrOffset.has(instructionOffset) ? this.instrAnalyzer.symbolInstrOffset.get(instructionOffset) : null; + if (offsetAddend !== null) { + const hiOffset = this.instrAnalyzer.lowToHiDict.has(instructionOffset) ? this.instrAnalyzer.lowToHiDict.get(instructionOffset) : null; + if (hiOffset !== null) this.instrAnalyzer.symbolInstrOffset.set(hiOffset, offsetAddend); + } + + if (relocInfo.staticReference !== null) { + // For static symbols which only reference the start of a section + let symbolVram = relocInfo.staticReference.sectionVram; + if (instr.hasOperandAlias(rabbitizer.OperandType.cpu_immediate)) { + if (this.instrAnalyzer.symbolInstrOffset.has(instructionOffset)) { + const addressOffset = this.instrAnalyzer.symbolInstrOffset.get(instructionOffset); + symbolVram += addressOffset; + } else { + symbolVram += instr.getProcessedImmediate(); + } + } + let contextSym = this.getSymbol(symbolVram, null, true); + if (contextSym === null) contextSym = this.addSymbol(symbolVram, undefined, true); + relocInfo.symbol = contextSym; + relocInfo.symbol._isStatic = true; + relocInfo.addend = symbolVram - contextSym.vram; + } else if (offsetAddend !== null) { + // Addends for global symbols + relocInfo.addend = offsetAddend; + } + } + } + + vrom += 4; + instructionOffset += 4; + } + } + + _bumpPossibleType(gotAddress, loOffset) { + const symAccess = this.instrAnalyzer.symbolTypesOffsets.get(loOffset); + if (symAccess !== undefined) { + if (!this.instrAnalyzer.possibleSymbolTypes.has(gotAddress)) this.instrAnalyzer.possibleSymbolTypes.set(gotAddress, new SymbolTypeInfoDict()); + const d = this.instrAnalyzer.possibleSymbolTypes.get(gotAddress); + if (!d.has(symAccess)) d.set(symAccess, 0); + d.set(symAccess, d.get(symAccess) + 1); + } + } + + _postProcessGotAccesses() { + if (!GlobalConfig.PIC) return; + + const globalGotOffsets = new Set(); + + for (const [gotAccessOffset, gotAccess] of this.instrAnalyzer.gotAccessAddresses) { + const gpAccess = this.context.gpAccesses.requestAddress(gotAccess); + if (gpAccess === null) { + Utils.eprint(1, `0x${hexU(this.instructions[gotAccessOffset / 4].vram, 8)}`, `0x${hexU(gotAccess, 8)}`, this.instructions[gotAccessOffset / 4].disassemble()); + continue; + } + + let gotAddress = gpAccess.address; + if (!gpAccess.isGotLocal) { + globalGotOffsets.add(gotAccessOffset); + const contextSym = this.addSymbol(gotAddress, undefined, true); + contextSym.isGot = gpAccess.isGot; + contextSym.isGotGlobal = gpAccess.isGotGlobal; + const loOffset = this.instrAnalyzer.hiToLowDict.get(gotAccessOffset); + if (loOffset !== undefined) { + this.instrAnalyzer.symbolLoInstrOffset.delete(loOffset); + this.instrAnalyzer.symbolInstrOffset.delete(loOffset); + } + } else { + // GOT-locals need to be paired + const loOffset = this.instrAnalyzer.hiToLowDict.get(gotAccessOffset); + if (loOffset !== undefined) { + const loInstr = this.instructions[loOffset / 4]; + gotAddress += loInstr.getProcessedImmediate(); + this.instrAnalyzer.symbolInstrOffset.set(loOffset, gotAddress); + this._bumpPossibleType(gotAddress, loOffset); + } + + const contextSym = this.addSymbol(gotAddress, undefined, true); + contextSym.isGot = true; + contextSym.isGotLocal = true; + } + this.instrAnalyzer.symbolInstrOffset.set(gotAccessOffset, gotAddress); + this.instrAnalyzer.referencedVrams.add(gotAddress); + } + + // Aditional lookup for unpaired GOT-locals + if (this.instrAnalyzer.gotAccessAddresses.size > 0) { + for (const [loOffset, gotAccessOffset] of this.instrAnalyzer.lowToHiDict) { + const gotAccess_ = this.instrAnalyzer.gotAccessAddresses.get(gotAccessOffset); + if (gotAccess_ === undefined) continue; + + const gpAccess = this.context.gpAccesses.requestAddress(gotAccess_); + if (gpAccess === null) { + Utils.eprint(2, `0x${hexU(this.instructions[gotAccessOffset / 4].vram, 8)}`, `0x${hexU(gotAccess_, 8)}`, this.instructions[gotAccessOffset / 4].disassemble()); + continue; + } + + if (!gpAccess.isGotLocal) continue; + + let gotAddress = gpAccess.address; + + const loInstr = this.instructions[loOffset / 4]; + gotAddress += loInstr.getProcessedImmediate(); + this.instrAnalyzer.symbolInstrOffset.set(loOffset, gotAddress); + + this._bumpPossibleType(gotAddress, loOffset); + + const contextSym = this.addSymbol(gotAddress, undefined, true); + contextSym.isGot = true; + contextSym.isGotLocal = true; + this.instrAnalyzer.symbolInstrOffset.set(gotAccessOffset, gotAddress); + this.instrAnalyzer.referencedVrams.add(gotAddress); + } + } + + for (const [loOffset, symVram0] of [...this.instrAnalyzer.symbolLoInstrOffset]) { + let symVram = symVram0; + const hiOffset = this.instrAnalyzer.lowToHiDict.get(loOffset); + if (hiOffset !== undefined && this.instrAnalyzer.gotAccessAddresses.has(hiOffset)) { + if (globalGotOffsets.has(hiOffset)) { + this.instrAnalyzer.symbolInstrOffset.delete(loOffset); + continue; + } + + if (this.instrAnalyzer.symbolInstrOffset.has(hiOffset)) { + symVram = this.instrAnalyzer.symbolInstrOffset.get(hiOffset); + this.instrAnalyzer.symbolLoInstrOffset.set(loOffset, symVram); + } + + if (this.instrAnalyzer.referencedJumpTableOffsets.has(loOffset)) this.instrAnalyzer.referencedJumpTableOffsets.set(loOffset, symVram); + + if (this.instrAnalyzer.indirectFunctionCallOffsets.has(loOffset)) this.instrAnalyzer.indirectFunctionCallOffsets.set(loOffset, symVram); + } + } + } + + /** (instr, instrOffset, contextSym=None, gotHiLo=False, gotSmall=False) */ + _getRelocTypeForInstruction(instr, instrOffset, contextSym = null, gotHiLo = false, gotSmall = false) { + if (instr.canBeHi()) { + if (GlobalConfig.PIC) { + if (contextSym !== null && gotHiLo) { + if (contextSym.isGotGlobal && contextSym.getTypeSpecial() === SymbolSpecialType.function) return RelocType.MIPS_CALL_HI16; + return RelocType.MIPS_GOT_HI16; + } + } + return RelocType.MIPS_HI16; + } + + if (isGpReg(instr.rs)) { + if (!GlobalConfig.PIC || gotSmall) { + if (instr.modifiesRt() && isGpReg(instr.rt)) { + // Shouldn't make a gprel access if the dst register is $gp too + return RelocType.MIPS_LO16; + } + return RelocType.MIPS_GPREL16; + } + + if (contextSym !== null) { + if (contextSym.isGotGlobal && contextSym.getTypeSpecial() === SymbolSpecialType.function && this.instrAnalyzer.indirectFunctionCallOffsets.has(instrOffset)) { + return RelocType.MIPS_CALL16; + } else if (contextSym.isGot) { + return RelocType.MIPS_GOT16; + } else { + return RelocType.MIPS_GPREL16; + } + } + } else if (GlobalConfig.PIC) { + if (contextSym !== null && gotHiLo) { + if (contextSym.isGotGlobal && contextSym.getTypeSpecial() === SymbolSpecialType.function) return RelocType.MIPS_CALL_LO16; + return RelocType.MIPS_GOT_LO16; + } + } + return RelocType.MIPS_LO16; + } + + _generateRelocsFromInstructionAnalyzer() { + const v142 = atLeast("1.42.0"); + + if (v142 && !GlobalConfig.IGNORE_BRANCHES) { + for (const [instrOffset, targetVram] of this.instrAnalyzer.branchInstrOffsets) { + const instr = this.instructions[instrOffset / 4]; + if (!instr.isBranch() && !instr.isUnconditionalBranch()) continue; + const branch = this.instrAnalyzer.branchTargetInstrOffsets.get(instrOffset); + const branchTargetVrom = this.getVromOffset(branch); + const labelSym = this.getSymbol(targetVram, branchTargetVrom, false); + if (labelSym === null || labelSym.unknownSegment) continue; + this.relocs.set(instrOffset, new RelocationInfo(RelocType.MIPS_PC16, labelSym)); + } + } + + for (const [instrOffset, address0] of this.instrAnalyzer.symbolInstrOffset) { + let address = address0; + if (this.context.isAddressBanned(address)) continue; + + let contextSym = this.getSymbol(address); + + let gotHiLo = false; + let gotSmall = false; + if (contextSym === null && address < 0 && GlobalConfig.PIC && GlobalConfig.GP_VALUE !== null) { + // Negative pointer may mean it is a weird GOT access + const gotAccess = GlobalConfig.GP_VALUE + address; + const gpAccess = this.context.gpAccesses.requestAddress(gotAccess); + if (gpAccess !== null) { + address = gpAccess.address; + contextSym = this.getSymbol(address); + gotHiLo = true; + gotSmall = gpAccess.isSmallSection; + } else { + Utils.eprint(4, `0x${hexU(this.instructions[instrOffset / 4].vram, 8)}`, `0x${hexU(gotAccess, 8)}`, this.instructions[instrOffset / 4].disassemble()); + } + } + + if (contextSym === null) continue; + + if (contextSym.isGotGlobal) { + if (!this.instrAnalyzer.gotAccessAddresses.has(instrOffset) && !gotHiLo) continue; + } + + const instr = this.instructions[instrOffset / 4]; + + const relocType = this._getRelocTypeForInstruction(instr, instrOffset, contextSym, gotHiLo, gotSmall); + if (relocType === RelocType.MIPS_GPREL16) contextSym.accessedAsGpRel = true; + this.relocs.set(instrOffset, new RelocationInfo(relocType, contextSym, address - contextSym.vram)); + } + + for (const instrOffset of this.instrAnalyzer.cploadOffsets) { + // .cpload directive is meant to use the `_gp_disp` pseudo-symbol + const instr = this.instructions[instrOffset / 4]; + const relocType = this._getRelocTypeForInstruction(instr, instrOffset); + this.relocs.set(instrOffset, new RelocationInfo(relocType, "_gp_disp")); + } + + for (const [instrOffset, gpInfo] of this.instrAnalyzer.gpSets) { + if (gpInfo === null) continue; + const hiInstrOffset = gpInfo.hiOffset; + const hiInstr = this.instructions[hiInstrOffset / 4]; + const instr = this.instructions[instrOffset / 4]; + + const hiRelocType = this._getRelocTypeForInstruction(hiInstr, hiInstrOffset); + const relocType = this._getRelocTypeForInstruction(instr, instrOffset); + if (!GlobalConfig.PIC && gpInfo.value === GlobalConfig.GP_VALUE) { + this.relocs.set(hiInstrOffset, new RelocationInfo(hiRelocType, "_gp")); + this.relocs.set(instrOffset, new RelocationInfo(relocType, "_gp")); + } else { + const address = gpInfo.value; + if (this.context.isAddressBanned(address)) continue; + + const contextSym = this.getSymbol(address); + if (contextSym === null) continue; + + const addend = v142 ? address - contextSym.vram : 0; + this.relocs.set(hiInstrOffset, new RelocationInfo(hiRelocType, contextSym, addend)); + this.relocs.set(instrOffset, new RelocationInfo(relocType, contextSym, addend)); + } + } + + for (const [instrOffset, constant] of this.instrAnalyzer.constantInstrOffset) { + const instr = this.instructions[instrOffset / 4]; + const relocType = this._getRelocTypeForInstruction(instr, instrOffset); + + if (relocType === RelocType.MIPS_HI16 || relocType === RelocType.MIPS_LO16) { + // We can only do this kind of shenanigans for normal %hi/%lo relocs + const symbol = this.getConstant(constant); + if (symbol !== null) { + this.relocs.set(instrOffset, new RelocationInfo(relocType, symbol.getName())); + } else if (GlobalConfig.SYMBOL_FINDER_FILTERED_ADDRESSES_AS_HILO) { + this.relocs.set(instrOffset, new RelocationInfo(relocType, `0x${hexU(constant)}`)); + } else { + // Pretend this pair is a constant + let loInstr = instr; + if (instr.canBeHi()) { + const lo = this.instrAnalyzer.hiToLowDict.get(instrOffset); + if (lo === undefined) throw new Error(`KeyError: ${instrOffset}`); + loInstr = this.instructions[lo / 4]; + } + + const generatedReloc = this._generateHiLoConstantReloc(constant, instr, loInstr); + if (generatedReloc !== null) this.relocs.set(instrOffset, generatedReloc); + } + } else { + const percent = relocType.getPercentRel(); + let comment = `Failed to symbolize address 0x${hexU(constant, 8)} for ${percent === null ? "None" : percent}. Make sure this address is within the recognized valid address space.`; + if (relocType === RelocType.MIPS_GPREL16 || relocType === RelocType.MIPS_GOT16) { + if (GlobalConfig.GP_VALUE === null) comment += " Please specify a gp_value."; + else if (!this.context.isInTotalVramRange(GlobalConfig.GP_VALUE)) comment += ` The provided gp_value (0x${hexU(GlobalConfig.GP_VALUE, 8)}) seems wrong.`; + } + this.endOfLineComment.set(instrOffset / 4, ` /* ${comment} */`); + } + } + + for (const [instrOffset, targetVram] of this.instrAnalyzer.funcCallInstrOffsets) { + const instr = this.instructions[instrOffset / 4]; + const is_j = instr.isJumpWithAddress() && !instr.doesLink(); + const symValidation = (contextSym) => { + const t = contextSym.type; + if (t === SymbolSpecialType.function) return true; + if (t === null) return true; + if (is_j && isSymbolSpecialType(t) && t.isTargetLabel()) return true; + return false; + }; + const funcSym = this.getSymbolFromAnySegment(targetVram, symValidation, false); + if (funcSym === null) continue; + this.relocs.set(instrOffset, new RelocationInfo(RelocType.MIPS_26, funcSym)); + } + } + + analyze() { + this.contextSym.inFileOffset = this.inFileOffset; + if (this.parent !== null) this.contextSym.parentFileName = this.parent.getName(); + + if (!GlobalConfig.DISASSEMBLE_UNKNOWN_INSTRUCTIONS && this.hasUnimplementedIntrs) { + let offset = 0; + for (const _instr of this.instructions) { + const currentVram = this.getVramOffset(offset); + const currentVrom = this.getVromOffset(offset); + const contextSym = this.getSymbol(currentVram, currentVrom, false); + if (contextSym !== null) contextSym.isDefined = true; + offset += 4; + } + return; + } + + this._runInstructionAnalyzer(); + + this._postProcessGotAccesses(); + this._processElfRelocSymbols(); + + // Branches + for (const [instrOffset, targetBranchVram] of this.instrAnalyzer.branchInstrOffsets) { + if (GlobalConfig.INPUT_FILE_TYPE === InputFileType.ELF) { + if (this.context.globalRelocationOverrides.has(this.getVromOffset(instrOffset))) continue; + } + const branch = this.instrAnalyzer.branchTargetInstrOffsets.get(instrOffset); + const labelSym = this.addBranchLabel(targetBranchVram, true, this.getVromOffset(branch)); + labelSym.referenceCounter += 1; + labelSym.referenceFunctions.add(this.contextSym); + labelSym.parentFunction = this.contextSym; + labelSym.parentFileName = this.contextSym.parentFileName; + this.contextSym.branchLabels.add(labelSym.vram, labelSym); + } + + // Function calls + for (const [instrOffset, targetVram] of this.instrAnalyzer.funcCallInstrOffsets) { + if (this.context.isAddressBanned(targetVram)) continue; + + if (GlobalConfig.INPUT_FILE_TYPE === InputFileType.ELF) { + if (this.context.globalRelocationOverrides.has(this.getVromOffset(instrOffset))) continue; + } + const funcSym = this.addFunction(targetVram, true); + funcSym.referenceCounter += 1; + funcSym.referenceFunctions.add(this.contextSym); + } + + const v142 = atLeast("1.42.0"); + const smallTypes = v142 ? new Set(["u16", "s16", "s8", "u8"]) : new Set(["u16", "s16", "u8"]); + + // Symbols + for (const [loOffset, symVram0] of this.instrAnalyzer.symbolLoInstrOffset) { + let symVram = symVram0; + if (this.context.isAddressBanned(symVram)) continue; + + if (GlobalConfig.INPUT_FILE_TYPE === InputFileType.ELF) { + if (this.context.globalRelocationOverrides.has(this.getVromOffset(loOffset))) continue; + } + + const symAccessDict = this.instrAnalyzer.possibleSymbolTypes.get(symVram); + let symAccess = null; + if (symAccessDict !== undefined && symAccessDict.size === 1) { + // Infer type info if there's only one access type + symAccess = symAccessDict.keys().next().value; + } + + let contextSym = this.addSymbol(symVram, undefined, true, null, true); + if (contextSym !== null) { + // TODO: do this in a less ugly way + if (contextSym.address !== symVram) { + if (contextSym.address % 4 !== 0 || symVram % 4 !== 0) { + if (smallTypes.has(contextSym.getType()) || (symAccess !== null && (isAccess(symAccess.accessType, "BYTE") || isAccess(symAccess.accessType, "SHORT")))) { + if (!(contextSym.getSize() > 4)) { + if (contextSym.userDeclaredSize === null || symVram >= contextSym.address + contextSym.userDeclaredSize) { + if (symAccess !== null) contextSym.setAccessTypeIfUnset(symAccess.accessType, symAccess.unsignedMemoryAccess); + contextSym.setFirstLoAccessIfUnset(loOffset); + contextSym = this.addSymbol(symVram, undefined, true); + } + } + } + } + } + } + + contextSym.referenceCounter += 1; + contextSym.referenceFunctions.add(this.contextSym); + contextSym.setFirstLoAccessIfUnset(loOffset); + if (symAccess !== null) { + contextSym.setAccessTypeIfUnset(symAccess.accessType, symAccess.unsignedMemoryAccess); + if (contextSym.isAutogenerated) { + // Handle mips1 doublefloats + if (isAccess(contextSym.accessType, "FLOAT") && GlobalConfig.ABI === Abi.O32) { + const instr = this.instructions[loOffset / 4]; + if (instr.doesDereference() && instr.isFloat() && !instr.isDouble()) { + if (enumValue(instr.ft) % 2 !== 0) { + // lwc1/swc1 with an odd fpr means it is an mips1 doublefloats reference + if (symVram % 8 !== 0) { + // We need to remove the the symbol pointing to the middle of this doublefloats + const got = contextSym.isGot; + const gotLocal = contextSym.isGotLocal; + const gotGlobal = contextSym.isGotGlobal; + this.removeSymbol(symVram); + + // Align down to 8 + symVram = Math.floor(symVram / 8) * 8; + contextSym = this.addSymbol(symVram, undefined, true); + contextSym.referenceCounter += 1; + contextSym.referenceFunctions.add(this.contextSym); + contextSym.setFirstLoAccessIfUnset(loOffset); + contextSym.isGot = got; + contextSym.isGotLocal = gotLocal; + contextSym.isGotGlobal = gotGlobal; + } + contextSym.accessType = rabbitizer.AccessType.DOUBLEFLOAT; + contextSym.unsignedAccessType = false; + contextSym.isMips1Double = true; + } + } + } + } + } + } + + this._generateRelocsFromInstructionAnalyzer(); + + // Jump tables + for (const targetVram of this.instrAnalyzer.referencedJumpTableOffsets.values()) { + const jumpTable = this.addJumpTable(targetVram, true); + jumpTable.parentFunction = this.contextSym; + this.contextSym.jumpTables.add(jumpTable.vram, jumpTable); + } + + if (this.isLikelyHandwritten) { + for (const instr of this.instructions) instr.inHandwrittenFunction = this.isLikelyHandwritten; + } + + this.contextSym.autodetectedSize = this.sizew * 4; + + this.referencedVrams = this.instrAnalyzer.referencedVrams; + } + + countExtraPadding() { + let count = 0; + if (this.contextSym.userDeclaredSize === this.sizew * 4) return 0; + + for (let i = this.instructions.length - 1; i > 0; i--) { + const instr = this.instructions[i]; + const nextInstr = this.instructions[i - 1]; + + if (nextInstr.hasDelaySlot()) return count; + if (!instr.isNop()) return count; + + count += 1; + } + return count; + } + + countDiffOpcodes(other) { + let result = 0; + for (let i = 0; i < Math.min(this.nInstr, other.nInstr); i++) { + if (!this.instructions[i].sameOpcode(other.instructions[i])) result += 1; + } + return result; + } + + countSameOpcodeButDifferentArguments(other) { + let result = 0; + for (let i = 0; i < Math.min(this.nInstr, other.nInstr); i++) { + if (this.instructions[i].sameOpcodeButDifferentArguments(other.instructions[i])) result += 1; + } + return result; + } + + blankOutDifferences(other_func) { + if (!GlobalConfig.REMOVE_POINTERS) return false; + let was_updated = false; + for (let i = 0; i < Math.min(this.nInstr, other_func.nInstr); i++) { + const instr1 = this.instructions[i]; + const instr2 = other_func.instructions[i]; + if (instr1.sameOpcodeButDifferentArguments(instr2)) { + instr1.blankOut(); + instr2.blankOut(); + was_updated = true; + } + } + return was_updated; + } + + removePointers() { + if (!GlobalConfig.REMOVE_POINTERS) return false; + + let was_updated = false; + + for (const instructionOffset of this.instrAnalyzer.symbolInstrOffset.keys()) this.instructions[instructionOffset / 4].blankOut(); + was_updated = this.instrAnalyzer.symbolInstrOffset.size > 0 || was_updated; + + for (const fileOffset of this.pointersOffsets) { + const index = Math.floor((fileOffset - this.inFileOffset) / 4); + if (index < 0) continue; + if (index >= this.nInstr) continue; + this.instructions[index].blankOut(); + } + + if (GlobalConfig.IGNORE_BRANCHES) { + for (const instructionOffset of this.instrAnalyzer.branchInstrOffsets.keys()) this.instructions[instructionOffset / 4].blankOut(); + was_updated = this.instrAnalyzer.branchInstrOffsets.size > 0 || was_updated; + } + + this.pointersRemoved = true; + + return was_updated; + } + + removeTrailingNops() { + let was_updated = false; + let first_nop = this.nInstr; + + for (let i = this.nInstr - 1; i >= 0; i--) { + const instr = this.instructions[i]; + if (!instr.isNop()) { + if (instr.isReturn()) first_nop += 1; + break; + } + first_nop = i; + } + + if (first_nop < this.nInstr) { + was_updated = true; + this.instructions.splice(first_nop); + } + return was_updated; + } + + _generateHiLoConstantReloc(constantValue, currentInstr, loInstr) { + if (loInstr === null) { + if (currentInstr.canBeHi()) return new RelocationInfo(RelocType.CUSTOM_CONSTANT_HI, `0x${hexU(constantValue)}`); + return null; + } + + if (loInstr.canBeLo()) { + if (loInstr.isUnsigned()) { + if (currentInstr.canBeHi()) return new RelocationInfo(RelocType.CUSTOM_CONSTANT_HI, `0x${hexU(constantValue)}`); + if (currentInstr.canBeLo()) return new RelocationInfo(RelocType.CUSTOM_CONSTANT_LO, `0x${hexU(constantValue)}`); + return null; + } else { + const loHalf = Number(BigInt(constantValue) & 0xffffn); + if (loHalf < 0x8000) { + // positive lo half + if (currentInstr.canBeHi()) return new RelocationInfo(RelocType.CUSTOM_CONSTANT_HI, `0x${hexU(constantValue)}`); + if (currentInstr.canBeLo()) return new RelocationInfo(RelocType.CUSTOM_CONSTANT_LO, `0x${hexU(constantValue)}`); + } else { + // negative lo half + } + } + } + return null; + } + + /** Returns [immOverride|null, relocInfo|null] */ + _getImmOverrideForInstruction(instr, instrOffset, isSplittedSymbol = false) { + if (this.pointersRemoved) return [null, null]; + + let relocInfo = this.getReloc(instrOffset); + if (relocInfo !== null) { + if (relocInfo.isRelocNone()) { + if (instr.isJumpWithAddress()) return [`0x${hexU(instr.getInstrIndexAsVram(), 8)}`, relocInfo]; + } else { + const ignoredRelocs = new Set(); + if (this.gpRelHack) ignoredRelocs.add(RelocType.MIPS_GPREL16); + return [relocInfo.getNameWithReloc(isSplittedSymbol, ignoredRelocs), relocInfo]; + } + } + + if (instr.isBranch() || instr.isUnconditionalBranch()) { + if (GlobalConfig.IGNORE_BRANCHES) return [null, null]; + const branchOffset = instr.getBranchOffsetGeneric(); + const targetBranchVram = this.getVramOffset(instrOffset + branchOffset); + const labelSymbol = this.getSymbol(targetBranchVram, null, false); + if (labelSymbol !== null) return [labelSymbol.getName(), null]; + return [null, null]; + } + + if (instr.hasOperandAlias(rabbitizer.OperandType.cpu_immediate)) { + if (this.instrAnalyzer.symbolInstrOffset.has(instrOffset)) { + const address = this.instrAnalyzer.symbolInstrOffset.get(instrOffset); + relocInfo = this._generateHiLoConstantReloc(address, instr, instr); + if (relocInfo !== null) return [relocInfo.getNameWithReloc(isSplittedSymbol), relocInfo]; + } else if (instr.canBeHi()) { + // Unpaired LUI + relocInfo = this._generateHiLoConstantReloc(instr.getProcessedImmediate() * 0x10000, instr, null); + if (relocInfo !== null) return [relocInfo.getNameWithReloc(isSplittedSymbol), relocInfo]; + } + } + + return [null, null]; + } + + getLabelForOffset(instructionOffset, migrate = false) { + if (GlobalConfig.IGNORE_BRANCHES || instructionOffset === 0) { + // Skip over this function to avoid duplication + return ""; + } + + const currentVram = this.getVramOffset(instructionOffset); + const currentVrom = this.getVromOffset(instructionOffset); + const labelSym = this.getSymbol(currentVram, currentVrom, false); + + if (labelSym === null || labelSym.overlayCategory !== this.overlayCategory) return ""; + + labelSym.isDefined = true; + labelSym.sectionType = this.sectionType; + labelSym.vromAddress = currentVrom; + const labelSymType = labelSym.getTypeSpecial(); + + let useLabelMacro = + labelSymType === null || + labelSymType === SymbolSpecialType.function || + (labelSymType === SymbolSpecialType.jumptablelabel && !migrate) || + labelSymType === SymbolSpecialType.gccexcepttablelabel; + if (!useLabelMacro) { + if (GlobalConfig.ASM_GLOBALIZE_TEXT_LABELS_REFERENCED_BY_NON_JUMPTABLE) { + // Check if any non-jumptable symbol references this label + for (const otherSym of labelSym.referenceSymbols) { + if (otherSym.getTypeSpecial() !== SymbolSpecialType.jumptable) { + useLabelMacro = true; + break; + } + } + } + } + + let label; + if (useLabelMacro) { + label = labelSym.getReferenceeSymbols(); + const labelMacro = labelSym.getLabelMacro(true); + if (labelMacro !== null) label += `${labelMacro} ${labelSym.getName()}${GlobalConfig.LINE_ENDS}`; + if (GlobalConfig.ASM_TEXT_FUNC_AS_LABEL) label += `${labelSym.getName()}:${GlobalConfig.LINE_ENDS}`; + } else { + label = labelSym.getName() + ":" + GlobalConfig.LINE_ENDS; + } + label = " ".repeat(GlobalConfig.ASM_INDENTATION_LABELS) + label; + if (atLeast("1.39.0") && GlobalConfig.ASM_EMIT_ALIGN_BRANCH_LABELS) label = `${this._getAlignDirectiveStr(2, instructionOffset)}${label}`; + return label; + } + + _emitInstruction(instr, instructionOffset, wasLastInstABranch, isSplittedSymbol = false) { + const [immOverride, relocInfo] = this._getImmOverrideForInstruction(instr, instructionOffset, isSplittedSymbol); + let comment = this.generateAsmLineComment(instructionOffset, instr.getRaw()); + let extraLJust = 0; + + if (wasLastInstABranch) { + extraLJust = -1; + comment += " "; + } + + let line = instr.disassemble(immOverride, extraLJust); + + if (this.gpRelHack) { + // Get rid of `%gp_rel` and `$gp` since old assemblers don't support `%gp_rel`. + if (relocInfo !== null && relocInfo.relocType === RelocType.MIPS_GPREL16) { + if (instr.canBeLo() && instr.doesDereference()) { + line = line.replace("($gp)", "").replace("($28)", ""); + } else if (sameRabbitizerEnum(instr.uniqueId, rabbitizer.InstrId.cpu_addiu)) { + line = line.replace("addiu ", "la ").replace(", $gp, ", ", ").replace(", $28, ", ", "); + } + + let endComment = this.endOfLineComment.has(instructionOffset / 4) ? this.endOfLineComment.get(instructionOffset / 4) : ""; + if (!endComment.includes(" /* gp_rel: ")) { + endComment += ` /* gp_rel: ${immOverride === null ? "None" : immOverride} */`; + this.endOfLineComment.set(instructionOffset / 4, endComment); + } + } + } + + return `${comment} ${line}`; + } + + _emitCpload(instr, instructionOffset, wasLastInstABranch, isSplittedSymbol = false) { + let output = ""; + + const cpload = this.instrAnalyzer.cploads.get(instructionOffset); + if (cpload !== undefined) { + const hiInstr = this.instructions[cpload.hiOffset / 4]; + const loInstr = this.instructions[cpload.loOffset / 4]; + let gpDisp = hiInstr.getProcessedImmediate() * 0x10000; + gpDisp += loInstr.getProcessedImmediate(); + output += `/* _gp_disp: 0x${hexU(gpDisp)} */${GlobalConfig.LINE_ENDS}`; + if (GlobalConfig.EMIT_CPLOAD) { + if (cpload.reg === null) throw new Error("AssertionError"); + output += `.cpload $${cpload.reg.name}`; + } else { + output += this._emitInstruction(instr, instructionOffset, wasLastInstABranch, isSplittedSymbol); + } + } else if (!GlobalConfig.EMIT_CPLOAD) { + output += this._emitInstruction(instr, instructionOffset, wasLastInstABranch, isSplittedSymbol); + } + // don't emit the other instructions which are part of .cpload if the directive was emitted + return output; + } + + disassemble(migrate = false, useGlobalLabel = true, isSplittedSymbol = false) { + let output = ""; + + if (migrate) output += this.getSpimdisasmVersionString(); + + const asData = atLeast("1.42.0") + ? (!GlobalConfig.DISASSEMBLE_UNKNOWN_INSTRUCTIONS && this.hasUnimplementedIntrs) || typeof this.contextSym.getTypeSpecial() === "string" + : !GlobalConfig.DISASSEMBLE_UNKNOWN_INSTRUCTIONS && this.hasUnimplementedIntrs; + if (asData) return this.disassembleAsData(useGlobalLabel, isSplittedSymbol); + + if (!GlobalConfig.PIC && this.gpRelHack && this.instrAnalyzer.gpReferencedSymbols.size > 0) { + output += `/* Symbols accessed via $gp register */${GlobalConfig.LINE_ENDS}`; + for (const gpAddress of this.instrAnalyzer.gpReferencedSymbols) { + const gpSym = this.getSymbol(gpAddress, null, true); + if (gpSym !== null) output += `.extern ${gpSym.getName()}, 1${GlobalConfig.LINE_ENDS}`; + } + output += GlobalConfig.LINE_ENDS; + } + + output += this.contextSym.getReferenceeSymbols(); + output += this.getPrevAlignDirective(0); + + if (this.isLikelyHandwritten && GlobalConfig.ASM_COMMENT) { + if (!this.isRsp) { + // RSP functions are always handwritten, so this is redundant + output += "/* Handwritten function */" + GlobalConfig.LINE_ENDS; + } + } + + this._generateRelocsFromInstructionAnalyzer(); + + const symName = this.getName(); + + let symSize = this.contextSym.getSize(); + if (this.contextSym.userDeclaredSize === null) { + // Fixup symbol size to avoid counting padding as part of the symbol + // on the emitted size and end directives. + symSize -= 4 * this.countExtraPadding(); + } + + output += this.getNonMatchingLabel(symName, symSize); + output += this.getSymbolAsmDeclaration(symName, useGlobalLabel); + + let wasLastInstABranch = false; + let instructionOffset = 0; + for (const instr of this.instructions) { + let currentLine = this.getLabelForOffset(instructionOffset, migrate); + + const isCpload = this.instrAnalyzer.cploadOffsets.has(instructionOffset); + if (isCpload) currentLine += this._emitCpload(instr, instructionOffset, wasLastInstABranch, isSplittedSymbol); + else currentLine += this._emitInstruction(instr, instructionOffset, wasLastInstABranch, isSplittedSymbol); + + currentLine += this.getEndOfLineComment(instructionOffset / 4); + if (currentLine !== "") currentLine += GlobalConfig.LINE_ENDS; + + if (GlobalConfig.EMIT_INLINE_RELOC) { + const relocInfo = this.getReloc(instructionOffset); + currentLine += this.relocToInlineStr(relocInfo, isSplittedSymbol); + } + + output += currentLine; + + wasLastInstABranch = instr.hasDelaySlot(); + instructionOffset += 4; + + if (instructionOffset === symSize) { + if (GlobalConfig.ASM_TEXT_END_LABEL) { + const endName = atLeast("1.39.0") ? symName : this.getName(); + output += `${GlobalConfig.ASM_TEXT_END_LABEL} ${endName}` + GlobalConfig.LINE_ENDS; + } + output += this.getSizeDirective(symName); + } + } + + const nameEnd = this.getNameEnd(); + if (nameEnd !== null) output += this.getSymbolAsmDeclaration(nameEnd, useGlobalLabel); + + return output; + } + + disassembleAsData(useGlobalLabel = true, isSplittedSymbol = false) { + this.contextSym.setTypeSpecial("u32", true); + this.words = []; + this.instructions.forEach((instr, i) => { + if (!instr.isImplemented() || !instr.isValid()) this.endOfLineComment.set(i, " /* invalid instruction */"); + this.words.push(instr.getRaw()); + }); + return super.disassembleAsData(useGlobalLabel, isSplittedSymbol); + } +} diff --git a/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolGccExceptTable.js b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolGccExceptTable.js new file mode 100644 index 00000000..d3338cce --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolGccExceptTable.js @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/MipsSymbolGccExceptTable.py + +import { FileSectionType } from "../../common/FileSectionType.js"; +import { SymbolBase } from "./MipsSymbolBase.js"; + +export class SymbolGccExceptTable extends SymbolBase { + constructor(context, vromStart, vromEnd, inFileOffset, vram, words, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, inFileOffset, vram, words, FileSectionType.GccExceptTable, segmentVromStart, overlayCategory); + } +} diff --git a/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolRodata.js b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolRodata.js new file mode 100644 index 00000000..463997b5 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolRodata.js @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/MipsSymbolRodata.py + +import { FileSectionType } from "../../common/FileSectionType.js"; +import { GlobalConfig } from "../../common/GlobalConfig.js"; +import { SymbolBase } from "./MipsSymbolBase.js"; + +export class SymbolRodata extends SymbolBase { + constructor(context, vromStart, vromEnd, inFileOffset, vram, words, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, inFileOffset, vram, words, FileSectionType.Rodata, segmentVromStart, overlayCategory); + this.stringEncoding = GlobalConfig.RODATA_STRING_ENCODING; + } + + isJumpTable() { + // jumptables must have at least 3 labels + if (this.sizew < 3) return false; + return this.contextSym.isJumpTable(); + } + + isMaybeConstVariable() { + if (this.isFloat(0)) { + if (this.sizew > 1) { + for (const w of this.words.slice(1)) if (w !== 0) return true; + } + return false; + } else if (this.isDouble(0)) { + if (this.sizew > 2) { + for (const w of this.words.slice(2)) if (w !== 0) return true; + } + return false; + } else if (this.isJumpTable()) { + return false; + } else if (this.isString()) { + return false; + } else if (this.isPascalString()) { + return false; + } + return true; + } + + /** @deprecated Checks if the current symbol is .rdata */ + isRdata() { + if (this.isMaybeConstVariable()) return true; + // This symbol could be an unreferenced non-const variable + if (this.contextSym.referenceFunctions.size === 1) return false; + return true; + } + + shouldMigrate() { + if (this.contextSym.functionOwnerForMigration !== null) return true; + if (this.contextSym.forceMigration) return true; + if (this.contextSym.forceNotMigration) return false; + if (this.contextSym.isMips1Double) return true; + + if (this.contextSym.referenceSymbols.size > 0) return false; + if (this.contextSym.referenceFunctions.size > 1) return false; + + if (this.isMaybeConstVariable()) { + if (GlobalConfig.ALLOW_MIGRATING_CONST_VARIABLES) return true; + if (!GlobalConfig.COMPILER.value.allowRdataMigration) return false; + } + + return true; + } + + analyze() { + if (this.contextSym.isDouble()) { + if (this.sizew % 2 !== 0) { + // doubles require an even amount of words + this.contextSym.setTypeSpecial(null, true); + } else { + for (let i = 0; i < Math.floor(this.sizew / 2); i++) { + if (!this.isDouble(i * 2)) { + // checks there's no other overlaping symbols + this.contextSym.setTypeSpecial(null, true); + break; + } + } + } + } + + super.analyze(); + } + + countExtraPadding() { + if (this.contextSym.hasUserDeclaredSize()) { + if (this.sizew * 4 === this.contextSym.getSize()) return 0; + } + + let count = 0; + if (this.isString()) { + for (let i = this.words.length - 1; i > 0; i--) { + if (this.words[i] !== 0) break; + if ((this.words[i - 1] & 0x000000ff) !== 0) break; + count += 1; + } + } else if (this.isDouble(0)) { + for (let i = this.words.length - 1; i > 0; i -= 2) { + if (this.words[i] !== 0 || this.words[i - 1] !== 0) break; + count += 2; + } + } else { + for (let i = this.words.length - 1; i > 0; i--) { + if (this.words[i] !== 0) break; + count += 1; + } + } + return count; + } +} diff --git a/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolText.js b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolText.js new file mode 100644 index 00000000..a8993110 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/MipsSymbolText.js @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/MipsSymbolText.py + +import { FileSectionType } from "../../common/FileSectionType.js"; +import { SymbolBase } from "./MipsSymbolBase.js"; + +export class SymbolText extends SymbolBase { + constructor(context, vromStart, vromEnd, inFileOffset, vram, words, segmentVromStart, overlayCategory) { + super(context, vromStart, vromEnd, inFileOffset, vram, words, FileSectionType.Text, segmentVromStart, overlayCategory); + } +} diff --git a/packages/romdev-spimdisasm/src/mips/symbols/analysis/InstrAnalyzer.js b/packages/romdev-spimdisasm/src/mips/symbols/analysis/InstrAnalyzer.js new file mode 100644 index 00000000..3411c434 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/analysis/InstrAnalyzer.js @@ -0,0 +1,560 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/analysis/InstrAnalyzer.py + +import { rabbitizer } from "../../../rabbitizer.js"; +import { GlobalConfig } from "../../../common/GlobalConfig.js"; +import { newIntSet } from "../../../common/symset.js"; +import { enumValue, hexU } from "../../../py/pyutils.js"; +import { atLeast } from "../../../version.js"; + +const GP_REG = 28; + +export function isGpReg(reg) { + return reg !== null && reg !== undefined && enumValue(reg) === GP_REG; +} + +export function sameRabbitizerEnum(a, b) { + if (a === b) return true; + if (a === null || a === undefined || b === null || b === undefined) return false; + return enumValue(a) === enumValue(b); +} + +export class SymbolTypeInfo { + constructor(accessType, unsignedMemoryAccess) { + this.accessType = accessType; + this.unsignedMemoryAccess = unsignedMemoryAccess; + } + + get _key() { + return `${enumValue(this.accessType)}|${this.unsignedMemoryAccess ? 1 : 0}`; + } + + equals(other) { + return other instanceof SymbolTypeInfo && sameRabbitizerEnum(this.accessType, other.accessType) && this.unsignedMemoryAccess === other.unsignedMemoryAccess; + } +} + +/** dict[SymbolTypeInfo, int] keyed by value equality, insertion ordered. */ +export class SymbolTypeInfoDict { + constructor() { + this._m = new Map(); + } + + get size() { + return this._m.size; + } + + has(info) { + return this._m.has(info._key); + } + + get(info, dflt = undefined) { + const e = this._m.get(info._key); + return e === undefined ? dflt : e[1]; + } + + set(info, value) { + const e = this._m.get(info._key); + if (e === undefined) this._m.set(info._key, [info, value]); + else e[1] = value; + return this; + } + + *keys() { + for (const [k] of this._m.values()) yield k; + } + + *entries() { + for (const [k, v] of this._m.values()) yield [k, v]; + } + + [Symbol.iterator]() { + return this.keys(); + } +} + +export class CploadInfo { + constructor(hiOffset, loOffset, adduOffset = null, reg = null) { + this.hiOffset = hiOffset; + this.loOffset = loOffset; + this.adduOffset = adduOffset; + this.reg = reg; + } +} + +/** Info for tracking when a $gp register is set */ +export class GpSetInfo { + constructor(hiOffset, loOffset, value) { + this.hiOffset = hiOffset; + this.loOffset = loOffset; + this.value = value; + } +} + +function luiValue(instr) { + return instr.getProcessedImmediate() * 0x10000; +} + +export class InstrAnalyzer { + constructor(funcVram, context) { + this.funcVram = funcVram; + /** read-only */ + this.context = context; + + this.currentGpValue = GlobalConfig.GP_VALUE; + + /** Every referenced vram found */ + this.referencedVrams = newIntSet(); + /** Every referenced constant found */ + this.referencedConstants = newIntSet(); + + this.referencedVramsInstrOffset = new Map(); + + // Branches + /** key: branch instruction offset, value: target vram */ + this.branchInstrOffsets = new Map(); + /** key: branch instruction offset, value: relative branch target */ + this.branchTargetInstrOffsets = new Map(); + this.branchLabelOffsets = newIntSet(); + + // Function calls + this.funcCallInstrOffsets = new Map(); + this.funcCallOutsideRangesOffsets = new Map(); + + // Jump register (jumptables) + this.jumpRegisterIntrOffset = new Map(); + this.referencedJumpTableOffsets = new Map(); + /** key: jr instr offset, value: [jumptable reference offset, jumptable address, branch offset] */ + this.rejectedjumpRegisterIntrOffset = new Map(); + + // Jump and link (functions) + this.indirectFunctionCallIntrOffset = new Map(); + this.indirectFunctionCallOffsets = new Map(); + + // Constants + this.constantHiInstrOffset = new Map(); + this.constantLoInstrOffset = new Map(); + this.constantInstrOffset = new Map(); + + // Symbols + this.symbolHiInstrOffset = new Map(); + this.symbolLoInstrOffset = new Map(); + + this.symbolGpInstrOffset = new Map(); + this.gpReferencedSymbols = newIntSet(); + + this.symbolInstrOffset = new Map(); + + /** key: address, value: SymbolTypeInfoDict */ + this.possibleSymbolTypes = new Map(); + this.symbolTypesOffsets = new Map(); + + // %hi/%lo pairing + this.hiToLowDict = new Map(); + this.lowToHiDict = new Map(); + + this.luiInstrs = new Map(); + + this.nonLoInstrOffsets = newIntSet(); + + this.gotAccessAddresses = new Map(); + + /** cploads which are not yet fully paired */ + this.unpairedCploads = []; + /** Offset of every cpload instruction */ + this.cploadOffsets = newIntSet(); + /** Completed cpload, key: offset of last instruction of the cpload */ + this.cploads = new Map(); + + /** Offsets of every instruction that set the $gp register */ + this.gpSetsOffsets = newIntSet(); + /** Instructions setting the $gp register, key: offset of the low instruction */ + this.gpSets = new Map(); + } + + processBranch(regsTracker, instr, instrOffset, _currentVram) { + regsTracker.processBranch(instr, instrOffset); + + if (this.branchInstrOffsets.has(instrOffset)) return; + + const branchOffset = instr.getBranchOffsetGeneric(); + const branch = instrOffset + branchOffset; + const targetBranchVram = this.funcVram + branch; + + if (!GlobalConfig.PIC) this.referencedVrams.add(targetBranchVram); + + this.branchLabelOffsets.add(branch); + this.branchInstrOffsets.set(instrOffset, targetBranchVram); + this.branchTargetInstrOffsets.set(instrOffset, branch); + } + + processFuncCall(instr, instrOffset) { + if (this.funcCallInstrOffsets.has(instrOffset)) return; + + const target = instr.getInstrIndexAsVram(); + if (!this.context.isAddressInGlobalRange(target)) this.funcCallOutsideRangesOffsets.set(instrOffset, target); + + if (!GlobalConfig.PIC) this.referencedVrams.add(target); + this.referencedVramsInstrOffset.set(instrOffset, target); + + this.funcCallInstrOffsets.set(instrOffset, target); + } + + processConstant(regsTracker, luiInstr, luiOffset, lowerInstr, lowerOffset) { + const upperHalf = luiValue(luiInstr); + const lowerHalf = lowerInstr.getProcessedImmediate(); + const constant = Number(BigInt(upperHalf) | BigInt(lowerHalf)); + + this.referencedConstants.add(constant); + + this.constantHiInstrOffset.set(luiOffset, constant); + this.constantLoInstrOffset.set(lowerOffset, constant); + this.constantInstrOffset.set(luiOffset, constant); + this.constantInstrOffset.set(lowerOffset, constant); + + this.hiToLowDict.set(luiOffset, lowerOffset); + this.lowToHiDict.set(lowerOffset, luiOffset); + + regsTracker.processConstant(lowerInstr, constant, lowerOffset); + + return constant; + } + + pairHiLo(hiValue, luiOffset, lowerInstr, lowerOffset) { + // lui being None means this symbol is a $gp access + if (!((hiValue === null && luiOffset === null) || (hiValue !== null && luiOffset !== null))) throw new Error("AssertionError"); + + const lowerHalf = lowerInstr.getProcessedImmediate(); + + if (this.symbolLoInstrOffset.has(lowerOffset)) { + // This %lo has been processed already + + // Check the other lui has the same immediate value as this one, and reject the pair if it doesn't + if (hiValue !== null) { + const otherLuiOffset = this.lowToHiDict.has(lowerOffset) ? this.lowToHiDict.get(lowerOffset) : null; + if (otherLuiOffset !== null) { + const otherLuiInstr = this.luiInstrs.has(otherLuiOffset) ? this.luiInstrs.get(otherLuiOffset) : null; + if (otherLuiInstr !== null) { + if (hiValue !== luiValue(otherLuiInstr)) return null; + } + } + } + + if (!GlobalConfig.COMPILER.value.pairMultipleHiToSameLow) { + // IDO does not pair multiples %hi to the same %lo + return this.symbolLoInstrOffset.get(lowerOffset); + } else { + if (luiOffset === null || hiValue === null) return null; + + if (this.hiToLowDict.get(luiOffset) === lowerOffset && this.lowToHiDict.get(lowerOffset) === luiOffset) { + // This pair has been already paired + return this.symbolLoInstrOffset.get(lowerOffset); + } + + if (luiOffset + 4 === lowerOffset) { + // Make an exception if the lower instruction is just after the LUI + } else { + const upperHalf = hiValue; + const address = upperHalf + lowerHalf; + if (address === this.symbolLoInstrOffset.get(lowerOffset)) { + // Make an exception if the resulting address is the same + } else { + return this.symbolLoInstrOffset.get(lowerOffset); + } + } + } + } + + if (hiValue === null && this.currentGpValue === null) { + // Trying to pair a gp relative offset, but we don't know the gp address + return null; + } + + let upperHalf; + if (hiValue !== null) upperHalf = hiValue; + else upperHalf = this.currentGpValue; + + return upperHalf + lowerHalf; + } + + processSymbol(address, luiOffset, lowerInstr, lowerOffset) { + if (address <= 0) { + // PS2 seems to do LUI/ADDIU pairs for 0 and -1 for some reason, filter them out + if (!GlobalConfig.PIC) return null; + } + + // filter out stuff that may not be a real symbol + let filterOut = false; + if (!this.context.totalVramRange.isInRange(address)) { + if (GlobalConfig.SYMBOL_FINDER_FILTER_LOW_ADDRESSES || GlobalConfig.SYMBOL_FINDER_FILTER_HIGH_ADDRESSES) { + filterOut ||= GlobalConfig.SYMBOL_FINDER_FILTER_LOW_ADDRESSES && address < GlobalConfig.SYMBOL_FINDER_FILTER_ADDRESSES_ADDR_LOW; + filterOut ||= GlobalConfig.SYMBOL_FINDER_FILTER_HIGH_ADDRESSES && address >= GlobalConfig.SYMBOL_FINDER_FILTER_ADDRESSES_ADDR_HIGH; + } else { + filterOut = true; + } + } + + if (filterOut) { + const contextSym = this.context.globalSegment.getSymbol(address); + if (contextSym !== null) { + if (contextSym.isUserDeclared) { + // If the user declared a symbol outside the total vram range then use it anyways + filterOut = false; + } + } + } + + if (address > 0 && filterOut && !sameRabbitizerEnum(lowerInstr.uniqueId, rabbitizer.InstrId.cpu_addiu)) { + if (GlobalConfig.SYMBOL_FINDER_FILTERED_ADDRESSES_AS_CONSTANTS) { + // Let's pretend this value is a constant + const constant = address; + this.referencedConstants.add(constant); + + this.constantLoInstrOffset.set(lowerOffset, constant); + this.constantInstrOffset.set(lowerOffset, constant); + if (luiOffset !== null) { + this.constantHiInstrOffset.set(luiOffset, constant); + this.constantInstrOffset.set(luiOffset, constant); + + this.hiToLowDict.set(luiOffset, lowerOffset); + this.lowToHiDict.set(lowerOffset, luiOffset); + } + } + return null; + } + + if (!GlobalConfig.PIC) this.referencedVrams.add(address); + + if (!this.symbolLoInstrOffset.has(lowerOffset)) { + this.symbolLoInstrOffset.set(lowerOffset, address); + this.symbolInstrOffset.set(lowerOffset, address); + this.referencedVramsInstrOffset.set(lowerOffset, address); + } + if (luiOffset !== null) { + if (!this.symbolHiInstrOffset.has(luiOffset)) { + this.symbolHiInstrOffset.set(luiOffset, address); + this.symbolInstrOffset.set(luiOffset, address); + this.referencedVramsInstrOffset.set(luiOffset, address); + } + + this.hiToLowDict.set(luiOffset, lowerOffset); + this.lowToHiDict.set(lowerOffset, luiOffset); + } else { + this.symbolGpInstrOffset.set(lowerOffset, address); + this.gpReferencedSymbols.add(address); + this.symbolInstrOffset.set(lowerOffset, address); + this.referencedVramsInstrOffset.set(lowerOffset, address); + } + + this.processSymbolType(address, lowerInstr, lowerOffset); + + return address; + } + + processGotSymbol(address, instr, instrOffset) { + if (address <= 0) return; + this.gotAccessAddresses.set(instrOffset, address); + } + + processSymbolType(address, instr, instrOffset) { + const accessType = instr.getAccessType(); + const unsignedMemoryAccess = instr.doesUnsignedMemoryAccess(); + if (sameRabbitizerEnum(accessType, rabbitizer.AccessType.INVALID)) return; + + if (!this.possibleSymbolTypes.has(address)) this.possibleSymbolTypes.set(address, new SymbolTypeInfoDict()); + const symAccess = new SymbolTypeInfo(accessType, unsignedMemoryAccess); + const dict = this.possibleSymbolTypes.get(address); + if (!dict.has(symAccess)) dict.set(symAccess, 0); + dict.set(symAccess, dict.get(symAccess) + 1); + + this.symbolTypesOffsets.set(instrOffset, symAccess); + } + + processSymbolDereferenceType(regsTracker, instr, instrOffset) { + const address = regsTracker.getAddressIfCanSetType(instr, instrOffset); + if (address === null || address === undefined) return; + this.processSymbolType(address, instr, instrOffset); + } + + symbolFinder(regsTracker, instr, prevInstr, instrOffset) { + if (instr.canBeHi()) { + if (prevInstr === null) regsTracker.processLui(instr, instrOffset); + else regsTracker.processLui(instr, instrOffset, prevInstr); + this.luiInstrs.set(instrOffset, instr); + return; + } + + if (instr.doesLoad() && isGpReg(instr.rs)) regsTracker.processGpLoad(instr, instrOffset); + + if (!instr.canBeLo()) return; + + if (instr.isUnsigned()) { + // Constants + const luiOffset = regsTracker.getLuiOffsetForConstant(instr); + if (luiOffset === null || luiOffset === undefined) return; + const luiInstr = this.luiInstrs.has(luiOffset) ? this.luiInstrs.get(luiOffset) : null; + if (luiInstr === null) return; + this.processConstant(regsTracker, luiInstr, luiOffset, instr, instrOffset); + return; + } + + if (this.nonLoInstrOffsets.has(instrOffset)) return; + + const pairingInfo = regsTracker.preprocessLoAndGetInfo(instr, instrOffset); + if (!pairingInfo.shouldProcess) { + if (regsTracker.hasLoButNoHi(instr)) this.nonLoInstrOffsets.add(instrOffset); + return; + } + + if (pairingInfo.isGpGot && !GlobalConfig.PIC) return; + + let upperHalf = pairingInfo.value; + let luiOffset = pairingInfo.instrOffset; + if (pairingInfo.isGpRel) { + if (atLeast("1.42.0") && !GlobalConfig.GP_VALUE && !GlobalConfig.PIC) { + // If there's no gp value configured then it is very unlikely + // for symbolizing as %gp_rel to be correct. + return; + } + upperHalf = null; + luiOffset = null; + } + + if (luiOffset !== null) { + const luiInstr = this.luiInstrs.get(luiOffset); + if (luiInstr !== undefined && isGpReg(luiInstr.rt)) { + if (instr.readsRs() && isGpReg(instr.rs) && instr.modifiesRt() && isGpReg(instr.rt)) { + if (GlobalConfig.PIC) { + // cpload + this.unpairedCploads.push(new CploadInfo(luiOffset, instrOffset)); + } else { + const hiGpValue = luiValue(luiInstr); + const loGpValue = instr.getProcessedImmediate(); + const gpValue = hiGpValue + loGpValue; + this.gpSets.set(instrOffset, new GpSetInfo(luiOffset, instrOffset, gpValue)); + this.gpSetsOffsets.add(luiOffset); + this.gpSetsOffsets.add(instrOffset); + if (!GlobalConfig.PIC) this.currentGpValue = gpValue; + } + // early return to avoid counting this pairing as a normal symbol + return; + } + } + } + + let address = this.pairHiLo(upperHalf, luiOffset, instr, instrOffset); + if (address === null) return; + + if (upperHalf === null) { + if (GlobalConfig.PIC) { + this.processGotSymbol(address, instr, instrOffset); + regsTracker.processLo(instr, address, instrOffset); + return; + } + } + + address = this.processSymbol(address, luiOffset, instr, instrOffset); + if (address !== null) regsTracker.processLo(instr, address, instrOffset); + } + + processJumpRegister(regsTracker, instr, instrOffset) { + const jrRegData = regsTracker.getJrRegData(instr); + if (jrRegData.hasInfo()) { + const offset = jrRegData.offset(); + const address = jrRegData.address(); + + if (jrRegData.checkedForBranching()) { + this.rejectedjumpRegisterIntrOffset.set(instrOffset, [offset, address, jrRegData.lastBranchOffset()]); + } else { + // Jumptables never check the register they are branching into, + // since the references should always be valid. + this.referencedJumpTableOffsets.set(offset, address); + } + + this.jumpRegisterIntrOffset.set(instrOffset, address); + if (!GlobalConfig.PIC) this.referencedVrams.add(address); + } + } + + processJumpAndLinkRegister(regsTracker, instr, instrOffset) { + const jrRegData = regsTracker.getJrRegData(instr); + if (jrRegData.hasInfo()) { + const offset = jrRegData.offset(); + const address = jrRegData.address(); + + this.indirectFunctionCallOffsets.set(offset, address); + this.indirectFunctionCallIntrOffset.set(instrOffset, address); + if (!GlobalConfig.PIC) this.referencedVrams.add(address); + } + } + + processInstr(regsTracker, instr, instrOffset, currentVram, prevInstr) { + if (instr.isBranch() || instr.isUnconditionalBranch()) { + this.processBranch(regsTracker, instr, instrOffset, currentVram); + } else if (instr.isJumpWithAddress()) { + this.processFuncCall(instr, instrOffset); + } else if (instr.hasOperandAlias(rabbitizer.OperandType.cpu_immediate)) { + this.symbolFinder(regsTracker, instr, prevInstr ?? null, instrOffset); + this.processSymbolDereferenceType(regsTracker, instr, instrOffset); + } else if (instr.isJumptableJump()) { + this.processJumpRegister(regsTracker, instr, instrOffset); + } else if (instr.isJump() && instr.doesLink()) { + // jalr, implicit not isJumpWithAddress + this.processJumpAndLinkRegister(regsTracker, instr, instrOffset); + } else if (sameRabbitizerEnum(instr.uniqueId, rabbitizer.InstrId.cpu_addu)) { + // special check for .cpload + if (this.unpairedCploads.length > 0) { + if (isGpReg(instr.rd) && isGpReg(instr.rs)) { + const cpload = this.unpairedCploads.pop(); + cpload.adduOffset = instrOffset; + cpload.reg = instr.rt; + this.cploadOffsets.add(cpload.hiOffset); + this.cploadOffsets.add(cpload.loOffset); + this.cploadOffsets.add(instrOffset); + this.cploads.set(instrOffset, cpload); + } + } + } + + regsTracker.overwriteRegisters(instr, instrOffset); + if (!GlobalConfig.PIC) { + const dstReg = instr.getDestinationGpr(); + if (dstReg !== null && dstReg !== undefined && isGpReg(dstReg)) { + if (!this.gpSets.has(instrOffset)) { + this.gpSets.set(instrOffset, null); + this.gpSetsOffsets.add(instrOffset); + this.currentGpValue = null; + } + } + } + } + + processPrevFuncCall(regsTracker, instr, prevInstr, _currentVram = null) { + regsTracker.unsetRegistersAfterFuncCall(instr, prevInstr); + } + + printAnalisisDebugInfo_IterInfo(regsTracker, instr, currentVram) { + if (!GlobalConfig.PRINT_FUNCTION_ANALYSIS_DEBUG_INFO) return; + process.stdout.write(`_printAnalisisDebugInfo_IterInfo\n\nvram: ${hexU(currentVram)}\n${instr}\n\n`); + } + + printSymbolFinderDebugInfo_UnpairedLuis() { + if (!GlobalConfig.PRINT_UNPAIRED_LUIS_DEBUG_INFO) return; + + let firstNotePrinted = false; + for (const [instructionOffset, luiInstr] of this.luiInstrs) { + if (this.constantInstrOffset.has(instructionOffset)) continue; + if (GlobalConfig.SYMBOL_FINDER_FILTER_LOW_ADDRESSES && luiInstr.getProcessedImmediate() < 0x8000) continue; + if (GlobalConfig.SYMBOL_FINDER_FILTER_HIGH_ADDRESSES && luiInstr.getProcessedImmediate() >= 0xc000) continue; + + if (!this.symbolInstrOffset.has(instructionOffset)) { + if (!firstNotePrinted) { + process.stdout.write(`_printSymbolFinderDebugInfo_UnpairedLuis\nfuncVram: ${hexU(this.funcVram, 8)}\n`); + firstNotePrinted = true; + } + process.stdout.write(`${hexU(luiInstr.vram, 6)} NO ${luiInstr}\n`); + } + } + if (firstNotePrinted) process.stdout.write("\n"); + } +} diff --git a/packages/romdev-spimdisasm/src/mips/symbols/analysis/index.js b/packages/romdev-spimdisasm/src/mips/symbols/analysis/index.js new file mode 100644 index 00000000..69ed7018 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/analysis/index.js @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/analysis/__init__.py + +export { InstrAnalyzer, SymbolTypeInfo, CploadInfo, GpSetInfo } from "./InstrAnalyzer.js"; diff --git a/packages/romdev-spimdisasm/src/mips/symbols/index.js b/packages/romdev-spimdisasm/src/mips/symbols/index.js new file mode 100644 index 00000000..eeff7f33 --- /dev/null +++ b/packages/romdev-spimdisasm/src/mips/symbols/index.js @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +// Port of spimdisasm/mips/symbols/__init__.py + +import * as analysis from "./analysis/index.js"; + +export { analysis }; +export { SymbolBase } from "./MipsSymbolBase.js"; +export { SymbolText } from "./MipsSymbolText.js"; +export { SymbolData } from "./MipsSymbolData.js"; +export { SymbolRodata } from "./MipsSymbolRodata.js"; +export { SymbolBss } from "./MipsSymbolBss.js"; +export { SymbolGccExceptTable } from "./MipsSymbolGccExceptTable.js"; +export { SymbolFunction } from "./MipsSymbolFunction.js"; diff --git a/packages/romdev-spimdisasm/src/py/cjk-tables-jp.js b/packages/romdev-spimdisasm/src/py/cjk-tables-jp.js new file mode 100644 index 00000000..2e0058ad --- /dev/null +++ b/packages/romdev-spimdisasm/src/py/cjk-tables-jp.js @@ -0,0 +1,406 @@ +// GENERATED by scripts/gen-cjk-tables.mjs - DO NOT EDIT. +// Japanese decode maps (JIS X 0208, JIS X 0212, CP932 extensions). +// Source: CPython 3.13 Modules/cjkcodecs/mappings_jp.h (sha1 29b25408074ca9779bc454e79e54e631b816bf59), +// itself generated by CPython's Tools/unicode/genmap_japanese.py. +// https://github.com/python/cpython/blob/3.13/Modules/cjkcodecs/mappings_jp.h +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved. +// Licensed under the Python Software Foundation License Version 2 (PSF-2.0). +// +// Format: data is a base64 little-endian Uint16 array (the C __ array, +// with U=0xFFFE, N=0xFFFF, D=0xFFFD); index[lead] is null or +// [offset, bottom, top] exactly like the C struct index array. + +export const jisx0208_decmap = { + length: 6956, + index: [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[0,33,126],[94,33,126],[188,48,122],[263,33,115],[346,33,118],[432,33,88],[488,33,113],[569,33,64],null,null,null,null,null,null,null,[601,33,126],[695,33,126],[789,33,126],[883,33,126],[977,33,126],[1071,33,126],[1165,33,126],[1259,33,126],[1353,33,126],[1447,33,126],[1541,33,126],[1635,33,126],[1729,33,126],[1823,33,126],[1917,33,126],[2011,33,126],[2105,33,126],[2199,33,126],[2293,33,126],[2387,33,126],[2481,33,126],[2575,33,126],[2669,33,126],[2763,33,126],[2857,33,126],[2951,33,126],[3045,33,126],[3139,33,126],[3233,33,126],[3327,33,126],[3421,33,126],[3515,33,83],[3566,33,126],[3660,33,126],[3754,33,126],[3848,33,126],[3942,33,126],[4036,33,126],[4130,33,126],[4224,33,126],[4318,33,126],[4412,33,126],[4506,33,126],[4600,33,126],[4694,33,126],[4788,33,126],[4882,33,126],[4976,33,126],[5070,33,126],[5164,33,126],[5258,33,126],[5352,33,126],[5446,33,126],[5540,33,126],[5634,33,126],[5728,33,126],[5822,33,126],[5916,33,126],[6010,33,126],[6104,33,126],[6198,33,126],[6292,33,126],[6386,33,126],[6480,33,126],[6574,33,126],[6668,33,126],[6762,33,126],[6856,33,126],[6950,33,38],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null], + data: + "ADABMAIwDP8O//swGv8b/x//Af+bMJwwtABA/6gAPv/j/z///TD+MJ0wnjADMN1OBTAGMAcw/DAVIBAgD/9cABwwFiBc/yYgJSAY" + + "IBkgHCAdIAj/Cf8UMBUwO/89/1v/Xf8IMAkwCjALMAwwDTAOMA8wEDARMAv/EiKxANcA9wAd/2AiHP8e/2YiZyIeIjQiQiZAJrAA" + + "MiAzIAMh5f8E/6IAowAF/wP/Bv8K/yD/pwAGJgUmyyXPJc4lxyXGJaEloCWzJbIlvSW8JTsgEjCSIZAhkSGTIRMw/v/+//7//v/+" + + "//7//v/+//7//v/+/wgiCyKGIocigiKDIioiKSL+//7//v/+//7//v/+//7/JyIoIqwA0iHUIQAiAyL+//7//v/+//7//v/+//7/" + + "/v/+//7/ICKlIhIjAiIHImEiUiJqImsiGiI9Ih0iNSIrIiwi/v/+//7//v/+//7//v8rITAgbyZtJmomICAhILYA/v/+//7//v/v" + + "JRD/Ef8S/xP/FP8V/xb/F/8Y/xn//v/+//7//v/+//7//v8h/yL/I/8k/yX/Jv8n/yj/Kf8q/yv/LP8t/y7/L/8w/zH/Mv8z/zT/" + + "Nf82/zf/OP85/zr//v/+//7//v/+//7/Qf9C/0P/RP9F/0b/R/9I/0n/Sv9L/0z/Tf9O/0//UP9R/1L/U/9U/1X/Vv9X/1j/Wf9a" + + "/0EwQjBDMEQwRTBGMEcwSDBJMEowSzBMME0wTjBPMFAwUTBSMFMwVDBVMFYwVzBYMFkwWjBbMFwwXTBeMF8wYDBhMGIwYzBkMGUw" + + "ZjBnMGgwaTBqMGswbDBtMG4wbzBwMHEwcjBzMHQwdTB2MHcweDB5MHowezB8MH0wfjB/MIAwgTCCMIMwhDCFMIYwhzCIMIkwijCL" + + "MIwwjTCOMI8wkDCRMJIwkzChMKIwozCkMKUwpjCnMKgwqTCqMKswrDCtMK4wrzCwMLEwsjCzMLQwtTC2MLcwuDC5MLowuzC8ML0w" + + "vjC/MMAwwTDCMMMwxDDFMMYwxzDIMMkwyjDLMMwwzTDOMM8w0DDRMNIw0zDUMNUw1jDXMNgw2TDaMNsw3DDdMN4w3zDgMOEw4jDj" + + "MOQw5TDmMOcw6DDpMOow6zDsMO0w7jDvMPAw8TDyMPMw9DD1MPYwkQOSA5MDlAOVA5YDlwOYA5kDmgObA5wDnQOeA58DoAOhA6MD" + + "pAOlA6YDpwOoA6kD/v/+//7//v/+//7//v/+/7EDsgOzA7QDtQO2A7cDuAO5A7oDuwO8A70DvgO/A8ADwQPDA8QDxQPGA8cDyAPJ" + + "AxAEEQQSBBMEFAQVBAEEFgQXBBgEGQQaBBsEHAQdBB4EHwQgBCEEIgQjBCQEJQQmBCcEKAQpBCoEKwQsBC0ELgQvBP7//v/+//7/" + + "/v/+//7//v/+//7//v/+//7//v/+/zAEMQQyBDMENAQ1BFEENgQ3BDgEOQQ6BDsEPAQ9BD4EPwRABEEEQgRDBEQERQRGBEcESARJ" + + "BEoESwRMBE0ETgRPBAAlAiUMJRAlGCUUJRwlLCUkJTQlPCUBJQMlDyUTJRslFyUjJTMlKyU7JUslICUvJSglNyU/JR0lMCUlJTgl" + + "QiWcThZVA1o/lsBUG2EoY/ZZIpB1hByDUHqqYOFjJW7tZWaEpoL1m5NoJ1ehZXFim1vQWXuG9Jhifb59jpsWYp98t4iJW7VeCWOX" + + "Zkhox5WNl09n5U4KT01PnU9JUPJWN1nUWQFaCVzfYA9hcGETZgVpunBPdXB1+3mtfe99w4AOhGOIAotVkHqQO1OVTqVO31eygMGQ" + + "73gATvFYom44kDJ6KIOLgi+cQVFwU71U4VTgVvtZFV/ymOtt5IAthWKWcJaglvuXC1TzU4dbz3C9f8KP6JZvU1ydunoRTpN4/IEm" + + "bhhWBFUdaxqFO5zlWalTZm3cdI+VQlaRTkuQ8pZPgwyZ4VO2VTBbcV8gZvNmBGg4bPNsKW1bdMh2Tno0mPGCW4hgiu2Ssm2rdcp2" + + "xZmmYAGLio2ylY5prVOGURJXMFhEWbRb9l4oYKlj9GO/bBRvjnAUcVlx1XE/cwF+doLRgpeFYJBbkhudaVi8ZVpsJXX5US5ZZVmA" + + "X9xfvGL6ZSpqJ2u0a4tzwX9WiSydDp3EnqFclmx7gwRRS1y2YcaBdmhhcllO+k94U2lgKW5PevOXC04WU+5OVU89T6FPc0+gUu9T" + + "CVYPWcFatlvhW9F5h2acZ7ZnTGuzbGtwwnONeb55PHqHe7GC24IEg3eD74PTg2aHsoopVqiM5o9OkB6XiobET+hcEWJZcjt15YG9" + + "gv6GwIzFlhOZ1ZnLThpP44neVkpYylj7XutfKmCUYGJg0GESYtBiOWVBm2ZmsGh3bXBwTHWGdnV9pYL5h4uVjpadjPFRvlIWWbNU" + + "s1sWXWhhgmmvbY14y4RXiHKKp5O4mmxtqJnZhqNX/2fOhg6Sg1KHVgRU017hYrlkPGg4aLtrcnO6eGt6monSiWuNA4/tkKOVlJZp" + + "l2Zbs1x9aU2YTpibYyB7K2p/arZoDZxfb3JSnVVwYOxiO20HbtFuW4QQiUSPFE45nPZTG2k6aoSXKmhcUcN6soTckYyTW1YonSJo" + + "BYMxhKV8CFLFguZ0fk6DT6BR0lsKUthS51L7XZpVKljmWYxbmFvbW3JeeV6jYB9hY2G+YdtjYmXRZ1No+mg+a1NrV2wib5dvRW+w" + + "dBh143YLd/96oXshfOl9Nn/wf52AZoKeg7OJzIqrjISQUZSTlZGVopVlltOXKJkYgjhOK1S4XMxdqXNMdjx3qVzrfwuNwZYRmFSY" + + "WJgBTw5PcVOcVWhW+ldHWQlbxFuQXAxefl7MX+5jOmfXZeJlH2fLaMRoX2owXsVrF2x9bH91SHljWwB6AH29X4+JGIq0jHeNzI4d" + + "j+KYDpo8m4BOfVAAUZNZnFsvYoBi7GQ6a6BykXVHeal/+4e8inCLrGPKg6CXCVQDVKtVVGhYanCKJ3h1Z82edFOiWxqBUIYGkBhO" + + "RU7HThFPylM4VK5bE18lYFFlPWdCbHJs42x4cAN0dnquegh7Gn3+fGZ952VbcrtTRVzoXdJi4GIZYyBuWoYxit2N+JIBb6Z5Wpuo" + + "TqtOrE6bT6BP0VBHUfZ6cVH2UVRTIVN/U+tTrFWDWOFcN19KXy9gUGBtYB9jWWVLasFswnLtcu93+IAFgQiCToX3kOGT/5dXmVqa" + + "8E7dUS1cgWZtaUBc8mZ1aYlzUGiBfMVQ5FJHV/5dJpOkZSNrPWs0dIF5vXlLe8p9uYLMg3+IX4k5i9GP0ZEfVICSXU42UOVTOlPX" + + "cpZz6Xfmgq+OxpnImdKZd1EaYV6GsFV6enZQ01tHkIWWMk7baueRUVxIXJhjn3qTbHSXYY+qeopxiJaCfBdocH5RaGyT8lIbVKuF" + + "E4qkf82O4ZBmU4iIQXnCT75QEVJEUVNVLVfqc4tXUVliX4RfdWB2YWdhqWGyYzpkbGVvZkJoE25mdT16+3xMfZl9S35rfw6DSoPN" + + "hgiKY4pmi/2OGpiPnbiCzo/om4dSH2KDZMBvmZZBaJFQIGt6bFRvdHpQfUCII4oIZ/ZOOVAmUGVQfFE4UmNSp1UPVwVYzFr6XrJh" + + "+GHzYnJjHGkpan1yrHIucxR4b3h5fQx3qYCLiRmL4ozSjmOQdZN6llWYE5p4nkNRn1OzU3teJl8bbpBuhHP+c0N9N4IAivqKUJZO" + + "TgtQ5FN8VPpW0VlkW/Fdq14nXzhiRWWvZ1Zu0HLKfLSIoYDhgPCDToaHiuiNN5LHlmeYE5+UTpJODU9IU0lUPlQvWoxfoV+fYKdo" + + "jmpadIF4noqkineLkJFeTsmbpE58T69PGVAWUElRbFGfUrlS/lKaU+NTEVQOVIlVUVeiV31ZVFtdW49b5V3nXfddeF6DXppet14Y" + + "X1JgTGGXYthip2M7ZQJmQ2b0Zm1nIWiXaMtpX2wqbWltL26dbjJ1h3ZseD964HwFfRh9Xn2xfRWAA4CvgLGAVIGPgSqCUoNMiGGI" + + "G4uijPyMypB1kXGSP3j8kqSVTZYFmJmZ2Jo7nVtSq1L3UwhU1Vj3YuBvaoxfj7meS1E7UkpU/VZAeneRYJ3SnkRzCW9wgRF1/V/a" + + "YKia23K8j2RrA5jKTvBWZFe+WFpaaGDHYQ9mBmY5aLFo923VdTp9boJCm5tOUE/JUwZVb13mXe5d+2eZbHN0AnhQipaT34hQV6de" + + "K2O1UKxQjVEAZ8lUXli7WbBbaV9NYqFjPWhzawhufXDHkYByFXgmeG15jmUwfdyDwYgJj5uWZFIoV1Bnan+hjLRRQlcqljpYimm0" + + "gLJUDl38V5V4+p1cT0pSi1Q+ZChmFGf1Z4R6VnsifS+TXGitmzl7GVOKUTdS31v2Yq5k5mQtZ7prqYXRlpB21ptMYwaTq5u/dlJm" + + "CU6YUMJTcVzoYJJkY2VfaOZxynMjdZd7gn6VhoOL24x4kRCZrGWrZotr1U7UTjpPf086UvhT8lPjVdtW61jLWclZ/1lQW01cAl4r" + + "XtdfHWAHYy9lXFuvZb1l6GWdZ2Jre2sPbEVzSXnBefh8GX0rfaKAAoHzgZaJXoppimaKjIruiseM3IzMlvyYb2uLTjxPjU9QUVdb" + + "+ltIYQFjQmYha8tuu2w+cr101HXBeDp5DIAzgOqBlISej1Bsf54PX1iLK536eviOjVvrlgNO8VP3VzFZyVqkW4lgf24Gb7516oyf" + + "WwCF4HtyUPRnnYJhXEqFHn4OgplRBFxoY2aNnGVucT55F30FgB2Lyo5ukMeGqpAfUPpSOlxTZ3xwNXJMkciRK5PlgsJbMV/5YDtO" + + "1lOIW0tiMWeKa+ly4HMuemuBo41SkZaZElHXU2pU/1uIYzlqrH0Al9pWzlNoVJdbMVzeXe5PAWH+YjJtwHnLeUJ9TX7Sf+2BH4KQ" + + "hEaIcomQi3SOL48xkEuRbJHGlpyRwE5PT0VRQVOTXw5i1GdBbAtuY3Mmfs2Rg5LUUxlZv1vRbV15Ln6bfH5Yn3H6UVOI8I/KT/tc" + + "JWasd+N6HIL/mcZRql/sZW9piWvzbZZuZG/+dhR94V11kIeRBpjmUR1SQGKRZtlmGm62XtJ9cn/4Zq+F94X4iqlS2VNzWY9ekF9V" + + "YOSSZJa3UB9R3VIgU0dT7FPoVEZVMVUXVmhZvlk8WrVbBlwPXBFcGlyEXope4F5wX39ihGLbYoxjd2MHZgxmLWZ2Zn5nomgfajVq" + + "vGyIbQluWG48cSZxZ3HHdQF3XXgBeWV58HngehF7p3w5fZaA1oOLhEmFXYjziB+KPIpUinOKYYzejKSRZpJ+kxiUnJaYlwpOCE4e" + + "TldOl1FwUs5XNFjMWCJbOF7FYP5kYWdWZ0RttnJzdWN6uIRyi7iRIJMxVvRX/pjtYg1plmvtcVR+d4ByguaJ35hVh7GPO1w4T+FP" + + "tU8HVSBa3VvpW8NfTmEvY7BlS2buaJtpeG3xbTN1uXUfd1555nkzfeOBr4KqhaqJOoqrjpuPMpDdkQeXuk7BTgNSdVjsWAtcGnU9" + + "XE6BCorFj2OWbZcle8+KCJhikfNWqFMXkDlUglclXqhjNGyKcGF3i3zgf3CIQpBUkRCTGJOPll50xJoHXWldcGWiZ6iN25ZuY0ln" + + "GWnFgxeYwJb+iIRvemT4WxZOLHBddS9mxFE2UuJS01mBXydgEGI/ZXRlH2Z0ZvJoFmhjawVucnIfddt2vnxWgPBY/Yh/iaCKk4rL" + + "ih2QkpFSl1mXiWUOegaBu5YtXtxgGmKlZRRmkGfzd016TXw+fgqBrIxkjeGNX46peAdS2WKlY0JkmGItioN6wHusiuqWdn0MgkmH" + + "2U5IUUNTYFOjWwJcFlzdXSZiR2KwZBNoNGjJbEVtF23TZ1xvTnF9cctlf3qte9p9Sn6of3qBG4I5gqaFborOjPWNeJB3kK2SkZKD" + + "la6bTVKEVThvNnFoUYV5VX6zgc58TFZRWKhcqmP+Zv1mWmnZco91jnUOeVZ533mXfCB9RH0HhjSKO5ZhkCCf51B1UsxT4lMJUKpV" + + "7lhPWT1yi1tkXB1T42DzYFxjg2M/Y7tjzWTpZflm413Naf1pFW/lcYlO6XX4dpN633zPfZx9YYBJg1iDbIS8hPuFxYhwjQGQbZCX" + + "kxyXEprPUJdYjmHTgTWFCI0gkMNPdFBHUnNTb2BJY19nLG6zjR+Q109eXMqMz2WafVJTloh2UcNjWFtrWwpcDWRRZ1yQ1k4aWSpZ" + + "cGxRij5VFVilWfBgU2LBZzWCVWlAlsSZKJpTTwZY/lsQgLFcL16FXyBgS2E0Yv9m8Gzebs6Af4HUgouIuIwAkC6Qipbbntub407w" + + "UydZLHuNkUyY+Z3dbidwU1NEVYVbWGKeYtNiomzvbyJ0F4o4lMFv/oo4g+dR+IbqU+lTRk9UkLCPalkxgf1d6nq/j9poN4z4ckic" + + "PWqwijlOWFMGVmZXxWKiY+ZlTmvhbVturXDtd+96qnu7fT2AxoDLhpWKW5PjVsdYPl+tZZZmgGq1azd1x4okUOV3MFcbX2VgemZg" + + "bPR1Gnpuf/SBGIdFkLOZyXtcdfl6UXvEhBCQ6XmSejaD4VpAdy1O8k6ZW+BfvWI8ZvFn6GxrhneIO4pOkfOS0JkXaiZwKnPngleE" + + "r4wBTkZRy1GLVfVbFl4zXoFeFF81X2tftF/yYRFjomYdZ25vUnI6dTp3dIA5gXiBdoe/ityKhY3zjZqSd5UCmOWcxVJXY/R2FWeI" + + "bM1zw4yuk3OWJW2cWA5pzGn9j5qT23UakFpYAmi0Y/tpQ08sb9hnu48mhbR9VJM/aXBvalf3WCxbLH0qcgpU45G0na1OTk9cUHVQ" + + "Q1KejEhUJFiaWx1elV6tXvdeH1+MYLViOmPQY69oQGyHeI55C3rgfUeCAormikSOE5C4kC2R2JEOn+VsWGTiZHVl9G6Edht7aZDR" + + "k7pu8lS5X6RkTY/tj0SSeFFrWClZVVyXXvttj34cdbyM4o5bmLlwHU+/a7FvMHX7lk5REFQ1WFdYrFlgXJJfl2VcZyFue3bfg+2M" + + "FJD9kE2TJXg6eKpSpl4fV3RZEmASUFpRrFHNUQBSEFVUWFhYV1mVW/Zci128YJViLWRxZ0NovGjfaNd22G1vbpttb3DIcVNf2HV3" + + "eUl7VHtSe9Z8cX0wUmOEaYXkhQ6KBItGjA+OA5APkBmUdpYtmDCa2JXNUNVSDFQCWA5cp2GeZB5ts3flevSABIRTkIWS4FwHnT9T" + + "l1+zX5xteXJjd7955HvSa+xyrYoDaGFq+FGBejRpSlz2nOuCxVtJkR5weFZvXMdgZmWMbFqMQZATmFFUx2YNkkhZo5CFUU1O6lGZ" + + "hQ6LWHB6Y0uTYmm0mQR+d3VXU2Bp347jll1sjE48XBBf6Y8CU9GMiYB5hv9e5WVzTmVRglk/XO6X+06KWc1fjYrhb7B5YnnnW3GE" + + "K3OxcXRe9V97Y5pkw3GYfENO/F5LTtxXolapYMNvDX39gDOBv4Gyj5eJpIb0XYpirWSHiXdn4mw+bTZ0NHhGWnV/rYKsmfNPw17d" + + "YpJjV2VvZ8N2THLMgLqAKY9NkQ1Q+VeSWoVoc2lkcf1yt4zyWOCMapYZkH+H5HnndymEL09lUlpTzWLPZ8psfXaUe5V8NoKEheuP" + + "3WYgbwZyG36rg8GZpp79UbF7cni4e4eASHvoamFejIBRdWB1a1FikoxuenaXkeqaEE9wf5xiT3ullemcelZZWOSGvJY0TyRSSlPN" + + "U9tTBl4sZJFlf2c+bE5sSHKvcu1zVHVBfiyC6YWpjMR7xpFpcRKY75g9Y2lmanXkdtB4Q4XuhipTUVMmVINZh158X7JgSWJ5Yqti" + + "kGXUa8xssnWudpF42HnLfXd/pYCriLmKu4x/kF6X25gLajh8mVA+XK5fh2fYazV0CXeOfzufymcXejlTi3XtmmZfnYHxg5iAPF/F" + + "X2J1Rns8kGdo61mbWhB9fnYsi/VPal8ZajdsAm/idGh5aIhVinmM317PY8V10nnXgiiT8pKchO2GLZzBVGxfjGVcbRVwp4zTjDuY" + + "T2X2dA1O2E7gVytZZlrMW6hRA16cXhZgdmJ3ZadlbmZubTZyJntQgZqBmYJci6CM5ox0jRyWRJauT6tkZmsegmGEaoXokAFcU2mo" + + "mHqEV4UPT29SqV9FXg1nj3l5gQeJhon1bRdfVWK4bM9OaXKSmwZSO1R0VrNYpGFuYhpxblmJfN58G33wlodlXoAZTnVPdVFAWGNe" + + "c14KX8RnJk49hYmVW5ZzfAGY+1DBWFZ2p3glUqV3EYWGe09QCVlHcsd76H26j9SPTZC/T8lSKVoBX62X3U8XguqSA1dVY2lrK3Xc" + + "iBSPQnrfUpNYVWEKYq5mzWs/fOmDI1D4TwVTRlQxWElZnVvwXO9cKV2WXrFiZ2M+ZbllC2fVbOFs+XAyeCt+3oCzggyE7IQChxKJ" + + "KopKjKaQ0pL9mPOcbJ1PTqFOjVBWUkpXqFk9Xthf2V8/YrRmG2fQZ9JoklEhfaqAqIEAi4yMv4x+kjKWIFQsmBdT1VBcU6hYsmQ0" + + "Z2dyZndGeuaRw1KhbIZrAFhMXlRZLGf7f+FRxnZpZOh4VJu7nstXuVknZppnzmvpVNlpVV6cgZVnqpv+Z1KcXWimTuNPyFO5Yitn" + + "q2zEj61PbX6/ngdOYmGAbitvE4VzVCpnRZvzXZV7rFzGWxyHSm7RhBR6CIGZWY18EWwgd9lSIlkhcV9y23cnl2GdC2l/WhhapVEN" + + "VH1UDmbfdvePmJL0nOpZXXLFbk1RyWi/fex9Ype6nnhkIWoCg4RZX1vbaxtz8nayfReAmYQyUShn2Z7udmJn/1IFmSRcO2J+fLCM" + + "T1W2YAt9gJUBU19OtlEcWTpyNoDOkSVf4neEU3lfBH2shTOKjY5Wl/NnroVTlAlhCGG5bFJ27Yo4jy9VUU8qUcdSy1OlW31eoGCC" + + "YdZjCWfaZ2dujG02czdzMXVQedWImIpKkJGQ9ZDElo2HFVmITllPDk6Jij+PEJitUHxellm5W7he2mP6Y8Fk3GZKadhpC222bpRx" + + "KHWveop/AIBJhMmEgYkhiwqOZZB9lgqZfmGRYjJrg2x0bcx//H/AbYV/uof4iGVnsYM8mPeWG21hfT2EapFxTnVTUF0Ea+tvzYUt" + + "hqeJKVIPVGVcTmeoaAZ0g3Tidc+I4YjMkeKWeJaLX4dzy3pOhKBjZXWJUkFtnG4JdFl1a3iSfIaW3HqNn7ZPbmHFZVyGhk6uTtpQ" + + "IU7MUe5bmWWBaLxtH3NCdq13HHrnfG+C0op8kM+RdZYYmJtS0X0rUJhTl2fLbdBxM3TogSqPo5ZXnJ+eYHRBWJltL31emORONk+L" + + "T7dRsVK6XRxgsnM8edOCNJK3lvaWCpeXnmKfpmZ0axdSo1LIcMKIyV5LYJBhI29JcT589H1vgO6EI5Ask0JUb5vTaolwwozvjTKX" + + "tFJBWspeBF8XZ3xplGlqbQ9vYnL8cu17AYB+gEuHzpBtUZOehHmLgDKT1ootUIxUcYpqa8SMB4HRYKBn8p2ZTphOEJxrisGFaIUA" + + "aX5ul3hVgQxfEE4VTipOMU42TjxOP05CTlZOWE6CToVOa4yKThKCDV+OTp5On06gTqJOsE6zTrZOzk7NTsROxk7CTtdO3k7tTt9O" + + "904JT1pPME9bT11PV09HT3ZPiE+PT5hPe09pT3BPkU9vT4ZPlk8YUdRP30/OT9hP20/RT9pP0E/kT+VPGlAoUBRQKlAlUAVQHE/2" + + "TyFQKVAsUP5P708RUAZQQ1BHUANnVVBQUEhQWlBWUGxQeFCAUJpQhVC0ULJQyVDKULNQwlDWUN5Q5VDtUONQ7lD5UPVQCVEBUQJR" + + "FlEVURRRGlEhUTpRN1E8UTtRP1FAUVJRTFFUUWJR+HppUWpRblGAUYJR2FaMUYlRj1GRUZNRlVGWUaRRplGiUalRqlGrUbNRsVGy" + + "UbBRtVG9UcVRyVHbUeBRVYbpUe1R8FH1Uf5RBFILUhRSDlInUipSLlIzUjlST1JEUktSTFJeUlRSalJ0UmlSc1J/Un1SjVKUUpJS" + + "cVKIUpFSqI+nj6xSrVK8UrVSwVLNUtdS3lLjUuZS7ZjgUvNS9VL4UvlSBlMIUzh1DVMQUw9TFVMaUyNTL1MxUzNTOFNAU0ZTRVMX" + + "TklTTVPWUV5TaVNuUxhZe1N3U4JTllOgU6ZTpVOuU7BTtlPDUxJ82ZbfU/xm7nHuU+hT7VP6UwFUPVRAVCxULVQ8VC5UNlQpVB1U" + + "TlSPVHVUjlRfVHFUd1RwVJJUe1SAVHZUhFSQVIZUx1SiVLhUpVSsVMRUyFSoVKtUwlSkVL5UvFTYVOVU5lQPVRRV/VTuVO1U+lTi" + + "VDlVQFVjVUxVLlVcVUVVVlVXVThVM1VdVZlVgFWvVIpVn1V7VX5VmFWeVa5VfFWDValVh1WoVdpVxVXfVcRV3FXkVdRVFFb3VRZW" + + "/lX9VRtW+VVOVlBW33E0VjZWMlY4VmtWZFYvVmxWalaGVoBWilagVpRWj1alVq5Wtla0VsJWvFbBVsNWwFbIVs5W0VbTVtdW7lb5" + + "VgBX/1YEVwlXCFcLVw1XE1cYVxZXx1UcVyZXN1c4V05XO1dAV09XaVfAV4hXYVd/V4lXk1egV7NXpFeqV7BXw1fGV9RX0lfTVwpY" + + "1lfjVwtYGVgdWHJYIVhiWEtYcFjAa1JYPVh5WIVYuVifWKtYuljeWLtYuFiuWMVY01jRWNdY2VjYWOVY3FjkWN9Y71j6WPlY+1j8" + + "WP1YAlkKWRBZG1mmaCVZLFktWTJZOFk+WdJ6VVlQWU5ZWllYWWJZYFlnWWxZaVl4WYFZnVleT6tPo1myWcZZ6FncWY1Z2VnaWSVa" + + "H1oRWhxaCVoaWkBabFpJWjVaNlpiWmpamlq8Wr5ay1rCWr1a41rXWuZa6VrWWvpa+1oMWwtbFlsyW9BaKls2Wz5bQ1tFW0BbUVtV" + + "W1pbW1tlW2lbcFtzW3VbeFuIZXpbgFuDW6ZbuFvDW8dbyVvUW9Bb5FvmW+Jb3lvlW+tb8Fv2W/NbBVwHXAhcDVwTXCBcIlwoXDhc" + + "OVxBXEZcTlxTXFBcT1xxW2xcblxiTnZceVyMXJFclFybWatcu1y2XLxct1zFXL5cx1zZXOlc/Vz6XO1cjF3qXAtdFV0XXVxdH10b" + + "XRFdFF0iXRpdGV0YXUxdUl1OXUtdbF1zXXZdh12EXYJdol2dXaxdrl29XZBdt128XcldzV3TXdJd1l3bXetd8l31XQteGl4ZXhFe" + + "G142XjdeRF5DXkBeTl5XXlReX15iXmReR151XnZeel68nn9eoF7BXsJeyF7QXs9e1l7jXt1e2l7bXuJe4V7oXule7F7xXvNe8F70" + + "Xvhe/l4DXwlfXV9cXwtfEV8WXylfLV84X0FfSF9MX05fL19RX1ZfV19ZX2FfbV9zX3dfg1+CX39fil+IX5Ffh1+eX5lfmF+gX6hf" + + "rV+8X9Zf+1/kX/hf8V/dX7Ng/18hYGBgGWAQYClgDmAxYBtgFWArYCZgD2A6YFpgQWBqYHdgX2BKYEZgTWBjYENgZGBCYGxga2BZ" + + "YIFgjWDnYINgmmCEYJtglmCXYJJgp2CLYOFguGDgYNNgtGDwX71gxmC1YNhgTWEVYQZh9mD3YABh9GD6YANhIWH7YPFgDWEOYUdh" + + "PmEoYSdhSmE/YTxhLGE0YT1hQmFEYXNhd2FYYVlhWmFrYXRhb2FlYXFhX2FdYVNhdWGZYZZhh2GsYZRhmmGKYZFhq2GuYcxhymHJ" + + "YfdhyGHDYcZhumHLYXl/zWHmYeNh9mH6YfRh/2H9Yfxh/mEAYghiCWINYgxiFGIbYh5iIWIqYi5iMGIyYjNiQWJOYl5iY2JbYmBi" + + "aGJ8YoJiiWJ+YpJik2KWYtRig2KUYtdi0WK7Ys9i/2LGYtRkyGLcYsxiymLCYsdim2LJYgxj7mLxYidjAmMIY+9i9WJQYz5jTWMc" + + "ZE9jlmOOY4Bjq2N2Y6Njj2OJY59jtWNrY2ljvmPpY8BjxmPjY8lj0mP2Y8RjFmQ0ZAZkE2QmZDZkHWUXZChkD2RnZG9kdmROZCpl" + + "lWSTZKVkqWSIZLxk2mTSZMVkx2S7ZNhkwmTxZOdkCYLgZOFkrGLjZO9kLGX2ZPRk8mT6ZABl/WQYZRxlBWUkZSNlK2U0ZTVlN2U2" + + "ZThlS3VIZVZlVWVNZVhlXmVdZXJleGWCZYNlioubZZ9lq2W3ZcNlxmXBZcRlzGXSZdtl2WXgZeFl8WVyZwpmA2b7ZXNnNWY2ZjRm" + + "HGZPZkRmSWZBZl5mXWZkZmdmaGZfZmJmcGaDZohmjmaJZoRmmGadZsFmuWbJZr5mvGbEZrhm1mbaZuBmP2bmZulm8Gb1ZvdmD2cW" + + "Zx5nJmcnZziXLmc/ZzZnQWc4ZzdnRmdeZ2BnWWdjZ2RniWdwZ6lnfGdqZ4xni2emZ6FnhWe3Z+9ntGfsZ7Nn6We4Z+Rn3mfdZ+Jn" + + "7me5Z85nxmfnZ5xqHmhGaCloQGhNaDJoTmizaCtoWWhjaHdof2ifaI9orWiUaJ1om2iDaK5quWh0aLVooGi6aA9pjWh+aAFpymgI" + + "adhoImkmaeFoDGnNaNRo52jVaDZpEmkEaddo42glaflo4GjvaChpKmkaaSNpIWnGaHlpd2lcaXhpa2lUaX5pbmk5aXRpPWlZaTBp" + + "YWleaV1pgWlqabJprmnQab9pwWnTab5pzmnoW8pp3Wm7acNpp2kuapFpoGmcaZVptGneaehpAmobav9pCmv5afJp52kFarFpHmrt" + + "aRRq62kKahJqwWojahNqRGoManJqNmp4akdqYmpZamZqSGo4aiJqkGqNaqBqhGqiaqNql2oXhrtqw2rCarhqs2qsat5q0Wrfaqpq" + + "2mrqavtqBWsWhvpqEmsWazGbH2s4azdr3HY5a+6YR2tDa0lrUGtZa1RrW2tfa2FreGt5a39rgGuEa4NrjWuYa5Vrnmuka6prq2uv" + + "a7JrsWuza7drvGvGa8tr02vfa+xr62vza+9rvp4IbBNsFGwbbCRsI2xebFVsYmxqbIJsjWyabIFsm2x+bGhsc2ySbJBsxGzxbNNs" + + "vWzXbMVs3WyubLFsvmy6bNts72zZbOpsH21NiDZtK209bThtGW01bTNtEm0MbWNtk21kbVpteW1ZbY5tlW3kb4Vt+W0VbgputW3H" + + "beZtuG3Gbext3m3Mbeht0m3Fbfpt2W3kbdVt6m3ubS1ubm4ubhlucm5fbj5uI25rbitudm5Nbh9uQ246bk5uJG7/bh1uOG6Cbqpu" + + "mG7Jbrdu0269bq9uxG6ybtRu1W6PbqVuwm6fbkFvEW9McOxu+G7+bj9v8m4xb+9uMm/Mbj5vE2/3boZvem94b4FvgG9vb1tv829t" + + "b4JvfG9Yb45vkW/Cb2Zvs2+jb6FvpG+5b8Zvqm/fb9Vv7G/Ub9hv8W/ub9tvCXALcPpvEXABcA9w/m8bcBpwdG8dcBhwH3AwcD5w" + + "MnBRcGNwmXCScK9w8XCscLhws3CucN9wy3DdcNlwCXH9cBxxGXFlcVVxiHFmcWJxTHFWcWxxj3H7cYRxlXGocaxx13G5cb5x0nHJ" + + "cdRxznHgcexx53H1cfxx+XH/cQ1yEHIbcihyLXIscjByMnI7cjxyP3JAckZyS3JYcnRyfnKCcoFyh3KScpZyonKncrlysnLDcsZy" + + "xHLOctJy4nLgcuFy+XL3cg9QF3MKcxxzFnMdczRzL3MpcyVzPnNOc09z2J5Xc2pzaHNwc3hzdXN7c3pzyHOzc85zu3PAc+Vz7nPe" + + "c6J0BXRvdCV0+HMydDp0VXQ/dF90WXRBdFx0aXRwdGN0anR2dH50i3SedKd0ynTPdNR08XPgdON053TpdO508nTwdPF0+HT3dAR1" + + "A3UFdQx1DnUNdRV1E3UedSZ1LHU8dUR1TXVKdUl1W3VGdVp1aXVkdWd1a3VtdXh1dnWGdYd1dHWKdYl1gnWUdZp1nXWldaN1wnWz" + + "dcN1tXW9dbh1vHWxdc11ynXSddl143Xedf51/3X8dQF28HX6dfJ183ULdg12CXYfdid2IHYhdiJ2JHY0djB2O3ZHdkh2RnZcdlh2" + + "YXZidmh2aXZqdmd2bHZwdnJ2dnZ4dnx2gHaDdoh2i3aOdpZ2k3aZdpp2sHa0drh2uXa6dsJ2zXbWdtJ23nbhduV253bqdi+G+3YI" + + "dwd3BHcpdyR3HncldyZ3G3c3dzh3R3dad2h3a3dbd2V3f3d+d3l3jneLd5F3oHeed7B3tne5d793vHe9d7t3x3fNd9d32nfcd+N3" + + "7nf8dwx4EngmeSB4KnlFeI54dHiGeHx4mniMeKN4tXiqeK940XjGeMt41Hi+eLx4xXjKeOx453jaeP149HgHeRJ5EXkZeSx5K3lA" + + "eWB5V3lfeVp5VXlTeXp5f3mKeZ15p3lLn6p5rnmzebl5unnJedV553nseeF543kIeg16GHoZeiB6H3qAeTF6O3o+ejd6Q3pXekl6" + + "YXpieml6nZ9wenl6fXqIepd6lXqYepZ6qXrIerB6tnrFesR6v3qDkMd6ynrNes961XrTetl62nrdeuF64nrmeu168HoCew97CnsG" + + "ezN7GHsZex57NXsoezZ7UHt6ewR7TXsLe0x7RXt1e2V7dHtne3B7cXtse257nXuYe597jXuce5p7i3uSe497XXuZe8t7wXvMe897" + + "tHvGe9176XsRfBR85nvle2B8AHwHfBN883v3exd8DXz2eyN8J3wqfB98N3wrfD18THxDfFR8T3xAfFB8WHxffGR8VnxlfGx8dXyD" + + "fJB8pHytfKJ8q3yhfKh8s3yyfLF8rny5fL18wHzFfMJ82HzSfNx84nw7m+988nz0fPZ8+nwGfQJ9HH0VfQp9RX1LfS59Mn0/fTV9" + + "Rn1zfVZ9Tn1yfWh9bn1PfWN9k32JfVt9j319fZt9un2ufaN9tX3Hfb19q309fqJ9r33cfbh9n32wfdh93X3kfd59+33yfeF9BX4K" + + "fiN+IX4SfjF+H34Jfgt+In5GfmZ+O341fjl+Q343fjJ+On5nfl1+Vn5efll+Wn55fmp+aX58fnt+g37VfX1+ro9/foh+iX6MfpJ+" + + "kH6TfpR+ln6Ofpt+nH44fzp/RX9Mf01/Tn9Qf1F/VX9Uf1h/X39gf2h/aX9nf3h/gn+Gf4N/iH+Hf4x/lH+ef51/mn+jf69/sn+5" + + "f65/tn+4f3GLxX/Gf8p/1X/Uf+F/5n/pf/N/+X/cmAaABIALgBKAGIAZgByAIYAogD+AO4BKgEaAUoBYgFqAX4BigGiAc4BygHCA" + + "doB5gH2Af4CEgIaAhYCbgJOAmoCtgJBRrIDbgOWA2YDdgMSA2oDWgAmB74DxgBuBKYEjgS+BS4GLlkaBPoFTgVGB/IBxgW6BZYFm" + + "gXSBg4GIgYqBgIGCgaCBlYGkgaOBX4GTgamBsIG1gb6BuIG9gcCBwoG6gcmBzYHRgdmB2IHIgdqB34HggeeB+oH7gf6BAYICggWC" + + "B4IKgg2CEIIWgimCK4I4gjOCQIJZgliCXYJagl+CZIJigmiCaoJrgi6CcYJ3gniCfoKNgpKCq4KfgruCrILhguOC34LSgvSC84L6" + + "gpODA4P7gvmC3oIGg9yCCYPZgjWDNIMWgzKDMYNAgzmDUINFgy+DK4MXgxiDhYOag6qDn4Oig5aDI4OOg4eDioN8g7WDc4N1g6CD" + + "iYOog/SDE4Trg86D/YMDhNiDC4TBg/eDB4Tgg/KDDYQihCCEvYM4hAaF+4NthCqEPIRahYSEd4RrhK2EboSChGmERoQshG+EeYQ1" + + "hMqEYoS5hL+En4TZhM2Eu4TahNCEwYTGhNaEoYQhhf+E9IQXhRiFLIUfhRWFFIX8hECFY4VYhUiFQYUChkuFVYWAhaSFiIWRhYqF" + + "qIVthZSFm4XqhYeFnIV3hX6FkIXJhbqFz4W5hdCF1YXdheWF3IX5hQqGE4YLhv6F+oUGhiKGGoYwhj+GTYZVTlSGX4ZnhnGGk4aj" + + "hqmGqoaLhoyGtoavhsSGxoawhsmGI4irhtSG3obphuyG34bbhu+GEocGhwiHAIcDh/uGEYcJhw2H+YYKhzSHP4c3hzuHJYcphxqH" + + "YIdfh3iHTIdOh3SHV4doh26HWYdTh2OHaocFiKKHn4eCh6+Hy4e9h8CH0IfWlquHxIezh8eHxoe7h++H8ofghw+IDYj+h/aH94cO" + + "iNKHEYgWiBWIIoghiDGINog5iCeIO4hEiEKIUohZiF6IYohriIGIfoieiHWIfYi1iHKIgoiXiJKIroiZiKKIjYikiLCIv4ixiMOI" + + "xIjUiNiI2YjdiPmIAon8iPSI6IjyiASJDIkKiROJQ4keiSWJKokriUGJRIk7iTaJOIlMiR2JYIleiWaJZIltiWqJb4l0iXeJfomD" + + "iYiJiomTiZiJoYmpiaaJrImvibKJuom9ib+JwInaidyJ3YnnifSJ+IkDihaKEIoMihuKHYolijaKQYpbilKKRopIinyKbYpsimKK" + + "hYqCioSKqIqhipGKpYqmipqKo4rEis2KworaiuuK84rniuSK8YoUi+CK4or3it6K24oMiweLGovhihaLEIsXiyCLM4urlyaLK4s+" + + "iyiLQYtMi0+LTotJi1aLW4tai2uLX4tsi2+LdIt9i4CLjIuOi5KLk4uWi5mLmos6jEGMP4xIjEyMToxQjFWMYoxsjHiMeoyCjImM" + + "hYyKjI2MjoyUjHyMmIwdYq2Mqoy9jLKMs4yujLaMyIzBjOSM44zajP2M+oz7jASNBY0KjQeND40NjRCNTp8Tjc2MFI0WjWeNbY1x" + + "jXONgY2ZjcKNvo26jc+N2o3WjcyN243LjeqN643fjeON/I0IjgmO/40djh6OEI4fjkKONY4wjjSOSo5HjkmOTI5QjkiOWY5kjmCO" + + "Ko5jjlWOdo5yjnyOgY6HjoWOhI6LjoqOk46RjpSOmY6qjqGOrI6wjsaOsY6+jsWOyI7LjtuO4478jvuO647+jgqPBY8VjxKPGY8T" + + "jxyPH48bjwyPJo8zjzuPOY9Fj0KPPo9Mj0mPRo9Oj1ePXI9ij2OPZI+cj5+Po4+tj6+Pt4/aj+WP4o/qj++Ph5D0jwWQ+Y/6jxGQ" + + "FZAhkA2QHpAWkAuQJ5A2kDWQOZD4j0+QUJBRkFKQDpBJkD6QVpBYkF6QaJBvkHaQqJZykIKQfZCBkICQipCJkI+QqJCvkLGQtZDi" + + "kOSQSGLbkAKREpEZkTKRMJFKkVaRWJFjkWWRaZFzkXKRi5GJkYKRopGrka+RqpG1kbSRupHAkcGRyZHLkdCR1pHfkeGR25H8kfWR" + + "9pEekv+RFJIskhWSEZJekleSRZJJkmSSSJKVkj+SS5JQkpySlpKTkpuSWpLPkrmSt5Lpkg+T+pJEky6TGZMikxqTI5M6kzWTO5Nc" + + "k2CTfJNuk1aTsJOsk62TlJO5k9aT15Pok+WT2JPDk92T0JPIk+STGpQUlBOUA5QHlBCUNpQrlDWUIZQ6lEGUUpRElFuUYJRilF6U" + + "apQpknCUdZR3lH2UWpR8lH6UgZR/lIKVh5WKlZSVlpWYlZmVoJWolaeVrZW8lbuVuZW+lcqV9m/Dlc2VzJXVldSV1pXcleGV5ZXi" + + "lSGWKJYuli+WQpZMlk+WS5Z3llyWXpZdll+WZpZylmyWjZaYlpWWl5aqlqeWsZaylrCWtJa2lriWuZbOlsuWyZbNlk2J3JYNl9WW" + + "+ZYElwaXCJcTlw6XEZcPlxaXGZcklyqXMJc5lz2XPpdEl0aXSJdCl0mXXJdgl2SXZpdol9JSa5dxl3mXhZd8l4GXepeGl4uXj5eQ" + + "l5yXqJeml6OXs5e0l8OXxpfIl8uX3Jftl0+f8pffevaX9ZcPmAyYOJgkmCGYN5g9mEaYT5hLmGuYb5hwmHGYdJhzmKqYr5ixmLaY" + + "xJjDmMaY6ZjrmAOZCZkSmRSZGJkhmR2ZHpkkmSCZLJkumT2ZPplCmUmZRZlQmUuZUZlSmUyZVZmXmZiZpZmtma6ZvJnfmduZ3ZnY" + + "mdGZ7ZnumfGZ8pn7mfiZAZoPmgWa4pkZmiuaN5pFmkKaQJpDmj6aVZpNmluaV5pfmmKaZZpkmmmaa5pqmq2asJq8msCaz5rRmtOa" + + "1Jremt+a4prjmuaa75rrmu6a9Jrxmvea+5oGmxibGpsfmyKbI5slmyebKJspmyqbLpsvmzKbRJtDm0+bTZtOm1GbWJt0m5Obg5uR" + + "m5abl5ufm6CbqJu0m8Cbypu5m8abz5vRm9Kb45vim+Sb1Jvhmzqc8pvxm/CbFZwUnAmcE5wMnAacCJwSnAqcBJwunBucJZwknCGc" + + "MJxHnDKcRpw+nFqcYJxnnHaceJznnOyc8JwJnQid65wDnQadKp0mna+dI50fnUSdFZ0SnUGdP50+nUadSJ1dnV6dZJ1RnVCdWZ1y" + + "nYmdh52rnW+dep2anaSdqZ2yncSdwZ27nbidup3Gnc+dwp3ZndOd+J3mne2d7539nRqeG54ennWeeZ59noGeiJ6Lnoyekp6VnpGe" + + "nZ6lnqmeuJ6qnq2eYZfMns6ez57QntSe3J7ent2e4J7lnuie7570nvae9575nvue/J79ngefCJ+3dhWfIZ8snz6fSp9Sn1SfY59f" + + "n2CfYZ9mn2efbJ9qn3efcp92n5WfnJ+gny9Yx2lZkGR03FGZcQ==", +}; + +export const jisx0212_decmap = { + length: 6179, + index: [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[0,47,113],null,null,null,[67,97,124],[95,66,126],null,[156,33,80],[204,33,119],[291,33,119],null,null,null,null,[378,33,126],[472,33,126],[566,33,126],[660,33,126],[754,33,126],[848,33,126],[942,33,126],[1036,33,126],[1130,33,126],[1224,33,126],[1318,33,126],[1412,33,126],[1506,33,126],[1600,33,126],[1694,33,126],[1788,33,126],[1882,33,126],[1976,33,126],[2070,33,126],[2164,33,126],[2258,33,126],[2352,33,126],[2446,33,126],[2540,33,126],[2634,33,126],[2728,33,126],[2822,33,126],[2916,33,126],[3010,33,126],[3104,33,126],[3198,33,126],[3292,33,126],[3386,33,126],[3480,33,126],[3574,33,126],[3668,33,126],[3762,33,126],[3856,33,126],[3950,33,126],[4044,33,126],[4138,33,126],[4232,33,126],[4326,33,126],[4420,33,126],[4514,33,126],[4608,33,126],[4702,33,126],[4796,33,126],[4890,33,126],[4984,33,126],[5078,33,126],[5172,33,126],[5266,33,126],[5360,33,126],[5454,33,126],[5548,33,126],[5642,33,126],[5736,33,126],[5830,33,126],[5924,33,126],[6018,33,126],[6112,33,99],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null], + data: + "2ALHArgA2QLdAq8A2wLaAn4AhAOFA/7//v/+//7//v/+//7//v+hAKYAvwD+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+" + + "//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+//7/ugCqAKkArgAiIaQAFiGGA4gDiQOKA6oD/v+MA/7/" + + "jgOrA/7/jwP+//7//v/+/6wDrQOuA68DygOQA8wDwgPNA8sDsAPOAwIEAwQEBAUEBgQHBAgECQQKBAsEDAQOBA8E/v/+//7//v/+" + + "//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+/1IEUwRUBFUEVgRXBFgE" + + "WQRaBFsEXAReBF8ExgAQAf7/JgH+/zIB/v9BAT8B/v9KAdgAUgH+/2YB3gD+//7//v/+//7//v/+//7//v/+//7//v/+//7//v/+" + + "/+YAEQHwACcBMQEzATgBQgFAAUkBSwH4AFMB3wBnAf4AwQDAAMQAwgACAc0BAAEEAcUAwwAGAQgBDAHHAAoBDgHJAMgAywDKABoB" + + "FgESARgB/v8cAR4BIgEgASQBzQDMAM8AzgDPATABKgEuASgBNAE2ATkBPQE7AUMBRwFFAdEA0wDSANYA1ADRAVABTAHVAFQBWAFW" + + "AVoBXAFgAV4BZAFiAdoA2QDcANsAbAHTAXABagFyAW4BaAHXAdsB2QHVAXQB3QB4AXYBeQF9AXsB4QDgAOQA4gADAc4BAQEFAeUA" + + "4wAHAQkBDQHnAAsBDwHpAOgA6wDqABsBFwETARkB9QEdAR8B/v8hASUB7QDsAO8A7gDQAf7/KwEvASkBNQE3AToBPgE8AUQBSAFG" + + "AfEA8wDyAPYA9ADSAVEBTQH1AFUBWQFXAVsBXQFhAV8BZQFjAfoA+QD8APsAbQHUAXEBawFzAW8BaQHYAdwB2gHWAXUB/QD/AHcB" + + "egF+AXwBAk4ETgVODE4STh9OI04kTihOK04uTi9OME41TkBOQU5ETkdOUU5aTlxOY05oTmlOdE51TnlOf06NTpZOl06dTq9OuU7D" + + "TtBO2k7bTuBO4U7iTuhO707xTvNO9U79Tv5O/04ATwJPA08ITwtPDE8STxVPFk8XTxlPLk8xT2BPM081TzdPOU87Tz5PQE9CT0hP" + + "SU9LT0xPUk9UT1ZPWE9fT2NPak9sT25PcU93T3hPeU96T31Pfk+BT4JPhE+FT4lPik+MT45PkE+ST5NPlE+XT5lPmk+eT59Psk+3" + + "T7lPu0+8T71Pvk/AT8FPxU/GT8hPyU/LT8xPzU/PT9JP3E/gT+JP8E/yT/xP/U//TwBQAVAEUAdQClAMUA5QEFATUBdQGFAbUBxQ" + + "HVAeUCJQJ1AuUDBQMlAzUDVQQFBBUEJQRVBGUEpQTFBOUFFQUlBTUFdQWVBfUGBQYlBjUGZQZ1BqUG1QcFBxUDtQgVCDUIRQhlCK" + + "UI5Qj1CQUJJQk1CUUJZQm1CcUJ5Qn1CgUKFQolCqUK9QsFC5ULpQvVDAUMNQxFDHUMxQzlDQUNNQ1FDYUNxQ3VDfUOJQ5FDmUOhQ" + + "6VDvUPFQ9lD6UP5QA1EGUQdRCFELUQxRDVEOUfJQEFEXURlRG1EcUR1RHlEjUSdRKFEsUS1RL1ExUTNRNFE1UThROVFCUUpRT1FT" + + "UVVRV1FYUV9RZFFmUX5Rg1GEUYtRjlGYUZ1RoVGjUa1RuFG6UbxRvlG/UcJRyFHPUdFR0lHTUdVR2FHeUeJR5VHuUfJR81H0UfdR" + + "AVICUgVSElITUhVSFlIYUiJSKFIxUjJSNVI8UkVSSVJVUldSWFJaUlxSX1JgUmFSZlJuUndSeFJ5UoBSglKFUopSjFKTUpVSllKX" + + "UphSmlKcUqRSpVKmUqdSr1KwUrZSt1K4UrpSu1K9UsBSxFLGUshSzFLPUtFS1FLWUttS3FLhUuVS6FLpUupS7FLwUvFS9FL2UvdS" + + "AFMDUwpTC1MMUxFTE1MYUxtTHFMeUx9TJVMnUyhTKVMrUyxTLVMwUzJTNVM8Uz1TPlNCU0xTS1NZU1tTYVNjU2VTbFNtU3JTeVN+" + + "U4NTh1OIU45Tk1OUU5lTnVOhU6RTqlOrU69TslO0U7VTt1O4U7pTvVPAU8VTz1PSU9NT1VPaU91T3lPgU+ZT51P1UwJUE1QaVCFU" + + "J1QoVCpUL1QxVDRUNVRDVERUR1RNVE9UXlRiVGRUZlRnVGlUa1RtVG5UdFR/VIFUg1SFVIhUiVSNVJFUlVSWVJxUn1ShVKZUp1Sp" + + "VKpUrVSuVLFUt1S5VLpUu1S/VMZUylTNVM5U4FTqVOxU71T2VPxU/lT/VABVAVUFVQhVCVUMVQ1VDlUVVSpVK1UyVTVVNlU7VTxV" + + "PVVBVUdVSVVKVU1VUFVRVVhVWlVbVV5VYFVhVWRVZlV/VYFVglWGVYhVjlWPVZFVklWTVZRVl1WjVaRVrVWyVb9VwVXDVcZVyVXL" + + "VcxVzlXRVdJV01XXVdhV21XeVeJV6VX2Vf9VBVYIVgpWDVYOVg9WEFYRVhJWGVYsVjBWM1Y1VjdWOVY7VjxWPVY/VkBWQVZDVkRW" + + "RlZJVktWTVZPVlRWXlZgVmFWYlZjVmZWaVZtVm9WcVZyVnVWhFaFVohWi1aMVpVWmVaaVp1WnlafVqZWp1aoVqlWq1asVq1WsVaz" + + "VrdWvlbFVslWylbLVs9W0FbMVs1W2VbcVt1W31bhVuRW5VbmVudW6FbxVutW7Vb2VvdWAVcCVwdXClcMVxFXFVcaVxtXHVcgVyJX" + + "I1ckVyVXKVcqVyxXLlcvVzNXNFc9Vz5XP1dFV0ZXTFdNV1JXYldlV2dXaFdrV21XbldvV3BXcVdzV3RXdVd3V3lXeld7V3xXfleB" + + "V4NXjFeUV5dXmVeaV5xXnVeeV59XoVeVV6dXqFepV6xXuFe9V8dXyFfMV89X1VfdV95X5FfmV+dX6VftV/BX9Vf2V/hX/Vf+V/9X" + + "A1gEWAhYCVjhVwxYDVgbWB5YH1ggWCZYJ1gtWDJYOVg/WElYTFhNWE9YUFhVWF9YYVhkWGdYaFh4WHxYf1iAWIFYh1iIWIlYiliM" + + "WI1Yj1iQWJRYllidWKBYoViiWKZYqVixWLJYxFi8WMJYyFjNWM5Y0FjSWNRY1ljaWN1Y4VjiWOlY81gFWQZZC1kMWRJZE1kUWUGG" + + "HVkhWSNZJFkoWS9ZMFkzWTVZNlk/WUNZRllSWVNZWVlbWV1ZXllfWWFZY1lrWW1Zb1lyWXVZdll5WXtZfFmLWYxZjlmSWZVZl1mf" + + "WaRZp1mtWa5Zr1mwWbNZt1m6WbxZwVnDWcRZyFnKWc1Z0lndWd5Z31njWeRZ51nuWe9Z8VnyWfRZ91kAWgRaDFoNWg5aEloTWh5a" + + "I1okWidaKFoqWi1aMFpEWkVaR1pIWkxaUFpVWl5aY1plWmdabVp3Wnpae1p+WotakFqTWpZamVqcWp5an1qgWqJap1qsWrFaslqz" + + "WrVauFq6Wrtav1rEWsZayFrPWtpa3FrgWuVa6lruWvVa9lr9WgBbAVsIWxdbNFsZWxtbHVshWyVbLVs4W0FbS1tMW1JbVlteW2hb" + + "bltvW3xbfVt+W39bgVuEW4ZbiluOW5BbkVuTW5RblluoW6lbrFutW69bsVuyW7dbulu8W8BbwVvNW89b1lvXW9hb2VvaW+Bb71vx" + + "W/Rb/VsMXBdcHlwfXCNcJlwpXCtcLFwuXDBcMlw1XDZcWVxaXFxcYlxjXGdcaFxpXG1ccFx0XHVcelx7XHxcfVyHXIhcilyPXJJc" + + "nVyfXKBcolyjXKZcqlyyXLRctVy6XMlcy1zSXN1c11zuXPFc8lz0XAFdBl0NXRJdK10jXSRdJl0nXTFdNF05XT1dP11CXUNdRl1I" + + "XVVdUV1ZXUpdX11gXWFdYl1kXWpdbV1wXXldel1+XX9dgV2DXYhdil2SXZNdlF2VXZldm12fXaBdp12rXbBdtF24Xbldw13HXctd" + + "0F3OXdhd2V3gXeRd6V34XfldAF4HXg1eEl4UXhVeGF4fXiBeLl4oXjJeNV4+XkteUF5JXlFeVl5YXlteXF5eXmheal5rXmxebV5u" + + "XnBegF6LXo5eol6kXqVeqF6qXqxesV6zXr1evl6/XsZezF7LXs5e0V7SXtRe1V7cXt5e5V7rXgJfBl8HXwhfDl8ZXxxfHV8hXyJf" + + "I18kXyhfK18sXy5fMF80XzZfO189Xz9fQF9EX0VfR19NX1BfVF9YX1tfYF9jX2RfZ19vX3JfdF91X3hfel99X35fiV+NX49fll+c" + + "X51fol+nX6tfpF+sX69fsF+xX7hfxF/HX8hfyV/LX9Bf0V/SX9Nf1F/eX+Ff4l/oX+lf6l/sX+1f7l/vX/Jf81/2X/pf/F8HYApg" + + "DWATYBRgF2AYYBpgH2AkYC1gM2A1YEBgR2BIYElgTGBRYFRgVmBXYF1gYWBnYHFgfmB/YIJghmCIYIpgjmCRYJNglWCYYJ1gnmCi" + + "YKRgpWCoYLBgsWC3YLtgvmDCYMRgyGDJYMpgy2DOYM9g1GDVYNlg22DdYN5g4mDlYPJg9WD4YPxg/WACYQdhCmEMYRBhEWESYRNh" + + "FGEWYRdhGWEcYR5hImEqYSthMGExYTVhNmE3YTlhQWFFYUZhSWFeYWBhbGFyYXhhe2F8YX9hgGGBYYNhhGGLYY1hkmGTYZdhmGGc" + + "YZ1hn2GgYaVhqGGqYa1huGG5YbxhwGHBYcJhzmHPYdVh3GHdYd5h32HhYeJh52HpYeVh7GHtYe9hAWIDYgRiB2ITYhViHGIgYiJi" + + "I2InYiliK2I5Yj1iQmJDYkRiRmJMYlBiUWJSYlRiVmJaYlxiZGJtYm9ic2J6Yn1ijWKOYo9ikGKmYqhis2K2YrdiumK+Yr9ixGLO" + + "YtVi1mLaYupi8mL0Yvxi/WIDYwRjCmMLYw1jEGMTYxZjGGMpYypjLWM1YzZjOWM8Y0FjQmNDY0RjRmNKY0tjTmNSY1NjVGNYY1tj" + + "ZWNmY2xjbWNxY3RjdWN4Y3xjfWN/Y4JjhGOHY4pjkGOUY5VjmWOaY55jpGOmY61jrmOvY71jwWPFY8hjzmPRY9Nj1GPVY9xj4GPl" + + "Y+pj7GPyY/Nj9WP4Y/ljCWQKZBBkEmQUZBhkHmQgZCJkJGQlZClkKmQvZDBkNWQ9ZD9kS2RPZFFkUmRTZFRkWmRbZFxkXWRfZGBk" + + "YWRjZG1kc2R0ZHtkfWSFZIdkj2SQZJFkmGSZZJtknWSfZKFko2SmZKhkrGSzZL1kvmS/ZMRkyWTKZMtkzGTOZNBk0WTVZNdk5GTl" + + "ZOlk6mTtZPBk9WT3ZPtk/2QBZQRlCGUJZQplD2UTZRRlFmUZZRtlHmUfZSJlJmUpZS5lMWU6ZTxlPWVDZUdlSWVQZVJlVGVfZWBl" + + "Z2VrZXplfWWBZYVlimWSZZVlmGWdZaBlo2WmZa5lsmWzZbRlv2XCZchlyWXOZdBl1GXWZdhl32XwZfJl9GX1Zfll/mX/ZQBmBGYI" + + "ZglmDWYRZhJmFWYWZh1mHmYhZiJmI2YkZiZmKWYqZitmLGYuZjBmMWYzZjlmN2ZAZkVmRmZKZkxmUWZOZldmWGZZZltmXGZgZmFm" + + "+2ZqZmtmbGZ+ZnNmdWZ/ZndmeGZ5ZntmgGZ8ZotmjGaNZpBmkmaZZppmm2acZp9moGakZq1msWayZrVmu2a/ZsBmwmbDZshmzGbO" + + "Zs9m1GbbZt9m6GbrZuxm7mb6ZgVnB2cOZxNnGWccZyBnImczZz5nRWdHZ0hnTGdUZ1VnXWdmZ2xnbmd0Z3Zne2eBZ4RnjmePZ5Fn" + + "k2eWZ5hnmWebZ7BnsWeyZ7Vnu2e8Z71n+WfAZ8Jnw2fFZ8hnyWfSZ9dn2WfcZ+Fn5mfwZ/Jn9mf3Z1JoFGgZaB1oH2goaCdoLGgt" + + "aC9oMGgxaDNoO2g/aERoRWhKaExoVWhXaFhoW2hraG5ob2hwaHFocmh1aHloemh7aHxogmiEaIZoiGiWaJhommicaKFoo2ilaKlo" + + "qmiuaLJou2jFaMhozGjPaNBo0WjTaNZo2WjcaN1o5WjoaOpo62jsaO1o8GjxaPVo9mj7aPxo/WgGaQlpCmkQaRFpE2kWaRdpMWkz" + + "aTVpOGk7aUJpRWlJaU5pV2lbaWNpZGllaWZpaGlpaWxpcGlxaXJpeml7aX9pgGmNaZJplmmYaaFppWmmaahpq2mtaa9pt2m4abpp" + + "vGnFachp0WnWaddp4mnlae5p72nxafNp9Wn+aQBqAWoDag9qEWoVahpqHWogaiRqKGowajJqNGo3ajtqPmo/akVqRmpJakpqTmpQ" + + "alFqUmpValZqW2pkamdqampxanNqfmqBaoNqhmqHaolqi2qRaptqnWqeap9qpWqraq9qsGqxarRqvWq+ar9qxmrJashqzGrQatRq" + + "1WrWatxq3Wrkaudq7GrwavFq8mr8av1qAmsDawZrB2sJaw9rEGsRaxdrG2seayRrKGsrayxrL2s1azZrO2s/a0ZrSmtNa1JrVmtY" + + "a11rYGtna2trbmtwa3VrfWt+a4JrhWuXa5trn2uga6Jro2uoa6lrrGuta65rsGu4a7lrvWu+a8NrxGvJa8xr1mvaa+Fr42vma+dr" + + "7mvxa/dr+Wv/awJsBGwFbAlsDWwObBBsEmwZbB9sJmwnbChsLGwubDNsNWw2bDpsO2w/bEpsS2xNbE9sUmxUbFlsW2xcbGtsbWxv" + + "bHRsdmx4bHlse2yFbIZsh2yJbJRslWyXbJhsnGyfbLBssmy0bMJsxmzNbM9s0GzRbNJs1GzWbNps3GzgbOds6WzrbOxs7mzybPRs" + + "BG0HbQptDm0PbRFtE20abSZtJ20obWdsLm0vbTFtOW08bT9tV21ebV9tYW1lbWdtb21wbXxtgm2HbZFtkm2UbZZtl22YbaptrG20" + + "bbdtuW29bb9txG3Ibcptzm3PbdZt223dbd9t4G3ibeVt6W3vbfBt9G32bfxtAG4Ebh5uIm4nbjJuNm45bjtuPG5EbkVuSG5Jbktu" + + "T25RblJuU25UblduXG5dbl5uYm5jbmhuc257bn1ujW6TbpluoG6nbq1urm6xbrNuu26/bsBuwW7DbsduyG7Kbs1uzm7Pbutu7W7u" + + "bvlu+279bgRvCG8KbwxvDW8WbxhvGm8bbyZvKW8qby9vMG8zbzZvO288by1vT29Rb1JvU29Xb1lvWm9db15vYW9ib2hvbG99b35v" + + "g2+Hb4hvi2+Mb41vkG+Sb5NvlG+Wb5pvn2+gb6Vvpm+nb6hvrm+vb7BvtW+2b7xvxW/Hb8hvym/ab95v6G/pb/Bv9W/5b/xv/W8A" + + "cAVwBnAHcA1wF3AgcCNwL3A0cDdwOXA8cENwRHBIcElwSnBLcFRwVXBdcF5wTnBkcGVwbHBucHVwdnB+cIFwhXCGcJRwlXCWcJdw" + + "mHCbcKRwq3CwcLFwtHC3cMpw0XDTcNRw1XDWcNhw3HDkcPpwA3EEcQVxBnEHcQtxDHEPcR5xIHErcS1xL3EwcTFxOHFBcUVxRnFH" + + "cUpxS3FQcVJxV3FacVxxXnFgcWhxeXGAcYVxh3GMcZJxmnGbcaBxonGvcbBxsnGzcbpxv3HAccFxxHHLccxx03HWcdlx2nHccfhx" + + "/nEAcgdyCHIJchNyF3Iach1yH3IkcityL3I0cjhyOXJBckJyQ3JFck5yT3JQclNyVXJWclpyXHJecmByY3JocmtybnJvcnFyd3J4" + + "cntyfHJ/coRyiXKNco5yk3KbcqhyrXKucrFytHK+csFyx3LJcsxy1XLWcthy33LlcvNy9HL6cvty/nICcwRzBXMHcwtzDXMScxNz" + + "GHMZcx5zInMkcydzKHMsczFzMnM1czpzO3M9c0NzTXNQc1JzVnNYc11zXnNfc2BzZnNnc2lza3Nsc25zb3Nxc3dzeXN8c4BzgXOD" + + "c4VzhnOOc5Bzk3OVc5dzmHOcc55zn3Ogc6JzpXOmc6pzq3Otc7Vzt3O5c7xzvXO/c8VzxnPJc8tzzHPPc9Jz03PWc9lz3XPhc+Nz" + + "5nPnc+lz9HP1c/dz+XP6c/tz/XP/cwB0AXQEdAd0CnQRdBp0G3QkdCZ0KHQpdCp0K3QsdC10LnQvdDB0MXQ5dEB0Q3REdEZ0R3RL" + + "dE10UXRSdFd0XXRidGZ0Z3RodGt0bXRudHF0cnSAdIF0hXSGdId0iXSPdJB0kXSSdJh0mXSadJx0n3SgdKF0o3SmdKh0qXSqdKt0" + + "rnSvdLF0snS1dLl0u3S/dMh0yXTMdNB003TYdNp023TedN905HTodOp063TvdPR0+nT7dPx0/3QGdRJ1FnUXdSB1IXUkdSd1KXUq" + + "dS91NnU5dT11PnU/dUB1Q3VHdUh1TnVQdVJ1V3VedV91YXVvdXF1eXV6dXt1fHV9dX51gXWFdZB1knWTdZV1mXWcdaJ1pHW0dbp1" + + "v3XAdcF1xHXGdcx1znXPddd13HXfdeB14XXkded17HXude918XX5dQB2AnYDdgR2B3YIdgp2DHYPdhJ2E3YVdhZ2GXYbdhx2HXYe" + + "diN2JXYmdil2LXYydjN2NXY4djl2OnY8dkp2QHZBdkN2RHZFdkl2S3ZVdll2X3ZkdmV2bXZudm92cXZ0doF2hXaMdo12lXabdpx2" + + "nXafdqB2onajdqR2pXamdqd2qHaqdq12vXbBdsV2yXbLdsx2znbUdtl24Hbmduh27HbwdvF29nb5dvx2AHcGdwp3DncSdxR3FXcX" + + "dxl3GnccdyJ3KHctdy53L3c0dzV3Nnc5dz13PndCd0V3RndKd013TndPd1J3VndXd1x3Xndfd2B3Yndkd2d3andsd3B3cndzd3R3" + + "end9d4B3hHeMd413lHeVd5Z3mnefd6J3p3eqd653r3exd7V3vnfDd8l30XfSd9V32Xfed9934Hfkd+Z36nfsd/B38Xf0d/h3+3cF" + + "eAZ4CXgNeA54EXgdeCF4IngjeC14LngweDV4N3hDeER4R3hIeEx4TnhSeFx4XnhgeGF4Y3hkeGh4anhueHp4fniKeI94lHiYeKF4" + + "nXieeJ94pHioeKx4rXiweLF4snizeLt4vXi/eMd4yHjJeMx4znjSeNN41XjWeOR423jfeOB44XjmeOp48njzeAB59nj3ePp4+3j/" + + "eAZ5DHkQeRp5HHkeeR95IHkleSd5KXkteTF5NHk1eTt5PXk/eUR5RXlGeUp5S3lPeVF5VHlYeVt5XHlneWl5a3lyeXl5e3l8eX55" + + "i3mMeZF5k3mUeZV5lnmYeZt5nHmheah5qXmrea95sXm0ebh5u3nCecR5x3nIecp5z3nUedZ52nnded554HnieeV56nnree158Xn4" + + "efx5AnoDegd6CXoKegx6EXoVeht6Hnoheid6K3otei96MHo0ejV6OHo5ejp6RHpFekd6SHpMelV6VnpZelx6XXpfemB6ZXpnemp6" + + "bXp1enh6fnqAeoJ6hXqGeop6i3qQepF6lHqeeqB6o3qserN6tXq5ert6vHrGesl6zHrOetF623roeul663rsevF69Hr7ev16/noH" + + "exR7H3sjeyd7KXsqeyt7LXsuey97MHsxezR7PXs/e0B7QXtHe057VXtge2R7Zntpe2p7bXtve3J7c3t3e4R7iXuOe5B7kXuWe5t7" + + "nnuge6V7rHuve7B7snu1e7Z7unu7e7x7vXvCe8V7yHvKe9R71nvXe9l72nvbe+h76nvye/R79Xv4e/l7+nv8e/57AXwCfAN8BHwG" + + "fAl8C3wMfA58D3wZfBt8IHwlfCZ8KHwsfDF8M3w0fDZ8OXw6fEZ8SnxVfFF8UnxTfFl8WnxbfFx8XXxefGF8Y3xnfGl8bXxufHB8" + + "cnx5fHx8fXyGfId8j3yUfJ58oHymfLB8tny3fLp8u3y8fL98xHzHfMh8yXzNfM9803zUfNV813zZfNp83XzmfOl863z1fAN9B30I" + + "fQl9D30RfRJ9E30WfR19Hn0jfSZ9Kn0tfTF9PH09fT59QH1BfUd9SH1NfVF9U31XfVl9Wn1cfV19ZX1nfWp9cH14fXp9e31/fYF9" + + "gn2DfYV9hn2IfYt9jH2NfZF9ln2XfZ19nn2mfad9qn2zfbZ9t325fcJ9w33EfcV9xn3Mfc19zn3Xfdl9AH7ifeV95n3qfet97X3x" + + "ffV99n35ffp9CH4QfhF+FX4Xfhx+HX4gfid+KH4sfi1+L34zfjZ+P35EfkV+R35OflB+Un5Yfl9+YX5ifmV+a35ufm9+c354fn5+" + + "gX6Gfod+in6NfpF+lX6Yfpp+nX6efjx/O389fz5/P39Df0R/R39Pf1J/U39bf1x/XX9hf2N/ZH9lf2Z/bX9xf31/fn9/f4B/i3+N" + + "f49/kH+Rf5Z/l3+cf6F/on+mf6p/rX+0f7x/v3/Af8N/yH/Of89/23/ff+N/5X/of+x/7n/vf/J/+n/9f/5//38HgAiACoANgA6A" + + "D4ARgBOAFIAWgB2AHoAfgCCAJIAmgCyALoAwgDSANYA3gDmAOoA8gD6AQIBEgGCAZIBmgG2AcYB1gIGAiICOgJyAnoCmgKeAq4C4" + + "gLmAyIDNgM+A0oDUgNWA14DYgOCA7YDugPCA8oDzgPaA+YD6gP6AA4ELgRaBF4EYgRyBHoEggSSBJ4EsgTCBNYE6gTyBRYFHgUqB" + + "TIFSgVeBYIFhgWeBaIFpgW2Bb4F3gYGBkIGEgYWBhoGLgY6BloGYgZuBnoGiga6BsoG0gbuBy4HDgcWByoHOgc+B1YHXgduB3YHe" + + "geGB5IHrgeyB8IHxgfKB9YH2gfiB+YH9gf+BAIIDgg+CE4IUghmCGoIdgiGCIoIogjKCNII6gkOCRIJFgkaCS4JOgk+CUYJWglyC" + + "YIJjgmeCbYJ0gnuCfYJ/goCCgYKDgoSCh4KJgoqCjoKRgpSCloKYgpqCm4KggqGCo4KkgqeCqIKpgqqCroKwgrKCtIK3grqCvIK+" + + "gr+CxoLQgtWC2oLgguKC5ILoguqC7YLvgvaC94L9gv6CAIMBgweDCIMKgwuDVIMbgx2DHoMfgyGDIoMsgy2DLoMwgzODN4M6gzyD" + + "PYNCg0ODRINHg02DToNRg1WDVoNXg3CDeIN9g3+DgIOCg4SDhoONg5KDlIOVg5iDmYObg5yDnYOmg6eDqYOsg76Dv4PAg8eDyYPP" + + "g9CD0YPUg92DU4Pog+qD9oP4g/mD/IMBhAaECoQPhBGEFYQZhK2DL4Q5hEWER4RIhEqETYRPhFGEUoRWhFiEWYRahFyEYIRkhGWE" + + "Z4RqhHCEc4R0hHaEeIR8hH2EgYSFhJKEk4SVhJ6EpoSohKmEqoSvhLGEtIS6hL2EvoTAhMKEx4TIhMyEz4TThNyE54TqhO+E8ITx" + + "hPKE94QyhfqE+4T9hAKFA4UHhQyFDoUQhRyFHoUihSOFJIUlhSeFKoUrhS+FM4U0hTaFP4VGhU+FUIVRhVKFU4VWhVmFXIVdhV6F" + + "X4VghWGFYoVkhWuFb4V5hXqFe4V9hX+FgYWFhYaFiYWLhYyFj4WThZiFnYWfhaCFooWlhaeFtIW2hbeFuIW8hb2FvoW/hcKFx4XK" + + "hcuFzoWthdiF2oXfheCF5oXohe2F84X2hfyF/4UAhgSGBYYNhg6GEIYRhhKGGIYZhhuGHoYhhieGKYY2hjiGOoY8hj2GQIZChkaG" + + "UoZThlaGV4ZYhlmGXYZghmGGYoZjhmSGaYZshm+GdYZ2hneGeoaNhpGGloaYhpqGnIahhqaGp4aohq2GsYazhrSGtYa3hriGuYa/" + + "hsCGwYbDhsWG0YbShtWG14bahtyG4IbjhuWG54aIhvqG/Ib9hgSHBYcHhwuHDocPhxCHE4cUhxmHHocfhyGHI4cohy6HL4cxhzKH" + + "OYc6hzyHPYc+h0CHQ4dFh02HWIddh2GHZIdlh2+HcYdyh3uHg4eEh4WHhoeHh4iHiYeLh4yHkIeTh5WHl4eYh5mHnoegh6OHp4es" + + "h62Hroexh7WHvoe/h8GHyIfJh8qHzofVh9aH2Yfah9yH34fih+OH5Ifqh+uH7Yfxh/OH+If6h/+HAYgDiAaICYgKiAuIEIgZiBKI" + + "E4gUiBiIGogbiByIHogfiCiILYguiDCIMog1iDqIPIhBiEOIRYhIiEmISohLiE6IUYhViFaIWIhaiFyIX4hgiGSIaYhxiHmIe4iA" + + "iJiImoibiJyIn4igiKiIqoi6iL2IvojAiMqIy4jMiM2IzojRiNKI04jbiN6I54jviPCI8Yj1iPeIAYkGiQ2JDokPiRWJFokYiRmJ" + + "GokciSCJJokniSiJMIkxiTKJNYk5iTqJPolAiUKJRYlGiUmJT4lSiVeJWolbiVyJYYliiWOJa4luiXCJc4l1iXqJe4l8iX2JiYmN" + + "iZCJlImViZuJnImfiaCJpYmwibSJtYm2ibeJvInUidWJ1onXidiJ5YnpieuJ7YnxifOJ9on5if2J/4kEigWKB4oPihGKEooUihWK" + + "HoogiiKKJIomiiuKLIovijWKN4o9ij6KQIpDikWKR4pJik2KTopTilaKV4pYilyKXYphimWKZ4p1inaKd4p5inqKe4p+in+KgIqD" + + "ioaKi4qPipCKkoqWipeKmYqfiqeKqYquiq+Ks4q2ireKu4q+isOKxorIismKyorRitOK1IrViteK3YrfiuyK8Ir0ivWK9or8iv+K" + + "BYsGiwuLEYscix6LH4sKiy2LMIs3izyLQotDi0SLRYtGi0iLUotTi1SLWYtNi16LY4tti3aLeIt5i3yLfouBi4SLhYuLi42Lj4uU" + + "i5WLnIuei5+LOIw5jD2MPoxFjEeMSYxLjE+MUYxTjFSMV4xYjFuMXYxZjGOMZIxmjGiMaYxtjHOMdYx2jHuMfoyGjIeMi4yQjJKM" + + "k4yZjJuMnIykjLmMuozFjMaMyYzLjM+M1ozVjNmM3YzhjOiM7IzvjPCM8oz1jPeM+Iz+jP+MAY0DjQmNEo0XjRuNZY1pjWyNbo1/" + + "jYKNhI2IjY2NkI2RjZWNno2fjaCNpo2rjayNr42yjbWNt425jbuNwI3FjcaNx43IjcqNzo3RjdSN1Y3XjdmN5I3ljeeN7I3wjbyN" + + "8Y3yjfSN/Y0BjgSOBY4GjguOEY4UjhaOII4hjiKOI44mjieOMY4zjjaON444jjmOPY5AjkGOS45Njk6OT45UjluOXI5djl6OYY5i" + + "jmmObI5tjm+OcI5xjnmOeo57joKOg46JjpCOko6VjpqOm46djp6Ooo6njqmOrY6ujrOOtY66jruOwI7BjsOOxI7Hjs+O0Y7UjtyO" + + "6I7ujvCO8Y73jvmO+o7tjgCPAo8HjwiPD48QjxaPF48Yjx6PII8hjyOPJY8njyiPLI8tjy6PNI81jzaPN486j0CPQY9Dj0ePT49R" + + "j1KPU49Uj1WPWI9dj16PZY+dj6CPoY+kj6WPpo+1j7aPuI++j8CPwY/Gj8qPy4/Nj9CP0o/Tj9WP4I/jj+SP6I/uj/GP9Y/2j/uP" + + "/o8CkASQCJAMkBiQG5AokCmQL5AqkCyQLZAzkDSQN5A/kEOQRJBMkFuQXZBikGaQZ5BskHCQdJB5kIWQiJCLkIyQjpCQkJWQl5CY" + + "kJmQm5CgkKGQopClkLCQspCzkLSQtpC9kMyQvpDDkMSQxZDHkMiQ1ZDXkNiQ2ZDckN2Q35DlkNKQ9pDrkO+Q8JD0kP6Q/5AAkQSR" + + "BZEGkQiRDZEQkRSRFpEXkRiRGpEckR6RIJElkSKRI5EnkSmRLpEvkTGRNJE2kTeROZE6kTyRPZFDkUeRSJFPkVORV5FZkVqRW5Fh" + + "kWSRZ5FtkXSReZF6kXuRgZGDkYWRhpGKkY6RkZGTkZSRlZGYkZ6RoZGmkaiRrJGtka6RsJGxkbKRs5G2kbuRvJG9kb+RwpHDkcWR" + + "05HUkdeR2ZHakd6R5JHlkemR6pHske2R7pHvkfCR8ZH3kfmR+5H9kQCSAZIEkgWSBpIHkgmSCpIMkhCSEpITkhaSGJIckh2SI5Ik" + + "kiWSJpIoki6SL5IwkjOSNZI2kjiSOZI6kjySPpJAkkKSQ5JGkkeSSpJNkk6ST5JRkliSWZJckl2SYJJhkmWSZ5JokmmSbpJvknCS" + + "dZJ2kneSeJJ5knuSfJJ9kn+SiJKJkoqSjZKOkpKSl5KZkp+SoJKkkqWSp5KokquSr5KykraSuJK6kruSvJK9kr+SwJLBksKSw5LF" + + "ksaSx5LIksuSzJLNks6S0JLTktWS15LYktmS3JLdkt+S4JLhkuOS5ZLnkuiS7JLukvCS+ZL7kv+SAJMCkwiTDZMRkxSTFZMckx2T" + + "HpMfkyGTJJMlkyeTKZMqkzOTNJM2kzeTR5NIk0mTUJNRk1KTVZNXk1iTWpNek2STZZNnk2mTapNtk2+TcJNxk3OTdJN2k3qTfZN/" + + "k4CTgZOCk4iTipOLk42Tj5OSk5WTmJObk56ToZOjk6STppOok6uTtJO1k7aTupOpk8GTxJPFk8aTx5PJk8qTy5PMk82T05PZk9yT" + + "3pPfk+KT5pPnk/mT95P4k/qT+5P9kwGUApQElAiUCZQNlA6UD5QVlBaUF5QflC6UL5QxlDKUM5Q0lDuUP5Q9lEOURZRIlEqUTJRV" + + "lFmUXJRflGGUY5RolGuUbZRulG+UcZRylISUg5R4lXmVfpWElYiVjJWNlY6VnZWelZ+VoZWmlamVq5WslbSVtpW6lb2Vv5XGlciV" + + "yZXLldCV0ZXSldOV2ZXald2V3pXfleCV5JXmlR2WHpYiliSWJZYmliyWMZYzljeWOJY5ljqWPJY9lkGWUpZUllaWV5ZYlmGWbpZ0" + + "lnuWfJZ+ln+WgZaCloOWhJaJlpGWlpaalp2Wn5aklqWWppaplq6Wr5azlrqWypbSlrJd2Jbalt2W3pbflumW75bxlvqWApcDlwWX" + + "CZcalxuXHZchlyKXI5colzGXM5dBl0OXSpdOl0+XVZdXl1iXWpdbl2OXZ5dql26Xc5d2l3eXeJd7l32Xf5eAl4mXlZeWl5eXmZea" + + "l56Xn5eil6yXrpexl7KXtZe2l7iXuZe6l7yXvpe/l8GXxJfFl8eXyZfKl8yXzZfOl9CX0ZfUl9eX2JfZl92X3pfgl9uX4Zfkl++X" + + "8Zf0l/eX+Jf6lweYCpgZmA2YDpgUmBaYHJgemCCYI5gmmCuYLpgvmDCYMpgzmDWYJZg+mESYR5hKmFGYUphTmFaYV5hZmFqYYphj" + + "mGWYZphqmGyYq5itmK6YsJi0mLeYuJi6mLuYv5jCmMWYyJjMmOGY45jlmOaY55jqmPOY9pgCmQeZCJkRmRWZFpkXmRqZG5kcmR+Z" + + "IpkmmSeZK5kxmTKZM5k0mTWZOZk6mTuZPJlAmUGZRplHmUiZTZlOmVSZWJlZmVuZXJlemV+ZYJmbmZ2Zn5mmmbCZsZmymbWZuZm6" + + "mb2Zv5nDmcmZ05nUmdmZ2pncmd6Z55nqmeuZ7JnwmfSZ9Zn5mf2Z/pkCmgOaBJoLmgyaEJoRmhaaHpogmiKaI5okmieaLZoumjOa" + + "NZo2mjiaR5pBmkSaSppLmkyaTppRmlSaVppdmqqarJqumq+aspq0mrWatpq5mruavpq/msGaw5rGmsiazprQmtKa1ZrWmtea25rc" + + "muCa5Jrlmuea6ZrsmvKa85r1mvma+pr9mv+aAJsBmwKbA5sEmwWbCJsJmwubDJsNmw6bEJsSmxabGZsbmxybIJsmmyubLZszmzSb" + + "NZs3mzmbOps9m0ibS5tMm1WbVptXm1ubXpthm2ObZZtmm2ibaptrm2ybbZtum3ObdZt3m3ibeZt/m4CbhJuFm4abh5uJm4qbi5uN" + + "m4+bkJuUm5qbnZuem6abp5upm6ybsJuxm7Kbt5u4m7ubvJu+m7+bwZvHm8ibzpvQm9eb2Jvdm9+b5Zvnm+qb65vvm/Ob95v4m/mb" + + "+pv9m/+bAJwCnAucD5wRnBacGJwZnBqcHJwenCKcI5wmnCecKJwpnCqcMZw1nDacN5w9nEGcQ5xEnEWcSZxKnE6cT5xQnFOcVJxW" + + "nFicW5xdnF6cX5xjnGmcapxcnGucaJxunHCccpx1nHece5zmnPKc95z5nAudAp0RnRedGJ0cnR2dHp0vnTCdMp0znTSdOp08nUWd" + + "PZ1CnUOdR51KnVOdVJ1fnWOdYp1lnWmdap1rnXCddp13nXudfJ1+nYOdhJ2GnYqdjZ2OnZKdk52VnZadl52YnaGdqp2sna6dsZ21" + + "nbmdvJ2/ncOdx53Jncqd1J3Vndad153and6d353gneWd553pneud7p3wnfOd9J3+nQqeAp4Hng6eEJ4RnhKeFZ4WnhmeHJ4dnnqe" + + "e558noCegp6DnoSehZ6Hno6ej56Wnpiem56enqSeqJ6snq6er56wnrOetJ61nsaeyJ7LntWe357knuee7J7tnu6e8J7xnvKe9Z74" + + "nv+eAp8DnwmfD58QnxGfEp8UnxafF58ZnxqfG58fnyKfJp8qnyufL58xnzKfNJ83nzmfOp88nz2fP59Bn0OfRJ9Fn0afR59Tn1Wf" + + "Vp9Xn1ifWp9dn16faJ9pn22fbp9vn3CfcZ9zn3Wfep99n4+fkJ+Rn5KflJ+Wn5efnp+hn6Kfo5+lnw==", +}; + +export const cp932ext_decmap = { + length: 969, + index: [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[0,95,202],null,null,null,null,null,[108,64,156],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[201,64,252],[390,64,252],null,null,null,null,null,null,null,null,null,null,null,[579,64,252],[768,64,252],[957,64,75],null,null,null], + data: + "PP9e/yUiXP8mICUgGCAZIBwgHSAI/wn/FDAVMDv/Pf9b/13/CDAJMAowCzAMMA0wDjAPMBAwETAL/w3/sQDXAP7/9wAd/2AiHP8e" + + "/2YiZyIeIjQiQiZAJrAAMiAzIAMh5f8E/+D/4f8F/wP/Bv8K/yD/pwAGJgUmyyXPJc4lxyXGJaEloCWzJbIlvSW8JTsgEjCSIZAh" + + "kSGTIRMw/v/+//7//v/+//7//v/+//7//v/+/wgiCyKGIocigiKDIioiKSL+//7//v/+//7//v/+//7/JyIoIuL/YCRhJGIkYyRk" + + "JGUkZiRnJGgkaSRqJGskbCRtJG4kbyRwJHEkciRzJGAhYSFiIWMhZCFlIWYhZyFoIWkh/v9JMxQzIjNNMxgzJzMDMzYzUTNXMw0z" + + "JjMjMyszSjM7M5wznTOeM44zjzPEM6Ez/v/+//7//v/+//7//v/+/3sz/v8dMB8wFiHNMyEhpDKlMqYypzKoMjEyMjI5Mn4zfTN8" + + "M1IiYSIrIi4iESIaIqUiICIfIr8iNSIpIioiin4ciUiTiJLchMlPu3AxZsho+ZL7ZkVfKE7hTvxOAE8DTzlPVk+ST4pPmk+UT81P" + + "QFAiUP9PHlBGUHBQQlCUUPRQ2FBKUWRRnVG+UexRFVKcUqZSwFLbUgBTB1MkU3JTk1OyU91TDvqcVIpUqVT/VIZVWVdlV6xXyFfH" + + "Vw/6/v8Q+p5YslgLWVNZW1ldWWNZpFm6WVZbwFsvddhb7FseXKZculz1XCddU10R+kJdbV24Xbld0F0hXzRfZ1+3X95fXWCFYIpg" + + "3mDVYCBh8mARYTdhMGGYYRNipmL1Y2BknWTOZE5lAGYVZjtmCWYuZh5mJGZlZldmWWYS+nNmmWagZrJmv2b6Zg5nKflmZ7tnUmjA" + + "ZwFoRGjPaBP6aGkU+php4mkwamtqRmpzan5q4mrkatZrP2xcbIZsb2zabARth21vbZZtrG3Pbfht8m38bTluXG4nbjxuv26Ib7Vv" + + "9W8FcAdwKHCFcKtwD3EEcVxxRnFHcRX6wXH+cbFyvnIkcxb6d3O9c8lz1nPjc9JzB3T1cyZ0KnQpdC50YnSJdJ90AXVvdYJ2nHae" + + "dpt2pnYX+kZ3r1IheE54ZHh6eDB5GPoZ+hr6lHkb+pt50Xrnehz663qeex36SH1cfbd9oH3WfVJ+R3+hfx76AYNig3+Dx4P2g0iE" + + "tIRThVmF/v9rhR/6sIUg+iH6B4j1iBKKN4p5iqeKvorfiiL69opTi3+L8Iz0jBKNdo0j+s+OJPol+meQ3pAm+hWRJ5HakdeR3pHt" + + "ke6R5JHlkQaSEJIKkjqSQJI8kk6SWZJRkjmSZ5KnkneSeJLnkteS2ZLQkif61ZLgktOSJZMhk/uSKPoek/+SHZMCk3CTV5Okk8aT" + + "3pP4kzGURZRIlJKV3Pkp+p2Wr5YzlzuXQ5dNl0+XUZdVl1eYZZgq+iv6J5ks+p6ZTprZmtyadZtym4+bsZu7mwCccJ1rnS36GZ7R" + + "nv7//v9wIXEhciFzIXQhdSF2IXcheCF5IeL/5P8H/wL/cCFxIXIhcyF0IXUhdiF3IXgheSFgIWEhYiFjIWQhZSFmIWchaCFpIeL/" + + "5P8H/wL/MTIWISEhNSKKfhyJSJOIktyEyU+7cDFmyGj5kvtmRV8oTuFO/E4ATwNPOU9WT5JPik+aT5RPzU9AUCJQ/08eUEZQcFBC" + + "UJRQ9FDYUEpR/v9kUZ1RvlHsURVSnFKmUsBS21IAUwdTJFNyU5NTslPdUw76nFSKVKlU/1SGVVlXZVesV8hXx1cP+hD6nliyWAtZ" + + "U1lbWV1ZY1mkWbpZVlvAWy912FvsWx5cply6XPVcJ11TXRH6Ql1tXbhduV3QXSFfNF9nX7df3l9dYIVgimDeYNVgIGHyYBFhN2Ew" + + "YZhhE2KmYvVjYGSdZM5kTmUAZhVmO2YJZi5mHmYkZmVmV2ZZZhL6c2aZZqBmsma/ZvpmDmcp+WZnu2dSaMBnAWhEaM9oE/poaRT6" + + "mGniaTBqa2pGanNqfmriauRq1ms/bFxshmxvbNpsBG2HbW9tlm2sbc9t+G3ybfxtOW5cbiduPG6/bohvtW/1bwVwB3AocIVwq3AP" + + "cQRxXHFGcUdxFfrBcf5xsXK+ciRzFvp3c71zyXPWc+Nz0nMHdPVzJnQqdCl0LnRidIl0n3QBdW91gnacdp52m3amdhf6RnevUiF4" + + "TnhkeHp4MHkY+hn6/v8a+pR5G/qbedF653oc+ut6nnsd+kh9XH23faB91n1Sfkd/oX8e+gGDYoN/g8eD9oNIhLSEU4VZhWuFH/qw" + + "hSD6IfoHiPWIEoo3inmKp4q+it+KIvr2ilOLf4vwjPSMEo12jSP6z44k+iX6Z5DekCb6FZEnkdqR15Heke2R7pHkkeWRBpIQkgqS" + + "OpJAkjySTpJZklGSOZJnkqeSd5J4kueS15LZktCSJ/rVkuCS05IlkyGT+5Io+h6T/5IdkwKTcJNXk6STxpPek/iTMZRFlEiUkpXc" + + "+Sn6nZavljOXO5dDl02XT5dRl1WXV5hlmCr6K/onmSz6nplOmtma3Jp1m3Kbj5uxm7ubAJxwnWudLfoZntGe", +}; diff --git a/packages/romdev-spimdisasm/src/py/codecs.js b/packages/romdev-spimdisasm/src/py/codecs.js new file mode 100644 index 00000000..4e67e356 --- /dev/null +++ b/packages/romdev-spimdisasm/src/py/codecs.js @@ -0,0 +1,458 @@ +// SPDX-License-Identifier: MIT +// +// Byte decoders that behave exactly like CPython's `bytes.decode(encoding)` +// in strict mode, for the codecs spimdisasm projects use. +// +// The Japanese codecs are line-by-line ports of CPython's +// Modules/cjkcodecs/_codecs_jp.c DECODER(euc_jp), DECODER(shift_jis) and +// DECODER(cp932) (non-STRICT_BUILD paths, which is how CPython is built), +// driven by the decode maps generated from CPython's mappings_jp.h (see +// scripts/gen-cjk-tables.mjs). Error reporting follows +// Modules/cjkcodecs/multibytecodec.c: a codec return value e > 0 is an +// "illegal multibyte sequence" covering [pos, pos+e), running out of input +// mid-character is an "incomplete multibyte sequence" covering the rest. +// +// The decoders were checked between CPython 3.12 and 3.13: the only +// differences in _codecs_jp.c are in the euc_jis_2004 and shift_jis_2004 +// ENCODERS, so decoding is identical. The alias table differs (3.13 adds +// "windows_31j" -> cp932), which `pythonVersion` selects. + +import * as T from "./cjk-tables-jp.js"; + +export class LookupError extends Error { + constructor(message) { + super(message); + this.name = "LookupError"; + } +} + +export class UnicodeDecodeError extends Error { + /** + * @param {string} encoding + * @param {Uint8Array} object + * @param {number} start + * @param {number} end + * @param {string} reason + */ + constructor(encoding, object, start, end, reason) { + const b = object[start]; + let msg; + if (end - start === 1 && b !== undefined) { + msg = `'${encoding}' codec can't decode byte 0x${b.toString(16).padStart(2, "0")} in position ${start}: ${reason}`; + } else { + msg = `'${encoding}' codec can't decode bytes in position ${start}-${end - 1}: ${reason}`; + } + super(msg); + this.name = "UnicodeDecodeError"; + this.encoding = encoding; + this.object = object; + this.start = start; + this.end = end; + this.reason = reason; + } +} + +// --------------------------------------------------------------------------- +// Encoding names + +// Subset of CPython Lib/encodings/aliases.py for the implemented codecs. +const ALIASES_COMMON = { + "646": "ascii", + "ansi_x3.4_1968": "ascii", + "ansi_x3_4_1968": "ascii", + "ansi_x3.4_1986": "ascii", + "cp367": "ascii", + "csascii": "ascii", + "ibm367": "ascii", + "iso646_us": "ascii", + "iso_646.irv_1991": "ascii", + "iso_ir_6": "ascii", + "us": "ascii", + "us_ascii": "ascii", + + "932": "cp932", + "ms932": "cp932", + "mskanji": "cp932", + "ms_kanji": "cp932", + + "eucjp": "euc_jp", + "ujis": "euc_jp", + "u_jis": "euc_jp", + + "8859": "latin_1", + "cp819": "latin_1", + "csisolatin1": "latin_1", + "ibm819": "latin_1", + "iso8859": "latin_1", + "iso8859_1": "latin_1", + "iso_8859_1": "latin_1", + "iso_8859_1_1987": "latin_1", + "iso_ir_100": "latin_1", + "l1": "latin_1", + "latin": "latin_1", + "latin1": "latin_1", + + "csshiftjis": "shift_jis", + "shiftjis": "shift_jis", + "sjis": "shift_jis", + "s_jis": "shift_jis", + "x_mac_japanese": "shift_jis", + + "u8": "utf_8", + "utf": "utf_8", + "utf8": "utf_8", + "utf8_ucs2": "utf_8", + "utf8_ucs4": "utf_8", + "cp65001": "utf_8", +}; +const ALIASES_313 = { "windows_31j": "cp932" }; + +const CODEC_NAMES = new Set(["ascii", "latin_1", "utf_8", "euc_jp", "shift_jis", "cp932"]); + +/** Python's str.isalnum() for a single character (Unicode-aware). */ +function isAlnum(c) { + return /^[\p{L}\p{Nd}\p{Nl}\p{No}]$/u.test(c); +} + +/** + * CPython encodings.normalize_encoding(): non-alphanumerics except '.' are + * collapsed into single underscores, leading/trailing ones dropped, + * non-ASCII alphanumerics dropped. + */ +export function pyNormalizeEncodingName(encoding) { + const chars = []; + let punct = false; + for (const c of encoding) { + if (isAlnum(c) || c === ".") { + if (punct && chars.length) chars.push("_"); + if (c.charCodeAt(0) < 0x80) chars.push(c); + punct = false; + } else { + punct = true; + } + } + return chars.join(""); +} + +/** + * Resolve an encoding name the way codecs.lookup() does (lowercase, then + * normalize_encoding, then the alias table). Returns the canonical codec + * module name (e.g. "shift_jis") or null when the codec is not implemented + * here. + * @param {string} name + * @param {{pythonVersion?: string}} [opts] + * @returns {string|null} + */ +export function normalizeEncoding(name, opts = {}) { + const ver = opts.pythonVersion ?? "3.13"; + const norm = pyNormalizeEncodingName(String(name).toLowerCase()); + const aliases = ver === "3.12" ? ALIASES_COMMON : { ...ALIASES_COMMON, ...ALIASES_313 }; + const aliased = aliases[norm] ?? aliases[norm.replace(/\./g, "_")]; + for (const cand of aliased !== undefined ? [aliased, norm] : [norm]) { + if (CODEC_NAMES.has(cand)) return cand; + } + return null; +} + +// --------------------------------------------------------------------------- +// Decode map access (mirrors cjkcodecs.h _TRYMAP_DEC) + +const UNIINV = 0xfffe; + +function loadTable(t) { + const buf = Buffer.from(t.data, "base64"); + const arr = new Uint16Array(t.length); + for (let i = 0; i < t.length; i++) arr[i] = buf.readUInt16LE(i * 2); + return { map: arr, index: t.index }; +} + +let tables = null; +function getTables() { + if (tables === null) { + tables = { + jisx0208: loadTable(T.jisx0208_decmap), + jisx0212: loadTable(T.jisx0212_decmap), + cp932ext: loadTable(T.cp932ext_decmap), + }; + } + return tables; +} + +/** TRYMAP_DEC(charset, c1, c2): returns the code point or -1. */ +function trymapDec(tbl, c1, c2) { + const ent = tbl.index[c1]; + if (ent === null || ent === undefined) return -1; + const [off, bottom, top] = ent; + if (c2 < bottom || c2 > top) return -1; + const v = tbl.map[off + c2 - bottom]; + return v === UNIINV ? -1 : v; +} + +// Internal decoder protocol: each decoder returns either the decoded +// string, or {pos, err} where err > 0 means "illegal multibyte sequence" +// of err bytes at pos, and err === TOOFEW means incomplete input at pos. +const TOOFEW = -2; + +function decodeEucJp(b) { + const t = getTables(); + const out = []; + let i = 0; + const n = b.length; + while (i < n) { + const c = b[i]; + if (c < 0x80) { + out.push(c); + i += 1; + continue; + } + if (c === 0x8e) { + if (n - i < 2) return { pos: i, err: TOOFEW }; + const c2 = b[i + 1]; + if (c2 >= 0xa1 && c2 <= 0xdf) { + out.push(0xfec0 + c2); + i += 2; + } else { + return { pos: i, err: 1 }; + } + } else if (c === 0x8f) { + if (n - i < 3) return { pos: i, err: TOOFEW }; + const c2 = b[i + 1]; + const c3 = b[i + 2]; + const d = trymapDec(t.jisx0212, c2 ^ 0x80, c3 ^ 0x80); + if (d >= 0) { + out.push(d); + i += 3; + } else { + return { pos: i, err: 1 }; + } + } else { + if (n - i < 2) return { pos: i, err: TOOFEW }; + const c2 = b[i + 1]; + if (c === 0xa1 && c2 === 0xc0) { + // FULL-WIDTH REVERSE SOLIDUS + out.push(0xff3c); + } else { + const d = trymapDec(t.jisx0208, c ^ 0x80, c2 ^ 0x80); + if (d >= 0) out.push(d); + else return { pos: i, err: 1 }; + } + i += 2; + } + } + return cpsToString(out); +} + +function decodeShiftJis(b) { + const t = getTables(); + const out = []; + let i = 0; + const n = b.length; + while (i < n) { + const c = b[i]; + if (c < 0x80) { + out.push(c); + } else if (c >= 0xa1 && c <= 0xdf) { + // JISX0201_K_DECODE + out.push(0xfec0 + c); + } else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)) { + if (n - i < 2) return { pos: i, err: TOOFEW }; + let c2 = b[i + 1]; + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) return { pos: i, err: 1 }; + let c1 = c < 0xe0 ? c - 0x81 : c - 0xc1; + c2 = c2 < 0x80 ? c2 - 0x40 : c2 - 0x41; + c1 = 2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21; + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + // Both are `unsigned char` in C; values stay within 0..255 here. + c1 &= 0xff; + c2 &= 0xff; + if (c1 === 0x21 && c2 === 0x40) { + // FULL-WIDTH REVERSE SOLIDUS + out.push(0xff3c); + i += 2; + continue; + } + const d = trymapDec(t.jisx0208, c1, c2); + if (d >= 0) { + out.push(d); + i += 2; + continue; + } + return { pos: i, err: 1 }; + } else { + return { pos: i, err: 1 }; + } + i += 1; // JIS X 0201 + } + return cpsToString(out); +} + +function decodeCp932(b) { + const t = getTables(); + const out = []; + let i = 0; + const n = b.length; + while (i < n) { + let c = b[i]; + if (c <= 0x80) { + out.push(c); + i += 1; + continue; + } else if (c >= 0xa0 && c <= 0xdf) { + out.push(c === 0xa0 ? 0xf8f0 : 0xfec0 + c); + i += 1; + continue; + } else if (c >= 0xfd) { + // Windows compatibility + out.push(0xf8f1 - 0xfd + c); + i += 1; + continue; + } + + if (n - i < 2) return { pos: i, err: TOOFEW }; + let c2 = b[i + 1]; + + const e = trymapDec(t.cp932ext, c, c2); + if (e >= 0) { + out.push(e); + } else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)) { + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) return { pos: i, err: 1 }; + c = c < 0xe0 ? c - 0x81 : c - 0xc1; + c2 = c2 < 0x80 ? c2 - 0x40 : c2 - 0x41; + c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21) & 0xff; + c2 = ((c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21) & 0xff; + const d = trymapDec(t.jisx0208, c, c2); + if (d >= 0) out.push(d); + else return { pos: i, err: 1 }; + } else if (c >= 0xf0 && c <= 0xf9) { + if ((c2 >= 0x40 && c2 <= 0x7e) || (c2 >= 0x80 && c2 <= 0xfc)) { + out.push(0xe000 + 188 * (c - 0xf0) + (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41)); + } else { + return { pos: i, err: 1 }; + } + } else { + return { pos: i, err: 1 }; + } + i += 2; + } + return cpsToString(out); +} + +function decodeAscii(b) { + let s = ""; + for (let i = 0; i < b.length; i++) { + if (b[i] >= 0x80) throw new UnicodeDecodeError("ascii", b, i, i + 1, "ordinal not in range(128)"); + s += String.fromCharCode(b[i]); + } + return s; +} + +function decodeLatin1(b) { + let s = ""; + for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]); + return s; +} + +/** Strict UTF-8 as in CPython Objects/stringlib/codecs.h + unicodeobject.c. */ +function decodeUtf8(b) { + const out = []; + const n = b.length; + let i = 0; + const fail = (start, end, reason) => { + throw new UnicodeDecodeError("utf-8", b, start, end, reason); + }; + while (i < n) { + const c = b[i]; + if (c < 0x80) { + out.push(c); + i++; + continue; + } + let need; + let lo = 0x80; + let hi = 0xbf; + let cp; + if (c >= 0xc2 && c <= 0xdf) { + need = 1; + cp = c & 0x1f; + } else if (c >= 0xe0 && c <= 0xef) { + need = 2; + cp = c & 0x0f; + if (c === 0xe0) lo = 0xa0; + if (c === 0xed) hi = 0x9f; // no surrogates + } else if (c >= 0xf0 && c <= 0xf4) { + need = 3; + cp = c & 0x07; + if (c === 0xf0) lo = 0x90; + if (c === 0xf4) hi = 0x8f; + } else { + fail(i, i + 1, "invalid start byte"); + } + for (let k = 1; k <= need; k++) { + if (i + k >= n) fail(i, n, "unexpected end of data"); + const cc = b[i + k]; + const l = k === 1 ? lo : 0x80; + const h = k === 1 ? hi : 0xbf; + if (cc < l || cc > h) fail(i, i + k, "invalid continuation byte"); + cp = (cp << 6) | (cc & 0x3f); + } + out.push(cp); + i += need + 1; + } + return cpsToString(out); +} + +const MB_DECODERS = { + euc_jp: decodeEucJp, + shift_jis: decodeShiftJis, + cp932: decodeCp932, +}; + +// Display names used in UnicodeDecodeError messages (codec.name). +const DISPLAY = { ascii: "ascii", latin_1: "latin-1", utf_8: "utf-8", euc_jp: "euc_jp", shift_jis: "shift_jis", cp932: "cp932" }; + +function cpsToString(cps) { + let s = ""; + for (let i = 0; i < cps.length; i += 4096) s += String.fromCodePoint(...cps.slice(i, i + 4096)); + return s; +} + +/** + * CPython `bytes.decode(encoding)` (errors="strict"). + * @param {Uint8Array|number[]} bytes + * @param {string} encoding + * @param {{pythonVersion?: string}} [opts] + * @returns {string} + * @throws {UnicodeDecodeError|LookupError} + */ +export function pyDecode(bytes, encoding, opts = {}) { + const b = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes); + const codec = normalizeEncoding(encoding, opts); + if (codec === null) throw new LookupError(`unknown encoding: ${encoding}`); + switch (codec) { + case "ascii": + return decodeAscii(b); + case "latin_1": + return decodeLatin1(b); + case "utf_8": + return decodeUtf8(b); + default: { + const r = MB_DECODERS[codec](b); + if (typeof r === "string") return r; + if (r.err === TOOFEW) { + throw new UnicodeDecodeError(DISPLAY[codec], b, r.pos, b.length, "incomplete multibyte sequence"); + } + throw new UnicodeDecodeError(DISPLAY[codec], b, r.pos, r.pos + r.err, "illegal multibyte sequence"); + } + } +} + +/** Convenience: true if pyDecode would succeed. */ +export function pyCanDecode(bytes, encoding, opts = {}) { + try { + pyDecode(bytes, encoding, opts); + return true; + } catch (e) { + if (e instanceof UnicodeDecodeError) return false; + throw e; + } +} diff --git a/packages/romdev-spimdisasm/src/py/pyfloat.js b/packages/romdev-spimdisasm/src/py/pyfloat.js new file mode 100644 index 00000000..99e87d75 --- /dev/null +++ b/packages/romdev-spimdisasm/src/py/pyfloat.js @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: MIT +// +// Python float formatting, reproduced exactly. +// +// formatG(x, p) == Python `format(x, f".{p}g")` +// floatRepr(x) == Python `repr(x)` +// +// Both follow CPython's Python/pystrtod.c `format_float_short`. `formatG` +// needs dtoa mode 2 (correctly rounded to `p` significant digits, ties to +// even on the exact binary value), which is computed here from the exact +// decimal expansion of the double with BigInt arithmetic. Number#toPrecision +// can not be used for this since it rounds exact ties away from zero. +// `floatRepr` needs dtoa mode 0 (shortest round-trip digits), which is what +// Number#toExponential() without an argument produces. + +const scratch = new DataView(new ArrayBuffer(8)); + +/** + * Split a finite, non-zero double into [mantissa (BigInt), exponent] with + * |x| == mantissa * 2**exponent. + * @param {number} x + * @returns {[bigint, number]} + */ +function decompose(x) { + scratch.setFloat64(0, x); + const bits = scratch.getBigUint64(0); + const biasedExp = Number((bits >> 52n) & 0x7FFn); + let mant = bits & 0xFFFFFFFFFFFFFn; + if (biasedExp === 0) { + return [mant, -1074]; + } + mant |= 0x10000000000000n; + return [mant, biasedExp - 1075]; +} + +/** + * Exact decimal digits of |x| (finite, non-zero). + * Returns {digits, decpt} with |x| == 0.digits * 10**decpt, digits has no + * leading zeros (it may have trailing zeros). + * @param {number} x + */ +function exactDecimal(x) { + const [mant, exp] = decompose(Math.abs(x)); + let digits; + let pow10 = 0; + if (exp >= 0) { + digits = (mant << BigInt(exp)).toString(); + } else { + const k = -exp; + digits = (mant * 5n ** BigInt(k)).toString(); + pow10 = -k; + } + // value == digits * 10**pow10 == 0.digits * 10**(pow10 + len) + return { digits, decpt: pow10 + digits.length }; +} + +/** + * dtoa mode 2: round |x| to `ndigits` significant digits, ties to even. + * Returns {digits, decpt} with trailing zeros stripped (like _Py_dg_dtoa), + * |rounded| == 0.digits * 10**decpt. + * @param {number} x finite non-zero + * @param {number} ndigits >= 1 + */ +function dtoaMode2(x, ndigits) { + const { digits, decpt } = exactDecimal(x); + let outDigits; + let outDecpt = decpt; + if (digits.length <= ndigits) { + outDigits = digits; + } else { + const kept = digits.slice(0, ndigits); + const rest = digits.slice(ndigits); + let roundUp; + const first = rest.charCodeAt(0) - 48; + if (first > 5) { + roundUp = true; + } else if (first < 5) { + roundUp = false; + } else { + // first digit is 5: tie only if everything after is zero + let allZero = true; + for (let i = 1; i < rest.length; i++) { + if (rest.charCodeAt(i) !== 48) { + allZero = false; + break; + } + } + if (!allZero) { + roundUp = true; + } else { + const lastKept = kept.charCodeAt(kept.length - 1) - 48; + roundUp = (lastKept % 2) === 1; + } + } + if (roundUp) { + const bumped = (BigInt(kept) + 1n).toString(); + if (bumped.length > kept.length) { + // 999 -> 1000 + outDecpt += 1; + } + outDigits = bumped; + } else { + outDigits = kept; + } + } + outDigits = outDigits.replace(/0+$/, ""); + if (outDigits === "") { + outDigits = "0"; + } + return { digits: outDigits, decpt: outDecpt }; +} + +/** + * dtoa mode 0: shortest round-trip digits. + * @param {number} x finite non-zero + */ +function dtoaMode0(x) { + const s = Math.abs(x).toExponential(); + const eIdx = s.indexOf("e"); + const mantissa = s.slice(0, eIdx).replace(".", ""); + const exp10 = parseInt(s.slice(eIdx + 1), 10); + let digits = mantissa.replace(/0+$/, ""); + if (digits === "") { + digits = "0"; + } + return { digits, decpt: exp10 + 1 }; +} + +/** + * Port of the digit layout part of CPython's format_float_short. + * @param {boolean} negative + * @param {string} digits + * @param {number} decpt + * @param {boolean} useExp + * @param {boolean} addDot0IfInteger + */ +function layout(negative, digits, decpt, useExp, addDot0IfInteger) { + const digitsLen = digits.length; + let vdigitsEnd = digitsLen; + let exp = 0; + if (useExp) { + exp = decpt - 1; + decpt = 1; + } + const vdigitsStart = decpt <= 0 ? decpt - 1 : 0; + if (!useExp && addDot0IfInteger) { + vdigitsEnd = vdigitsEnd > decpt ? vdigitsEnd : decpt + 1; + } else { + vdigitsEnd = vdigitsEnd > decpt ? vdigitsEnd : decpt; + } + + let out = negative ? "-" : ""; + if (decpt <= 0) { + out += "0".repeat(decpt - vdigitsStart); + out += "."; + out += "0".repeat(0 - decpt); + } else { + out += "0".repeat(0 - vdigitsStart); + } + + if (0 < decpt && decpt <= digitsLen) { + out += digits.slice(0, decpt); + out += "."; + out += digits.slice(decpt); + } else { + out += digits; + } + + if (digitsLen < decpt) { + out += "0".repeat(decpt - digitsLen); + out += "."; + out += "0".repeat(vdigitsEnd - decpt); + } else { + out += "0".repeat(vdigitsEnd - digitsLen); + } + + if (out.endsWith(".")) { + out = out.slice(0, -1); + } + + if (useExp) { + const sign = exp < 0 ? "-" : "+"; + const mag = Math.abs(exp).toString().padStart(2, "0"); + out += `e${sign}${mag}`; + } + return out; +} + +function nonFinite(x) { + if (Number.isNaN(x)) { + return "nan"; + } + return x < 0 ? "-inf" : "inf"; +} + +/** + * Python `format(x, f".{precision}g")`. + * @param {number} x + * @param {number} precision + * @returns {string} + */ +export function formatG(x, precision) { + if (!Number.isFinite(x)) { + return nonFinite(x); + } + if (precision === 0) { + precision = 1; + } + const negative = x < 0 || Object.is(x, -0); + let digits; + let decpt; + if (x === 0) { + digits = "0"; + decpt = 1; + } else { + ({ digits, decpt } = dtoaMode2(x, precision)); + } + const useExp = decpt <= -4 || decpt > precision; + return layout(negative, digits, decpt, useExp, false); +} + +/** + * Python `repr(x)` for a float. + * @param {number} x + * @returns {string} + */ +export function floatRepr(x) { + if (!Number.isFinite(x)) { + return nonFinite(x); + } + const negative = x < 0 || Object.is(x, -0); + let digits; + let decpt; + if (x === 0) { + digits = "0"; + decpt = 1; + } else { + ({ digits, decpt } = dtoaMode0(x)); + } + const useExp = decpt <= -4 || decpt > 16; + return layout(negative, digits, decpt, useExp, true); +} + +/** + * struct.unpack(">f", struct.pack(">I", word))[0], widened to a double. + * @param {number} word + * @returns {number} + */ +export function wordToFloat(word) { + scratch.setUint32(0, word >>> 0); + return scratch.getFloat32(0); +} + +/** + * struct.unpack(">d", struct.pack(">Q", qword))[0]. + * @param {bigint} qword + * @returns {number} + */ +export function qwordToDouble(qword) { + scratch.setBigUint64(0, BigInt.asUintN(64, BigInt(qword))); + return scratch.getFloat64(0); +} diff --git a/packages/romdev-spimdisasm/src/py/pyset.js b/packages/romdev-spimdisasm/src/py/pyset.js new file mode 100644 index 00000000..cf3b3777 --- /dev/null +++ b/packages/romdev-spimdisasm/src/py/pyset.js @@ -0,0 +1,544 @@ +// SPDX-License-Identifier: MIT +// +// A set that iterates in exactly the same order as a CPython `set`. +// +// This is a port of the hash table logic of CPython's Objects/setobject.c +// (open addressing, LINEAR_PROBES linear probes followed by perturbed +// probing, dummy entries left by deletions, table growth when +// fill*5 >= mask*3, set_insert_clean on resize, set_merge fast paths). +// CPython 3.12 and 3.13 only differ in free-threading bookkeeping (3.13 +// re-checks that a remembered dummy slot is still a dummy before reusing +// it, which can not change without concurrent mutation), so both produce +// the same iteration order and a single implementation covers both. +// +// Keys default to Python ints (JS numbers that are integers, or BigInts), +// hashed like CPython's int hash. Other key kinds can be used by passing a +// `hash` function (returning a BigInt Python hash) and an `eq` function. + +const LINEAR_PROBES = 9; +const PERTURB_SHIFT = 5n; +const PYSET_MINSIZE = 8; + +const HASH_MODULUS = (1n << 61n) - 1n; +const DUMMY = Symbol("PySet.dummy"); + +/** CPython 3.12+ `hash(None)`. */ +export const PY_HASH_NONE = 0xFCA86420n; + +/** + * Python `hash()` of an int. Returns a signed 64-bit BigInt. + * @param {number|bigint} n + * @returns {bigint} + */ +export function pyHashInt(n) { + if (typeof n === "number") { + if (!Number.isInteger(n)) { + throw new TypeError(`pyHashInt: not an integer: ${n}`); + } + n = BigInt(n); + } else if (typeof n === "boolean") { + n = n ? 1n : 0n; + } + let h; + if (n >= 0n) { + h = n % HASH_MODULUS; + } else { + h = -((-n) % HASH_MODULUS); + } + if (h === -1n) { + h = -2n; + } + return h; +} + +const XXPRIME_1 = 11400714785074694791n; +const XXPRIME_2 = 14029467366897019727n; +const XXPRIME_5 = 2870177450012600261n; +const U64 = (1n << 64n) - 1n; + +/** + * Python `hash()` of a value made of ints, bools, None (null/undefined) + * and tuples (JS arrays). Returns a signed 64-bit BigInt. + * @param {any} value + * @returns {bigint} + */ +export function pyHash(value) { + if (value === null || value === undefined) { + return PY_HASH_NONE; + } + if (Array.isArray(value)) { + return pyHashTuple(value); + } + if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") { + return pyHashInt(value); + } + throw new TypeError(`pyHash: unsupported value ${String(value)}`); +} + +/** + * CPython's tuple hash (Objects/tupleobject.c, xxHash based, 64-bit + * Py_uhash_t). Items are hashed with `pyHash`. + * @param {any[]} items + * @returns {bigint} + */ +export function pyHashTuple(items) { + let acc = XXPRIME_5; + for (const item of items) { + const lane = BigInt.asUintN(64, pyHash(item)); + acc = (acc + lane * XXPRIME_2) & U64; + acc = ((acc << 31n) | (acc >> 33n)) & U64; + acc = (acc * XXPRIME_1) & U64; + } + acc = (acc + (BigInt(items.length) ^ (XXPRIME_5 ^ 3527539n))) & U64; + if (acc === U64) { + return 1546275796n; + } + return BigInt.asIntN(64, acc); +} + +function defaultEq(a, b) { + // Python int equality between JS numbers and BigInts + return a == b; +} + +export class PySet { + /** + * @param {Iterable|null} [iterable] + * @param {{hash?: (key: any) => bigint, eq?: (a: any, b: any) => boolean}} [options] + */ + constructor(iterable = null, options = {}) { + this._hashFn = options.hash ?? pyHashInt; + this._eqFn = options.eq ?? defaultEq; + this._emptyToMinsize(); + if (iterable !== null && iterable !== undefined) { + this.update(iterable); + } + } + + _emptyToMinsize() { + this._mask = PYSET_MINSIZE - 1; + /** @type {any[]} undefined == empty slot, DUMMY == deleted */ + this._keys = new Array(PYSET_MINSIZE); + /** @type {bigint[]} */ + this._hashes = new Array(PYSET_MINSIZE).fill(0n); + this._fill = 0; + this._used = 0; + } + + _newEmptyLike() { + return new PySet(null, { hash: this._hashFn, eq: this._eqFn }); + } + + _hash(key) { + return this._hashFn(key); + } + + _keyEq(a, b) { + return a === b || this._eqFn(a, b); + } + + /** set_lookkey: returns slot index of the key or of the empty slot. */ + _lookkey(key, hash) { + let mask = this._mask; + let perturb = BigInt.asUintN(64, hash); + let i = Number(perturb & BigInt(mask)); + for (;;) { + let probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES : 0; + let j = i; + do { + const k = this._keys[j]; + if (k === undefined) { + return j; + } + if (this._hashes[j] === hash && k !== DUMMY && this._keyEq(k, key)) { + return j; + } + j++; + } while (probes-- > 0); + perturb >>= PERTURB_SHIFT; + i = (i * 5 + 1 + Number(perturb & BigInt(mask))) & mask; + } + } + + /** set_add_entry */ + _addEntry(key, hash) { + const mask = this._mask; + let perturb = BigInt.asUintN(64, hash); + let i = Number(perturb & BigInt(mask)); + let freeslot = -1; + for (;;) { + let probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES : 0; + let j = i; + do { + const k = this._keys[j]; + if (k === undefined) { + // found_unused_or_dummy + if (freeslot >= 0) { + this._used++; + this._keys[freeslot] = key; + this._hashes[freeslot] = hash; + return; + } + this._fill++; + this._used++; + this._keys[j] = key; + this._hashes[j] = hash; + if (this._fill * 5 < mask * 3) { + return; + } + this._tableResize(this._used > 50000 ? this._used * 2 : this._used * 4); + return; + } + if (this._hashes[j] === hash) { + if (k !== DUMMY && this._keyEq(k, key)) { + // found_active + return; + } + } else if (k === DUMMY) { + freeslot = j; + } + j++; + } while (probes-- > 0); + perturb >>= PERTURB_SHIFT; + i = (i * 5 + 1 + Number(perturb & BigInt(mask))) & mask; + } + } + + /** set_insert_clean */ + static _insertClean(keys, hashes, mask, key, hash) { + let perturb = BigInt.asUintN(64, hash); + let i = Number(perturb & BigInt(mask)); + for (;;) { + if (keys[i] === undefined) { + keys[i] = key; + hashes[i] = hash; + return; + } + if (i + LINEAR_PROBES <= mask) { + for (let j = 1; j <= LINEAR_PROBES; j++) { + if (keys[i + j] === undefined) { + keys[i + j] = key; + hashes[i + j] = hash; + return; + } + } + } + perturb >>= PERTURB_SHIFT; + i = (i * 5 + 1 + Number(perturb & BigInt(mask))) & mask; + } + } + + /** set_table_resize */ + _tableResize(minused) { + let newsize = PYSET_MINSIZE; + while (newsize <= minused) { + newsize *= 2; + } + const oldKeys = this._keys; + const oldHashes = this._hashes; + const oldMask = this._mask; + if (newsize === PYSET_MINSIZE && oldMask === PYSET_MINSIZE - 1 && this._fill === this._used) { + // small table, no dummies: nothing to do + return; + } + const newMask = newsize - 1; + const keys = new Array(newsize); + const hashes = new Array(newsize).fill(0n); + const hadDummies = this._fill !== this._used; + if (hadDummies) { + this._fill = this._used; + } + for (let idx = 0; idx <= oldMask; idx++) { + const k = oldKeys[idx]; + if (k !== undefined && k !== DUMMY) { + PySet._insertClean(keys, hashes, newMask, k, oldHashes[idx]); + } + } + this._keys = keys; + this._hashes = hashes; + this._mask = newMask; + } + + /** set_discard_entry, returns true if found */ + _discardEntry(key, hash) { + const j = this._lookkey(key, hash); + if (this._keys[j] === undefined) { + return false; + } + this._keys[j] = DUMMY; + this._hashes[j] = -1n; + this._used--; + return true; + } + + _containsEntry(key, hash) { + return this._keys[this._lookkey(key, hash)] !== undefined; + } + + /** set_merge */ + _merge(other) { + if (other === this || other._used === 0) { + return; + } + if ((this._fill + other._used) * 5 >= this._mask * 3) { + this._tableResize((this._used + other._used) * 2); + } + if (this._fill === 0 && this._mask === other._mask && other._fill === other._used) { + for (let i = 0; i <= other._mask; i++) { + const k = other._keys[i]; + if (k !== undefined) { + this._keys[i] = k; + this._hashes[i] = other._hashes[i]; + } + } + this._fill = other._fill; + this._used = other._used; + return; + } + if (this._fill === 0) { + this._fill = other._used; + this._used = other._used; + for (let i = 0; i <= other._mask; i++) { + const k = other._keys[i]; + if (k !== undefined && k !== DUMMY) { + PySet._insertClean(this._keys, this._hashes, this._mask, k, other._hashes[i]); + } + } + return; + } + for (let i = 0; i <= other._mask; i++) { + const k = other._keys[i]; + if (k !== undefined && k !== DUMMY) { + this._addEntry(k, other._hashes[i]); + } + } + } + + /** set_next style entries of the live table: [key, hash] */ + *_entries() { + const used = this._used; + const keys = this._keys; + for (let i = 0; i <= this._mask; i++) { + if (this._used !== used || this._keys !== keys) { + throw new Error("Set changed size during iteration"); + } + const k = keys[i]; + if (k !== undefined && k !== DUMMY) { + yield [k, this._hashes[i]]; + } + } + } + + // ---- JS Set-like API ---- + + get size() { + return this._used; + } + + add(key) { + this._addEntry(key, this._hash(key)); + return this; + } + + has(key) { + return this._containsEntry(key, this._hash(key)); + } + + /** Python `discard`; returns whether the key was present. */ + delete(key) { + return this._discardEntry(key, this._hash(key)); + } + + discard(key) { + this.delete(key); + } + + /** Python `remove`: throws if missing. */ + remove(key) { + if (!this.delete(key)) { + throw new Error(`KeyError: ${String(key)}`); + } + } + + clear() { + this._emptyToMinsize(); + } + + *[Symbol.iterator]() { + for (const [k] of this._entries()) { + yield k; + } + } + + values() { + return this[Symbol.iterator](); + } + + keys() { + return this[Symbol.iterator](); + } + + *entries() { + for (const k of this) { + yield [k, k]; + } + } + + forEach(callback, thisArg) { + for (const k of this) { + callback.call(thisArg, k, k, this); + } + } + + // ---- Python API ---- + + /** set.update / `|=` with a single argument. */ + update(iterable) { + if (iterable instanceof PySet) { + this._merge(iterable); + return this; + } + for (const k of iterable) { + this.add(k); + } + return this; + } + + copy() { + const result = this._newEmptyLike(); + result._merge(this); + return result; + } + + /** set.union / `|` */ + union(...others) { + const result = this.copy(); + for (const other of others) { + if (other === this) { + continue; + } + result.update(other); + } + return result; + } + + /** set.intersection / `&` with a single argument */ + intersection(other) { + if (other === this) { + return this.copy(); + } + const result = this._newEmptyLike(); + if (other instanceof PySet) { + let so = this; + let ot = other; + if (ot._used > so._used) { + [so, ot] = [ot, so]; + } + for (const [k, h] of ot._entries()) { + if (so._containsEntry(k, h)) { + result._addEntry(k, h); + } + } + return result; + } + for (const k of other) { + const h = this._hash(k); + if (this._containsEntry(k, h)) { + result._addEntry(k, h); + if (result._used >= this._used) { + break; + } + } + } + return result; + } + + /** set.intersection_update / `&=` */ + intersectionUpdate(other) { + const tmp = this.intersection(other); + this._keys = tmp._keys; + this._hashes = tmp._hashes; + this._mask = tmp._mask; + this._fill = tmp._fill; + this._used = tmp._used; + return this; + } + + /** set_difference_update_internal (`-=`) */ + differenceUpdate(other) { + if (other === this) { + this.clear(); + return this; + } + if (other instanceof PySet) { + let ot = other; + if ((ot._used >> 3) > this._used) { + ot = this.intersection(ot); + } + for (const [k, h] of ot._entries()) { + this._discardEntry(k, h); + } + } else { + for (const k of other) { + this.delete(k); + } + } + if ((this._fill - this._used) <= Math.floor(this._mask / 4)) { + return this; + } + this._tableResize(this._used > 50000 ? this._used * 2 : this._used * 4); + return this; + } + + /** set.difference / `-` with a single argument */ + difference(other) { + if (!(other instanceof PySet)) { + return this.copy().differenceUpdate(other); + } + if ((this._used >> 2) > other._used) { + return this.copy().differenceUpdate(other); + } + const result = this._newEmptyLike(); + for (const [k, h] of this._entries()) { + if (!other._containsEntry(k, h)) { + result._addEntry(k, h); + } + } + return result; + } + + isdisjoint(other) { + if (other === this) { + return this._used === 0; + } + if (other instanceof PySet) { + let so = this; + let ot = other; + if (ot._used > so._used) { + [so, ot] = [ot, so]; + } + for (const [k, h] of ot._entries()) { + if (so._containsEntry(k, h)) { + return false; + } + } + return true; + } + for (const k of other) { + if (this.has(k)) { + return false; + } + } + return true; + } + + /** Debug helper: the raw slot layout ("" empty, "", or key). */ + _debugSlots() { + const out = []; + for (let i = 0; i <= this._mask; i++) { + const k = this._keys[i]; + out.push(k === undefined ? "" : (k === DUMMY ? "" : k)); + } + return out; + } +} diff --git a/packages/romdev-spimdisasm/src/py/pyutils.js b/packages/romdev-spimdisasm/src/py/pyutils.js new file mode 100644 index 00000000..8222e1fb --- /dev/null +++ b/packages/romdev-spimdisasm/src/py/pyutils.js @@ -0,0 +1,256 @@ +// SPDX-License-Identifier: MIT +// Small Python-compatibility helpers used by the spimdisasm port. + +/** Python-style enum. Members are unique frozen objects with .name/.value. */ +export function createEnum(enumName, entries, memberMethods = {}, staticMethods = {}) { + const proto = Object.create(null); + Object.assign(proto, memberMethods); + proto.toString = function () { + return `${enumName}.${this.name}`; + }; + proto[Symbol.toPrimitive] = function (hint) { + if (hint === "number") return typeof this.value === "number" ? this.value : NaN; + return `${enumName}.${this.name}`; + }; + const e = {}; + const members = []; + for (const [name, value] of entries) { + const m = Object.create(proto); + Object.defineProperty(m, "name", { value: name, enumerable: true }); + Object.defineProperty(m, "value", { value, enumerable: true, writable: false }); + Object.defineProperty(m, "__enumName", { value: enumName }); + Object.freeze(m); + e[name] = m; + members.push(m); + } + Object.defineProperty(e, "__name", { value: enumName }); + Object.defineProperty(e, "members", { value: Object.freeze(members) }); + Object.defineProperty(e, Symbol.iterator, { value: function* () { yield* members; } }); + Object.defineProperty(e, "fromValueOrNull", { + value: (v) => { + for (const m of members) if (m.value === v) return m; + return null; + }, + }); + for (const [k, fn] of Object.entries(staticMethods)) { + Object.defineProperty(e, k, { value: fn }); + } + return Object.freeze(e); +} + +/** Python `str()` of a scalar/enum/None/bool. */ +export function pyStr(v) { + if (v === null || v === undefined) return "None"; + if (v === true) return "True"; + if (v === false) return "False"; + if (typeof v === "bigint") return v.toString(); + if (typeof v === "object" && v.__enumName !== undefined) return `${v.__enumName}.${v.name}`; + return String(v); +} + +/** f"{n:0{width}X}" (Python semantics, incl. negative numbers and bigint). */ +export function hexU(n, width = 0) { + let neg = false; + let s; + if (typeof n === "bigint") { + if (n < 0n) { neg = true; n = -n; } + s = n.toString(16).toUpperCase(); + } else { + if (n < 0) { neg = true; n = -n; } + s = n.toString(16).toUpperCase(); + } + const sign = neg ? "-" : ""; + const padTo = width - sign.length; + if (s.length < padTo) s = "0".repeat(padTo - s.length) + s; + return sign + s; +} + +/** f"{n:0{width}x}" lowercase. */ +export function hexL(n, width = 0) { + return hexU(n, width).toLowerCase(); +} + +/** Python floor division for numbers. */ +export function floordiv(a, b) { + return Math.floor(a / b); +} + +/** Python modulo (sign of divisor). */ +export function pymod(a, b) { + const r = a % b; + return r !== 0 && (r < 0) !== (b < 0) ? r + b : r; +} + +// Unicode whitespace per Python str.isspace() (bidirectional type WS/B/S or category Zs). +const PY_SPACE = new Set([ + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x85, 0xa0, 0x1680, + 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, + 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, +]); + +export function isPySpaceChar(ch) { + return PY_SPACE.has(ch.codePointAt(0)); +} + +export function anyPySpace(s) { + for (const ch of s) if (PY_SPACE.has(ch.codePointAt(0))) return true; + return false; +} + +/** Python str.split() with no arguments. */ +export function splitWs(s) { + const out = []; + let cur = ""; + let inWord = false; + for (const ch of s) { + if (PY_SPACE.has(ch.codePointAt(0))) { + if (inWord) { out.push(cur); cur = ""; inWord = false; } + } else { + cur += ch; + inWord = true; + } + } + if (inWord) out.push(cur); + return out; +} + +/** Python str.strip() with no arguments. */ +export function pyStrip(s) { + const chars = Array.from(s); + let a = 0; + let b = chars.length; + while (a < b && PY_SPACE.has(chars[a].codePointAt(0))) a++; + while (b > a && PY_SPACE.has(chars[b - 1].codePointAt(0))) b--; + return chars.slice(a, b).join(""); +} + +/** Python str.strip(chars). */ +export function pyStripChars(s, chars) { + let a = 0; + let b = s.length; + while (a < b && chars.includes(s[a])) a++; + while (b > a && chars.includes(s[b - 1])) b--; + return s.slice(a, b); +} + +/** + * Python int(s, base) for base 0 or 16/10. Throws ValueError-like Error on failure. + * Returns a Number (safe for the 32/48-bit values spimdisasm deals with). + */ +export class ValueError extends Error { + constructor(msg) { + super(msg); + this.name = "ValueError"; + } +} + +export function pyInt(str, base = 10) { + if (typeof str !== "string") throw new TypeError("pyInt expects a string"); + let s = pyStrip(str); + let sign = 1; + if (s.startsWith("+")) s = s.slice(1); + else if (s.startsWith("-")) { sign = -1; s = s.slice(1); } + let b = base; + const lower = s.toLowerCase(); + if (base === 0) { + if (lower.startsWith("0x")) { b = 16; s = s.slice(2); } + else if (lower.startsWith("0o")) { b = 8; s = s.slice(2); } + else if (lower.startsWith("0b")) { b = 2; s = s.slice(2); } + else { + b = 10; + // base 0 disallows leading zeros in non-zero decimal numbers + if (/^0+[1-9]/.test(s.replace(/_/g, ""))) throw new ValueError(`invalid literal for int() with base 0: '${str}'`); + } + if (s.startsWith("_")) s = s.slice(1); + } else if (base === 16 && lower.startsWith("0x")) { + s = s.slice(2); + if (s.startsWith("_")) s = s.slice(1); + } else if (base === 8 && lower.startsWith("0o")) { + s = s.slice(2); + } else if (base === 2 && lower.startsWith("0b")) { + s = s.slice(2); + } + if (s.length === 0 || s.startsWith("_") || s.endsWith("_") || s.includes("__")) { + throw new ValueError(`invalid literal for int() with base ${base}: '${str}'`); + } + s = s.replace(/_/g, ""); + const digits = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, b); + let v = 0n; + const bb = BigInt(b); + for (const ch of s.toLowerCase()) { + const d = digits.indexOf(ch); + if (d < 0) throw new ValueError(`invalid literal for int() with base ${base}: '${str}'`); + v = v * bb + BigInt(d); + } + if (sign < 0) v = -v; + if (v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= BigInt(Number.MIN_SAFE_INTEGER)) return Number(v); + return v; +} + +/** Stable sort by key (Python sorted is stable). Returns a new array. */ +export function sortedBy(arr, keyFn) { + const tmp = arr.map((x, i) => [keyFn(x), i, x]); + tmp.sort((a, b) => { + const c = pyCompare(a[0], b[0]); + return c !== 0 ? c : a[1] - b[1]; + }); + return tmp.map((t) => t[2]); +} + +/** Python ordering compare for numbers/strings/bigints/arrays (tuples). */ +export function pyCompare(a, b) { + if (Array.isArray(a) && Array.isArray(b)) { + const n = Math.min(a.length, b.length); + for (let i = 0; i < n; i++) { + const c = pyCompare(a[i], b[i]); + if (c !== 0) return c; + } + return a.length - b.length; + } + if (typeof a === "string" && typeof b === "string") { + // Python compares by code point + const aa = Array.from(a, (c) => c.codePointAt(0)); + const bb = Array.from(b, (c) => c.codePointAt(0)); + return pyCompare(aa, bb); + } + if (a < b) return -1; + if (a > b) return 1; + return 0; +} + +/** sorted(set_of_ints) */ +export function sortedNumbers(iterable) { + return Array.from(iterable).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); +} + +/** Resolve Python negative index for `del list[i]` / `list[i]`. */ +export function pyIndex(len, i) { + if (i < 0) i += len; + if (i < 0 || i >= len) throw new RangeError("list index out of range"); + return i; +} + +/** Map.get with default */ +export function mapGet(m, k, dflt = null) { + return m.has(k) ? m.get(k) : dflt; +} + +/** Enum-ish equality for rabbitizer enums (which may or may not be singletons). */ +export function enumValue(x) { + if (x === null || x === undefined) return x; + if (typeof x === "object" && "value" in x) return x.value; + return x; +} + +export function sameEnum(a, b) { + if (a === b) return true; + if (a === null || a === undefined || b === null || b === undefined) return false; + if (typeof a === "object" && typeof b === "object") { + if (a.value !== b.value) return false; + const ta = a.enumType ?? a.__enumName; + const tb = b.enumType ?? b.__enumName; + if (ta !== undefined && tb !== undefined) return ta === tb; + return a.name === b.name; + } + return false; +} diff --git a/packages/romdev-spimdisasm/src/rabbitizer.js b/packages/romdev-spimdisasm/src/rabbitizer.js new file mode 100644 index 00000000..a014c3c4 --- /dev/null +++ b/packages/romdev-spimdisasm/src/rabbitizer.js @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT +// Single access point to the rabbitizer module (romdev-rabbitizer, a WASM +// build of rabbitizer whose JS API mirrors the Python rabbitizer module). +// +// Every other module reads `rabbitizer.` through the proxy exported here, +// which forwards to the active rabbitizer instance. configureVersion() swaps +// the instance for the rabbitizer release paired with the selected spimdisasm +// release. Callers that configure rabbitizer (for example splat setting +// `rabbitizer.config.*`) must use this same proxy (exported by the package as +// `rabbitizer`) so their settings reach the instance spimdisasm decodes with. + +import { loadRabbitizerSync } from "romdev-rabbitizer"; +import { RABBITIZER_VERSION_FOR, onVersionChange, versionString } from "./version.js"; + +const loaded = new Map(); +let mod = null; + +function load(version) { + if (!loaded.has(version)) loaded.set(version, loadRabbitizerSync(version)); + return loaded.get(version); +} + +/** Activate the rabbitizer instance for the given rabbitizer release. */ +export function useRabbitizerVersion(version) { + mod = load(version); + return mod; +} + +const handler = { + get(_t, prop) { + if (mod === null) throw new Error("romdev-spimdisasm: no rabbitizer instance active"); + return mod[prop]; + }, + set(_t, prop, value) { + mod[prop] = value; + return true; + }, + has(_t, prop) { + return mod !== null && prop in mod; + }, + ownKeys() { + return mod === null ? [] : Reflect.ownKeys(mod); + }, + getOwnPropertyDescriptor(_t, prop) { + if (mod === null) return undefined; + const d = Reflect.getOwnPropertyDescriptor(mod, prop); + if (d) d.configurable = true; + return d; + }, +}; + +/** Proxy that forwards to the active rabbitizer module. */ +export const rabbitizer = new Proxy({}, handler); + +/** Replace the active rabbitizer instance (tests, custom builds). */ +export function setRabbitizer(m) { + mod = m; +} + +export function getRabbitizer() { + return mod; +} + +export function hasRabbitizer() { + return mod !== null; +} + +// Activate the rabbitizer release paired with the default spimdisasm release, +// and follow configureVersion(). +useRabbitizerVersion(RABBITIZER_VERSION_FOR[versionString()]); +onVersionChange((v) => useRabbitizerVersion(RABBITIZER_VERSION_FOR[v])); diff --git a/packages/romdev-spimdisasm/src/version.js b/packages/romdev-spimdisasm/src/version.js new file mode 100644 index 00000000..c3fc27f4 --- /dev/null +++ b/packages/romdev-spimdisasm/src/version.js @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MIT +// Version selection for the spimdisasm port. +// +// The package reproduces several upstream spimdisasm releases. The selected +// release changes GlobalConfig defaults, compiler properties and a handful of +// code paths (gated with `atLeast`). Each spimdisasm release is paired with the +// rabbitizer release it was published against. + +export const SUPPORTED_VERSIONS = Object.freeze(["1.35.0", "1.39.3", "1.42.4"]); + +export const RABBITIZER_VERSION_FOR = Object.freeze({ + "1.35.0": "1.13.0", + "1.39.3": "1.14.3", + "1.42.4": "1.16.2", +}); + +export const DEFAULT_VERSION = "1.42.4"; + +let currentStr = DEFAULT_VERSION; +let current = [1, 42, 4]; +const hooks = []; + +export function parseVersion(v) { + if (Array.isArray(v)) return v.map(Number); + const parts = String(v).split(".").map((x) => Number.parseInt(x, 10)); + while (parts.length < 3) parts.push(0); + return parts; +} + +function cmp(a, b) { + for (let i = 0; i < 3; i++) { + if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1; + } + return 0; +} + +/** True when the configured spimdisasm version is >= the given version. */ +export function atLeast(v) { + return cmp(current, parseVersion(v)) >= 0; +} + +export function versionString() { + return currentStr; +} + +export function versionInfo() { + return [...current]; +} + +/** Register a callback run after every version change (used to reset defaults). */ +export function onVersionChange(fn) { + hooks.push(fn); +} + +export function setVersion(v) { + const s = Array.isArray(v) ? v.join(".") : String(v); + if (!SUPPORTED_VERSIONS.includes(s)) { + throw new Error(`romdev-spimdisasm: unsupported spimdisasm version '${s}'. Supported: ${SUPPORTED_VERSIONS.join(", ")}`); + } + currentStr = s; + current = parseVersion(s); + for (const fn of hooks) fn(s); +} diff --git a/packages/romdev-spimdisasm/test/codecs.test.mjs b/packages/romdev-spimdisasm/test/codecs.test.mjs new file mode 100644 index 00000000..36115224 --- /dev/null +++ b/packages/romdev-spimdisasm/test/codecs.test.mjs @@ -0,0 +1,211 @@ +// Tests for src/py/codecs.js: CPython-faithful strict byte decoding. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { pyDecode, pyCanDecode, normalizeEncoding, pyNormalizeEncodingName, UnicodeDecodeError, LookupError } from "../src/py/codecs.js"; +import * as DEC from "../src/py/cjk-tables-jp.js"; +import * as ENC from "./data/cjk-encmap-jp.js"; + +const U = (...b) => Uint8Array.from(b); + +function load(t) { + const buf = Buffer.from(t.data, "base64"); + const a = new Uint16Array(t.length); + for (let i = 0; i < t.length; i++) a[i] = buf.readUInt16LE(i * 2); + return { a, idx: t.index }; +} +function look(t, hi, lo, invalid) { + const e = t.idx[hi]; + if (!e) return -1; + const [o, b, top] = e; + if (lo < b || lo > top) return -1; + const v = t.a[o + lo - b]; + return v === invalid ? -1 : v; +} +function entries(t) { + const out = []; + for (let c1 = 0; c1 < 256; c1++) { + const e = t.idx[c1]; + if (!e) continue; + for (let c2 = e[1]; c2 <= e[2]; c2++) { + const u = t.a[e[0] + c2 - e[1]]; + if (u !== 0xfffe) out.push([c1, c2, u]); + } + } + return out; +} +function expectError(bytes, enc, start, end, reason) { + assert.throws(() => pyDecode(bytes, enc), (e) => { + assert.ok(e instanceof UnicodeDecodeError, String(e)); + if (start !== undefined) assert.equal(e.start, start); + if (end !== undefined) assert.equal(e.end, end); + if (reason !== undefined) assert.equal(e.reason, reason); + return true; + }); +} + +test("generated tables have the C array sizes of CPython mappings_jp.h", () => { + assert.equal(DEC.jisx0208_decmap.length, 6956); + assert.equal(DEC.jisx0212_decmap.length, 6179); + assert.equal(DEC.cp932ext_decmap.length, 969); + assert.equal(ENC.jisxcommon_encmap.length, 22016); + assert.equal(ENC.cp932ext_encmap.length, 9686); + for (const t of [DEC.jisx0208_decmap, DEC.jisx0212_decmap, DEC.cp932ext_decmap, ENC.jisxcommon_encmap, ENC.cp932ext_encmap]) { + assert.equal(t.index.length, 256); + assert.equal(Buffer.from(t.data, "base64").length, t.length * 2); + } + // Defined code counts (non-UNIINV cells): JIS X 0208 has 6879, JIS X 0212 6067. + assert.equal(entries(load(DEC.jisx0208_decmap)).length, 6879); + assert.equal(entries(load(DEC.jisx0212_decmap)).length, 6067); + assert.equal(entries(load(DEC.cp932ext_decmap)).length, 933); +}); + +test("JIS X 0208 and JIS X 0212 decode maps are exact inverses of CPython's jisxcommon encode map", () => { + const enc = load(ENC.jisxcommon_encmap); + for (const [name, flag] of [["jisx0208_decmap", 0], ["jisx0212_decmap", 0x8000]]) { + const all = entries(load(DEC[name])); + const bad = all.filter(([c1, c2, u]) => look(enc, u >> 8, u & 0xff, 0xffff) !== (((c1 << 8) | c2) | flag)); + assert.deepEqual(bad, [], name); + // every cell lies in the 94x94 plane + assert.ok(all.every(([c1, c2]) => c1 >= 0x21 && c1 <= 0x7e && c2 >= 0x21 && c2 <= 0x7e), name); + } +}); + +test("cp932ext decode entries either round-trip or are documented duplicates/JIS-overrides", () => { + const dec = load(DEC.cp932ext_decmap); + const enc = load(ENC.cp932ext_encmap); + let roundTrip = 0; + let duplicate = 0; + let noExtEncoding = 0; + for (const [c1, c2, u] of entries(dec)) { + const code = look(enc, u >> 8, u & 0xff, 0xffff); + if (code === ((c1 << 8) | c2)) roundTrip++; + else if (code === -1) noExtEncoding++; + else { + // The canonical code must decode back to the same character. + assert.equal(look(dec, code >> 8, code & 0xff, 0xfffe), u); + duplicate++; + } + } + assert.deepEqual({ roundTrip, duplicate, noExtEncoding }, { roundTrip: 454, duplicate: 388, noExtEncoding: 91 }); +}); + +test("shift_jis: every lead/trail byte class behaves like CPython DECODER(shift_jis)", () => { + for (let c = 0; c < 256; c++) { + const single = pyCanDecode(U(c), "shift_jis"); + assert.equal(single, c < 0x80 || (c >= 0xa1 && c <= 0xdf), `single 0x${c.toString(16)}`); + } + // Leads 0x81-0x9F, 0xE0-0xEA; trails 0x40-0x7E, 0x80-0xFC. + const lead = (c) => (c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea); + let decodable = 0; + for (let c1 = 0x80; c1 <= 0xff; c1++) { + for (let c2 = 0; c2 <= 0xff; c2++) { + const ok = pyCanDecode(U(c1, c2), "shift_jis"); + const singleOk = c1 >= 0xa1 && c1 <= 0xdf; + if (!lead(c1)) { + // two independent single bytes + assert.equal(ok, singleOk && pyCanDecode(U(c2), "shift_jis")); + continue; + } + const trailOk = (c2 >= 0x40 && c2 <= 0x7e) || (c2 >= 0x80 && c2 <= 0xfc); + if (!trailOk) assert.equal(ok, false, `0x${c1.toString(16)} 0x${c2.toString(16)}`); + if (ok) decodable++; + } + } + // JIS X 0208's 6879 codes, all reachable through Shift-JIS + assert.equal(decodable, 6879); +}); + +test("shift_jis hand cases", () => { + // "テスト" in Shift-JIS + assert.equal(pyDecode(U(0x83, 0x65, 0x83, 0x58, 0x83, 0x67), "shift_jis"), "テスト"); + // 0x5C and 0x7E pass through as ASCII (non-STRICT_BUILD) + assert.equal(pyDecode(U(0x5c, 0x7e), "shift_jis"), "\\~"); + // halfwidth katakana + assert.equal(pyDecode(U(0xa1, 0xb1, 0xdf), "shift_jis"), "。ア゚"); + // 0x815F is FULLWIDTH REVERSE SOLIDUS in CPython (JIS0208.TXT says U+005C) + assert.equal(pyDecode(U(0x81, 0x5f), "shift_jis"), "\"); + // lead byte followed by an invalid trail + expectError(U(0x41, 0x83, 0x20), "shift_jis", 1, 2, "illegal multibyte sequence"); + expectError(U(0x83, 0x7f), "shift_jis", 0, 1, "illegal multibyte sequence"); + // unmapped cell inside the valid trail range (row 0x85 is empty in JIS X 0208) + expectError(U(0x85, 0x40), "shift_jis", 0, 1, "illegal multibyte sequence"); + // lone lead byte at the end + expectError(U(0x41, 0x42, 0x83), "shift_jis", 2, 3, "incomplete multibyte sequence"); + // bytes that are never valid in shift_jis + for (const b of [0x80, 0xa0, 0xeb, 0xf0, 0xfd, 0xfe, 0xff]) expectError(U(0x41, b, 0x41), "shift_jis", 1, 2, "illegal multibyte sequence"); +}); + +test("euc_jp hand cases", () => { + // "日本" in EUC-JP + assert.equal(pyDecode(U(0xc6, 0xfc, 0xcb, 0xdc), "euc_jp"), "日本"); + // SS2 halfwidth katakana + assert.equal(pyDecode(U(0x8e, 0xb1), "euc_jp"), "ア"); + expectError(U(0x8e, 0xa0), "euc_jp", 0, 1); + // SS3 JIS X 0212: 0x8F 0xB0 0xA1 = U+4E02 + assert.equal(pyDecode(U(0x8f, 0xb0, 0xa1), "euc_jp"), "丂"); + // JIS X 0212 0x2237 is U+007E in CPython (glibc says U+FF5E) + assert.equal(pyDecode(U(0x8f, 0xa2, 0xb7), "euc_jp"), "~"); + expectError(U(0x8f, 0xa1, 0xa1), "euc_jp", 0, 1, "illegal multibyte sequence"); + expectError(U(0x8f, 0xb0), "euc_jp", 0, 2, "incomplete multibyte sequence"); + // FULL-WIDTH REVERSE SOLIDUS special case + assert.equal(pyDecode(U(0xa1, 0xc0), "euc_jp"), "\"); + // C1 single bytes are rejected by CPython (glibc accepts them) + expectError(U(0x80), "euc_jp", 0, 1); + expectError(U(0x90, 0xa1), "euc_jp", 0, 1); + expectError(U(0xc6), "euc_jp", 0, 1, "incomplete multibyte sequence"); +}); + +test("cp932 hand cases", () => { + assert.equal(pyDecode(U(0x80, 0xa0, 0xfd, 0xfe, 0xff), "cp932"), "\u0080"); + // NEC row 13 circled one + assert.equal(pyDecode(U(0x87, 0x40), "cp932"), "①"); + // user-defined area maps into the PUA + assert.equal(pyDecode(U(0xf0, 0x40), "cp932"), ""); + // 0x815F is FULLWIDTH REVERSE SOLIDUS in cp932 too (cp932ext entry) + assert.equal(pyDecode(U(0x81, 0x5f), "cp932"), "\"); + expectError(U(0x81), "cp932", 0, 1, "incomplete multibyte sequence"); +}); + +test("ascii, latin_1 and utf_8 strictness", () => { + assert.equal(pyDecode(U(0x41, 0x7f), "ascii"), "A\x7f"); + expectError(U(0x41, 0x80), "ascii", 1, 2, "ordinal not in range(128)"); + assert.equal(pyDecode(U(0xe9, 0xff), "latin_1"), "éÿ"); + assert.equal(pyDecode(U(0xe6, 0x97, 0xa5), "utf-8"), "日"); + assert.equal(pyDecode(U(0xf0, 0x9f, 0x98, 0x80), "utf8"), "\u{1f600}"); + expectError(U(0xc0, 0x80), "utf-8", 0, 1, "invalid start byte"); // overlong + expectError(U(0xed, 0xa0, 0x80), "utf-8", 0, 1, "invalid continuation byte"); // surrogate + expectError(U(0xf4, 0x90, 0x80, 0x80), "utf-8", 0, 1, "invalid continuation byte"); // > U+10FFFF + expectError(U(0xe6, 0x97), "utf-8", 0, 2, "unexpected end of data"); +}); + +test("encoding names resolve like codecs.lookup", () => { + assert.equal(normalizeEncoding("SHIFT-JIS"), "shift_jis"); + assert.equal(normalizeEncoding("Shift_JIS"), "shift_jis"); + assert.equal(normalizeEncoding("sjis"), "shift_jis"); + assert.equal(normalizeEncoding("EUC-JP"), "euc_jp"); + assert.equal(normalizeEncoding("ujis"), "euc_jp"); + assert.equal(normalizeEncoding("ASCII"), "ascii"); + assert.equal(normalizeEncoding("us-ascii"), "ascii"); + assert.equal(normalizeEncoding("UTF-8"), "utf_8"); + assert.equal(normalizeEncoding("latin1"), "latin_1"); + assert.equal(normalizeEncoding("MS932"), "cp932"); + assert.equal(normalizeEncoding("windows-31j"), "cp932"); + assert.equal(normalizeEncoding("windows-31j", { pythonVersion: "3.12" }), null); + assert.equal(pyNormalizeEncodingName(" -euc--jp;# "), "euc_jp"); + assert.equal(normalizeEncoding("EUC-CN"), null); + assert.throws(() => pyDecode(U(0x41), "no-such-codec"), LookupError); +}); + +test("perturbing one byte flips a successful decode into an error", () => { + const good = U(0x83, 0x65, 0x83, 0x58, 0x83, 0x67, 0x00); + assert.equal(pyCanDecode(good, "shift_jis"), true); + const bad = Uint8Array.from(good); + bad[3] = 0x7f; // trail byte out of range + assert.equal(pyCanDecode(bad, "shift_jis"), false); + const eucGood = U(0xc6, 0xfc, 0xcb, 0xdc); + assert.equal(pyCanDecode(eucGood, "euc_jp"), true); + const eucBad = Uint8Array.from(eucGood); + eucBad[1] = 0x41; + assert.equal(pyCanDecode(eucBad, "euc_jp"), false); +}); diff --git a/packages/romdev-spimdisasm/test/data/cjk-encmap-jp.js b/packages/romdev-spimdisasm/test/data/cjk-encmap-jp.js new file mode 100644 index 00000000..099bddb6 --- /dev/null +++ b/packages/romdev-spimdisasm/test/data/cjk-encmap-jp.js @@ -0,0 +1,870 @@ +// GENERATED by scripts/gen-cjk-tables.mjs - DO NOT EDIT. +// Japanese encode maps, used only by the structural invariant tests. +// Source: CPython 3.13 Modules/cjkcodecs/mappings_jp.h (sha1 29b25408074ca9779bc454e79e54e631b816bf59), +// itself generated by CPython's Tools/unicode/genmap_japanese.py. +// https://github.com/python/cpython/blob/3.13/Modules/cjkcodecs/mappings_jp.h +// Copyright (c) 2001 Python Software Foundation; All Rights Reserved. +// Licensed under the Python Software Foundation License Version 2 (PSF-2.0). +// +// Format: data is a base64 little-endian Uint16 array (the C __ array, +// with U=0xFFFE, N=0xFFFF, D=0xFFFD); index[lead] is null or +// [offset, bottom, top] exactly like the C struct index array. + +export const jisxcommon_encmap = { + length: 22016, + index: [[0,92,255],[164,0,245],[410,199,221],[433,132,206],[508,1,95],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[603,16,59],[647,3,212],[857,0,165],[1023,18,18],null,[1024,0,239],[1264,5,111],null,null,null,null,null,null,null,null,null,[1371,0,254],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[1626,0,255],[1882,0,255],[2138,0,254],[2393,0,254],[2648,0,255],[2904,0,250],[3155,1,255],[3410,0,255],[3666,5,255],[3917,0,255],[4173,0,253],[4427,2,255],[4681,0,253],[4935,0,255],[5191,1,253],[5444,1,254],[5698,0,255],[5954,1,255],[6209,7,253],[6456,0,255],[6712,0,255],[6968,1,250],[7218,6,255],[7468,0,255],[7724,0,255],[7980,0,255],[8236,2,253],[8488,0,255],[8744,0,253],[8998,2,255],[9252,2,244],[9495,4,252],[9744,0,255],[10000,1,254],[10254,0,253],[10508,3,255],[10761,0,254],[11016,2,255],[11270,0,255],[11526,3,255],[11779,0,254],[12034,0,252],[12287,2,255],[12541,0,252],[12794,0,255],[13050,2,254],[13303,0,254],[13558,0,251],[13810,0,158],[13969,54,255],[14171,0,254],[14426,2,255],[14680,0,254],[14935,0,253],[15189,1,255],[15444,0,255],[15700,0,254],[15955,0,255],[16211,1,254],[16465,1,255],[16720,0,255],[16976,0,159],[17136,55,255],[17337,1,255],[17592,1,254],[17846,0,254],[18101,0,255],[18357,0,255],[18613,0,255],[18869,0,253],[19123,1,132],[19255,119,230],[19367,28,251],[19591,0,255],[19847,1,254],[20101,2,255],[20355,1,255],[20610,0,255],[20866,0,249],[21116,2,254],[21369,2,255],[21623,2,165],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[21787,1,229]], + data: + "QCH///////////////////////////////////////////////////////////////////////////////////////83ov//////" + + "////////////////////////////////////////////////////////////////////////////////////QqJxIXIhcKL//0Oi" + + "eCEvIW2ibKL//0wi//9uojSiayFeIf////8tIf//eSL//zGi//9rov//////////RKIiqiGqJKoqqiOqKaohqS6qMqoxqjSqM6pA" + + "qj+qQqpBqv//UKpSqlGqVKpYqlOqXyEsqWOqYqplqmSqcqowqU6pIqshqySrKqsjqymrQakuqzKrMas0qzOrQKs/q0KrQatDqVCr" + + "UqtRq1SrWKtTq2AhTKljq2KrZatkq3KrUKlzqyeqJ6slqiWrKKooqyuqK6ssqiyrL6ovqy2qLaswqjCrIqlCqTeqN6v/////Nqo2" + + "qziqOKs1qjWrOqo6qzuqO6s9qj2rPKr//z6qPqskqUSpR6pHq0WqRav/////RqpGq0SqRakmqUapSKpIq0mqSatHqUqqSqtMqkyr" + + "S6pLqympSakoqUipTapNq0+qT6tOqk6rSqkrqUupV6pXq/////9WqlarLalNqVmqWatbqlurWqpaq1yqXKtdql2rX6pfq16qXqth" + + "qmGrYKpgqy+pT6lsqmyraappq2aqZqtrqmuraKpoq2qqaqtxqnGrdKp0q3Oqdap1q3eqd6t2qnar////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////Jqomq0OqQ6tVqlWr" + + "Z6pnq3CqcKttqm2rb6pvq26qbqv///////////////////////////////////////////////////////////////85qzCi////" + + "//////////////////////////////////////8vojKiNqI1ov//M6I4ojmiYab//2KmY6Zkpv//Z6b//2mmbKZ2piEmIiYjJiQm" + + "JSYmJicmKCYpJiomKyYsJi0mLiYvJjAmMSb//zImMyY0JjUmNiY3JjgmZaZqpnGmcqZzpnSme6ZBJkImQyZEJkUmRiZHJkgmSSZK" + + "JksmTCZNJk4mTyZQJlEmeKZSJlMmVCZVJlYmVyZYJnWmeqZ3pnmmfKYnJ0KnQ6dEp0WnRqdHp0inSadKp0unTKf//02nTqchJyIn" + + "IyckJyUnJicoJyknKicrJywnLScuJy8nMCcxJzInMyc0JzUnNic3JzgnOSc6JzsnPCc9Jz4nPydAJ0EnUSdSJ1MnVCdVJ1YnWCdZ" + + "J1onWydcJ10nXidfJ2AnYSdiJ2MnZCdlJ2YnZydoJ2knaidrJ2wnbSduJ28ncCdxJ///Vydyp3OndKd1p3and6d4p3mneqd7p3yn" + + "//99p36nPiH//////////z0hQiH//0YhRyH/////SCFJIf////93Ingi////////RSFEIf///////////////////////3Mi//9s" + + "IW0h//////////////////8oIm4h////////////////////////////////////////////////caL/////////////////////" + + "////////b6L/////////////////////ciL/////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/ysiLCIqIi0i////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////////////////00i//9OIk8i//9fIlAi////" + + "////YCI6Iv////87Iv///////////////10h//////////////////9lIv////9nImch//9cIv///////////////0oiSyJBIkAi" + + "aSJqIv//////////////////aCFoIv//////////////////ZiL/////////////////////////////////////////////////" + + "////YiL//////////////////////////////////2IhYSL//////////2UhZiH/////YyJkIv//////////////////////////" + + "////////////////////////////////PiI/Iv////88Ij0i////////////////////////////////////////////////////" + + "/////////////////////////10iXiIhKCwoIigtKP////////////////////8jKP////8uKCQo/////y8oJij/////MSglKP//" + + "//8wKCcoPCj/////Nyj/////MigpKD4o/////zko/////zQoKCj/////OCg9KP////8zKCoo/////zooPyj/////NSgrKP////87" + + "KP////9AKP////////////////////82KP//////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////yMiIiL/////////////////////////////////////" + + "/////yUiJCL/////////////////////JyImIv////////////////////8hIn4h////////eyH/////fSF8If//////////////" + + "////////////////////////////////////////////////////////////////////fiJ6IXkh////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////aiH//2kh////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////diL/////dSL//3QiISEiISMhNyH//zkhOiE7IVIhUyFUIVUhViFXIVghWSFa" + + "IVshKSIuIkwhTSH///////////////9BIf//////////////////////////////////////////////////////////////////" + + "/////////////////////////////yEkIiQjJCQkJSQmJCckKCQpJCokKyQsJC0kLiQvJDAkMSQyJDMkNCQ1JDYkNyQ4JDkkOiQ7" + + "JDwkPSQ+JD8kQCRBJEIkQyREJEUkRiRHJEgkSSRKJEskTCRNJE4kTyRQJFEkUiRTJFQkVSRWJFckWCRZJFokWyRcJF0kXiRfJGAk" + + "YSRiJGMkZCRlJGYkZyRoJGkkaiRrJGwkbSRuJG8kcCRxJHIkcyT//////////////////yshLCE1ITYh/////yElIiUjJSQlJSUm" + + "JSclKCUpJSolKyUsJS0lLiUvJTAlMSUyJTMlNCU1JTYlNyU4JTklOiU7JTwlPSU+JT8lQCVBJUIlQyVEJUUlRiVHJUglSSVKJUsl" + + "TCVNJU4lTyVQJVElUiVTJVQlVSVWJVclWCVZJVolWyVcJV0lXiVfJWAlYSViJWMlZCVlJWYlZyVoJWklaiVrJWwlbSVuJW8lcCVx" + + "JXIlcyV0JXUldiX//////////yYhPCEzITQhbDB6QyGwNzwisCOw//98S2Y+MDtlPjwyJLBUST9N//8iUC8xJbD//24zI1AkQEJS" + + "VjU6Sv//////////Zz4msP//Pk7//yewKLD//0JK//8psP//JFAqsP//ZkMrsCywLbAlUHo2/////y6wJlD//100MEP//2c8J1D/" + + "////KFAvsDCwKVA1RzGwVzX//zKw////////N0f//2NGQzgzS///M7D///////9JaSpQaD4rUDUyNLD//zWwZTZwOGlM/////yZW" + + "NrD//////////zewOLD//////////////////3BN//99RjmwOrD///////87sP//////////JTQ8sDU1//8sUP////8tUDtO//89" + + "TWhBL1B2O3NGPbAyUP////8+MV84//9eOGYwPrA/sEtPSk///zM6ITBAsDNQNFA1UDRLNlD//3I4ZzByS///fDX/////fTV+NWJE" + + "PE5BsDdQ/////zhQ/////zlQ/////0KwTT//////////////Oj1OPz5QQ7A8UP//PVBYNf////8jOnAy//87UDpQKUpEsP//////" + + "/0Y7RTs+Qj9QVUlnQEWwRrD//zghQFBCUEewSLBJsGVCYU5KMP////9KsP//////////QVA+MkuwRDZMsGdDTbD//06wbzdDUP//" + + "/////yRH//9PsFCwUbBSsGs0U7BUsP//////////VbBEUEswVrBXsGA4bDR6STJIWTVYsP////9ZsFqwW7D//1ywcTL//2dQQUX/" + + "/////////////////////////////////////////12wbEdGUF6w//9gsDxIYbBiTmKwLT9jsEc7ZLB3O0AyZbD//2aw//9nsFFE" + + "/////yJDSlBosGmw//9qsGuwTDBjRDs9NDokTWywTkJtsD8ybrBJUG+wPk1FUEdQbjpIUCRVcLBfsP////9xsP////////////9Q" + + "UHKw//9zsP//dLBTUFFQdbD//0Iy//87SktQdrB3sHiwebBPUHM4erB7sEg7//98sH2wJjR+sCGxVFD//0xQIrEjsWNOJLF4OyWx" + + "TVAmsVJQJ7EosSmx//9VUCqxTlArsSyxITb//00wLbEusSI2QTL///////////////////////8lVf//eUtuSXQ4/////y+x////" + + "/y8/N04wsf//MbH//zKxM7E0sTWxWEo2sTexODclQmQyOLE5sf//OrE7sVM9PLE9sT6xWVA/sV5QXFBAsf//V1D/////L0JaUP//" + + "XVBbUEGxXUr//1hQQrEuP0Oxc0tfUGBQ/////////////////////yQ9bVBEsf//RbFQR///NkloUP//cEr//zYy//9GsUexbFBI" + + "sUmxSrH/////S7FmUG9QTLH//1JBTbFEOE6xXEdPsUdgULFuUF1FUbFjUP//djhSsVOxdThhUFSxVbFWsVexWjz//2lQWLFvSk1D" + + "ZVBxN1mxYlBqUGRQUU5rUEFPWrH//1ux//9csV2x//9esWY2/////3A3//92sf//////////X7FgsWGxcFD//2KxY7FxUHVQTjBk" + + "sf//ZbH//2axUEp0UGexaLFpsf//c1B3UGqx//9rsXZQ//9kRP////9ssW2x//9usW+x//9yN3CxcbH/////crH//3hQc7H/////" + + "dLF1sUU8//8mQmVEdjb//3lQ//////////82Nf////96UHex//94sXmxfFB6sf///////3ux/////zVLfLF9sX6xZjchsiKyI7L/" + + "/ySy//8xO3dIe1Alsiay//8nsiiyKbIqsiuy//////////////////8ssv//RTpDTf//LbIusv//flAjUX1QRDr//309//8vsjCy" + + "/////zGyOTf//zKy//8kUTOyNLJPNv//NbL//yFRIlH//zayL0Y3snxBOLIjNv//ObI6sk1LJVH//zuy//89Tv//PLI9siZRPrL/" + + "////P7IpUUCyJ1FBsk5BQrJDsv///////yhRKlFEsv//RbJRsv////8sUUay/////ytRR7JISv////9Isjc1LlEvUUmyLzL//0qy" + + "S7JMsi1R//9Nsk6yT7JQsv//UrL//3Q8//8yUTFRMFFTslZQVLIzUVWyVrJXsliyfj3//zRR//9Zsv///////1qyW7L//yVN//9c" + + "sl2y//9esv//X7JZTGCyYbJisv//NlFjsmSyNVE4UTdR/////zlROlF0MGWyNTg7Nzw9e0MkNmhAdzhmsm45PFFITEZFZ7J5O///" + + "O1Fosj1RabL//2qya7L//15F//91M/////9ssv////8+Uf//bbJ+Rm6y//80QUBRQVEsSHg4O09CUf////8mNv///////zxKNkJx" + + "NjVF////////czf//2+y//9DUf//RFFwsnGyYkZfMf////9HUX06crJGUUY6c7JIUW5mSVFBS0pR//9LUUxRaT50skw8////////" + + "dbL/////JzR2sk9Rd7JNUT1MTlH//1pJUFFRUVJRX0V4sv////9WUVRRVVFTUWM6V1FqTGROebL//3qy//97slhRfLJ9sv////9+" + + "sv//KEBZUVo9//8hs1pR//98Qz9OYEX//yKz//8jsySzJbP//yazRVL//yez/////1tRJXRFNiiz//9cUV5LKbP/////KrNoPXxC" + + "//9eUWRG/////19RK7P//2BRLjMssy2zLrNhUSc2L7NMRnoxUD3/////IUhiUWFFMLMxs08/Y1EysyxKWkAiNP//KTRkUf////9m" + + "Uf////86NzOzNLNlUTWzNrNzTjez//////////9pPf//////////OLP//z1ITEr//2dRObN4TWhR////////aVH//35FOrM7s2pR" + + "//88sylAfjp0N2tRSTtvOT2z////////////////ZkRtUT6z//8nQv//P7NvOm5Rb1EwQf//bFH//////////3FRQLM2S0GzQrP/" + + "/0OzZDlEs///cFFFs0azR7P//3U3XjptR0iz/////3RRclH///////9Js3tJaj57UWQzdVFzUU9B//9Ks0uzTLP///////93Uf//" + + "dlFNs///TrNEM///T7P//2A3fFEtTlCz//9Rs3hR////////fVF6UVKzeVFTs1SzVbNWs///V7NPTliz/////3k4QzL/////dE5Z" + + "s1qzW7Ncs///dT1YRWU5IlIjUv//XbNes2VO/////ytPJVJfs2CzYbN6OGKzY7MkUmSzLzP//2WzJlL//1ZLZrM8RGezJk1os1lK" + + "/////2mzJ1L//2qz//9rs1Vw//9sszBGbbMoUio0M0z//26zb7MhPilSZ0otUnCzKkAqUlA2cbMrUis0crNzs3Sz//91s///////" + + "/3azd7MuNy5SeLMvUnmzerMwUjFSWzz///////97OF5Me7NoTHdGfLP//3FKMlL//zNS//99s36zIbQ1Uv//N1I2UiK0//8jtP//" + + "OFI9MkxLJLR8OjlSJbQmtFlBJ7QotCI+KTb//zpS//8ptP//KrQrtCy0W0gttC60L7T//ztSMLQ8UjG0PVL//zK0/////z5SJElo" + + "NmUwM7Q0tDW0P0Y/Uj09NrRpQP//QVJAUiM+YThDUj5IOLQ3tERS////////XEg0Qm5CKDb/////bkYxQzm0bkc6tE5L//9GUv//" + + "akA7tP//PLT//z20NTf/////R1L/////PrQ/tEhSLDF1MG00QLQoQlE1cU3//0tSNzJBtP//SlL/////QrQqNv////9MUkO0cUz/" + + "////RLRFtP////////////9GtP//////////R7RItP//TVL//1JOSbR8OP////9KtP//NjhOUku0/////0y0UFJPUv//Xz85MU20" + + "TrT//14xUVJPtFJS//9QtDc4UbRStFNSU7RUtP//VbRuNf//VrT/////V7T//zI7VFL//1i0/////3RLNTpaNSdNUEE/SH08WbT/" + + "////WrRbtEc9XLRoPHU8//92PV20QEj//160X7RXUmC0QzFRQX04RThnNmG0YrRbUiFDfkIrNiQ+XFJaUkQyZkI4PEs7JjH//2O0" + + "cDNmOUo7//9dUl5SZLRJNUYz////////ZzlINV9EJTExRj5MITl5TUdFfjj//2W0////////////////ZrQvN///Z1L//2M2Sktn" + + "tP//////////XUhotGm0ZlJqtF40YVJiUmRSa7T//2y0/////220brRlUv//WzVhP///LUpjUl9SYzj//2BS//8kT2+0cLT//3JK" + + "cbRoRGI4cDn/////crRoUnO0//9dRv///////////////////////////////3S0bFL/////dbT//3a0//93tHi0fjx5tHY8erT/" + + "/3u0fLT//29SbVL//yNMfbRqUnNSblL///////9xUkY4P0z//360clIhtf//IrV0UiO1dlL//yS1JbX//3A6Qk8mtWtSaVJ1Uie1" + + "cFL/////KLUptf////////////8qtf////8rtf//LLV4Uv//I1N6Ui21LrV+Ui+1MLUhU3tSMbUytT5T//8ztWk6MTP///////80" + + "tXlSNbU2tTe1JVN2MCRTOLUlMEpJIlP//3xS//85tXdSfVJIOjq1/////zu1PLX///////////////////////8mU///////////" + + "////////PbV3MC9T/////ydTKFP//yU+aUs+tf//P7UtUyxTQLX/////L0X///////9Btf///////y5T//9CtStTQ7VEtUW1RrX/" + + "////NDFHtTY6MD9ItUm1/////0q1S7VMtSlTYkX///////8qU021IjD/////////////////////////////////////////////" + + "/////061T7X/////NFMjTf//Jz5QtTpT//9RtVK1//85UzBT//9TtVS1VbVDQv//MVNWtf////9vQjZTJj5Xtf//WLVZtf//M1Na" + + "tf//ZExbtVy1//88N/////83UzhTXbX//161X7U1UztTYLX//2G1YrX//zJTY7X//2S1////////////////////////////////" + + "/////////////////////0FTRlP//0JTZbU9U2a1Z7VHUzFB//9otUlTabUiOT9TfUP/////arVrtf//bLVttW61b7X/////cLVD" + + "UzxTLTT//240ZTNEU0BT////////cbVytf////92N0pTSFNTQUo1LDZztUVT//90Nv//dLX///////9EMf//////////////////" + + "//91tf//drX//3e1TlNMU3i1J1T//3m1//96tXu1//98tf////99tX61IbZRU/////8itiO2//9LUyS2T1P//yW2TVP/////JrZM" + + "O1BT//////////8ntv///////////////////////////////yi2U1P//1hT////////VlNVUym2KrYyQ///K7ZFMiy2/////y22" + + "LrYvtjC2MbYytv//UlP//1RTKD4zMTO2//9XU///////////////////////////////////XjL/////NLb/////YlM1tnw+XlM2" + + "tlxTN7ZdUzi2X1M5tv//OrY7tjy2//89tj62P7Y9MUC2Qbb//0K2/////0O2//9EtjlBRbZZU0a2WlP///////9Htv//////////" + + "/////3oz/////0i2//9Jtkq2S7ZMtmFT//9Ntv//bzROtmRTYFNjU0+2//9Qtv//UbZStv//LkpTtv////9VRv//OEj/////////" + + "////ZlP///////9UtlW2ZVNFM1a2//9nU1e2WLb/////alP//////////2lTWbb///////9atlu2/////1y2XbZetmhT//85R///" + + "//9rU1+2YLZhtmK2//9jtmS2ZbZsU/////9mtv//Z7ZuU///bVNotv//////////cFP//2m2//9zU3FTb1NyU///arb/////dFNr" + + "tmy2bbZwtnG2dVNutm+2dlP//3dT////////eFNFUXK2fDxNO3O2dLZzMnW2eDB2tv//REN3tni2ebZ6tnu2/////322//9+tnlT" + + "//8kOny2TzBeP/////8htyK3//96U0c4/////3E5//98U3tTI7ckt2BKfVP/////JbchVH5TJrciVCe3I1T//3c3//8ot2AxJFT/" + + "/ym3JlT//yVU//8qtyu3KFQst///WkUtt///LrcvtzC3MbcpVDUwXzoytzO3//80tz03Nbc2t09D/////ze3OLf/////KlQrVP//" + + "//8tVP//Obc6tzu3LlT//2Q6/////zy3PbdRNv////83S///Prc/tyxUL1RBOiM5QLf/////////////////////////////////" + + "////M1RBt///JTpCtzNDQ7dEtzBUWkRFt///RrdHt0i3SbdKt///S7dMt023//9Ot///T7dQt1G3Urf//1O3NFT//1S3Yj9Vt///" + + "////////MlQ1VP//PzdWt////////////////zZUV7dgt///WLf//1m3Wrf//1u3XLddt163N1RftyQ5QDM5VP////9ht2K3Y7c6" + + "VP//ZLf///////87VP////84VP//////////Zbf//////////2a3/////zFU/////zxU/////z1UZ7dot/////9kS2m3//9rPmq3" + + "/////z9UQFQ+VGu3QlT/////////////OEdst223aDBWSX63//9DVG63//9vt3C3//9xt////////3K3/////3O3////////fT50" + + "t3W3OTx2t11HcDT//2s6d7d4t3m3WUv//zJGerd7t3g3T0L//3y3fbdBVERUIbgiuP//////////////////REL///////9FVP//" + + "I7j//0ZUJLgluCa4SFT/////aUT//ye4KLj/////LjT/////Kbj//yF0YTFzSiq4//9sPkhF////////K7hmOv////9OVP//LLg9" + + "Sl1O//////////////////8tuHQySlQuuC+4//8wuDG4OkFNVP//Y0UyuP//SUVkRTlITUT///////9JOjO4//80uElU//81uP//" + + "//82uDe4djH//zZF//////////9LVP//R1T/////UD//////OLhPVP////85uP//Tj06uDu4PLj//y02//9QVP//Pbg+uD+4QLj/" + + "/0G4Qrj//0O4RLj/////aEpFuP//Rrh9Qf//////////RkRHuP//UlRIuEm4Srj///////9LuP//T0tMuP//U1T/////WFT/////" + + "TbhOuC9K//////////9XVFFUVFRWVFC4//8mOv////9JSlG4//9PuFlU//9FQ1K4//91Mv//bT5TuFS4//9VuFtUVrhaVFe4aDlY" + + "uFxUXlRdVFm4//9gVFq4VVRiVP//W7hcuP//YVRfVP///////124//9OO1E///9UQWNUPEBtMGRHXrj///////9bRP//ZVRkVGZU" + + "Z1RoVGlU/////1+4YLj/////UUpqVGG4Yrj/////RjJrVP//Y7hkuGW4PE0wM///SVJIPT9CbFRrTGe4////////aLg0TGm4arhu" + + "VP//Z0JruDdFQEJXSW9UcFR7MWy4bbg6PHFUbrj//2+4cLhQMHJU/////////////3NUcbj///////9yuGIx//9zuHE0YEZ0Sv//" + + "////////d1RVQXZUQDd0uHW4W0t1VP//ZUV5VHa4eFR3uP//eLh5uHq4e1R7uHpUfLj//3wx//98VCk+flQlQ324fVR+uDNKIbn/" + + "////Irl3PVtFI7kkuf//IVUluf//JrknuSU5////////IlUhR15IUUz/////////////JUcouSm5K1Uquf///////yu5ODX//yy5" + + "RU0tuf//L0z//yxW//8jVf//Lrn///////8mVS+5RUL//zC5OEv///////9KRTG5MrkzuTS5//8nVTW5////////Nrn//2VLN7lK" + + "Oji5//8qPv////85uf//Ork7uf//KFX//zy5UDs9uU87//8+uf////85MEg4P7krQFEw//////////8sVS1V//8qVUC5QblCuf//" + + "/////0O5RLk4MS80RbkpVf//RUwxSf////9GuUe5//9IuUm5//9Kuf//KDBLuf///////3kw////////UTtMuVIw//8jME25////" + + "//////8yVf////9OuU+5ULn/////MFVRuVK5//////////88TP//M1X//zFV//9TuS9VMT//////VLlVuS5V//9WuVe5WkpYuf//" + + "//9Zuf//ZDhauf//////////N1U4Vf////////////8rPv///////zRVLE//////W7lcuUxHXbleuTZV/////1+5////////YLn/" + + "/////////2G5//////////8nOv///////2K5////////OVVjuf//ZLlYSWW5/////zpV//81VWa5////////////////////////" + + "Z7n/////aLlpuf////9quTtM/////////////////////////////2u5//////////9suf//Xkdtuf////9uuf////9vuTtVMklw" + + "uf//cblyuXO5//90uf//////////dbn//////////3a5//////////93uXi5ebn//3q5/////3u5//98uX25PFVAVT1Vfrn//0cy" + + "P1X//yG6//8iuv//I7o7PP//PlV5N/////8kukxV/////////////0VVQlX/////Jbr//ya6////////J7pkQ///QVX//yi6Q1X/" + + "////RFUpuv///////yq6////////////////K7osuv///////0ZVR1X//y26Lrovuv///////////////zC6cjT//0lVSFX/////" + + "//////////////////9KVTG6//8zuv//NLr//zW6////////NrpuPv////83uv//////////TVX//1xEOLr/////RTH//0tV//8y" + + "uv//TlX//zm6/////////////09V//9SVTq6//9QVf//UVX/////////////O7o8uv///////1I7U1U9uv//JjlUVT66ejs4Qv//" + + "VVVWVVo7Jzk/ulJM////////KDVJOFdVWDP//0C6WFX//zlC/////0G6QrpZVSNW//9aVf//W1X/////XFX//15V//9DukS6RbpG" + + "ul9VR7r//2BVSLpwQkm6JzFpPEIwSrpXQTA0NTxLuig5TLpNuv//TrpPumZFULohPTE0aENqRDgwOTV1Sv//Qjz/////UjVrQDw8" + + "KE1hVf//UbpSuv////9TulS6XDVVuks6VrpXujIzYzEsPkgyWLpiVUZNWbr//1q6/////0k9W7pcumQ8Y1VzNFJGKUxkVf//ZVX/" + + "////WUlduv//XrpnVf//KDR3NmZV//9fumC6YbpiumO6MjT//zI/a1UhO2S6STJqVf//aFVsVWlVK0dNXDM///9tVf////9ATmW6" + + "blVmuv//cFVnun5Db1X//yNA//97O/////9oulBCdzx1SWxA//9NPHFVLT5yVXNVUzA6QlI/abp0VTNGLj7//y8+//91Vf////9t" + + "QGq6/////zA+////////a7psunZV//93VW26YEz//266//94VW+6//9wunG6RjZyuv//c7oiPXS6/////3W6drr//3lVelVcPCw/" + + "dEZUP3hIIkdJNntV////////bzV8Vf//fjb//09GMDL//1M7fVUiViFWfTb//35V//84Rf///////3e6eLr//3m6//8wQv//S0VI" + + "PHq6e7pYQXpN//98un26frr/////JFYhuyVWVkYiuzM7/////yO7JLsnVv////8oViW7Jrsnuyi7////////////////////////" + + "Kbsqu///K7v//ylW/////yy7dDQqVi27//8rVv////////////////////8uu///L7swuywyMbsyu/////8zu///O0FkNDS7LVYo" + + "TP//////////UkI1u1kzNrs3uy9WMVZfNP//OLsuVjBW//8zVv///////////////zJW//80Vv//Obv//zq7////////////////" + + "O7v//////////z27//81Vv///////zy7/////z1GLjb///////////////9lMjZWO1b/////OVY+u3dKdko/u0C7//9Bu///Z0X/" + + "//////84VlQ9//83VkK7//////////9Du3I/////////PFb//0S7ajr/////QlZFu///Q1Y9VjMzPlZHVkZWRVZBVv///////0BW" + + "/////0RWR7tIu///SbtKu///eEr//0a7/////////////0u7/////0y7//////////9Nu////////067//9Pu/////9Qu1G7////" + + "/1K7//9Tu///V7tLVkhW//9KVv//ck1Vu0lW/////1S7////////Vrv/////P1b/////WLtZu1q7W7v//1y7//////////9zP127" + + "//9MVl67//83Ol+7/////01W/////05W/////2C7Ybv///////9iu2O7//9ku1FWZbtQVv////9PVma7//9nu2hFOlb///////9X" + + "Vv//aLtpu2q7a7v///////9su///bbv//1NW//9uu2+7//9SVv//////////cLv///////9xu1RW//9VVv//crv//3Tm//9zu///" + + "//9YVnS7dbtmTv//WVZWVv////////////92u////////3e7//9aVv//eLtgNFtWerv//3m7//9dVlxW/////15W//97u3y7//9f" + + "Vv//bkAjPf//fbtkPf//Y0F+uyk5ODoqOXA1Ibz//2BW/////zk6/////0o4YVYmTENHYlb//ys5IrwjvP//LDT//ydDUjYkvP//" + + "VDtbSf////9BSCW8////////Y1Z1NCa8////////ZlYnvP//KLwpvCFE//8qvGVWZFZnVv//a0T//yu8LLz//////////2M/////" + + "/y68/////1U7//9KQC28U0IiNf//L7wiRP//MLxoVmlWbz7//////////zlLMbz//2xW/////2tWalZ9Sf//c1b//zS8//8yvFpL" + + "//9tVv//M7w1vP////9vVmtLNrxuVje8/////zi8Obz//zq8cFb//yhIcVY+SnJW////////O7z//zy8Pbw+vD+8QLz//0G8//8z" + + "ND9KL0d0VnVW//8sOTQ0dlY4OERNKU12NHhWQrwjRP//LTkxPv////9fSP////8yPkO8/////0S8eD3/////////////bER5SjlF" + + "/////y45//9cSf///////3lW//9FvP//RrxHvFlFQjpIvP//SbxLOEq8bUT///////9LvP//TLz//0Mwbj0vOUdN//////////9N" + + "vE68T7z//3pWe1ZRR/////9QvP//fFZ3Ti1PUrxRvP//U7x+Vn1WVLxVvEczVrxXvCFX////////JFclV1i8I1dZvEBJMz4nVyZX" + + "Ilf//1q8/////yhXKVf//1u8Klf///////8tVytX//8sVy5X//9kMW5EL1f//3o3djI2R///MFd7RltKXLwxVy5P//9dvF68X7wy" + + "V0BKNVchUDFQYLwwPHVGNlf//101JER6MDdXJkowOWG8//9QQ2K8Y7z//29E//9kvGW8ZrxnvG9MOThMOGi8OFf//2m8arw5V2u8" + + "P1dsvGU8/////228JURuvC82Olf/////b7wrSXC8RkNxvHK8O1f/////c7x0vP//dbw8V///MDb//z1Xdrw+V///d7xAV///dkV4" + + "vP//QVdCV3m8Q1f//3q8NFczV/////97vERXQTd8vH28//8nSX68//9MOjdJJkRLSUVX//8hvTQ+RjEivUZXI70kvf//R1clvXJM" + + "Jr3//2BIJ70ovUpXfTEsQElXSFdCN1RC//9OV0xXKb1LVydOZTgqvf//K715PU1XTEU+Pf////8svUBGUVdQV/////8tvS69T1f/" + + "/1JXZjgvvf//Mr3/////ML1TV3xJWz0xvTO9VFd5SDS9Nb02vf//QUYnRP///////ze9MEX/////VVcrNf////////////80Pzi9" + + "LEn//zm9Or07vf//PL13NCZH/////z29Pr0/vUC9Qb3//1ZXVjs6SztL/////34xW1dCvf//aUNDvUS9//9YV////////0W9Rr1H" + + "vXcySL1JvUq9S70tWFpXTL1Nvf//MEdOvf//WVf//0+9V1dQvXo5//9dV1G9/////1K9/////1O9Y1dpV2FX//9cRVS9Vb1mV11J" + + "Vr1XvWBXWL1lV2dOVzv//1m9VUJeV/////9avV41aFctQGUxYld4MmdX//9bvf//MTb//2RX//9cvf//Xb3//////////2pX////" + + "/////////169bFd2V3RX/////3FXX71gvWG9cFd4TmK9clf/////MjZjvTE5//9kvXo9Zb1mvf//eVdrV/////9nvf//b1dfV2i9" + + "ejJzV3VXUUP//2m9KDo4Mm1XeFd3VzM2//8pQmYzar3///////9DN///blf///////////////9rvWy9//96V229fVchWP//br3/" + + "/2+9PTxwvSdYcER7V3G9/////3K9JVhzvXkydL0jWCRYdb3//35XIlj//3a9d71nOCpN//94vTU0eb16vVkxJlh7vTpHLTD/////" + + "////////fL19vWFIXFcsWDBYZUx+vSlY/////yG+aUUuWCK+////////I77//yS+cD4vWFdGJb4mvie+KL7/////Kb4qvv//R0//" + + "/ytYK74svv////8xWC2+ezkuvktAL74wvlQwKlgoWDG+WkH//zK+//98VzQ7//////////////////9GQj1YM75bQThYNL41WDZY" + + "Nb5mPDlYPFg2vje+N1glPTi+Olj/////NFg5vnxMe0w6vv//O74+WD9YVTA8vj2+Pr4/vkC+M1hBvkK+//9DvnI2JjBEvv//Rb42" + + "NP//O1hGvv//////////Q1hCWP//R75IvkdY////////Sb5Kvv////9IWEu+TL5Nvv//Tr7/////RlhJWEFYRVj//0++Slj//0tY" + + "UL5RvkBYfDtSvkRYVkIyOTJYNT///////////1hY//9pSv////9OWE9YUFj/////V1hTvlZYVL7//31LNzT//1RY//9FNzQz////" + + "/1FYVb7//zhOU1hWMFVYVr5MWFJYWVhEN01YV77/////WL5Zvv//XU1avlu+XL4rTV2+Xr7/////XFj/////YFhfvv//YL5+Qf//" + + "eU5hWGG+Yr5eWP//W1hjvmS+WlhfWP//Zb5mvv//Z75ovv///////zBKab7//zRGar5GN2u+YlhdWGy+Y1j///////97N///////" + + "/zEy//9tvm6+a1j//2++//84NP//cL5xvnK+aVj/////algpOmhYZlhlWGxYZFhuWHO+dL57Mv//////////db7/////////////" + + "//92vne+eL55vv//er57vnBY//9+vm9YfL7//32+/////yG/Ir///yO//////yhE//9zWP//cVhnWHw3//9yWP//dlh1WHdYdFh4" + + "WCS///8lvya//////ye/eVh6WGpK//98WHtYPz3//y5AZjJ8Mii/fVgpvz8w////////TEB+WCq/Q2whWWE3K78iWSy/Lb//////" + + "b0Auv///L78jWTC//////yRZOjUlWf//JlknWVdC////////TTgxv///YUz//zK///88S2o9KFkzvzS/Nb///za/cEA9bmJI//9q" + + "PDe/TTopWf//OL85vzq/R0I7vydKPL///3FC//89vyxZPr///ypZ//8tWf////8rWT+/////////Lln//////////0C/MUpBv///" + + "NzD//0K//////15J/////2NIQ7///y9ZRL8yWTU+OzX//zBZN1k2Pv//////////MVlER/////9Fv0a/R79Iv15NM1k0WThZakU1" + + "WTM5XkD/////Rlk0SP//ckL//////////////////0m///9Kv/////9kSC1a//////////96Sv//S7///3FETL9Nv///dUtOvztZ" + + "ITJqQ0+/UL//////RFn//1G/NEM+WUVZQFlHWUNZ//9CWW9HUr88WX0yOllxNXNCNllTv1S/OVk0OVtAVb83PkFZUkf/////cjVI" + + "M/////////////////////9Wv///ZzMhP0lZTln//0pZV799N1i/T1kiO2k5//////////9Zv1q/Jj09WX07TFlbv1y//////1g7" + + "TVlEMF2/Xr9IWV+//////2C/KUT//2G//////2K///9jv3M1/////////////zQ2//////////////////9LWScwZL9lv0M6//9m" + + "v///Nj//////////////Z79ov/////9pv3JE//9qv1RIUVleQf//a79sv22/br///2+//////ypCcL9xvys7Ullyv1RZUFn//3O/" + + "dL91v2FK//89RHa//////3e/XEH/////////////////////eL95v3tKTjxgWf//X1l6v3u/eD//////fL9+N///fb9+v1lZOT4h" + + "wP//aEYxRyLAI8D//yTAV1n//yXAXUEmwP////8nwHg8XFkowP//OD7//1ZZW1kpwP//U0f//yrAK8BVWf//ITcswC3AXTP/////" + + "LsBdWStOTjo1Q1pZL8BcQDDANTlkP2YxPEFYWUU1McAywDPA/////0c3//9PRF5Z/////////////19B//80wGFZ//9jWTXA//83" + + "QmlZNsBkWf//N8BmWf//////////OMBBSXNEOcBnWTrAO8A8wCxN////////SE05ND3A////////PsAuMP//ZVn//z/A////////" + + "YllAwP//QcD//3g0////////QsBDwGcxRMBoWf//RcBGwElNbFn/////R8BIwP////87Qv//c1lJwP//SsBtWUvA//9qWXFZTMD/" + + "//////9TWf//TcD//07A//9PwP//UMBRwG5Z//9yWVLAU8D//0JIa0X//1TAVcD///////9rWVbAb1n///////9IN/////9XwHE6" + + "WMD/////XUD/////////////////////WcD/////d1lawP//W8BcwF3AXsD///////8mRf//X8BgwGHAYsD//2PAZMBlwP//ZsD/" + + "//////90Wf//YEv///////9nwP//dVn///////9owGnA//92Wf//Tkz//yJAasD//2vA/////////////2I3//9swP//bcB9Wf//" + + "/////////////27Ab8BwwDU7eln//3lZ/////3HAcsAyR3PA//90wDVGdcD//3bA//93wDFFe1l4wP//ecB8Wf//b0l6wEVHIzv/" + + "/3FA//9QS3vA/////////////0kz//8lWn5ZfMB9wH7A//9KTSda//8hwSNa//8kWv//IsEjwSTBJcFgQSbB//8nwSjBIlr//z9Z" + + "KcH//yrBJlr//yFa/////////////ytaLFonRS5aK8EswSQ7KVr//y3BLsH//zw1L8H//y9aMMEoWjNa//8yWjHBMVoywf////80" + + "WjPB//82WnE+NME1WjXB/////zbBOVr/////N8E4wTnB//////////86wf///////zvBPMH//z3B//83Wj7B//8/wThacFlAwUHB" + + "/////0LBO1o6Wv//Q8H/////RMF4WTxaMFr//0XBWTv//0bB/////z1aPlpAWj9aQVp+MkfBNjlIwUnBfEovQP///////0rB//9O" + + "OP//S8FDWkzB////////Rlr//1JJTcFfNU7B//9PwUVaRFpUR0daNTb///////9JWkhaUMFRwf//OjQ2O/////9YRlLB////////" + + "U8FJN////////3Q///9KWv//MEAoRf//X0lLWv//VMH/////VcH///////9WwUxaTVr//1fB//84Sl1VRkBYwf//TEn//1g6//9l" + + "SENIWcH/////WsH//01FW8FBTv//T1pQPFzB//9QWl3BNjD//17BVDZNQF/BYEn///////9RWkI7R0NgwVs7Nz///2HBYsFjwf//" + + "//9SWv//fUr/////dzFcO///ZMH//1VaZcFTWlZaOU5UWv//ZsFnwf//e0BXWv//aMEyQmnB//9YWv//asH//2vBejRswVpa//9Z" + + "Wv///////23BW1pcWns0/////3xGNkNsNV07YUH/////XD0wMP////9uwV1ab8H//3DBccH///////9ywSIyYVr/////c8F0wXXB" + + "//83OWBadsH//ys6Oj53wXjBX1r//zs+ecFATCo6//96wXvBVzBOQHzBfcH/////////////Zlp+wSHCMUBHMSLCI8IkwiXCVT0m" + + "wmZLcjonwijCKcIqwjw+K8InQCzCLcL//y7CZVpjWmRaMML//y/C/////2tD/////yZbMcJqWn47ODloWjLCM8L/////aVo0wjg/" + + "NcL//zfCZ1r//zbCLzv//////////zjCOcI6wv//O8I8wmxaa1pwWj3CPsJxWv//bVr//yIzblpvWlVIQMJBwkLC//9hSUo3clr/" + + "////RMIyQEXCPT5HwkjCScJSQ0rCTML//0PCRsJLwkc2//9zWnda/////0sydFp2Wv//TcJOwk/CdVr//1DCaz1Rwv///////0hD" + + "RTB4WlLCU8JUwlXCeVr//1bCV8L//ypE//9Ywv//cU7//////////0M7//9ZwmtK/////1rCW8L//z1LXML/////Ilt7Wv//XcJ+" + + "Wv//fVpewl/CelpgwmHCIVv/////XkZiwnxa/////2PC//9kwmXC//////////9mwv//I1v/////bD0kW2fCS014R///aMIlW///" + + "//////////8nW///acIoW///asJrwv//bML//ylb//9KNkgxOTkqW///K1txPWJBbcI/wlhSPkE9QVhCRzr/////clD//27C//9v" + + "wm43LU3//35K//9+SXDCLFv///////9xwnM6P0QtWy9P//9ywv//PktzwitELlt8NHTC//91wv///////y9bMFtaTP//JEx2S1xL" + + "JTsyW/////9rPP//dsJRS///NFs3WzZb//95NP////9gNXfCM1v//zVb////////eMI4W3nCesJ5P/////97wv//e01JMGA6PEL/" + + "/108fMJ9wnM+/////ztb/////05FfsI5WytCOltyPl1MPFs9W2hNIcP///////9CW///IsM6OSPDVUc/W2xFXlpiWiTDTzUlw0dH" + + "////////JsNBW///Pj5ESP//J8P/////KMNHW///ekj//z5b//9EW0Nb//8pwyrDT0Arw///LMP//21LLcNTTi7DL8NnSzDDTDJe" + + "O/////9IT0ZbdT////////9FW/////9AW/////////////9PODHDMsMzw0xbSls0w00ySFtOW1Rb//81wzbDN8P/////OcNIQjrD" + + "O8NBSjzDVlv//z3DPsMiSf///////1VbcEc/Szs0P8N3QEA9/////0DDU0RBwy5N//9Cw1FbUFv/////Q8NSW///T1v//0TDV1v/" + + "/01b/////0tb//9TW0lbRcNsQ0bDeExGPHQ6R8NIw///OMP//zo6/////29LQTNOREpGSTH/////////////////////////////" + + "////////ckBKw///NEAqN///S8P///////9Mw1lbTcP//zs5fDP//////////0/DTsNbW3QzYVtQw1HD//9Sw1PDVMNeW1XDc0D/" + + "//////9LMyw6//9Ww0ozTzr//1fDXFtlN0s3bUVYw1nDWlv//0Yw//9aw///W8NdW19b//9NNiw3ScM8NEs1XMP//13DXsNiW///" + + "X8N5OnFL//83O////////2Nb////////MEn///////9gw/////9hw2LDY8Nkw2XD//9vW2bDMzJkW///Z8Now2nDasP//3VbZVv/" + + "/0JOa8NsW2zDX0dtw///bsP//////////3Rb//9nW////////zQwaVv//2/DPDlww///ccNrW3LDalv//2ZbcVtzwz8+dMP//3XD" + + "bVRoOHxNdsN3w/////9oW3jDdEQjMy06ecNgW///cFthM/////9uW3JbesNuRf//////////////////fjR7wzJc//98w0lMd1t9" + + "NH3Dflv//37DIcQixEBLI8QhXCNcJMQnXHlbJcQqQ///JsQnxP//b0UrXHxb//8oXP//KMT//yJcKcT//yrEK8QsxC3EOT8sXC7E" + + "L8QzQP////8wxDHE/////ypcPTQyxDPENMRQT3Zb/////yZcWDA1xP//eFs2xDfEOkx9WyI/R0RzWzjEOcQlXDrE/////zvEPMT/" + + "/3o/L1xxMyE4//////////8xXHpbMFz//ylce1v//y1c//8uXP////////////8/XD3E//8+xE5GP8QkXP//QMQ7XP//QcT//z1c" + + "//9YRP////9CxP////9DxP///////0TETE3///////9FxP//////////dkk4XEpC//9GxP//Plw/QUfENVxCXEFc//9vRkBcakZI" + + "xEnESsRLxP//TMRNxERcN1xOxEg2OlxdPU/EUMRRxGBHPFxLNv//NFw2XDNcUsRTxDBPWjM5XFTEVcRDXDUz////////////////" + + "//9nOv////9WxF0x/////1RcV8T//zFPV1xYxP//WcT/////Oj9WXP///////1VcWsT///////9bxFzEUlxdxP////9exP//X8RG" + + "XGDE//9jXEVc//9YXP////9hxGLE//9jxFBcZMT//0tcSFz//0lc//9RXP//ZcT//yJ0ZsT//05cPTlIRGRBTFz//0dcZ8T//0pc" + + "/////2jEacRNTWpL////////T1xZXP///////2rE/////2vE//9hXFpc/////2dc//9lXGzEbcT//27EYFxvxP//cMT///////9f" + + "XP//UET//2VBccRdXHLEc8RbXHTE//9iXP//////////aFx1SG5c/////3XE//92xGlcbFxmXHfE//90Q///OEl4xFxc//95xGRc" + + "QD56xE9MeFxrXHvE////////fMQiOCMyXzP/////U1z//33E//9+xP//IcVBPnBcIsV3XHk8cjMjxf//LkMkxSXF//////////9t" + + "XCbFJ8VyXHZcKMUpxTY2/////yrF//8rxSzFLcX/////LsUvxf//TDV0XP//MMX///////8hNf//S0ZzXP//McX//3VcMsX/////" + + "M8X///////////////80xW9cNcX//////////3Fc/////////////zbFYDNJQzfF//84xXxc//85xTrF//87xf//PMX//3pcaTj/" + + "/3lcPcX/////////////IV3///////8+xVhbP8VAxUHFe1z//31cflz//0LF//////////8sXUPFKF3//21bRMVFxUbF//8nXUfF" + + "////////Jl3/////I13//0jFScVKxf//alwlXSRd/////0vF//9NxUzF/////07F////////T8UqXf//Jk9QxVHFUsX///////8t" + + "XXs2U8VUxSldK13//////////1XF/////1bFJ0j//y5d//9Xxf///////1jFWcVaxf//////////////////Ml0vXVvFXMVdxV7F" + + "c00wXV/FYMX//2HFXlz//////////2LFY8VkxTNd////////NF1lxf///////2bF//81MWfFNl1nNyE8//9VNmjF/////yQyacX/" + + "////asVrxf////9sxf////9fTf////9txW7FOF03XTpdPTVvxf//VjY+NHDF////////PV3/////ccU8Xf//Pl1yxf//TjJzxTdD" + + "//8/Xf//dMU/NEFd//91xf//dsVAXf//Ql3//3fF//9DXXjFRF1fOzVAITr//3BJecX//2JKRE96xf////97xXU7fMX/////UDpy" + + "Tn3F/////0VdRl3//2A7//9+xSHGR11IXf//IsZKXUldI8ZYS/////9ePWw8RDv//0td//////////////////9NXSM/JMZMXf//" + + "//8lxv////9OXSbGJ8b//yjGKcZPXf///////yrGK8ZQXVFdLMYtxi7GUl0vxlRdU11VXSUySkP//1ZdMMYxxiY7TDNXXTLGM8ZC" + + "RUxU/////zTGNcYjNVhd/////zbG//9ZXTfGbEpoS////////0dGWl1mSP//OMb//3tI//85xlNM////////W13//zrG//87xv//" + + "//88xj3G////////XV1cXf//PsZfXf//P8b//15d////////QMb//0HG/////////////0LGQ8b//0TGRcb/////YV1Gxv//////" + + "/0fGSMZhO0nGMUxKxmJdY13/////JDX//0vG//9kXf///////0zG////////Zl1lXf//TcZOxk/G////////UMb//1HG////////" + + "//9SxmU/U8ZUxjlJSjH//1XGVsb/////RUhXxnVEQT1hNf//////////////////WMZZxv//WsZGSFvGLjz//1zG//9dxmhd//9A" + + "NP//XsZ4MV/GYMZyRmddPjlTQ///aV3//////////zbHcV3//2pdYcb//2LG//9jxkFC//9iNXJdZMb//2XG//9mxmfGaDdoxv//" + + "JTVwXf////9uXWtdYE3//2nGasZrxkBEbMb/////WUZsXf////90Xf//c10jN23GbsYtMm/GcMY7Om1db11xxv////9yxv//V0t0" + + "Qv////////////////////93S/////98Xf//c8Z9XXTGTzJ1xv///////yhKfUwhXiM8Qj54XX5daDH//zc2dsb//3Vdel13xv//" + + "//90QHFH//9nSHjG//95xnrGe8Z8xnddfcYhS37GeV3//yReIcciXiLHe13/////I8ciS0hHYzX//yVF//8kx21DJcclXibHJ8f/" + + "/yjHI15ZQnZdKcdLMSrHK8f/////LMf/////LcdOTTBe//8uxy/H//8wxy9eMcf///////92QP//LF4yx2xN/////zZGJl7/////" + + "////////RUQzxzTHNcdMMT85KV7/////N8c4x///OccnPS5e//8tXihe//8rXjrH//9oMzvHKl5JRzzH//8uTv////90PnVA////" + + "/////////////////////////////////////////z3H//82XjRe//9NSf//Psc/x///QMf//zFeM15BxzoxQsf//0A5Mk///z0z" + + "//9iSUPHRMf///////9hTf////8kMzs/NV7/////Rcf/////////////Rsf/////Ol7//0fHQz7///////8wTf//N17/////SMdJ" + + "xzJeSsc4XkvHTMdNx15O//9zRUJG//////////////////////////////////9Ox///T8f/////NjP/////VTH//1DHPl7//1HH" + + "QV5Sx/////9DTlPH//9Ux2RN////////VcdIXkJeP15Wx///V8dUTkVe//9Yx1nH//9KPUde/////0xeWsf//3FFSl7//1vH//9c" + + "x0ReXcdexzhDX8f//0teYMdAXv//Rl5hx01efDBDXv//Tl5ix2PHPD///189ZMclSmXHLjr//zteSV46RWbHZ8f///////9oxzZA" + + "//9pM1E6RD49XkI9//////////////////9MN///PF7///////9SXm09Ojj//2FeacdbXnQ1T0Vqx1ZeX14vMDIxa8f//zky//9Y" + + "XixCT15RXkE5/////2zH////////bcf//2JebsddXm/HcMf//1Ve//////////9cXnHHcsf/////c8d0xytMdcf//1peXl52x///" + + "d8d4x3nHesf//1A4e8dFPv////85Q3zHfcd+x1Re/////yHIIsj///////8vTSPI/////1de/////1BeckX/////U14kyP////9Z" + + "Xv//////////Jcj//ybIUU8+PH5L//9jXv///////////////////////y5IJ8j//29eOzj/////KMj/////YD3//2VeKcj/////" + + "L05COf//cl4qyP//bjD/////cF7//yvI/////2Re/////yzILchqXv//LshsXi/I/////09NZ17/////LkUwyP//aV7//zHIMsgz" + + "yHFeNMhrXkdM//81yDbIZl43yCI8fl44yDnIOsj//2oz//9oXm1ebl7//////////////////2xCWkL/////////////////////" + + "//////////87yHZePMg9yHxe/////3pe//8pRf////8jX3dePsj//z/I//9AyHheYF55NTpJ//9ByP//Pzz//0LIdzlDyP//RMhF" + + "yP//M0///3Re//8iX2kxZkFGyP//R8j//0jIScj//////////3lH//9BNHpO/////0rI/////0vITMghTFJEU8j//03ITsh7Xn1e" + + "T8j/////UMj//zJB/////1HIUsj//yFfeV7//3Ne////////QzT///////////////////////9UyP//VchWyFfIaTf/////WMgv" + + "X1nIWsgqX3hAW8hcyGMz//9dyF7I//9hPf//M1///1/I////////YMgsXyxEKV9ZRP///////0xf////////Jl///yVf//8uX2HI" + + "Ysj//yhfJ18tX2PIIUD//yRfZMhlyP////9myGfIaMgwX///acgxX2rIa8hsyP//bchCNP////9uyP//////////b8hwyDZf//81" + + "XzdfcchyyHPIdMj//zpf////////dch2yHfIQ0X//zRf//94yHnI/////zhf/////3rI////////Yzd5QjJfO0f//3vIOV98yH3I" + + "//9+yP///////////////////////z5fPF//////P1///yHJQl//////Isk7X2o5KEf/////OV7///////8jySTJ//90TT1f//9B" + + "X3VCJclAX///K1///ybJaW//////J8lFX///KMkpyUlfKslHX////////yvJLMktyf//Q1///0Rf//8uyf//SF///0Zf////////" + + "Tkn//y/JTl///0tfSl///01fVEZPXzDJ/////zHJ/////3VDbUL//////////yVA/////zLJUF///1Jf//8zyf////80yf//Ncn/" + + "////Nsn//1Ff//////////83yTjJ////////Ock6yTvJPMl1Xv//Qcn/////U1//////Pck+yf////9nRv//////////P8lAyf//" + + "////////VF9CyUPJ/////////////1AyRMn//0XJdEUlM///////////RslHyf//ZDX///////9ePFI6SMn/////Scn///////9K" + + "yUvJ/////ydPZj////////9qMf///////1Zf//9MyU3JTslPyVDJVV///1HJ/////////////////////1LJ////////////////" + + "U8lZXzpDXF9XX1TJVcn//1tfVsn/////V8laX0BFWTD//////////////////////////////////3VO//9YyV5f////////KDH/" + + "/1nJ//9ayVvJXMldyf//XslgX/////9fyV9f//9dX///////////YMn///////////////////////////////9YX///////////" + + "////////I0thyf////9iX2LJY8lkyWXJZsn//2Ff//9nyWjJ/////2nJ//////////9rMf//////////ZF8ySv//Y1///2rJ//9r" + + "yTVM//////////9HPv//////////bMn//23J//9uyW/JcMn//////////zNB//9xyf///////0Y+//////////9yyf///////3PJ" + + "dMl1yf//e052yXfJal///3lA//94yf//ecn/////Zl9rX3rJ//9sMXvJ//98yf//fcn//37J//9pX///YUdlX2hfSD4hylFI////" + + "/2xf//9RPP//////////////////////////Isr///////96QP////8jyv///////29fJMr//yXKZ1///yc3//8myv////9tX///" + + "//8nyv//UE1wX////////yZ0KMopyv///////089Ksr//yvK/////////////3Ff////////cl//////LMotyi5HLsovyv//////" + + "//////90XzDK////////dV8xyjLKM8r//zNHNMr///////91RXdf//81yjbK//95X///VU7//3ZfN8p4X20xOMpzX///Oco6yv//" + + "O8r/////W1N6X///////////Z0E4O3xf//////////97XyQ/WVL///////////////99X/////88yiFg//9uX35f//89yiJgPsr/" + + "////////////ekc/ykDKQcr///////8jYP////8kYP////9Cyv///////0PK/////0TKJWD//0XK//9Gyv//////////R8r/////" + + "//8mYP//XkRIyihgJ2D//0nKKWD//ypg//9Kyl88Y0n//0vKTMpsTCtgLGBWQSQ8LWAuYE3KTspPyv//UMovYFJKR0j/////MGBX" + + "R///UcpSylPK//8tRFTK//9VylbK//8xYGcyV8ptNVjKRkxZyjZMWso0MjRPW8r///////9SS1zKKkr//13K/////17KX8r//2DK" + + "N0D//zJg/////2HKYspDRv//Y8pkyiM4M2BlylQ6NWA0YP//Zsr/////NmD//2fK////////aMppyv///////zdgasr/////OGD/" + + "/////////2vK//////////8+Nf//OWD//////////zpgbMr///////8kOG3KbspISP//b8o8YP//cMr//3U+/////ztg////////" + + "//9xyv////9yyjg2PWA/YP//PmBzyv//dMr/////dcr//0Bg//9ROP//QWD/////dsp3ymk2eMpAQf//fTn///////95ykNgRGBC" + + "YP////96yv///////208/////0hGOTb/////////////e8p8yv////9GYCxDRWB9yn7KNU9iRyHLIsv//yPLJMv//yXL/////0lg" + + "Jsv//yfL//////////8oyynL/////0tgSGAqyyvL//9UTEpgTGAsy0RO/////y3L//8uy1Bg//8vyzDLT2B2Qy1HMcv//yU4TmD/" + + "/zLLM8v//01gNMsxTTJN/////zXLNsv//zfLUWBuMf///////zjLdjliO///////////////////OctSYFNgOsv//zvL////////" + + "PMtVYD3L//////////8+yz/LQMtBy/////9DPf////9Cy0PLV2BEy1ZgRctGy///R8tIy1hgSctNM/////9aYP//SstZYEvLXGBb" + + "YEzL////////TctOy///T8s8OFDLUcsoTv//TDb//yYy/////1LL//9Ty/////9Uy///VctqNlbLV8v///////9Yy///Wctay1vL" + + "//9cy/////9dy17L/////2E0X8tgy///Ycv//////////2hOXmD//2LL//9jy///ZMv//2BgZctmy///Z8thYP//UTL/////aMtp" + + "y///XWBqyzk7a8tsy0FEX2Bty/////9uy2/L/////3DL/////3HL////////cstkYP//bjxzy///dMv//2Jgdct2y///d8s+N///" + + "//9JSGNg/////35g/////3jLecv//3rLaWB7y3zLfcv//37LPTghzCLMI8z//2U1JMxmYH1NJcz//zBOJsz///////////////8n" + + "zP////////////////////8ozCnM////////////////dkL//yrMaGArzP//LMwtzC7ML8wwzDHMMswzzDTMNcxqYFZOVzZ8SEpH" + + "/////zbMa2D//////////21gN8xwYP//OMw5zP//Osw7zP///////zzM//89zP///////z7MP8z/////bGD//0DM//9vYGo4TTFx" + + "YEHMcD9uYFxO//9CzHRgJHT//0PMRMxFzHJgdWBGzP//R8xIzGdgc2BJzErMPDr/////dmD//////////////////3dg//9LzEzM" + + "//9+Tf//TcxOzE/M//9QzP//eGD///////9RzFLMU8xUzP////////////9VzFbMV8z//1jM//95YFnMWsxbzGVgXMz/////Xcx6" + + "YF7MX8xgzGHM/////2LMY8xENGTMZcz/////Zsz///////9nzP//aMz//yU8//9pzP////////////////////9qzGvMe2D//2zM" + + "/////3xgbcz/////bsx9YP///////2/M//9wzHHMOzH//3LMc8whYf//O0kiYXTM//8kNCNhdcwkYXbMd8z/////JWF4zCdhKGEm" + + "Yf//ecz//1NJKmEpYf//esx7zHzM/////33MLGErYS1hfsz/////////////LmEwYS9h/////3k5Ic0yYf//MWEizSPNRTT//1M/" + + "//88Rf//M2E4QCTNJc3//zo7Js15MTRhJ81RTSjNKc1jSjVh/////yrNREUzTUM5PT//////K81LQzRSLM0uRGgyNmEtzS7NL80w" + + "zf////8xzTdh//88YTLNM806YTlhQlomMzhhNM1aMDXNKkg2zf//Skj/////N83//zFOPWE7YVxDJkA4zTnNK0g6zS1J//8/YSxO" + + "TTdAYf//PmFWSEFh//9CYf//O81bMDzN//92Pkdh//9EYW1GQ2E9zT7NP81AzUHNQs0mNf//Q81KYf////9EzUVhRmH//0lhSGEl" + + "Sf////9CQUFBRc0/NUbNR81LYUjN////////Sc1MYf//Ss1NYf//////////S81PYUzNTmH/////////////VjH/////////////" + + "V2FoSFFhTc1TYf////9VYT4/Ts3//1ZhVGFAPE/NUM1RzVBhUmFSzUJJU81JPv////9ZYf//VM1YYVXNVs3/////WmH//yY8Lzr/" + + "/1fNd0VbYf//S0RYzf//XWFZzVrNW80hTlxhXM3/////Xc3//2lB/////17N//9fzWDNYmFhzWRhZWFUQ///////////Ys1jYf//" + + "YGH//15hX2FjzWFhZM1lzWbN/////2fNaM1oYWnNZmFqzWdh//9rzf////9szW3N//9uzW/N/////3DN//9xzXLNc810zWlha2Fs" + + "YW1hdc1uYXbNd81qYf//eM3///////95zf////9wYf//es17zW9hfM3/////fc1+zSHOcWEizv///////yTOJc5FTibOJ84oznRh" + + "cmFzYSnOI84qzmI0/////////////35M/////yvOSkr//3ZhLM7/////dWH/////Lc7//3dheGH//y7OL87//3xheWF6YXth//99" + + "YTDOMc4yzn5hM84hYv//NM7//yJi//8jYv//L0hQRSRickc0Sf//JWI1zv//JmIqRTbOJzNEOSdi/////yhiN844zili//8pO///" + + "//8rYv//Oc4qYv////8sYi1iOs47zjzO//89zj7O//8/zkDOQc5CzkPORM5Fzv//Rs7/////R85pSP//LmL///////8vYv////9p" + + "czBiMWIyYv////9Izv//Ljv//0nOM2JWR///Ss5fS///TjFLzlcxTM5NzjRiTs7///////82Yv//T87//zVicEX//1DO//85QDld" + + "//83YkFMUc44Yv//RjRXSDliUs46YlPO//87Yv//VM7//1xM//9VzlbOVUz//z5E//9Xzv//akFYzv//PWJZzv//Yj1azko+////" + + "/0Bi//9bzj9iPmJ9SFzORzQpOP//Xc7///////9ezv//X85gzv//Yc7//2LOY85GYmTO//9DYj8/Mkz//2XO//9CYkRiRWL//2bO" + + "QWL///////9nzmjOac7//////////2rOa85szkdiSGJtzi9E//9jNG7Ob87//2VD//9wzv////9xznLOSWL/////c87/////dM51" + + "znbO/////3fO////////eM55zv////9KYk1ies7//3vOfM59zmc/fs5ERiHPTmJTSyLPS2L//yPPTGIkz////////yXP//8mzyfP" + + "KM///////////1FiKc//////Ks9QYk9iK8////////8sz////////////////1NiLc8uz1Ji/////1Ri/////y/PMM8xz///////" + + "/zLP////////VmIzz1Vi//80z/////9NSv//Nc//////Ns///1Y9Rk43zzjPV2I5z///N0b//zrPWGL/////WWL//11iW2JcYjvP" + + "WmL///////88z////////15i//89z////////19i////////Ps8/z/////9Az///YGL//0HPYWI3TGJi//9Cz0PPRM///3BMY2JF" + + "z05DRs9qR///azZHz///SM87Q2RiOjZJz0rP//9QQEvP////////TM//////Tc9lYj06/////07PT8//////UM//////ZmJRz1LP" + + "/////1PPZ2L//yY4VTr//////////////////1TP/////2liVc9Wz1fP//9WRVY6TjX/////////////WM9Zz///Ws///yRL//9L" + + "R1vP//9cz/////9XRf//////////XDn///////9dz17Pa2L//1/PYM////////9hz///Ys////////9jz///////////////////" + + "/////2TPSz5lz///Zs9nz///aM9pz////////2rP//9rzzJORTn//2zPJzj/////I0j//21i/////////////23P//9vYv//bs//" + + "////azj//////////25idkT/////b8///3FiNzNsYnDP//9qSP//MDFxz2w6//9ST3LP//9wYv////90z3XPds///3PP//9yYnfP" + + "/////0tKeM9ZQHRi//95z3rP//91YnvPfM99z37P//9zYv//////////TjMh0HtiItB6YiPQ//8nPP///////3xid2Ik0CXQJtB9" + + "YnhiJ9D//yjQ//9YSHZiKdAq0HliK9As0P///////yJjLtD///////8v0DDQMdD/////LdD//zLQIWNhS///M9D//35i/////2sw" + + "/////zTQNdAkY///N9A40P////850DrQ//8jY///O9A20Ew+//////////880CVj//////////890P//Q0H//z7QJ2MmY///////" + + "/////////yhjP9D//0DQ//9B0ELQQ9D//////////0TQaGJF0P//RtBqYipjKWNH0P///////0jQ/////0nQStD//////////yg8" + + "S9BpTkzQUjxN0CtjNzf/////TtBP0FDQQDUnNWM7UdBS0P///////1PQNE1U0P//MWNV0DBjREEtY1bQ//8vY1fQWNBLPUA/LmMs" + + "Y///Kkf/////TT7//1nQPEla0P//W9D//1c6//////////9c0P//////////eEX//13QMmNe0F/Q//9g0DNjSWNYNv////89TzVB" + + "//////////80Y2HQYtBSMndEIUr//2PQ//9k0GXQZtBn0P//aND/////adBq0DVj////////a9D//////////3o1NmNs0G3QOGNu" + + "0P////85Y2/QKUdw0P//OmNx0P///////3LQO2M8Y3PQ//9ZNlMyRUYoPWQ7dND//3XQ/////3bQd9A9Y3jQKT3///////950P//" + + "SjJDSf//etA+Y3vQ//9rSP//fND/////fdB+0EVBIdFBYyLRQmNpRyPRQT8/Y///YUMk0SXRQGMm0f////9OPifR////////////" + + "////KNH/////XDAp0Sk1//8q0SvR////////LNFDYy3RLtF4RC/RRGNHQP////8w0f////8tTDHR//8jSUVjRmNVQzLRR07//zPR" + + "SGNHYzTR/////////////zXR////////NtH//zfRbzw40TnRSmNwMP//OtE70f//TWM80T3RPtFLY1QyTjdMY0Y5cjn//2ZKTmM/" + + "0UDRVEtB0ULRUGP/////Q9FRQE8xOjIsMP//////////RNFF0U9j//9G0f////9H0UjR//9J0UrRUWNSY3c+//9L0f//TNH//1Nj" + + "TdFPM///TtH/////VWP///////9qN0/RZjX//1DRVmN1Nv////9XY1HRfEBS0U1GU9FgQHU6VNFV0f//WGP//1bRV9H/////////" + + "/1jRWdFiQ2tBWtFaY1xjWWNbY/////////////9b0SI3XNH/////XdH/////////////XWMmN///XtH//2c1Uk1fY/////9f0f//" + + "YNFgY/////9h0S4xYtFj0f////9jY////////3YzYmNhY2TRZWNeY2XRZmMpTmbRZ2Nn0Whj//9o0XRUamP//2lj////////a2Ns" + + "Y2nRNU5tY///b3BPPm5jb2NXPf//OEZwY///atFr0ShDbNFt0XFj//88Q3JjbtH/////b9H//yU2//8/UV1DMzxw0f//cdFy0Ug0" + + "c2P//yJk//92Y3PRaDX//3VjJGT///////90Y///UD7/////dNH///////94Y3lj//8rRf////96Y3XRXjP/////dtH//1o/ZEl3" + + "0XxjeNF50XrRaEJ70XzRfdF+0SHS//93YyLSe2N9Y/////97Ov///////yPS//8k0iXSJtL///////8mZC5JJ9ImSHlF//9aNiVk" + + "I2Qo0jVIfmNeQ3tF//96RSnSdjr///////////////84ZP////8q0v///////yvSKGQs0ipk//8t0i7S//8tZC/SLmQw0itkLGQx" + + "0jLSKWQnZP//M9L/////IWT///////////////////////800v//T0pVMv//NdL//zVk//8yZDbSN2Q30jjSNmT//3NHJ0w50js7" + + "MGQ5ZDRkOtIzZC9kO9IxZDzSSTT///////890v//////////PUP//z7SfUD//z/SQNIiSEHS//8+ZELSQ9L//yRI//9E0kXSRtJH" + + "0v////9hQDtkSNL//09ISdI/ZFNKStJbQ0vSOmQ8ZP////89ZP//////////TNL//03STtL//0/SUNJR0v//QGT/////RDz/////" + + "//9GRkVkRGT//1LSQWRT0v////82T///////////VNJKZFXSVtJOZEtkV9JY0lnS//9a0v//W9JHZFzSXdJe0l/S//9g0khk//9h" + + "0v//YtJj0k1kZNJl0v//QmRVUklkQ2T/////TGT//2bS//9n0v///////1JkaNJKNP//T2T//2nSatJQZGvS//9RZFRkbNL/////" + + "/////23S//9u0m/S//9w0lNkdkhx0nLS/////1VkfE5tSlpk/////1dk/////3PS////////dNL//1ZkUkD//1lkW2R20nfSeNJY" + + "ZHXSX2T//1xkedJ60nvSfNJ90n7SXWRGZCHT//8i015kYGT//yPT//8k0/////9hZCXTJtP//yfT//8o00ZK//9iZP///////ynT" + + "/////yrTK9NiTP////9ONik3Y2T/////LNMt0///NEr//2g///8wTP//LtNkZP//M07//y/TdEf//0ZBNEf/////TT3/////MNNA" + + "MDHTaWRnZP//ZWQhNDLTUT5qZP////9oZP//ZmRuZP//M9NtZGxka2T/////NNM10///b2Q20zfTONNwZDpAOdNxZP//c2T//zrT" + + "cmT//zvTPNM901I4/////z7TOEE/0/////91ZEDTQdNC03xFQ9N0ZETTRdP//3ZkRtM1SmxBRzn//3dk////////R9NITv//SNP/" + + "/0nT////////eWT/////emT//3tkStN8ZP//ZTv//31kTzf/////ajUqNf//IWVL03NMSDl+ZEzTTdNO0yRlZkz//zxH//9P0zNJ" + + "UNNR01LTYz0jZVPTUzxJOWY7aTU2SiJlVNNV0///R0FCS3c6VtP/////V9P///////9Y02c7XURZ0ydlX05ZOlrTKGVCP///KmX/" + + "//////9SPjA6//9b01zTXdMpZV7TX9MqPT44SEElZStlYNNh0/////8mZVA3YtMuZTJlazdj0///ZNP/////LWVl0///ZtNn0zZl" + + "aNNp00o5/////21NPDAzZf//atNrNWvTMGX//2zT////////MWX//23TfUUvZSxl//8oM2RA//9u0yg4b9Nw0///OGX//3HT//9y" + + "03PTdNP//3XTdtP//3fTNWX//3jTedN60///N2X//3vT//80Zf////98033T//9RNzNCOWVuQX7TIdRGZf////9CZTxl/////yLU" + + "I9T/////JNRAZXo8XTA7ZUNlR2VLOVZMJdRWRD1lJtQn1EVlKNQ6ZT5D//8/ZT0wSkz/////KdQq1CvULNQt1D5l/////1s2bEgu" + + "1C/UMNRtQf//UE5vPf////9uZf//MdRIZTLUfkD//0RlSWVLZf//eUROZTTU//9KZTXUNtT//1RKSzQ31DjUS0w51P//XjD//zrU" + + "TWX//31OO9Q81P////891D7UTGUz1G8x/////2xGT2X/////P9RWZVBlV2X//////////0DUQdRTZf////9C1P//Q9T///////97" + + "R0TURdRKPFVlRtRSZVhlUWX/////RD1H1EjU/////yVLSdRK1Ew9S9T//1RlYGVM1P//XGVN1F9l//9dZWFlW2X//0FlU0BO1P//" + + "S0j//15lT9RQ1FllUdT/////IUFSN///Kz1S1P//U9T//1TU//8lPzZBZGX//1XUZmVnZf////9jZWVlVtT//1fUWNT/////WdRa" + + "ZWJl//9qZWllWtT//3pLW9Rc1Cs3/////13U//////////9e1Ghl//9sZWtlb2Vf1HFl//9g1Dw7bWX/////YdRi1HJlc2Vj1P//" + + "dGVk1HplO0V2ZWXUdWV3ZXhlZtR5Zf//Z9T//2jUe2V8ZWnUatRMNP//fWX//35lbNRr1G3UbtRv1P///////3DUcdQhZv//ctT/" + + "/////////yJmI2YkZnPUJWYmZnTUddQoZidm/////ylm/////3bUd9R41P//KmYrZnnU//961HvUfNR91C5mLGYtZmE6Uzf//37U" + + "VkP//zNIIdVwPf////9NR///bUgvZm1Y////////ItUj1STVJdX//zBmMmb//2VNMWY0ZjNm//9TTSbVNWYn1X5IKNUp1SrV////" + + "/zZm//8r1SzV/////zlm//8t1ThmN2b/////LtUv1TpmMjf//zDV//8iQUE1MdX/////MtU+Zjtm/////zxm//8z1f//P2b//0Bm" + + "PWb/////NNUpMf//NdU21Scy//831f//QmZDZv//ONX//0Rm//9iTf//OdU61f////8sPf//RmZFZv////////////871f//////" + + "/zzVaT9HZv//PdX//z7VSGb//z/VSWb//2U0QNX//0HVQtVNNP//Q9VKZv////////////9LZkTVXUtjTUXVRtVH1VRNN0///005" + + "TmZUPE1mSNVJ1f//StVPZik8S9VM1U3VUUJO1VBmT9VQ1Uw5UdVXTFFmUmb/////U2ZS1VPVVNVV1VRm/////1bV//9X1f//VWb/" + + "//////9Y1f//WdX//1rV/////yo8W9Vc1W1MXdX//17VX9VXZmDVP0Nh1VZmYtX///////9j1f//WWb///////9YZv//////////" + + "////////Wmb///////87QP//W2b//1xm////////OUpdZmTVb0FeZv//ZdX//2bV//9fZv//////////Z9X//35OYmZo1WFmYGYw" + + "RGnVY2YmP///ZGb///////9lZjhPZmb//2rV/////2dmaWZoZiVIa9V5Rv//Pk8pSP//bNX//////////2tm/////1M+//8qSf//" + + "bGZqZm3VTjRu1f////9UOGg7/////25Ib9Vw1f//KjhDS3HVb2ZtZv//Tjn//085aTD//2g6////////ctVz1VlH////////////" + + "/////////18wdGb//0BD//901f///////1hHddVbQnbV/////3fV//941XnVdmZ61XvVcmZ1ZnBm//9zZiZL//981VU4/////30w" + + "cWb//////////////////33VftV4ZiHWeWYi1iPWOUb//yTW//87NiXWJtb//yZnPUcn1mk7KNb//zw2SEBGTy5Md2ZUQCnW////" + + "//////////////////////8q1ivWLNb//1M1emYt1v//Ltb//y/W/////3xmMNb/////Mdb//3tm/////zLW/////31mM9YmQ///" + + "Pkf//zTW////////MUQ11v//Ntb//yNn////////////////N9YiZzjW/////znWfmY61v//VT///2VJJWc71iRnUDlTT///PNb/" + + "/////////////////zVnPdY+1v///////ylnKmc/1kDWQdb//3A8//9C1ihnQ9Z4OSdn/////ytn/////0TWMkQiSiNB////////" + + "//9cQi9nRdYwZyxnR9ZI1knW//8tZ///LmdK1v////9L1lE5Rtb/////Nmf//zJnTNb//03W//9mSU7WbEsoSU/W//8xZ///UNY0" + + "ZzNn////////REs3Z///////////Udb//zhn//9S1jdBU9Y5Z/////87Z///P2dU1v//PGc6Zz9HPWf//z5nVtb//1fWMjL//0Vn" + + "QGdY1lXW//9BZ1nWWtb//0Jn//8hQv//W9b//1zWRGdDZ0ZnXdb//17WX9ZHZ0hnYNb//0M/YdZpMv//SWdXTv//Kzxi1mPWLT3/" + + "////ZNZl1mbWajtXQ2fWaNb//2nWatZKZ0tnMTFr1kxnbNZt1k1nTmdu1v//T2f//1BnPTYqWlFn//9lQFJnSzxv1lNn//8wUHDW" + + "cdb//1RnXkpcNHLWc9YkQVg9dNZxSS49//911nbW/////////////3fWVWdSOVZnTEj//2Rn////////eNZYZ3nWSUJ1Rz84V2cl" + + "QXrW/////////////1ln/////3vWfNZ91n7WekT///////8h1/////8i1yPX//8k1///////////Jdf//1tnWmddZ///JtdcZ///" + + "Xmcn1///YGco119n//9PNCnXYWf//2JnY2f//yrXMTpJTv//ZWcnP///K9f//3AxZmdnZ/////8s1///LddoZy7XL9cw1///Mdcy" + + "1/////8z1///NNc113Iw//9pZzbX/////zfXamf//zjX//851///OtdnSTvXPNf//0c8//9sZz3XPtf//z/XQNcpMzIwQddC10PX" + + "RNdrZ25nTkdF10Q/RtdWMkfXJ0tI1/////9J1103XDZK121nS9dqMkzXTdf/////////////IzRO1///////////////////////" + + "/0/XcTFyZ2pOXUJQ1///REn//35nUddXMnxn//96Z3FnUtdvZ1PXcGdU12M8bDZ3Q1XX//9W11FG//9X1///WNf//1Ex//90Z3Nn" + + "//9Z11rX//95Z3VneGf//1vXXNdd117XUEx3Z1gyfTN7Z1/XYNd9Z2HXYtf/////VDf//////////////////yNoLGgtaP////9k" + + "1yswZddm12fX//9o12nXNGj//////////3Ew/////ytoatdr12zXKmht1yVoJGhu1yJoIWhjQ2/Xe0InaHDX//9x13LX/////yZo" + + "//9z13TXddcpaP//dtf//3BBVTf/////d9d410ExKGh511M5Pthj13rXe9d813FB////////////////////////////////////" + + "/////////////////////////33X/////zpo//87aP//WTJ+1/////8uMjhoIdj//yLYI9j//yTY//8l2C5oJtg2aP//PWg3aP//" + + "//8n2DVo////////KNh2ZynYKtgzaP//K9gs2C9oLdgu2C/YUDQxaDxo//8yaP///////zDYMdg+aDLYMGh8RzPYTNj///////9p" + + "Tf///////zlo//////////////////9PaDTYNdg22Edo////////ez///zfY//842EY1//9dNv//Qmg52DrYO9j//1syPNj//1Q+" + + "//9FaP///////1o6Pdj//1FFSmj//////////////////z/YbkpA2EFo////////WjJWOClJS2j//z9o//9B2EhoQthD2P//UmhE" + + "2ENoRdj//0RoOkb//0bYSWj/////R9hGaChLTGhgMEjY//9J2P//QGj//0rY////////S9j///////////////9OaP//TWj/////" + + "//////////9rR1Ro//9faP////9N2P//fjP///////9iaP////9QaE7Y/////1Vobk3//////////////////0/YXmhQ2FHYVU1S" + + "2P////9T2CpOVNj//1XYVtj///////9X2HhDWNhZ2FrYazNb2P///////1zYcklkaCFGXdhe2DEwX9j//11oYNhZaHJBU2hbaGBo" + + "YdgsR///Ythj2CowZNhYaGXYYWh4Sf//Zthn2P///////2jYXGj//1doadj/////////////VT7//////////y89//9q2GvYLDxs" + + "2P///////1hM/////0dJ//9t2Gdo//9waP//////////btj//2/YcNhx2P////9aaP//ctj//3PYdzP//3TY////////eD5laHXY" + + "amhzQXbYd9hmaHjYbWh52P//X0P//25oeth72FZNY2g4M3zYaWj//33YbGgsTP//ftj/////b2j/////aGhraP//Idn/////////" + + "/////////////////yLZ/////yPZ//8pS///IU8k2SXZJtkn2f//c2j/////KNn/////Ktkr2XpoLNn//3JoQzz//y3ZLtn/////" + + "UWgv2f//////////MNn//zHZ//8y2U5K//8iTHloeGj//3RodWj//zYx//8z2f//NNl3aP//cWg12TbZN9k42VVEOdn/////Otk7" + + "2XZofjD//zzZ/////ynZPdk+2SJCP9n///////////////9DSv//QNl7aCFp//9ZSP////9B2f//fmhWPkk8I2n/////PjZC2UPZ" + + "RNlF2UbZ//8kaUfZeUl9aEjZVmj//0nZStlL2UzZTdlO2U/ZfGhQ2f///////09PIkZzSVHZ//8raf//Utn/////////////////" + + "/zFp//9T2VTZVdn//1bZMmlX2SVpWNn/////dkdZ2VrZL2knaVvZKWlc2V3Z/////17ZM2koaf//X9ksaf////9yMWDZZUb//y1p" + + "MGlh2f//Ytlj2f//ZNn//yZpZdkmQWbZKmknO0U/MDd0THTZeUxyPf//////////Z9n//2jZadlq2TdpNWn//2vZbNlt2W7Z//9O" + + "T2/Z//////////9w2f//NGlx2XLZ//91TXPZNmk4af//////////OWn/////ddn//3bZ//88aTpp//932XjZ////////I0Y7aXnZ" + + "//962U1ILmn/////e9n/////////////fNn/////fdlzPf//PWlCaXRBftn//0FpIdoi2v//Imn//yPaJNpDaUlB/////z5pQGn/" + + "/yXaJtr//yfaKNop2j9p/////zFdIl0q2ivaRWks2v////8t2v////8u2kRp//////////8v2v//MNr///////92Tf//PGJGaf//" + + "//////////8x2v//Mtr//zPa//802jXa//9HaTbaZrg32v///////zja////////////////SGlXOP//VDX//znaOtpKaV1RO9o8" + + "2j3aPtp1Nf//Ok4/2nM2S2lA2kHaQtpD2kTa/////0xp//9F2v//bkNG2v////9H2v//TWn///////9I2knaStr//3pGS9o6MP//" + + "/////////////////////////////23a//9jMlJpU2lM2v///////03a//9Oaf//PTtO2v//T9r//1Da//9R2v//////////Utr/" + + "/09pQkf//1PaVNpV2lBpUWlbaf//Vtr//1VpWGlX2v//WNpZ2lraVGlb2lzaXdr/////////////Xtpf2mDa//9h2lZpYtpXaVg8" + + "//9Zaf//QUP//1Y3QjP/////Y9pk2v//XGll2v//Ztr//z8zZ9phaWja//9daWBpadr/////ato6SGva//9s2v//Xmn/////X2lI" + + "SVpIYmn/////////////////////fUJsaW7aaGlv2nDaazJmaf//KktnaXHactpkaXPaZWlqaW1pdNr//2tpddp22nfaaWljaXja" + + "edr///////9YQ3radGn//ypM//972nza//992v//ftr//3Jp/////yHbc2n//////////yLbI9v//yTbJdv//25p/////3Bp//8m" + + "2yfbcWko2ynbKttvaSvb/////yzb//8t2////////2ZA//85T3hpLtt5af//////////IWr//yo///97aS/bfmn///////8w2///" + + "dml1aTHb//8iajLbM9tcMv//fGn//yNq////////fWk02///Nds22///emn//zNE//93af////832////////2hH/////ydqONs5" + + "2zrbO9s82z3bPtv//z/bQNs7Tf////9B2/////9C2///Q9v//0TbRdtG2///////////R9smakjb//8laknb////////Stv/////" + + "//8uakvbTNtN2yhq//9O2///MGr//0/b//////////9mTTNq//8qalDbUdsralLb/////y9q//8yajFqU9tU21XbKWr/////Vtv/" + + "/yxq//89av////9X21jb/////1nbWtv//1vb/////1zbNmr//13bXttf2/////////////9g22Hb//9i2///NGr//2PbNWpk2///" + + "//86ajtqZdsqM2bbQjX/////OWpn22jb//9p2///JGpq2/////9r22zbbdv//zhqPGo3am7bPmpw23HbcttAaj9q//9z22/bdNt1" + + "23bb//9323jb//9CakFqWmn///////9Gannb//////////9623vb//9820Nqfdv/////fttEav////9FaiHcR2oi3P///////2w3" + + "I9xJaiTcSGol3DA9//8m3CfcKNwp3FQ5J14q3P////8r3EpqUT3//yzcLdw5My7cS2ov3FIxMNxXPkxqMdwy3FU5TWphMDPc////" + + "////PUk03P//Tmr//////////2o/NdxVav////9Sav//b0P//zbc//833P//U2pQal42ONxPalZq/////////////zY3/////15C" + + "//9cav//////////WGr///////81QldqOdxaajrcO9w83P//UWo93D7c//9bav//XWr///////8/3P//QNxvSP////9Zav//Xmpg" + + "av////9TOFRq//9BMP////9B3P////9C3EPcX2pE3Fs6dk5hamJqdUH//////////0XcRtxH3EjcSdwiTv//StxL3EzcY2o1Tf//" + + "//9kamVq//9N3GRKZmpO3EA6//8jTv////////////9P3Gtq////////////////UNxR3FLcbGpYPmpqU9z//1TcZ01nav////9p" + + "aj1Afj9V3Ghq//9tav//VtwjSv////9vav//bmpX3FjcWdxsM///K0twav//Wtxb3P//XNxd3F7c//9f3Hxqcmr//2Dc////////" + + "//9zamHcYtxj3P//dGp1av//////////ZNxl3Gbc/////2fceWr//3pqaNxp3Hhq/////2rc//9r3HZqbNxxandqbdxu3P////9v" + + "3P////97ajdw//9w3P////9x3P///////ygyctz/////c9x03HXc//9+al82fWp23HfceNwia///IWv///////8ka3nc//8ja3rc" + + "JWt73P//MT183CZrfdz//ydr/////37cId0i3SPdKGs+QP//V03//ylr/////yRKRkcqayTdK2srOP//Jd3//yw1Jt3/////LGsn" + + "3SjdaztBRy1r//9QMyndKt3/////K90s3S5r////////Ld0wa3dN//8va0Y///8xa/////8yay7d//8za1E0L90w3THdMt3/////" + + "NGv//zPdNWv//zZrN2v/////////////////////////////////////////////UTP//zTdNd023TfdON3//zhr//85azpr////" + + "/////////3Iy//853Sg/O2v//zrd//873f//PN3///////893f//Pt08a///P93//z1rQN3///////9B3f//Qt1AOP//e0Q+a0Pd" + + "RN3//0XdVzf//1Y///9Ba///JEZG3UBrR91I3TE3Sd1K3T9rd0ItNf////9Ca///Q2tL3Vk+TN3//03dbTdO3URrT93///////8s" + + "S1DdUd1fQP//Ut3//3Y1//91TEpBU91Fa1Td/////0c/cENaPlXdVt3//1fdRmv//1jd//9Z3UlrWt1Ka1vd////////XN1d3f//" + + "PjpCQkhrXt1bPj5JX91g3WHd/////0drYt1j3Ww7//9TMWTdTmtYN///Zd1uO2bd//9tO///TU9Na0xrJ0H//001Q086M1w+//9n" + + "3Wjdad3//2rda91s3Utr//9t3W7db93//1BrcN1Ra09rcd1YOP//QE3//3LdbzsnR///c9103VRrdd1AQP//QkN23XfdNk143Vdr" + + "////////bDh53T9AU2v//1hrbThVa1Zret1Sa3vd/////2JASUZ83X3dL0P//10yft3/////Id4i3v//cEj//yPeQzX//yTeNET/" + + "////W2sl3llr//8m3kxDJ94o3ineQUBSNFpr//9bP///Kt5KTiveLN4t3kBPLt7/////XGtnazVEL95mazDeY2tra2Rr//9ga///" + + "fERfa////////11rMd4hTXA7//8y3mFr//9eazPeNN413mVrdD3//0E4//823v//ekI33kVLWjFiMP//JUY43jneaWv/////P946" + + "3mhr//9mRv//bWs73v////9ia///bGtua///LDhqa1Y5PN5VPD3ePt5va1hN//////////9ya///dWv/////c2s1SUDe/////0He" + + "/////3Br////////Qt7//2A2/////0Pe//90a/////92a0TeRd5G3kfeSN7//0neemv/////d2tO3nlreGv/////St5L3kze//97" + + "a///MTxN3n1rfGtoSf//T94hbP///////1De/////1k3//////////9+ayJsUd7//yNsRDVBZnk+//8kbP//Ut5uOFPeVN7/////" + + "Vd4lbFbe//8mbFfe//8+O1jeWd7//////////05aWt4nbFveKGxc3jI9//8pbCpsXd5e3its/////yxsLWz//1/e//9g3mHeK0Ni" + + "3mPeLmz/////ZN5l3jBs//8vbP///////2beJkZn3jFsaN4tS2neMmz//zNsat40bGve//9s3m3eNWz//27eb95y3lpGcN7//3He" + + "////////XT42bHPedN7//3Xe//923nfeazkuUDdseN7/////////////ed7//3ree97//zhsP0k5bHzeQWz//33e////////Omz/" + + "////PGx+3iHf//87bD1sIt9GSz5sP2z//yPf//8k3yXfQGz///////9CbCbf//8n3yjfLTNnRP//aUliOlc5//8p3/////9PSV8y" + + "TkhFbFM0VUBEbElseUNjTP//R2xIbC41//9KbGNHX0Iq3yvfcUg9RUZs//9HS2wyTGwoT0JERU8s3y3fcTtLbC7fMUIv3///XGwo" + + "QTDf//94Rv//UEn//zLfMd//////M99PbD87cjs0314+//9lRzXfLThObE1s//9qSf//Nt///0E8//8331JF//843znf//863///" + + "//873///PN893///UWxSbFg5UGw+3z/fQN///0HfU2xUbP//VmwjQkLfVWxmNP//WGz//1dsWWz//0PfW2xdbP//XmxE3///////" + + "/0Xf////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////VkBG" + + "3088X2z//0ff//9SM0jfYGxJ3///dkFhbP//YmxrSf////8vNf//////////////////St///2NsS9///0zfNkT/////Td///1sx" + + "/////07f/////0/fUN////////9R3////////2Rs//////////9S31PfVN//////cTz/////Vd///3Y//////1bfV9//////WN//" + + "////Wd8tQv//Wt///1vf//9c32dsXd9v3///Zmz//17f//9lbP////9f32DfYd9i3///Y99tbGts//9k32hs//9l3/////9m32ff" + + "amxo3///ad9pbGxs//93Nf//cGz//1dA//9xbGrfa9///2zfWTj//25sb2xt3/////8pT27fcN9x3zdEct8pQf//////////////" + + "/3Jsc9///3VsdN//////dd9233ff//9zbHRsWU143////////ydGeGx53/////963///e9////////////////92bHdseWx8333f" + + "ft8h4P////8i4CPg/////ylt/////////////3xsJOD//yXgfWx7bCbgJ+Ao4Cng////////KuD/////K+As4Hps//99RP////8h" + + "bSVtIm1+bC3gI20u4C/gMOAkbf///////zHgK23///////8mbf//MuAz4DTgNeBYQChtNuA34CptJ23//////////zjg/////zng" + + "OuD//zvgPOA94C1t//8zPf//LG3/////PuA/4EDgLm3//////////y9tQeBC4DJtMW3//zBt//9D4DRtM23//3ZM/////0TgNm1F" + + "4DVtN21G4P///////zhtR+BI4P//SeBK4P////86bUvg//////////9M4P//TeA5bUg/O21O4E/gbTY8bT5t//9Q4P//UeD/////" + + "/////1LgU+D/////P23//1TgVeD//1bgV+BAbT1tWOBBbf//VjxCbTA1Mzf//1ng//9a4C44//9b4P///////////////0NtXOD/" + + "////cEb/////PkVEbf//////////XeD/////R23//2TgXuD//1/gYOD/////////////YeA0PGLgY+BGbUVtWjdIbWXg//9m4FMz" + + "//9Kbf//Z+Bo4Fw6SW3//1Jt/////2ngauD//0xtTm1lSktta+Bs4G3gTW3//1FtT20xNW7gUG1v4HDg//9x4P//cuBTbXPgdOBa" + + "R1hO//914Hbgd+A0Pf///////1RteOB54Hrge+AiTVZtfOBVbf////9ZbUFNfeB+4FhtIeFtM1dtXG0i4f//W23/////Wm0yRV1t" + + "I+H//yThJeEm4SfhKOH//15tKeH///////9fbSrhK+FsOf//JTdgbWFtYm0s4f//////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//9JP2NtLeEtPGRtLuEv4f//ZW0w4THhMuEhUn5R//////////9mbXBlZ20kQys/QEf/////M+E04WhtNeH//1VKVER+Of//NuEp" + + "QzfhOOEqMf//eEtXPznh////////OuE74f//POFeN///PeFhNj7hP+FWSkDh//////////9pbf////////////9B4f//a21C4UPh" + + "am1gMv//ROF2Rmxtd0f//zNFReFtbVI9RuH/////b21H4UjhQkx+bXFtcm1J4f//SURK4WBCd0FL4ShGTOFwbVU1//9N4f////95" + + "bU7hdm0lbilGYENzbf//fkRTRXRteG1gP0/hZ0dMRFDh//9CQHdtLkIkQnVtKTAiT////////3ptUeFS4VTh//9V4VbhYUJT4f//" + + "NT1KP1fhWOF8bXttWeFvMH1t/////y9J//8nblrh//9bRms/W+Fc4VlD//94Nv//Jm43TT8xXeFXSmEyIW4ibiNuJG47RiNDYzAo" + + "bv//KW4jdP//XuE9Ql/hKm7//3MxTEFg4S84//9aTWHhYuErbixF/////2PheEFXPCxuZOH//y9u//9l4WU9LW4rQSpBZuFkMP//" + + "S04xbv//ckgzbjJuMG5kY1Q0Z+H//25taOE1bjRuaeFq4f//a+E2bmzhOE3///////9t4f//buFv4XDh//9x4f//////////cuFz" + + "4XThYUb//3XhLkv//zdu//9ZPP//////////OG524Tlud+F44XnhOm564f//IUX//////////3vhfeH/////ajD//37hIeIi4v//" + + "I+Ik4v//WTn//3zh//86T////////y3i/////yXi//8m4ifiKOL//z5uKeIq4v//K+L//zQ3O27//zxuLOL/////dEn/////L+L/" + + "/1Qz//8w4jHi////////MuI5TS7iPzb/////////////VEUz4jTiNeL//z9u//824jfiOOL//zni//////////864v////874v//" + + "QG7//zzi//894j7iP+JBbkDi//9B4v//QuL//0Pi//9F4kbi//9E4v//R+L//0ji////////IkVJ4kriQ25L4kJu//9M4v//TeJO" + + "4v//T+JQ4v//UeJS4v////////////9T4v///////1TiVeJTRkRuNj1gPFtHcUNW4v////9yPFfibD///0VuWOJGblniWuJb4v//" + + "//////////9c4l0/R25d4khu//9e4v//SW5vTf//Nz1f4v//////////S25KbmDiWjn//3M5QDth4mLiY+L/////////////ZOJO" + + "bmXi//9m4mfiZj3//01uaOJMbv//aUJp4v//bzhq4kNAa+Js4m3i//8wSG7i////////OT3//2/i/////3DiT27//18+//9x4v//" + + "cuL//1JuUG5z4nTideJRbnbid+J44nniVG5Tbnri//96Pv//VW574nzifeL//37iVm5XbiHjIuP//yPjUEhTOmE8WG7//1luJE5F" + + "PW5MTE5abmI2//8k4yXj//9bbibjI0Un4yjjXm54M0s/KeNcbv//XW7//2BEKuMr41VLfDb//yzjLeP//y7jL+Mw4zHjMuMz4///" + + "/////2BuYW404///NeP//zbjX2434///Y2444znj/////zrjO+M84z3j//8+4z/j//9A419GQzP//0HjZ25C40PjZG5mbkTj//9F" + + "4////////0bjR+Nibv//////////SONJ40rjS+P//0zjT2//////ZW7//03jTuNP4/////9Q42tOUeNS41o4U+NU41Xj//9W4///" + + "V+Nvbljj//9Z41rjNEVqblvjXONtbmtuXeNwbv//XuNf42DjcW5h4/////////////9pbmLjY+N2bnQxZONl42hu//9m42fjLUj/" + + "/2xuaONgPmnjauNr4///////////bONt427jWzn///////9v43DjceNy43Pj//9043XjduNIS3fjZDb/////Rj3//zxG/////3jj" + + "eeN64/////9743zj/////y1BfeN0bv//bm5zbn7jQ0wh5DhEdW5ybv////8i5CPk////////JOQl5P//JuQn5P////8o5P//LEH/" + + "/ynk/////yrk////////K+R5bizkeG4t5C7kL+Qw5P//MeQy5DPkNOQ15P//NuQ35DjkOeT/////OuQ75DzkPeR3bj7k//8vSz/k" + + "//9A5P//QeRC5EPk/////0TkReT//0bkR+RI5P//SeR7PUrk//9L5Ezkem5fSv//TeRUMU7k//9P5P//RklyQ///////////eDVQ" + + "5HxuUeRdOf////9S5FPk//9U5P///////yw7//9V5P//////////VuT//3tubT9X5P////9Y5Fnk/////24/IW8jb///WuRb5Fzk" + + "XeR7Pl7kIm8kb1/kYORTNmHkRUli5GPkYjwjT///fm54Ov////8/T2TkZeQmb2bkZ+T/////JW8nb/////////////////////99" + + "bv////9o5GnkauT//2lG//9VRf////9r5GzkbeT//1dEbuQsb2/kcOT//3HkQ0Mob///cuT//ylv////////c+R05P//deT//3bk" + + "d+T//y03eOQrb3nkeuR75P//fOR95DA4fuT///////8h5f//Km8i5WE+I+Uk5SXlJuX/////////////J+X//yjlKeV5Myrl//8r" + + "5f////8s5f//MG8t5T86eUEu5f//SkQv5f////8w5f////8x5f//MuUz5f//NOU7MzXlO+X//zblLm8vb0NE//8tb////////zfl" + + "OOU55f////8xbzrl////////////////POX//zdvPeU+5T/lQOU6b0HlQuVD5UTlReX/////OW8tRf//RuX/////Mm8zbzZvR+X/" + + "////SOU4b0nlSuX//0A2S+X//ztvNW9M5U3lNG//////////////////////////////////////T+VQ5U7lUeVS5f//U+VU5VXl" + + "P29W5f////9Ab1flWOX///////9Z5VrlW+VBb/////8+bz1vXOVd5V7lYj4qRjxv//////////9f5f//RW//////////////////" + + "//////9Db/////9g5WHl//9i5WPlZOVl5URvQm///3hC//9Gb2bl//9o5f//Z+X//0dv//9p5UlvauX/////a+X//2zl//9t5f//" + + "////////VTRIb3pM//9u5f///////2/lVG9Kb3Dl//9Nb3HlS29y5Uxvc+X//////////3Tl//9Ob3Xl//925XfleOVQb3nleuX/" + + "////UW///1Jv//////////9Vb1NvVm9Yb///V2///3zle+U5RH3lfuX//////////yHm//9nTP//WW8uQSLm/////1pvI+ZESltv" + + "KzMk5iXmJuY8Mf//VzT//1Y0XG///11v//9eb19v////////J+Yo5inmYG8q5lg0VTNeOTZIK+Zib2FvLOb//y3mLuZjb///////" + + "////XDH//y/m//8w5v////9mbzHmZW9kbzLmZ28z5v///////2pv/////zTmRzA15jbmaG835mxva2//////OOY55jrmO+Zub21v" + + "b2///y5GPOY95v//cG8+5j/mQOZB5nFvc2///0Lmcm9D5mxJROZF5v////90b0bm//9H5kjmSeb//3Vv//9lOv//Sub//3Zvd2//" + + "/0vmSUtM5v///////03mTuZP5lDmS0FR5lLm//8kMEtCU+Z4b///bUn///////////////97b3lvXzn//3pvQjj//1Tm//9V5v//" + + "VuZX5ljm/////0VKfW8hcH5vInD//1nmITFYP3w9WTQjcP///////2ZH//8lcP//Wub//yIx//8kcEREW+ZNTitGfG8mTv//MThc" + + "5l3mW01e5l/m//9g5mHmYuZj5nk2NE7//yg3ZOZiQiFn//8mcCwzbz///2Xm/////1YzKHBm5ilwJ3BkN2fmXTpjPmjm//9p5iMx" + + "/////1lOauZr5mzmK3Aubm3mKnD///////9u5m/mLnAscC1wcOYvcP//MHBsTjFwMnBx5klAO0j///////99P2c0/////zpNbTI4" + + "PVs4//81cHLmNHBzOzZwM3D/////KDtz5v////86cC1q//915lZSduZ3Pzhwd+Z45nnm/////yVOcUb//////////ysxeuZjQDY8" + + "////////e+Y3SnzmQDH///////9tTmtN//87cH3mRUV7PP//fuYh5zxwIuc9cEw/PnAj525O/////zlwQHBCcP//QXD//z9w////" + + "/0Nw/////0RwJOcl53pBJudiMv////8n5yjnKedFcP////84TCrn//9GcP////////////9HcCvnKk8s5///////////MVtIcP//" + + "/////0lwSnD/////LedOcC7nS3D//0xw//9NcE9wL+f///////8w5zHn/////0RA/////zLnd0wz5zTnRUA15zbnUHD//3NI//9R" + + "cFNzTEw351Jw//9TcDjnVHBXMznnVnD//1k/Ouf/////V3D//zvnJDf//zznPec+51hwXHA/51pwQOf//0HnQudbcP////9zM1lw" + + "XXD/////Q+f//15w//9IMP//X3BgcP//////////ROdF50bnZD5H50jn//9hcP//SedK50c1//9L52Rw/////2Nw//9icP////9x" + + "a0znXEpN5/////9O50/nZXBmcFDnUef//1LnU+dU5///Vef//1bnV+f//1jn//9ncFnnWudocFvnaXBc513nanBe51/nYOf//2Hn" + + "Yuf//1o0Y+f/////ZOdl52bn//9q52twZ+do5///aedr5/////9s5/////////////////////9scCNHbef//27nbnA7Mm/ncXBw" + + "cHDncef//3LnJDH///////9BNkdKOkQiOv//YDlnPXPnXD///3Tn//9zcHbnd+dycEJNaDRSSFxGeOf//3nnfD9OTnXnWzf//3rn" + + "//975///fOd2cP//fed1cCjofuf//////////yHoS0ssRiLoI+gk6P//Jegm6FAxJ+j//3dwdHD/////UUlqTXhwKej/////////" + + "////Kuj//3lwK+j/////LOh7cGpCWzNcM3pw//8t6C7oL+hpNDI4MOgx6Go0Mugz6D9F/////2BO////////NOg16P//Nug36Fw4" + + "/////zjofHA56P////99cH5wIXH//yNxInH/////////////////////////////////////////////////////////////////" + + "//////////////////////////////////////////////////////////////////////93Sf//JHE66P//O+g86CVxPegmcf//" + + "//8+6P//J3E/6EDo//9B6ELo////////Q+j/////ROgpcShxRegqcf//Ruj///////9H6P//////////////////////////////" + + "//////90SExm/////yk///9I6DI1Sej//0roS+hM6P//K3FN6Cxx//8sUjtdU0j/////ezBO6Dsw//9P6P////////////90OzBL" + + "fj5Q6C1x//9fTP//UehS6C5xXE3//0Ix////////QTtT6C9xbjIwcVToVehW6DFx//9X6FjoWegzcTRxWug2cTJxW+j//zVx//9c" + + "6F3oWzT/////Xug3cf//OHH/////X+hg6GHoYuhj6P///////2ToZehm6GfoOXE6cf//aOhp6Dtx/////z1xauhr6GzoPHH//z9x" + + "QnFt6G7o//8+cUBxQXH//2/oQ3H//0I2cOhx6P//cuhz6P//dOh16Hbo////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////////////////////////////////////3M8" + + "RHFFcWE5//936P//eOj//3no/////////////0Zxeuj//z4z////////T0dHcUhx//976HzofehaQ2tGfuj///////8h6SLp//9J" + + "cSPp//8k6f//fUf//yXpTEJYMW42//9vNibp////////////////c0NOcXA2J+ko6W8y/////01xKekq6UtxK+lMcSzpSnH/////" + + "WHH//////////y3p/////y7pL+kw6U9xUHH//zHpUXFScf//Mukz6f////9UcTTp//9Tcf//Nek26Vk9VXE36TjpOelXcf//////" + + "//////866Tvp//8zNVZxPOk96XtBMzj/////Pun/////WXH//////////z/p//9A6f//QelC6UPp/////0TpTUL/////WnH//0Xp" + + "Run//y1G/////0fp//9I6UnpW3FK6f////////////9gcf//XnFM6V1xX3FN6Vxx//9L6f////9O6U/pUOlicVHp/////1Lp////" + + "/1PpYXFU6WRx/////0M2Y3H//1Xp//9lcf////9mcf//aHFncf///////2lxa3Fqcf//////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////3w5//9W6f//V+lscVjpWeltcf//Wun//1vpXOld6f//PDNe6f//X+lucf//YOlh6W9xYun//2Pp" + + "cT///2Tp//9l6f////////////9m6XBxZ+lxcWjpcnFzcWnpaulr6WI5/////2zpben//3RxdXFu6f//dnF3cW/pcOl4cXHp//9y" + + "6TFIenFz6SZJe3F5cf//fXF06XXpfHF26f//fnH//3fpeOkhcv//een//3rpe+l86X3pfukh6iLqInL//yPqJOr//yXqJuon6ijq" + + "//8p6v//Kur///////8r6v//I3Is6iRyLeou6v////8lci/q//8mcidy//8ocjDqKXIqcityLHIx6v//Muotci5y//81XS9yM+o0" + + "6jXq//826v//N+o46nhkNDU56v///////yEzMjoxcjByJUz/////Our/////O+o86jNyNHIycv//NXL/////Yks96j7qP+o2cv//" + + "ezVA6v////9B6v////9C6v//Q+r//0TqRer//0bq//9H6kjqSepK6kvqJU////////9M6jdyTer//07qT+pQ6v////////////9R" + + "6lLq/////zlyU+pU6lXqVur//1fqWOpZ6v//Wuo+MFvqXOo6citKOHJd6v//O3I8cv////9e6v////9f6mDqPXI+cv//////////" + + "//9h6mLqP3Jj6m5LLTtk6no6L0H//2XqZupn6v//QHL/////aOpp6kNy//9q6mvq//9s6m3qQXJu6v//////////RHJv6nDqcThC" + + "cv///////3HqRXJy6kZyR3L//0ty//8qO3PqdOr/////ZEL//3Xq//926v//THJJckhySnJ36v//eOpfN///eep66v///////3vq" + + "UHJPck5yfOr//zMw//996n7qIesi6/////8j6///JOsl6///Juv//1py//9Wcv//V3JTcllyJ+tVcmIz//8o60xPKetYclRyUnJR" + + "cirr//8r6yzrLetcci7r//8v6/////9fcjDrMetecl1yMusz6zTrNes26/////9JSVtyczBgcjfrYnL/////OOs56zrr//9vM01y" + + "NzH//zvrZHL/////POv//z3rPus/62NyYXItQ0DrQev///////9C60PrROv//3BLRetG6///R+taTkjr//9lcknrUOtK60vrTOtm" + + "cv////9N6////////2dyUutO60/rUev/////U+v//1Tr//9V6/////9W62hyV+tpcv////9Y6///////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////ztEWetqcv//N0j//29ya3L///////9scv//WusxS0RM//9Q" + + "Rlvr//9c617rcHL/////cXI+Rm5ybXL//13r/////yoy/////1/reXL/////eHL//2DrYev/////dTFi62PrZOt2cv///////3Vy" + + "/////3Ny//97M///cnIyPCky/////2XrZuv//2fraOtp6/////////////9q62M5a+tt63xye3L//3pybutv63dybOt9cnDrfnL/" + + "/3Hr/////////////yVzJHP//3Lrc+v//////////yZz/////y0xIXMic3TrdDk5THbrdesjc3fr////////eOt563rrMkv/////" + + "K3N76///J3P///////98633r/////yxzfush7P//Iuz//////////yPsJOz//yXsKXP//yhzJuz/////J+wo7Fw3/////ynsKuz/" + + "/yvsLOwt7C7s//8tc////////////////y/s/////y5z//////////8vczDsKnMx7P//Mux0cv//M+wwc///YUQ07P////80czXs" + + "NXMzczbs/////zfs//8yczhzOOwxc///NnM57P//Ouw77P//////////N3P///////86czzsPew+7D/s//85c0Ds////////QexC" + + "7EPs//////////9E7DxzRez//0bs//9H7P//PXNI7D5zSez//0lPSuxL7P///////ztza0JtOv////8/c0zsTuz//////////0/s" + + "/////03s////////UOz//1HsUuxT7P////9U7FXs/////1bsQHNBc1fsWOxCc///////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////////////////////////////////////////////////////////////////9Dc/////80" + + "OERzWexa7FvsRXP//y88XOxGc13sXuxf7GDs//9h7Edz/////0hzSXP//2LsY+z//0xzSnM8T///S3Nk7G9OZez/////Zuz//01z" + + "Z+xbTv//////////aOxOc35H//9p7E9zUXP//2rsUnNr7Gzsbez/////buxv7HDs/////1BzbTlNTGNLd1b//2Bde0v/////////" + + "/ysy//9x7P//cuz/////c+xUc1A1VXNWc1dz//91Of//WHN07P////9UYFtM//9jQllzW3Nac3XsXHP///////927F1z//937F5z" + + "////////eOx57HrsX3N77Hzsfez//2Bzfuxhc2JzIe1jc///ZHNlc2Zz//8i7SPtJO3///////9nc2hzJe3//////////yRFJu0n" + + "7SjtKe1dOCrtanMr7Szt//8t7S7tL+3///////8w7U1Ba3Mx7f///////zLt////////M+007Wxz/////zXt//827Tft//847f//" + + "//857f//Ou077SFJPO097W1zPu3//z/t//9A7UHtQu1D7UTt/////25zN2P/////WmxtcP////9vc0XtcHNG7UftSO1J7f//Su3/" + + "////S+1M7XJzc3N0c3BOcXP/////dXN2c03tTu14c///d3NP7VDtUe1S7VPtenNU7f//Ve17c3lz/////1bt/////1ft////////" + + "////////////////////////////////Nk7//1jtWe1a7Vvt//9c7XxzXe1e7f//////////fXNUY1/t//9+c2DtYe1i7f//Y+0q" + + "If//dCFwIXMhdSH//0ohSyF2IVwhJCH//yUhPyEwIzEjMiMzIzQjNSM2IzcjOCM5IychKCFjIWEhZCEpIXchQSNCI0MjRCNFI0Yj" + + "RyNII0kjSiNLI0wjTSNOI08jUCNRI1IjUyNUI1UjViNXI1gjWSNaI04h//9PITAhMiEuIWEjYiNjI2QjZSNmI2cjaCNpI2ojayNs" + + "I20jbiNvI3AjcSNyI3MjdCN1I3YjdyN4I3kjeiNQIUMhUSH/////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/zEh//9vIQ==", +}; + +export const cp932ext_encmap = { + length: 9686, + index: [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[0,22,121],[100,17,191],null,[275,96,115],null,null,null,null,null,null,null,null,null,null,null,[295,29,31],null,[298,49,168],[418,3,205],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[621,40,252],[834,0,255],[1090,30,244],[1305,74,236],[1468,21,219],[1667,0,221],[1889,138,255],[2007,134,134],null,[2008,89,200],[2120,158,178],[2141,11,186],null,[2317,86,236],[2468,30,245],[2684,39,208],null,[2854,33,222],[3044,93,242],[3194,17,152],[3330,19,166],[3478,245,245],[3479,96,206],[3590,78,78],[3591,0,251],[3843,14,192],[4022,1,207],[4229,104,226],[4352,48,228],[4533,214,214],[4534,63,218],[4690,4,252],[4939,39,191],[5092,136,245],[5202,5,187],[5385,4,254],[5636,177,190],[5650,36,245],[5860,7,159],[6013,1,111],[6124,130,166],[6161,70,70],[6162,33,122],[6252,48,155],[6360,209,235],[6387,158,158],null,[6388,72,214],[6531,82,138],[6588,71,161],null,null,null,[6679,1,246],[6925,72,220],[7074,83,176],null,null,[7168,7,245],[7407,28,28],[7408,18,246],[7637,83,127],[7682,240,244],[7687,18,118],[7788,207,207],null,[7789,103,222],[7909,21,238],[8127,6,255],[8377,2,248],[8624,49,72],[8648,146,146],[8649,157,175],[8668,51,85],[8703,87,101],[8718,39,158],[8838,78,220],[8981,114,187],[9055,0,0],[9056,107,112],[9062,25,209],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[9247,41,220],[9427,14,45],null,null,null,null,[9459,2,228]], + data: + "gof//////////////////////////4SH////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////////////////////////////////////1SH" + + "VYdWh1eHWIdZh1qHW4dch12H////////////////7+7w7vHu8u7z7vTu9e727vfu+O6Uh///////////////////////////////" + + "////mIf/////////////YYH/////////////////////k4f/////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////+Zh0CHQYdCh0OHRIdFh0aHR4dIh0mHSodLh0yHTYdOh0+HUIdRh1KHU4eAh///gYeKh4uH" + + "////////////////jIf/////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/4WHhoeHh4iHiYdlh////////////////////////2mH////////////////YIf///////9jh////////////////////////2GH" + + "a4f/////aodkh////////2yH//////////////////////////9mh///////////bof/////////////////////////////////" + + "/1+HbYf/////Yof///////9nh/////////////9oh///////////////////////////////////////////////////////////" + + "//////////////////////////////////9+h4+HjoeNh////////////////////////////////////////3KHc4f/////////" + + "//////////////////////9vh3CHcYf/////dYf/////////////////////////////////////////////////////////////" + + "/////////////////////////////3SH/////////////////////4OHTO3/////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////03t////////////////////////////////////////////////" + + "/////////////////////07tT+3/////UO3/////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////Ue3/////////////////////" + + "/////////////////////////////////////////////////////1Lt////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////VO3/////" + + "/////////////1Pt//9W7f////////////9V7f//////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////Re3///////9X7f//////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////Wu1b7f///////1nt/////////////////////////////////////////////////////////////////////////////1jt" + + "//9e7f///////1zt////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////13t////////////////////////////////////////////////////////////////////////" + + "/////////////////////1/t////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//9h7f///////////////////////////////////////////////////////////////////////2DtYu3/////////////////" + + "/////////////////////////////////////////////////2Pt////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/2Tt/////////////////////////////////////////////////////////////////////////////////////2Xt////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////Zu1n7f//////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////////////////////////////////////////////////9o7f//////////////////////" + + "/2nt/////////////////////1vu//////////////////////////////////////////9q7f//////////////////////////" + + "//////////////////////////////////////////9r7Wzt////////////////be3/////////////////////////////////" + + "/////////////////////////////////////////27t////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////2/t////////////////////////////////////////////////" + + "/////////////////////////////////////3Dt////////////////////////////////////////////////////////////" + + "////////////////////ce3/////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////////9y7XXt/////////////////////////////////////////////3Tt////////////" + + "////////////////////du3/////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////3fteO157f////////////////////////////967f//////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////e+3/////////////////////" + + "////////////////////////////////////////////////fe187YHt////////////////////////////////////////////" + + "//////+C7YPt////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/4Tt//////////////////+F7f//hu3/////////////h+3/////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////4jt////////////////////////////////////////////////////////ie2K7f//////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////4vt////////////////////////////////////" + + "/////////////////////////43t//////////////////////////////////////////////////+O7Y/t////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////kO3//////////////////////////////////////////////////5Ht" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////////////////////////////+S7ZPt////////////////////////////////////////" + + "/////////////////////////////5bt//////////////////////////////////////////+U7f//////////////////////" + + "////////////////////////////////////////////l+3/////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////mO2Z7f//////////////////////////////////////////////////" + + "////////mu2b7f///////////////////////////////////////////////5zt////////////////////////////////////" + + "//////9L7f///////////////////////////////////////////////////////////////////////////////////////53t" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////+e7f//////////////////////////////////////////////////////////////////////////////////////" + + "//////////////+f7aDt////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////oe3//////////6Lt////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////6Tt/////////////////////6Pt////////////////////////////////////" + + "//////////////+m7aft/////////////////////////////////////6Xt////////////////////////////////////////" + + "qe3///////////////+o7f//////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////////////////6rtq+3/////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////rO2t7a7t////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////r+3/////////////////////////////////////////////////////////" + + "//////////////////////////////////////////////////////////////////////+w7bHtsu3/////////////////////" + + "te3/////////////////////////////s+3/////////////////////t+3/////////////uO3///////////////////////+2" + + "7f////9H7f///////////////////////7Tt////////////////////////////////////////////////////////////////" + + "////////uu3//7vt/////////////////////////////7nt//////////////////////////////////+97f//////////////" + + "////////////////////////////////////////////////////////////////////////////////////vu3/////////////" + + "//+/7f/////////////////////////////////////////////A7f///////////////////////////////8Ht////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "///////////////////////////////////////////C7Urtw+3/////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "///////////////////////////////////////////////////////////////////////////////////F7f//////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////8bt///////////I7cnt////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////yu3//////////////////////////////////8ft////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////SO3////////////////L7c3t////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////8/t////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "///Q7dHt////////////////////////////////////////////////////////0+3/////////////////////////////////" + + "///////////////////////////////////////////////////////////////S7f//////////////////1O3/////////////" + + "/////////////9Xt////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////1u3//9ft2O3Z7f//////" + + "////////////////////////////////////////////////////////////////////2u3/////////////////////////////" + + "///////////////////c7f//////////////////////////////////////////////////////////2+3/////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////3e3e7f//////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////4O3/////" + + "////////////////////////////////////////////////////////3+3/////////////////////////////////////4e3/" + + "///////////////////////////////////////////////////////i7f//////////////////////////////////////////" + + "////////////////////////////////////////////////4+3/////////////////////////////////////////////////" + + "/////////////////////////////////////////+Xt/////////////+Tt////////5u3p7f//////////////////////////" + + "///////////////////n7f/////q7f//////////////////////////////////////////////////////////////////////" + + "////////////6O3/////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////6+3s7f//////////////////" + + "///////////////////////////////////////////////////////////////////////////////////////////////////t" + + "7f//////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////////+7t7+3///Dt////////////////////" + + "//////////////////////////////////////////////////////////////////Ht////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////Lt////////////////////////////////////////////////////////////////////////////////////" + + "///////////////z7f///////////////////////////////////////0bt9e3///////////////////////////Tt////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////9+347f/////////////////////////////////////////////////////27f//" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////+u3/////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "///////////////////////////77fzt////////////////////////////////QO5B7v//////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////Q+7/////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////////////////////////////////////////////////9E7v//////////////////////" + + "//////9F7v////////////////////9I7v///////0bu////////////////////////////////R+7/////////////////////" + + "////////////////////////Su5J7v//////////////////////////////////////////////////////////////////////" + + "/////////0vu/////03uTO7///////9O7v//////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////////0/u////////////////////////////" + + "/////////////////////////////////////////////////////////////////////////1Du////////////////////////" + + "////////////////////////////////Ue5S7v//////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////4zt////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////U+5U7v///////////////////////////////////////////////////////////////1fu" + + "Ve7//1bu//////////////////9Y7lruXO7/////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////Xe7/////////////////////////////////////////////" + + "//////////9e7v///////////////////////////////////////////////////////1/uYO7/////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////////////9k7v///////////////2buZ+7/////////////////////////////////////" + + "//////////////////9o7v///////2rua+5t7v//////////////////////////////////////////////////bu7/////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////////3Du////////////////////////////" + + "//////////////////////////////9v7v//////////////////////////////////////////////////////////////////" + + "/////////////3Hucu7/////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////0Dtc+7/////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////dO527v//////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////////3fu////////////////////////////" + + "//////////////////////////////////////////////947v//////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////////////957v//////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////eu577v//////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////////////////////////////////////////////////987v//////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////0Ttfe7/////////////fu7/////////////////" + + "////////////////////////////gO7/////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////gu6F7v//////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////4buQe2H7v//////////////////////////////////////////" + + "/////////////////////////////////////////////////////4ju////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////4nu////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////iu7/////////////////////////////////////////////" + + "/////////////4vu////////////////////////////////////////////////////////////////////////////////////" + + "/4zu//////////////////////////////////////////////////////////+O7o/u////////////////////////////////" + + "//////////////////////////////////////////////////////////////////////////////////+Q7pHu////////ku6T" + + "7v//////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////5Tulu6Z7v//////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////mu6c7v//////" + + "//////////////////////////////////////+d7v//////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////n+7/////nu7///////+g7v////////////+j7qTu//////////////////+h7qLupe7///////+n7v////////////+m" + + "7v//////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////ru6o7v//qu7///////+p7v//////////////////////////////////q+7/////re7//////////////////6zu////" + + "//////////////////////////////+v7v///////////////////////////////////////7Husu7/////////////////////" + + "//////////////////9D7f//////////////////////////////////////////////////////////////////////////////" + + "/7Du////////////////////////////////////////////////////////////////////////////////////////////////" + + "//////////+27v////+67v//uO7//7Tu//+17v///////////////7nu////////////////s+7/////////////////////////" + + "////////////////////Se3//73u////////wO7C7v//////////////////////////////////////////////////////////" + + "///////////B7r/u/////7zu////////u+7/////////////////////////////////////////////////////////////////" + + "/////////////////////////0Lt/////////////////////////////////////8Tu////////////////////////////////" + + "////////////////////////////////w+7/////////////////////////////////////////////////////////////////" + + "///////////////////////////////////////////////////////////////////////F7v//////////////////////////" + + "/////////////////////////////////////////////////////////////8bu////////////////////////////////////" + + "/////////////////////////8fu///////////////////////////////////////////////////////////////////I7snu" + + "///////////////////////////////////////////////////K7v/////L7szuz+7/////////////////////////////////" + + "////////////0O7R7v//////////////////0u7//////////////////9Pu////////////////////////1O7//9Xu///W7v//" + + "/////9fu2O7//////////////////////////////////9nu3O7/////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "/////////////////////////////////////////////////////////////////97u3+7/////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "///////////////////////////////////////g7v/////h7uPu/////+Lu////////////////////////////////////////" + + "///////////////////////////k7v//////////////////////////////////////////////////////////////////////" + + "/////////////////+Xu////////////////////////5u7n7unu///////////o7uvu////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////7O7E7f//////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////ze5z7X7tgO2V7bztzO3O7fntQu5Z7mHuYu5j7mXuae5s7nXuge6D7oTuje6V7pfu" + + "mO6b7rfuvu7O7tru2+7d7uru/O7///////////vu/////////////3yB////////////////////////////////////////////" + + "//////////////////////////////////////////////////////////////////////////////9fgf//////////////////" + + "/////////////////////////////////////////////////////////////////////2CB////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////////////////////////////////////////////////////////////////////////////////////////" + + "////////////////kYGSgcqB///67g==", +}; diff --git a/packages/romdev-spimdisasm/test/disasm.test.mjs b/packages/romdev-spimdisasm/test/disasm.test.mjs new file mode 100644 index 00000000..5a9b7bdf --- /dev/null +++ b/packages/romdev-spimdisasm/test/disasm.test.mjs @@ -0,0 +1,239 @@ +// Synthetic (ROM-free) tests for the spimdisasm port: symbol naming, jump +// tables, string guessing with Shift-JIS, float/double text and version gates. +// Expected texts follow upstream spimdisasm semantics; the port has also been +// checked byte-for-byte against real Python spimdisasm output trees (see the +// package report), so these pin that behaviour against regressions. +import test from "node:test"; +import assert from "node:assert/strict"; + +import { RABBITIZER_SKIP } from "./helpers/payload.mjs"; + +// Loading the port loads romdev-rabbitizer's WASM; without that payload every +// test here skips with the reason instead of the file failing to import. +const spim = RABBITIZER_SKIP ? null : await import("../src/index.js"); +const { common, mips } = spim ?? {}; + +function be(words, size) { + const b = new Uint8Array(size ?? words.length * 4); + const dv = new DataView(b.buffer); + words.forEach((w, i) => dv.setUint32(i * 4, w >>> 0)); + return b; +} + +function freshContext(version = "1.42.4") { + spim.configureVersion(version); + common.GlobalConfig.GLABEL_ASM_COUNT = false; + const ctx = new common.Context(); + ctx.changeGlobalSegmentRanges(0, 0x1000, 0x80000000, 0x80001000); + return ctx; +} + +const JTBL_TEXT = [ + 0x2c810003, // sltiu at, a0, 3 + 0x10200009, // beqz at, .L8000002C + 0x00047080, // sll t6, a0, 2 + 0x3c018000, // lui at, %hi(jtbl) + 0x002e0821, // addu at, at, t6 + 0x8c2e0100, // lw t6, %lo(jtbl)(at) + 0x01c00008, // jr t6 + 0x00000000, + 0x03e00008, // case label + 0x24020001, + 0x03e00008, + 0x00001025, +]; + +function jumptableOutput(textWords, jtblWords) { + const ctx = freshContext(); + const t = new mips.sections.SectionText(ctx, 0, 0x30, 0x80000000, "t", be(textWords, 0x100), 0, null); + t.analyze(); + const r = new mips.sections.SectionRodata(ctx, 0, 0x10, 0x80000100, "r", be(jtblWords), 0, null); + r.analyze(); + return [t.disassemble(), r.disassemble(), t, r]; +} + +test("jump table: hi/lo pair, jr, jlabel and .word .L entries", { skip: RABBITIZER_SKIP }, () => { + const [text, rodata] = jumptableOutput(JTBL_TEXT, [0x80000020, 0x80000028, 0x80000020, 0]); + assert.equal( + text, + `/* Generated by spimdisasm 1.42.4 */ + +nonmatching func_80000000, 0x30 + +glabel func_80000000 + /* 000000 80000000 2C810003 */ sltiu $at, $a0, 0x3 + /* 000004 80000004 10200009 */ beqz $at, .L8000002C + /* 000008 80000008 00047080 */ sll $t6, $a0, 2 + /* 00000C 8000000C 3C018000 */ lui $at, %hi(jtbl_80000100) + /* 000010 80000010 002E0821 */ addu $at, $at, $t6 + /* 000014 80000014 8C2E0100 */ lw $t6, %lo(jtbl_80000100)($at) + /* 000018 80000018 01C00008 */ jr $t6 + /* 00001C 8000001C 00000000 */ nop + jlabel .L80000020 + /* 000020 80000020 03E00008 */ jr $ra + /* 000024 80000024 24020001 */ addiu $v0, $zero, 0x1 + jlabel .L80000028 + /* 000028 80000028 03E00008 */ jr $ra + .L8000002C: + /* 00002C 8000002C 00001025 */ move $v0, $zero +endlabel func_80000000 +`, + ); + assert.equal( + rodata, + `/* Generated by spimdisasm 1.42.4 */ + +nonmatching jtbl_80000100 + +dlabel jtbl_80000100 + /* 000000 80000100 80000020 */ .word .L80000020 + /* 000004 80000104 80000028 */ .word .L80000028 + /* 000008 80000108 80000020 */ .word .L80000020 + /* 00000C 8000010C 00000000 */ .word 0x00000000 +enddlabel jtbl_80000100 +`, + ); +}); + +test("jump table output changes when one input word is perturbed", { skip: RABBITIZER_SKIP }, () => { + const [, base] = jumptableOutput(JTBL_TEXT, [0x80000020, 0x80000028, 0x80000020, 0]); + const [, pert] = jumptableOutput(JTBL_TEXT, [0x80000020, 0x80000024, 0x80000020, 0]); + assert.notEqual(base, pert); + assert.match(pert, /\.word \.L80000024/); +}); + +function stringRodata(bytesAt, encoding = "SHIFT-JIS") { + const ctx = freshContext(); + const G = common.GlobalConfig; + G.RODATA_STRING_ENCODING = encoding; + G.RODATA_STRING_GUESSER_LEVEL = 2; + const b = new Uint8Array(0x40); + for (const [o, arr] of bytesAt) b.set(arr, o); + for (const [o] of bytesAt) ctx.globalSegment.addSymbol(0x80000100 + o); + const r = new mips.sections.SectionRodata(ctx, 0, 0x10, 0x80000100, "r", b, 0, null); + r.analyze(); + return r.disassemble(); +} + +test("string guesser: Shift-JIS text, 0x5C trail byte split, escapes", { skip: RABBITIZER_SKIP }, () => { + const out = stringRodata([ + [0x00, [0x82, 0xa0, 0x82, 0xa2, 0x41, 0x00, 0, 0]], + [0x08, [0x83, 0x5c, 0x0a, 0x22, 0x00, 0, 0, 0]], + ]); + assert.equal( + out, + `/* Generated by spimdisasm 1.42.4 */ + +.align 2 +nonmatching RO_STR_80000100 + +dlabel RO_STR_80000100 + /* 000000 80000100 */ .asciz "あいA" + /* 82A082A241000000 */ +.align 2 +enddlabel RO_STR_80000100 + +.align 2 +nonmatching RO_STR_80000108 + +dlabel RO_STR_80000108 + /* 000008 80000108 */ .ascii "\\x83" + .ascii "\\x5C" + .asciz "\\n\\"" + /* 835C0A2200000000 */ +.align 2 +enddlabel RO_STR_80000108 +`, + ); +}); + +test("string guesser: a Shift-JIS decode error keeps the symbol as words", { skip: RABBITIZER_SKIP }, () => { + // 0x85 0x40 is an unassigned JIS X 0208 row: CPython's shift_jis raises + const bad = stringRodata([[0x00, [0x85, 0x40, 0x42, 0x00]], [0x08, [0x41, 0x42, 0x00, 0x00]]]); + assert.match(bad, /dlabel RO_80000100\n {4}\/\* 000000 80000100 85404200 \*\/ \.word 0x85404200/); + assert.match(bad, /\.asciz "AB"/); + // One changed byte (0x85 0x40 -> 0x82 0x60, fullwidth A) flips it into a string + const good = stringRodata([[0x00, [0x82, 0x60, 0x42, 0x00]], [0x08, [0x41, 0x42, 0x00, 0x00]]]); + assert.match(good, /dlabel RO_STR_80000100/); + assert.notEqual(bad, good); + // The same bytes are not a string in ASCII + const ascii = stringRodata([[0x00, [0x82, 0x40, 0x42, 0x00]]], "ASCII"); + assert.match(ascii, /\.word 0x82404200/); +}); + +test("float and double text use Python's .10g/.18g formatting", { skip: RABBITIZER_SKIP }, () => { + const ctx = freshContext(); + const b = be([0x3f800000, 0x3dcccccd, 0x37800000, 0, 0x3fb99999, 0x9999999a, 0x7e37e43c, 0x8800759c]); + ctx.globalSegment.addSymbol(0x80000100).setTypeSpecial("f32", false); + ctx.globalSegment.addSymbol(0x80000110).setTypeSpecial("f64", false); + ctx.globalSegment.addSymbol(0x80000118).setTypeSpecial("f64", false); + const r = new mips.sections.SectionRodata(ctx, 0, 0x20, 0x80000100, "r", b, 0, null); + r.analyze(); + const out = r.disassemble(); + assert.match(out, /3F800000 \*\/ \.float 1\n/); + assert.match(out, /3DCCCCCD \*\/ \.float 0\.1000000015\n/); + assert.match(out, /37800000 \*\/ \.float 1\.525878906e-05\n/); + assert.match(out, /3FB999999999999A \*\/ \.double 0\.100000000000000006\n/); + assert.match(out, /7E37E43C8800759C \*\/ \.double 1\.00000000000000005e\+300\n/); + assert.match(out, /dlabel RO_FLT_80000100/); + assert.match(out, /\.align 3\nnonmatching RO_DBL_80000110/); +}); + +test("ContextSymbol default names and quoting", { skip: RABBITIZER_SKIP }, () => { + const ctx = freshContext(); + const seg = ctx.globalSegment; + assert.equal(seg.addFunction(0x80000400).getName(), "func_80000400"); + assert.equal(seg.addBranchLabel(0x80000404).getName(), ".L80000404"); + assert.equal(seg.addJumpTable(0x80000500).getName(), "jtbl_80000500"); + const d = seg.addSymbol(0x80000600, common.FileSectionType.Rodata); + assert.equal(d.getName(), "RO_80000600"); + d.setTypeSpecial("f32", false); + assert.equal(d.getName(), "RO_FLT_80000600"); + const b = seg.addSymbol(0x80000700, common.FileSectionType.Bss); + assert.equal(b.getName(), "B_80000700"); + common.GlobalConfig.AUTOGENERATED_NAMES_BASED_ON_SECTION_TYPE = false; + assert.equal(b.getName(), "D_80000700"); + const named = seg.addSymbol(0x80000800); + named.name = "has space"; + assert.equal(named.getName(), '"has space"'); + named.name = "a@b"; + assert.equal(named.getName(), '"a@b"'); + // 1.39 did not quote whitespace + freshContext("1.39.3"); + const s2 = new common.Context().globalSegment.addSymbol(0x80000800); + s2.name = "has space"; + assert.equal(s2.getName(), "has space"); +}); + +test("version selection resets defaults and pairs rabbitizer", { skip: RABBITIZER_SKIP }, () => { + assert.deepEqual(spim.configureVersion("1.35.0"), { spimdisasm: "1.35.0", rabbitizer: "1.13.0" }); + assert.equal(spim.__version__, "1.35.0"); + assert.equal(spim.rabbitizer.__version__, "1.13.0"); + assert.equal(common.GlobalConfig.ASM_TEXT_END_LABEL, ""); + assert.equal(common.GlobalConfig.ASM_EMIT_SIZE_DIRECTIVE, true); + assert.equal(common.Compiler.IDO.value.prevAlign_double, null); + assert.equal(common.Compiler.PSYQ.value.prevAlign_double, 3); + + spim.configureVersion("1.39.3"); + assert.equal(spim.rabbitizer.__version__, "1.14.3"); + assert.equal(common.GlobalConfig.ASM_NM_LABEL, "nonmatching"); + assert.equal(common.GlobalConfig.CREATE_BSS_PADS, undefined); + assert.equal(common.Compiler.MWCCPS2.value.bigAddendWorkaroundForMigratedFunctions, true); + + spim.configureVersion("1.42.4"); + assert.deepEqual([...spim.__version_info__], [1, 42, 4]); + assert.equal(common.GlobalConfig.CREATE_BSS_PADS, true); + assert.equal(common.Compiler.MWCCPS2.value.bigAddendWorkaroundForMigratedFunctions, false); + assert.throws(() => spim.configureVersion("1.40.0")); +}); + +test("bss pads from user-declared sizes (1.42 CREATE_BSS_PADS)", { skip: RABBITIZER_SKIP }, () => { + const ctx = freshContext(); + const s = ctx.globalSegment.addSymbol(0x80000900); + s.userDeclaredSize = 8; + const bss = new mips.sections.SectionBss(ctx, 0x10, 0x10, 0x80000900, 0x80000920, "b", 0, null); + bss.analyze(); + const out = bss.disassemble(); + assert.match(out, /dlabel B_80000900\n {4}\/\* 80000900 \*\/ \.space 0x08\n/); + assert.match(out, /Automatically generated and unreferenced pad \*\/\ndlabel B_80000908\n {4}\/\* 80000908 \*\/ \.space 0x18\n/); +}); diff --git a/packages/romdev-spimdisasm/test/elf32.test.mjs b/packages/romdev-spimdisasm/test/elf32.test.mjs new file mode 100644 index 00000000..8e0db00b --- /dev/null +++ b/packages/romdev-spimdisasm/test/elf32.test.mjs @@ -0,0 +1,270 @@ +// Tests for the elf32 port, on synthetic in-memory ELF32 MIPS objects. +import test from "node:test"; +import assert from "node:assert/strict"; + +import { RABBITIZER_SKIP } from "./helpers/payload.mjs"; + +// Loading the port loads romdev-rabbitizer's WASM; without that payload every +// test here skips with the reason instead of the file failing to import. +const { configureVersion, common, elf32 } = RABBITIZER_SKIP ? {} : await import("../src/index.js"); +const { Elf32File, Elf32HeaderFlag, Elf32SectionHeaderFlag, Elf32SectionHeaderType, Elf32ObjectFileType, Elf32Constants, Elf32Relocs } = elf32 ?? {}; + +const SHT = { NULL: 0, PROGBITS: 1, SYMTAB: 2, STRTAB: 3, NOBITS: 8, REL: 9, REGINFO: 0x70000006 }; + +/** Build a small relocatable MIPS ELF32 object. */ +function buildElf({ little = false, flags = 0x20921001, gp = -0x7ff0 } = {}) { + const u8 = []; + const w = (n, size) => { + for (let i = 0; i < size; i++) { + const shift = little ? i * 8 : (size - 1 - i) * 8; + u8.push(Number((BigInt.asUintN(64, BigInt(n)) >> BigInt(shift)) & 0xffn)); + } + }; + const bytesAt = () => u8.length; + const align = (a) => { + while (u8.length % a) u8.push(0); + }; + + // placeholder header, filled at the end + for (let i = 0; i < 0x34; i++) u8.push(0); + + const text = [0x27bdfff8, 0x0c000000, 0x00000000, 0x03e00008, 0x27bd0008]; + const textOff = bytesAt(); + for (const x of text) w(x, 4); + + const shstr = "\0.text\0.rel.text\0.symtab\0.strtab\0.shstrtab\0.reginfo\0.bss\0"; + const shName = (n) => shstr.indexOf(`\0${n}\0`) + 1; + const shstrOff = bytesAt(); + for (const c of shstr) u8.push(c.charCodeAt(0)); + + const str = "\0func_a\0data_b\0"; + const strOff = bytesAt(); + for (const c of str) u8.push(c.charCodeAt(0)); + align(4); + + // symtab: null, section .text, func_a (FUNC GLOBAL in .text), data_b (OBJECT LOCAL, UNDEF) + const symOff = bytesAt(); + const sym = (name, value, size, info, other, shndx) => { + w(name, 4); + w(value, 4); + w(size, 4); + u8.push(info, other); + w(shndx, 2); + }; + sym(0, 0, 0, 0, 0, 0); + sym(0, 0, 0, 0x03, 0, 1); + sym(1, 0, 0x14, 0x12, 0, 1); + sym(8, 0x10, 4, 0x01, 2, 0); + const symSize = bytesAt() - symOff; + + // .rel.text: R_MIPS_26 against func_a at 4, R_MIPS_HI16 against data_b at 0 + const relOff = bytesAt(); + w(4, 4); + w((2 << 8) | 4, 4); + w(0, 4); + w((3 << 8) | 5, 4); + const relSize = bytesAt() - relOff; + + // .reginfo + const regOff = bytesAt(); + w(0x800000f0, 4); + for (const x of [1, 2, 3, 0xffffffff]) w(x, 4); + w(gp, 4); + + align(4); + const shoff = bytesAt(); + const sh = (name, type, fl, addr, off, size, link, info, al, ent) => { + for (const x of [name, type, fl, addr, off, size, link, info, al, ent]) w(x, 4); + }; + sh(0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + sh(shName(".text"), SHT.PROGBITS, 0x6, 0, textOff, text.length * 4, 0, 0, 16, 0); + sh(shName(".rel.text"), SHT.REL, 0x40, 0, relOff, relSize, 3, 1, 4, 8); + sh(shName(".symtab"), SHT.SYMTAB, 0, 0, symOff, symSize, 4, 2, 4, 16); + sh(shName(".strtab"), SHT.STRTAB, 0, 0, strOff, str.length, 0, 0, 1, 0); + sh(shName(".shstrtab"), SHT.STRTAB, 0, 0, shstrOff, shstr.length, 0, 0, 1, 0); + sh(shName(".reginfo"), SHT.REGINFO, 0x2, 0, regOff, 0x18, 0, 0, 4, 0x18); + sh(shName(".bss"), SHT.NOBITS, 0x3, 0, regOff + 0x18, 0x40, 0, 0, 16, 0); + const shnum = 8; + + // header + const hdr = []; + const hw = (n, size) => { + for (let i = 0; i < size; i++) hdr.push((n >>> (little ? i * 8 : (size - 1 - i) * 8)) & 0xff); + }; + hdr.push(0x7f, 0x45, 0x4c, 0x46, 1, little ? 1 : 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0); + hw(1, 2); // REL + hw(8, 2); // EM_MIPS + hw(1, 4); + hw(0, 4); // entry + hw(0, 4); // phoff + hw(shoff, 4); + hw(flags, 4); + hw(0x34, 2); + hw(0, 2); + hw(0, 2); + hw(0x28, 2); + hw(shnum, 2); + hw(5, 2); // shstrndx + for (let i = 0; i < 0x34; i++) u8[i] = hdr[i]; + return Uint8Array.from(u8); +} + +function summarize(elf) { + return { + type: elf.header.type, + machine: elf.header.machine, + shnum: elf.header.shnum, + names: elf.sectionHeaders.sections.map((s) => elf.shstrtab.get(s.name)), + flags: elf.elfFlags.map((f) => f.name), + unknown: elf.unknownElfFlags, + syms: elf.symtab.symbols.map((s) => [elf.strtab.get(s.name), s.value, s.size, s.stBind, s.stType, s.other, s.shndx]), + rels: [...elf.relPerName.get(".text")].map((r) => [r.offset, r.rSym, r.rType]), + gp: elf.reginfo.gpValue, + cpr: elf.reginfo.cprmask, + exec: [...elf.progbitsExecute.keys()], + nobits: [...elf.nobitsPerName.keys()], + }; +} + +const EXPECTED = { + type: 1, + machine: 8, + shnum: 8, + names: ["", ".text", ".rel.text", ".symtab", ".strtab", ".shstrtab", ".reginfo", ".bss"], + flags: ["NOREORDER", "O32", "_5900", "ARCH_3"], + unknown: 0, + syms: [ + ["", 0, 0, 0, 0, 0, 0], + ["", 0, 0, 0, 3, 0, 1], + ["func_a", 0, 0x14, 1, 2, 0, 1], + ["data_b", 0x10, 4, 0, 1, 2, 0], + ], + rels: [ + [4, 2, 4], + [0, 3, 5], + ], + gp: -0x7ff0, + cpr: [1, 2, 3, 0xffffffff], + exec: [".text"], + nobits: [".bss"], +}; + +if (!RABBITIZER_SKIP) { + test.beforeEach(() => configureVersion("1.42.4")); + test.after(() => configureVersion("1.42.4")); +} + +for (const little of [false, true]) { + test(`parses a synthetic ${little ? "little" : "big"}-endian MIPS ELF32 object`, { skip: RABBITIZER_SKIP }, () => { + const elf = new Elf32File(buildElf({ little })); + assert.deepEqual(summarize(elf), EXPECTED); + assert.equal(common.GlobalConfig.ENDIAN, little ? common.InputEndian.LITTLE : common.InputEndian.BIG); + assert.equal(elf.header.type, Elf32ObjectFileType.REL.value); + assert.equal(elf.sectionHeaders.mipsText, elf.sectionHeaders.sections[1]); + assert.equal(elf.rel.get(common.FileSectionType.Text).sectionName, ".rel.text"); + assert.equal(Elf32Relocs.fromValue(elf.relPerName.get(".text").relocations[0].rType), Elf32Relocs.MIPS_26); + }); +} + +test("names used by the splat PS2 elf reader exist with Python semantics", { skip: RABBITIZER_SKIP }, () => { + const elf = new Elf32File(buildElf()); + assert.ok(elf.elfFlags.includes(Elf32Constants.Elf32HeaderFlag._5900)); + const [flags, unknown] = Elf32SectionHeaderFlag.parseFlags(elf.sectionHeaders.sections[7].flags); + assert.deepEqual(flags, [Elf32SectionHeaderFlag.WRITE, Elf32SectionHeaderFlag.ALLOC]); + assert.equal(unknown, 0); + assert.equal(Elf32Constants.Elf32SectionHeaderType.fromValue(8), Elf32SectionHeaderType.NOBITS); + assert.equal(Elf32Constants.Elf32SectionHeaderType.fromValue(0x12345), null); + const sorted = [...elf.sectionHeaders].sort((a, b) => a.offset - b.offset); + assert.equal(sorted.length, 8); + // SHN special indices and out-of-range behaviour of Elf32SectionHeaders.__getitem__ + assert.equal(elf.sectionHeaders.get(0), null); + assert.equal(elf.sectionHeaders.get(0xff01), elf.sectionHeaders.mipsText); + assert.equal(elf.sectionHeaders.get(9), null); + assert.throws(() => elf.sectionHeaders.get(8), /index out of range/); + // Enum aliases resolve to the same member + const { OsAbi } = Elf32Constants.Elf32HeaderIdentifier; + assert.equal(OsAbi.SYSV, OsAbi.NONE); + assert.equal(OsAbi.LINUX, OsAbi.GNU); + assert.equal([...OsAbi].length, 14); +}); + +test("header flag parsing keeps unknown bits", { skip: RABBITIZER_SKIP }, () => { + const [flags, unknown] = Elf32HeaderFlag.parseFlags(0x40000000 | 0x00ab0000 | 0x800 | 0x2); + assert.deepEqual(flags.map((f) => f.name), ["PIC", "ARCH_5"]); + assert.equal(unknown, 0x00ab0800); + const [f2, u2] = Elf32HeaderFlag.parseFlags(0x90000000); + assert.deepEqual(f2, []); + assert.equal(u2, 0x90000000); +}); + +test("handleFlags version gates (ARCH_5 level, N64 ABI)", { skip: RABBITIZER_SKIP }, () => { + const arch5 = buildElf({ flags: 0x40001000 }); + configureVersion("1.42.4"); + new Elf32File(arch5).handleFlags(); + assert.equal(common.GlobalConfig.ARCHLEVEL, common.ArchLevel.MIPS4); + configureVersion("1.39.3"); + new Elf32File(arch5).handleFlags(); + assert.equal(common.GlobalConfig.ARCHLEVEL, common.ArchLevel.MIPS5); + + const n64 = buildElf({ flags: 0x20002020 }); + configureVersion("1.39.3"); + new Elf32File(n64).handleFlags(); + assert.equal(common.GlobalConfig.ABI, common.Abi.N64); + configureVersion("1.35.0"); + new Elf32File(n64).handleFlags(); + assert.equal(common.GlobalConfig.ABI, common.Abi.N32); + + configureVersion("1.42.4"); + new Elf32File(buildElf({ flags: 0x00000006 })).handleFlags(); + assert.equal(common.GlobalConfig.PIC, true); +}); + +test("perturbing one byte changes the parse result", { skip: RABBITIZER_SKIP }, () => { + const good = buildElf(); + const base = summarize(new Elf32File(good)); + assert.deepEqual(base, EXPECTED); + + // e_flags low byte: NOREORDER cleared + const flagsByte = good.slice(); + flagsByte[0x27] ^= 0x01; + assert.notDeepEqual(summarize(new Elf32File(flagsByte)), base); + + // a relocation info byte (rType of the first entry) + const elf = new Elf32File(good); + const relOff = elf.sectionHeaders.sections[2].offset; + const relByte = good.slice(); + relByte[relOff + 7] = 6; + assert.notDeepEqual(summarize(new Elf32File(relByte)), base); + + // magic and class bytes are rejected + const magic = good.slice(); + magic[1] = 0x46; + assert.throws(() => new Elf32File(magic), /wrong magic/); + const cls = good.slice(); + cls[4] = 2; + assert.throws(() => new Elf32File(cls), /Unsupported ELF file class/); + const enc = good.slice(); + enc[5] = 0; + assert.throws(() => new Elf32File(enc), /Unsupported ELF data encoding/); +}); + +test("string table iteration and readelf output", { skip: RABBITIZER_SKIP }, () => { + const elf = new Elf32File(buildElf()); + assert.deepEqual([...elf.strtab], ["", "func_a", "data_b"]); + const chunks = []; + const orig = process.stdout.write.bind(process.stdout); + process.stdout.write = (s) => { + chunks.push(String(s)); + return true; + }; + try { + elf.readelf_sectionHeaders(); + elf.readelf_syms(); + } finally { + process.stdout.write = orig; + } + const text = chunks.join(""); + assert.match(text, /\n {2}\[ 1\] \.text {14}PROGBITS {8}00000000 000034 000014 00 {2}AX {2}0 {2} 0 10\n/); + assert.match(text, / {4}2: 00000000 {4}14 FUNC {4}GLOBAL DEFAULT {13}\.text func_a\n/); + assert.match(text, / {4}3: 00000010 {5}4 OBJECT {2}LOCAL {2}HIDDEN {14}UNDEF data_b\n/); +}); diff --git a/packages/romdev-spimdisasm/test/helpers/payload.mjs b/packages/romdev-spimdisasm/test/helpers/payload.mjs new file mode 100644 index 00000000..57c9b1ac --- /dev/null +++ b/packages/romdev-spimdisasm/test/helpers/payload.mjs @@ -0,0 +1,26 @@ +// payload.mjs - is romdev-rabbitizer's WASM here, or why not. +// +// spimdisasm decodes every instruction through romdev-rabbitizer, whose +// wasm/ payload is gitignored: a dev box builds it, CI fills it from the +// published npm tarball (scripts/fetch-payloads.mjs). Loading src/index.js +// without it throws ENOENT before a single test is registered, which reads +// like a broken port. Tests that need it import the package dynamically and +// skip with this reason instead, the contract romdevtools' test-rom.js set. + +import { existsSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const RABBITIZER_VERSIONS = ["1.16.2", "1.14.3", "1.13.0"]; + +function rabbitizerDir() { + try { return path.resolve(path.dirname(fileURLToPath(import.meta.resolve("romdev-rabbitizer"))), ".."); } catch { return null; } +} + +/** false when every shipped rabbitizer WASM is present, else the skip reason. */ +export const RABBITIZER_SKIP = (() => { + const dir = rabbitizerDir(); + if (!dir) return "romdev-rabbitizer is not installed"; + const absent = RABBITIZER_VERSIONS.map((v) => `wasm/rabbitizer-${v}.wasm`).filter((f) => !existsSync(path.join(dir, f))); + return absent.length ? `romdev-rabbitizer payload absent (${absent.join(", ")}): gitignored WASM, built by packages/romdevtools/scripts/build-rabbitizer.sh or filled from npm by scripts/fetch-payloads.mjs` : false; +})(); diff --git a/packages/romdev-spimdisasm/test/pyfloat.test.mjs b/packages/romdev-spimdisasm/test/pyfloat.test.mjs new file mode 100644 index 00000000..e7d7c9de --- /dev/null +++ b/packages/romdev-spimdisasm/test/pyfloat.test.mjs @@ -0,0 +1,111 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { formatG, floatRepr, wordToFloat, qwordToDouble } from "../src/py/pyfloat.js"; + +// Expected strings are derived from CPython's format_float_short +// (Python/pystrtod.c) with dtoa mode 2 for '.Ng' and mode 0 for repr. + +test("formatG .10g basics", () => { + const cases = [ + [0, "0"], + [-0, "-0"], + [1, "1"], + [-1, "-1"], + [100, "100"], + [0.5, "0.5"], + [1.5, "1.5"], + [1234567890, "1234567890"], + [1e10, "1e+10"], + [12345678901, "1.23456789e+10"], + [0.0001, "0.0001"], + [0.00001, "1e-05"], + [1.5e20, "1.5e+20"], + [1e100, "1e+100"], + [1e-100, "1e-100"], + [Infinity, "inf"], + [-Infinity, "-inf"], + [NaN, "nan"], + ]; + for (const [x, want] of cases) { + assert.equal(formatG(x, 10), want, `formatG(${x}, 10)`); + } +}); + +test("formatG rounds exact ties to even, unlike toPrecision", () => { + // 2**-15 == 3.0517578125e-05 exactly: 11 digits, the 11th is a 5 tie, + // previous digit 2 is even so it stays. + assert.equal(formatG(2 ** -15, 10), "3.051757812e-05"); + assert.notEqual((2 ** -15).toPrecision(10), "3.051757812e-05"); + // 3 * 2**-15 == 9.1552734375e-05 exactly: tie with odd previous digit. + assert.equal(formatG(3 * 2 ** -15, 10), "9.155273438e-05"); + // 2**-16 == 1.52587890625e-05: not a tie (rest is "25"). + assert.equal(formatG(2 ** -16, 10), "1.525878906e-05"); + // 2.5 at .1g: tie, 2 even -> 2; 3.5 -> 4 + assert.equal(formatG(2.5, 1), "2"); + assert.equal(formatG(3.5, 1), "4"); + assert.equal(formatG(0.125, 2), "0.12"); + assert.equal(formatG(0.375, 2), "0.38"); +}); + +test("formatG on float32 values widened to double (.float path)", () => { + assert.equal(formatG(wordToFloat(0x3DCCCCCD), 10), "0.1000000015"); + assert.equal(formatG(wordToFloat(0x3F800000), 10), "1"); + assert.equal(formatG(wordToFloat(0xBF800000), 10), "-1"); + assert.equal(formatG(wordToFloat(0x80000000), 10), "-0"); + assert.equal(formatG(wordToFloat(0x7F7FFFFF), 10), "3.402823466e+38"); + assert.equal(formatG(wordToFloat(0x00000001), 10), "1.401298464e-45"); + // float32 0.0001 == 9.99999974737875...e-05, so it goes exponential + assert.equal(formatG(wordToFloat(0x38D1B717), 10), "9.999999747e-05"); + assert.equal(formatG(wordToFloat(0x40490FDB), 10), "3.141592741"); + assert.equal(formatG(wordToFloat(0x7F800000), 10), "inf"); + // 999999.9999 area: carry that bumps the exponent + assert.equal(formatG(9999999999.5, 10), "1e+10"); + assert.equal(formatG(0.999999999975, 10), "1"); +}); + +test("formatG .18g (.double path)", () => { + assert.equal(formatG(0.1, 18), "0.100000000000000006"); + assert.equal(formatG(1 / 3, 18), "0.333333333333333315"); + assert.equal(formatG(2 ** 60, 18), "1.15292150460684698e+18"); + assert.equal(formatG(1, 18), "1"); + assert.equal(formatG(3.141592653589793, 18), "3.14159265358979312"); + assert.equal(formatG(1e-5, 18), "1.00000000000000008e-05"); + assert.equal(formatG(qwordToDouble(0x3FF0000000000000n), 18), "1"); +}); + +test("floatRepr", () => { + const cases = [ + [0, "0.0"], + [-0, "-0.0"], + [1, "1.0"], + [100, "100.0"], + [1.5, "1.5"], + [0.1, "0.1"], + [0.0001, "0.0001"], + [0.00001, "1e-05"], + [1e15, "1000000000000000.0"], + [1e16, "1e+16"], + [1.5e20, "1.5e+20"], + [123456789012345680, "1.2345678901234568e+17"], + [1e22, "1e+22"], + [5e-324, "5e-324"], + [1.7976931348623157e308, "1.7976931348623157e+308"], + [Infinity, "inf"], + [-Infinity, "-inf"], + [NaN, "nan"], + ]; + for (const [x, want] of cases) { + assert.equal(floatRepr(x), want, `floatRepr(${x})`); + } +}); + +test("wordToFloat / qwordToDouble", () => { + assert.equal(wordToFloat(0x3F800000), 1); + assert.equal(wordToFloat(0xC0000000), -2); + assert.equal(wordToFloat(0x3DCCCCCD), Math.fround(0.1)); + assert.equal(qwordToDouble(0x3FF0000000000000n), 1); + assert.equal(qwordToDouble(0xC000000000000000n), -2); + assert.equal(qwordToDouble(0x3FB999999999999An), 0.1); + assert.ok(Object.is(qwordToDouble(0x8000000000000000n), -0)); +}); diff --git a/packages/romdev-spimdisasm/test/pyset.test.mjs b/packages/romdev-spimdisasm/test/pyset.test.mjs new file mode 100644 index 00000000..fe2dd410 --- /dev/null +++ b/packages/romdev-spimdisasm/test/pyset.test.mjs @@ -0,0 +1,131 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { PySet, pyHashInt, pyHashTuple, pyHash, PY_HASH_NONE } from "../src/py/pyset.js"; + +// Expected orders are hand-simulated from CPython's Objects/setobject.c: +// slot = hash & mask, LINEAR_PROBES=9 only while i+9 <= mask, then +// perturb >>= 5; i = (i*5 + 1 + perturb) & mask; resize when +// fill*5 >= mask*3 to the smallest power of two > used*4. + +const order = (s) => [...s]; + +test("small table collisions use perturbed probing", () => { + // 1 -> slot 1; 9 -> slot 1 taken, i=(1*5+1)&7=6; 17 -> 1, 6, then 7 + assert.deepEqual(order(new PySet([1, 9, 17])), [1, 9, 17]); + assert.deepEqual(order(new PySet([17, 9, 1])), [17, 9, 1]); + // no collisions: slot order, not insertion order + assert.deepEqual(order(new PySet([5, 1, 3])), [1, 3, 5]); +}); + +test("addresses with high bits", () => { + // 0x80000004 -> slot 4, 0x80000008 -> slot 0 + assert.deepEqual(order(new PySet([0x80000004, 0x80000008])), [0x80000008, 0x80000004]); + // 0x80000010: slot 0 taken, perturb=0x4000000, i=1 taken, + // perturb=0x200000, i=(5+1+0x200000)&7=6 + const s = new PySet([0x80000010, 0x80000008, 0x80000000]); + assert.deepEqual(s._debugSlots().map((x) => (x === "" ? "" : x.toString(16))), + ["80000010", "80000008", "", "", "", "", "80000000", ""]); +}); + +test("resize at fill*5 >= mask*3 reinserts in old slot order", () => { + const s = new PySet([40, 1, 2, 3]); + assert.deepEqual(order(s), [40, 1, 2, 3]); // 40 & 7 == 0 + s.add(4); // fill 5 -> resize to 32 slots, 40 & 31 == 8 + assert.deepEqual(order(s), [1, 2, 3, 4, 40]); + assert.equal(s._mask, 31); + // linear probing in the 32 slot table: 33 & 31 == 1, slots 2..4 taken + s.add(33); + assert.deepEqual(order(s), [1, 2, 3, 4, 33, 40]); +}); + +test("discard leaves a dummy that the next colliding add reuses", () => { + const s = new PySet([1, 9]); + assert.equal(s.delete(1), true); + assert.equal(s.delete(1), false); + s.add(17); // slot 1 dummy remembered, 6 has 9, 7 empty -> goes to dummy slot 1 + assert.deepEqual(order(s), [17, 9]); + s.add(1); // 1 -> 17 at slot 1, 9 at 6, empty 7 + assert.deepEqual(order(s), [17, 9, 1]); + assert.equal(s.size, 3); +}); + +test("negative ints hash like CPython", () => { + assert.equal(pyHashInt(-1), -2n); + assert.equal(pyHashInt(-2), -2n); + assert.equal(pyHashInt(2n ** 61n - 1n), 0n); + assert.equal(pyHashInt(2n ** 61n), 1n); + assert.equal(pyHashInt(-(2n ** 61n)), -1n - 1n); // -1 -> -2 + // 0 -> 0, -1 (hash -2, slot 6), 2 -> 2, -2 (hash -2, not equal to -1) + // probes slot 6 until perturb runs out, then (6*5+1)&7 == 7 + assert.deepEqual(order(new PySet([0, -1, 2, -2])), [0, 2, -1, -2]); +}); + +test("numbers and bigints are the same Python int", () => { + const s = new PySet([1, 2n, 3]); + assert.equal(s.has(1n), true); + assert.equal(s.has(2), true); + s.add(2); + assert.equal(s.size, 3); +}); + +test("set operations follow CPython iteration rules", () => { + const a = new PySet([1, 9, 17]); + const b = new PySet([17, 1]); + // the smaller set is iterated: b is [17, 1] + assert.deepEqual(order(a.intersection(b)), [17, 1]); + assert.deepEqual(order(b.intersection(a)), [17, 1]); + assert.deepEqual(order(a.difference(b)), [9]); + assert.deepEqual(order(a.union(new PySet([2]))), [1, 2, 9, 17]); + assert.deepEqual(order(a.copy()), order(a)); + assert.equal(a.isdisjoint(new PySet([2, 3])), true); + assert.equal(a.isdisjoint([3, 9]), false); + const c = new PySet([1, 2, 3]); + c.update([40]); + assert.deepEqual(order(c), [40, 1, 2, 3]); + c.clear(); + assert.equal(c.size, 0); + assert.deepEqual(order(c), []); +}); + +test("perturbing one inserted value changes the order", () => { + // Same as the first case but 17 -> 25 (25 & 7 == 1 too, perturb 0): + // collision chain is identical so order is unchanged... + assert.deepEqual(order(new PySet([1, 9, 25])), [1, 9, 25]); + // ...while 17 -> 16 lands in slot 0 and moves to the front. + const perturbed = order(new PySet([1, 9, 16])); + assert.notDeepEqual(perturbed, [1, 9, 16]); + assert.deepEqual(perturbed, [16, 1, 9]); +}); + +test("tuple and None hashes", () => { + assert.equal(PY_HASH_NONE, 0xFCA86420n); + assert.equal(pyHash(null), 0xFCA86420n); + // hash(()) on 64-bit CPython 3.8+ + assert.equal(pyHashTuple([]), 5740354900026072187n); + // hash((1, 2)) on 64-bit CPython 3.8+ + assert.equal(pyHashTuple([1, 2]), -3550055125485641917n); + assert.notEqual(pyHashTuple([0x80000000, null]), pyHashTuple([0x80000000, 0])); +}); + +test("custom hash/eq for non-int members", () => { + const hash = (o) => pyHashTuple([o.address, o.vrom]); + const eq = (x, y) => x.address === y.address && x.vrom === y.vrom; + const s = new PySet(null, { hash, eq }); + const a = { address: 0x80001000, vrom: null }; + s.add(a); + s.add({ address: 0x80001000, vrom: null }); + assert.equal(s.size, 1); + assert.equal(s.has({ address: 0x80001000, vrom: null }), true); + s.add({ address: 0x80001004, vrom: 0x1004 }); + assert.equal(s.size, 2); +}); + +test("iterating while mutating throws like CPython", () => { + const s = new PySet([1, 2, 3]); + assert.throws(() => { + for (const k of s) { + s.add(k + 100); + } + }); +}); diff --git a/packages/romdev-splat/LICENSE b/packages/romdev-splat/LICENSE new file mode 100644 index 00000000..059e530e --- /dev/null +++ b/packages/romdev-splat/LICENSE @@ -0,0 +1,96 @@ +MIT License + +Copyright (c) 2021 Ethan Roseman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +src/n64img/image.js is a port of n64img: + +MIT License + +Copyright (c) 2022 Decompals + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +src/n64img/png.js is a port of part of pypng (png.py): + +Copyright (C) 2006 Johann C. Rocholl +Portions Copyright (C) 2009 David Jones +And probably portions Copyright (C) 2006 Nicko van Someren + +LICENCE (MIT) + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation files +(the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +src/wasm/zlib-stream.wasm contains zlib: + +Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. diff --git a/packages/romdev-splat/NOTICE b/packages/romdev-splat/NOTICE new file mode 100644 index 00000000..5790361c --- /dev/null +++ b/packages/romdev-splat/NOTICE @@ -0,0 +1,47 @@ +romdev-splat +============ + +This package is a JavaScript port of splat, the binary splitting tool used by +N64/PS1 decompilation projects, made for romdev. Its output (assembly files, +linker scripts, dependency files, undefined symbol files, binary and image +assets, C stubs, symbol dumps) is byte-identical to Python splat's for the +same inputs. It is licensed under the MIT License (see LICENSE). + +Components and attribution +-------------------------- + +1. splat + https://github.com/ethteck/splat + Ported from splat64 0.37.1 (PyPI sdist / tag v0.37.1), with the behaviour + of splat64 0.34.1 reproduced behind a version option. + Copyright (c) 2021 Ethan Roseman and the splat contributors. + Licensed under the MIT License (LICENSE). + src/**/*.js are module-by-module translations of splat/**/*.py + (scripts/split.py, util/, segtypes/, disassembler/, platforms/). + +2. n64img + https://github.com/decompals/n64img + src/n64img/image.js is a translation of n64img 0.3.3 (image.py, iter.py). + Copyright (c) 2022 Decompals. MIT License (LICENSE). + +3. pypng + https://gitlab.com/drj11/pypng + src/n64img/png.js translates the Writer code paths of png.py + (pypng 0.20220715.0) that n64img uses. + Copyright (C) 2006 Johann C. Rocholl, portions (C) 2009 David Jones, + (C) 2006 Nicko van Someren. MIT License (LICENSE). + +4. zlib + https://zlib.net + src/wasm/zlib-stream.wasm is vanilla zlib (emscripten's zlib port, + emsdk 4.0.18: zlib 1.3.1) with a small stream API + (packages/romdevtools/scripts/src/zlib-stream.c in the romdev repository, + built by scripts/build-zlib-wasm.sh). zlib License (LICENSE). + +5. Project extension segtypes + src/ext/index.js contains JS translations of splat extension segtypes + (extensions_path/*.py) shipped by specific decompilation projects, each + identified by the sha256 of its Python source. + +Not contained in this package: the disassembler (romdev-spimdisasm, a port +of spimdisasm, and romdev-rabbitizer), loaded at run time. diff --git a/packages/romdev-splat/README.md b/packages/romdev-splat/README.md new file mode 100644 index 00000000..0346cccb --- /dev/null +++ b/packages/romdev-splat/README.md @@ -0,0 +1,70 @@ +# romdev-splat + +A plain JavaScript (ESM) port of [splat](https://github.com/ethteck/splat), the +binary splitting tool N64 and PS1 decompilation projects use to cut a ROM or +executable into assembly, data, asset and linker-script files from a YAML +config. For the same inputs its output (assembly, linker scripts, dependency +files, undefined-symbol files, binary and image assets, C stubs, symbol dumps) +is byte-identical to Python splat's. No Python is needed. + +It is part of [romdev](https://github.com/monteslu/romdev). + +## Upstream and license + +- Upstream: splat (Ethan Roseman and contributors), https://github.com/ethteck/splat +- Ported from splat64 0.37.1 (tag `v0.37.1`), with the behaviour of splat64 + 0.34.1 reproduced behind a version option. +- Also translated: [n64img](https://github.com/decompals/n64img) 0.3.3 (MIT) + and the writer paths of [pypng](https://gitlab.com/drj11/pypng) + 0.20220715.0 (MIT). `src/wasm/zlib-stream.wasm` is zlib 1.3.1 (zlib license) + with a small stream API. +- `src/ext/` holds JS translations of splat extension segtypes that specific + decomp projects ship, each identified by the sha256 of its Python source. +- License: MIT. See `LICENSE` and `NOTICE`. + +## How romdev uses it + +romdevtools' `decomp` tool runs it when a project's own setup recipe calls +`splat split` (`decomp({op:'setup'})`, `decomp({op:'import'})`). The splat and +spimdisasm versions are read from what the project pins (`uv.lock`, +requirements files or a vendored copy). + +## Command line + +```sh +npx romdev-splat split config/game.yaml --modes all +``` + +The bin is `romdev-splat`. It mirrors `splat split`: `CONFIG...`, `--modes`, +`--verbose`, `--use-cache`, `--skip-version-check`, `--stdout-only`, +`--disassemble-all`, `--make-full-disasm-for-code`, plus +`--splat-version V|auto`, `--spimdisasm-version V|auto`, `--cwd DIR` and +`--base-path DIR`. Only the `split` command is ported. + +## API + +```js +import { split } from "romdev-splat"; + +const r = await split(["config/game.yaml"], { cwd: "/path/to/project" }); +// { exitCode, stdout, stderr, error, splatVersion, spimdisasmVersion, extensions } +``` + +`split(configPaths, options)` never reads or changes `process.cwd()`: relative +paths resolve against `options.cwd`. Options include `modes`, `splatVersion` +(`'0.37.1'` default, `'0.34.1'` or `'auto'`), `spimdisasmVersion`, `basePath`, +`backend` (a `{ spimdisasm, rabbitizer }` pair to use instead of the +dependencies) and `onOutput`. Calls are queued, so concurrent splits run one at +a time. Also exported: `detectProjectVersions`, `SUPPORTED_SPLAT_VERSIONS`, +`DEFAULT_SPLAT_VERSION`, `PORTED_EXTENSIONS`, `SplatError`. Exports: `.` only. + +## Requirements + +Node >= 24, ESM only. Depends on +[`romdev-spimdisasm`](https://www.npmjs.com/package/romdev-spimdisasm), +[`romdev-rabbitizer`](https://www.npmjs.com/package/romdev-rabbitizer) and +`yaml`. No Python, no native code. + +## Versions + +romdev-splat 0.1.0 ports splat64 0.37.1 (and reproduces 0.34.1). diff --git a/packages/romdev-splat/package.json b/packages/romdev-splat/package.json new file mode 100644 index 00000000..c687cea1 --- /dev/null +++ b/packages/romdev-splat/package.json @@ -0,0 +1,41 @@ +{ + "name": "romdev-splat", + "version": "0.1.0", + "description": "splat (the N64/PS1 decomp binary splitter) ported to plain JavaScript ESM, for romdev. Output is byte-identical to Python splat 0.37.1 / 0.34.1.", + "type": "module", + "main": "src/index.js", + "exports": { + ".": "./src/index.js", + "./package.json": "./package.json" + }, + "bin": { + "romdev-splat": "src/cli.js" + }, + "files": [ + "src", + "LICENSE", + "NOTICE" + ], + "scripts": { + "test": "node --test --test-concurrency=4 'test/**/*.test.mjs'" + }, + "engines": { + "node": ">=24" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/monteslu/romdev.git", + "directory": "packages/romdev-splat" + }, + "homepage": "https://github.com/monteslu/romdev#readme", + "bugs": { + "url": "https://github.com/monteslu/romdev/issues" + }, + "author": "Luis Montes", + "dependencies": { + "romdev-rabbitizer": "0.1.0", + "romdev-spimdisasm": "0.1.0", + "yaml": "2.9.0" + } +} diff --git a/packages/romdev-splat/scripts/build-zlib-wasm.sh b/packages/romdev-splat/scripts/build-zlib-wasm.sh new file mode 100755 index 00000000..becf2cd6 --- /dev/null +++ b/packages/romdev-splat/scripts/build-zlib-wasm.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Build src/wasm/zlib-stream.wasm: vanilla zlib (emscripten's zlib port, +# emsdk 4.0.18 = zlib 1.3.1) with a small deflate-stream API +# (packages/romdevtools/scripts/src/zlib-stream.c). romdev-splat writes PNG +# IDAT data through it so the bytes match CPython's zlib module; Node's zlib +# is Chromium's fork and writes different streams. +# +# Standalone WASM (no JS glue): src/zlib.js instantiates it directly. +# Host deps (build time only): emcc (emsdk 4.0.18). +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +PKG="$(cd "$HERE/.." && pwd)" +SRC="$PKG/../romdevtools/scripts/src/zlib-stream.c" +OUT="$PKG/src/wasm/zlib-stream.wasm" +if [ -n "${EMSDK:-}" ] && [ -f "$EMSDK/emsdk_env.sh" ]; then + # shellcheck source=/dev/null + source "$EMSDK/emsdk_env.sh" > /dev/null 2>&1 +fi +command -v emcc >/dev/null || { echo "emcc is required" >&2; exit 1; } +mkdir -p "$(dirname "$OUT")" +emcc -O2 -sUSE_ZLIB=1 -sSTANDALONE_WASM=1 --no-entry -sALLOW_MEMORY_GROWTH=1 \ + -sINITIAL_MEMORY=16777216 -sSTACK_SIZE=65536 -sFILESYSTEM=0 \ + -sEXPORTED_FUNCTIONS=_zs_malloc,_zs_mfree,_zs_new,_zs_compress,_zs_out_ptr,_zs_out_len,_zs_free,_zs_crc32 \ + "$SRC" -o "$OUT" +echo "zlib-stream -> $OUT ($(wc -c < "$OUT") bytes)" diff --git a/packages/romdev-splat/src/cli.js b/packages/romdev-splat/src/cli.js new file mode 100755 index 00000000..cce7c18d --- /dev/null +++ b/packages/romdev-splat/src/cli.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node +// romdev-splat CLI, mirroring `splat split`: +// romdev-splat [split] CONFIG... [--modes M...] [--verbose] [--use-cache] +// [--skip-version-check] [--stdout-only] [--disassemble-all] +// [--make-full-disasm-for-code] [--splat-version V|auto] +// [--spimdisasm-version V|auto] [--cwd DIR] [--base-path DIR] +import { split } from './index.js'; + +const argv = process.argv.slice(2); +if (argv[0] === 'split') argv.shift(); +if (argv[0] === '-V' || argv[0] === '--version') { + const { default: pkg } = await import('../package.json', { with: { type: 'json' } }); + console.log(`romdev-splat ${pkg.version} (splat 0.37.1 / 0.34.1)`); + process.exit(0); +} + +const configs = []; +const o = {}; +for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const val = () => { + if (i + 1 >= argv.length) { console.error(`${a} needs a value`); process.exit(2); } + return argv[++i]; + }; + switch (a) { + case '--modes': { + o.modes = []; + while (i + 1 < argv.length && !argv[i + 1].startsWith('--')) o.modes.push(argv[++i]); + break; + } + case '--verbose': o.verbose = true; break; + case '--use-cache': o.useCache = true; break; + case '--skip-version-check': o.skipVersionCheck = true; break; + case '--stdout-only': o.stdoutOnly = true; break; + case '--disassemble-all': o.disassembleAll = true; break; + case '--make-full-disasm-for-code': o.makeFullDisasmForCode = true; break; + case '--splat-version': o.splatVersion = val(); break; + case '--spimdisasm-version': o.spimdisasmVersion = val(); break; + case '--cwd': o.cwd = val(); break; + case '--base-path': o.basePath = val(); break; + case '-h': case '--help': + console.log('usage: romdev-splat [split] CONFIG [CONFIG ...] [--modes MODES ...] [--verbose] [--use-cache] [--skip-version-check] [--stdout-only] [--disassemble-all] [--make-full-disasm-for-code] [--splat-version V|auto] [--spimdisasm-version V|auto] [--cwd DIR] [--base-path DIR]'); + process.exit(0); + break; + default: + if (a.startsWith('--')) { console.error(`unknown option ${a}`); process.exit(2); } + configs.push(a); + } +} +if (!configs.length) { console.error('at least one config yaml is required'); process.exit(2); } + +const r = await split(configs, { ...o, onOutput: (stream, text) => (stream === 'stderr' ? process.stderr : process.stdout).write(text) }); +process.exitCode = r.exitCode; diff --git a/packages/romdev-splat/src/disassembler/disassembler_instance.js b/packages/romdev-splat/src/disassembler/disassembler_instance.js new file mode 100644 index 00000000..709d0049 --- /dev/null +++ b/packages/romdev-splat/src/disassembler/disassembler_instance.js @@ -0,0 +1,127 @@ +// splat.disassembler.disassembler_instance + spimdisasm_disassembler +import { atLeast } from '../runtime.js'; +import * as log from '../util/log.js'; +import { opts } from '../util/options.js'; +import { spim, rabbitizer } from './spim.js'; + +class NullDisassembler { + configure() {} + check_version() {} + known_types() { return new Set(); } +} + +function versionTuple(v) { return String(v).split('.').map((x) => parseInt(x, 10)); } +function tupleLt(a, b) { + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const x = a[i] || 0; const y = b[i] || 0; + if (x !== y) return x < y; + } + return false; +} + +class SpimdisasmDisassembler { + get SPIMDISASM_MIN() { return atLeast('0.35.0') ? [1, 39, 0] : [1, 33, 0]; } + + configure() { + const S = spim(); + const R = rabbitizer(); + const G = S.common.GlobalConfig; + const modern = atLeast('0.35.0'); + + G.PRODUCE_SYMBOLS_PLUS_OFFSET = true; + G.TRUST_USER_FUNCTIONS = true; + G.TRUST_JAL_FUNCTIONS = true; + G.GLABEL_ASM_COUNT = false; + G.ASM_COMMENT_OFFSET_WIDTH = opts.rom_address_padding ? 6 : 0; + G.AUTOGENERATED_NAMES_BASED_ON_SECTION_TYPE = false; + G.AUTOGENERATED_NAMES_BASED_ON_DATA_TYPE = false; + G.SYMBOL_FINDER_FILTERED_ADDRESSES_AS_HILO = false; + if (opts.rodata_string_guesser_level !== null) G.RODATA_STRING_GUESSER_LEVEL = opts.rodata_string_guesser_level; + if (opts.data_string_guesser_level !== null) G.DATA_STRING_GUESSER_LEVEL = opts.data_string_guesser_level; + + R.config.regNames_userFpcCsr = false; + R.config.regNames_vr4300Cop0NamedRegisters = false; + R.config.misc_opcodeLJust = opts.mnemonic_ljust - 1; + R.config.regNames_gprAbiNames = R.Abi.fromStr(opts.mips_abi_gpr); + R.config.regNames_fprAbiNames = R.Abi.fromStr(opts.mips_abi_float_regs); + + G.ENDIAN = opts.endianness === 'big' ? S.common.InputEndian.BIG : S.common.InputEndian.LITTLE; + + R.config.pseudos_pseudoMove = false; + + const selected = opts.compiler; + const spimCompiler = S.common.Compiler.fromStr(selected.name); + if (spimCompiler === null || spimCompiler === undefined) { + log.write(`Unsupported selected compiler for spimdisasm: ${selected.name}`, { status: 'error' }); + log.error(`The following options are supported: [${Object.keys(S.common.compilerOptions).map((k) => `'${k}'`).join(', ')}]`); + } + G.COMPILER = spimCompiler; + if (selected.name === 'SN64') { + R.config.regNames_namedRegisters = false; + R.config.toolchainTweaks_sn64DivFix = true; + G.ASM_COMMENT = false; + G.SYMBOL_FINDER_FILTERED_ADDRESSES_AS_HILO = false; + } + if (modern && opts.align_on_branch_labels) G.ASM_EMIT_ALIGN_BRANCH_LABELS = true; + R.config.toolchainTweaks_treatJAsUnconditionalBranch = selected.j_as_branch; + + G.DETECT_REDUNDANT_FUNCTION_END = opts.detect_redundant_function_end; + G.GP_VALUE = opts.gp; + + G.ASM_TEXT_LABEL = opts.asm_function_macro; + G.ASM_TEXT_ALT_LABEL = opts.asm_function_alt_macro; + G.ASM_JTBL_LABEL = opts.asm_jtbl_label_macro; + G.ASM_DATA_LABEL = opts.asm_data_macro; + G.ASM_TEXT_END_LABEL = opts.asm_end_label; + if (modern) G.ASM_DATA_END_LABEL = opts.asm_data_end_label; + G.ASM_EHTBL_LABEL = opts.asm_ehtable_label_macro; + if (modern) G.ASM_NM_LABEL = opts.asm_nonmatching_label_macro; + + if (opts.asm_emit_size_directive !== null) G.ASM_EMIT_SIZE_DIRECTIVE = opts.asm_emit_size_directive; + + if (G.ASM_TEXT_LABEL === '.globl') { + G.ASM_TEXT_ENT_LABEL = '.ent'; + G.ASM_TEXT_FUNC_AS_LABEL = true; + } + if (G.ASM_DATA_LABEL === '.globl') G.ASM_DATA_SYM_AS_LABEL = true; + + G.LINE_ENDS = opts.c_newline; + G.ALLOW_ALL_ADDENDS_ON_DATA = opts.allow_data_addends; + G.DISASSEMBLE_UNKNOWN_INSTRUCTIONS = opts.disasm_unknown; + } + + check_version(skipVersionCheck, splatVersion) { + const S = spim(); + const have = S.__version_info__ ? [...S.__version_info__] : versionTuple(S.__version__); + if (!skipVersionCheck && tupleLt(have, this.SPIMDISASM_MIN)) { + log.error(`splat ${splatVersion} requires as minimum spimdisasm (${this.SPIMDISASM_MIN.join(', ')}), but the installed version is (${have.join(', ')})`); + } + log.write(`splat ${splatVersion} (powered by spimdisasm ${S.__version__})`); + } + + known_types() { + const t = spim().common.gKnownTypes; + return t instanceof Set ? t : new Set(t); + } +} + +let instance = new NullDisassembler(); +let initialized = false; + +export function reset() { instance = new NullDisassembler(); initialized = false; } + +export function createDisassemblerInstance(skipVersionCheck, splatVersion) { + if (['n64', 'psx', 'ps2', 'psp'].includes(opts.platform)) { + instance = new SpimdisasmDisassembler(); + initialized = true; + instance.check_version(skipVersionCheck, splatVersion); + instance.configure(); + return; + } + throw new Error('No disassembler for requested platform'); +} + +export function getInstance() { + if (!initialized) throw new Error('Disassembler instance not initialized'); + return instance; +} diff --git a/packages/romdev-splat/src/disassembler/disassembler_section.js b/packages/romdev-splat/src/disassembler/disassembler_section.js new file mode 100644 index 00000000..c9fbbd64 --- /dev/null +++ b/packages/romdev-splat/src/disassembler/disassembler_section.js @@ -0,0 +1,43 @@ +// splat.disassembler.disassembler_section +import { opts } from '../util/options.js'; +import { state as symbolsState } from '../util/symbols.js'; +import { spim } from './spim.js'; + +export class SpimdisasmDisassemberSection { + constructor() { this.spim_section = null; } + + disassemble() { return this.spim_section.disassemble(); } + analyze() { this.spim_section.analyze(); } + set_comment_offset(romStart) { this.spim_section.setCommentOffset(romStart); } + get_section() { return this.spim_section; } + + make_bss_section(romStart, romEnd, vramStart, bssEnd, name, segmentRomStart, exclusiveRamId) { + this.spim_section = new (spim().mips.sections.SectionBss)(symbolsState.spim_context, romStart, romEnd, + vramStart, bssEnd, name, segmentRomStart, exclusiveRamId); + } + + make_data_section(romStart, romEnd, vramStart, name, romBytes, segmentRomStart, exclusiveRamId) { + this.spim_section = new (spim().mips.sections.SectionData)(symbolsState.spim_context, romStart, romEnd, + vramStart, name, romBytes, segmentRomStart, exclusiveRamId); + } + + make_rodata_section(romStart, romEnd, vramStart, name, romBytes, segmentRomStart, exclusiveRamId) { + this.spim_section = new (spim().mips.sections.SectionRodata)(symbolsState.spim_context, romStart, romEnd, + vramStart, name, romBytes, segmentRomStart, exclusiveRamId); + } + + make_text_section(romStart, romEnd, vramStart, name, romBytes, segmentRomStart, exclusiveRamId) { + this.spim_section = new (spim().mips.sections.SectionText)(symbolsState.spim_context, romStart, romEnd, + vramStart, name, romBytes, segmentRomStart, exclusiveRamId); + } +} + +function make() { + if (['n64', 'psx', 'ps2', 'psp'].includes(opts.platform)) return new SpimdisasmDisassemberSection(); + throw new Error('No disassembler section for requested platform'); +} + +export function makeTextSection(...a) { const s = make(); s.make_text_section(...a); return s; } +export function makeDataSection(...a) { const s = make(); s.make_data_section(...a); return s; } +export function makeRodataSection(...a) { const s = make(); s.make_rodata_section(...a); return s; } +export function makeBssSection(...a) { const s = make(); s.make_bss_section(...a); return s; } diff --git a/packages/romdev-splat/src/disassembler/spim.js b/packages/romdev-splat/src/disassembler/spim.js new file mode 100644 index 00000000..cde6ea18 --- /dev/null +++ b/packages/romdev-splat/src/disassembler/spim.js @@ -0,0 +1,58 @@ +// Access to the disassembler backend (romdev-spimdisasm, a 1:1 port of the +// Python spimdisasm module, and romdev-rabbitizer). Loaded lazily so the +// parts of splat that never disassemble work without them, and so a caller +// can inject a backend (tests). +// +// Python splat runs in a fresh process, so spimdisasm's GlobalConfig and +// rabbitizer's config start from their defaults every time. Here they are +// process globals shared by every run: each run re-selects the spimdisasm +// version (which resets GlobalConfig) and restores rabbitizer's config to the +// values it had when its WASM module was first loaded. + +let backend = null; +const rabbitizerDefaults = new Map(); // rabbitizer module -> {name: value} + +const DEFAULT_SPIMDISASM = '1.42.4'; + +function snapshotConfig(rab) { + if (rabbitizerDefaults.has(rab)) return; + const snap = {}; + for (const k of Object.keys(rab.config)) snap[k] = rab.config[k]; + rabbitizerDefaults.set(rab, snap); +} + +function restoreConfig(rab) { + const snap = rabbitizerDefaults.get(rab); + if (!snap) return; + for (const [k, v] of Object.entries(snap)) rab.config[k] = v; +} + +/** Load (or reuse) romdev-spimdisasm configured for `spimdisasmVersion`. */ +export async function loadBackend({ spimdisasmVersion = null } = {}) { + const spimdisasm = await import('romdev-spimdisasm'); + const rabMod = await import('romdev-rabbitizer'); + const version = spimdisasmVersion || DEFAULT_SPIMDISASM; + if (!spimdisasm.SUPPORTED_VERSIONS.includes(version)) { + throw new Error(`romdev-spimdisasm does not reproduce spimdisasm ${version} (supported: ${spimdisasm.SUPPORTED_VERSIONS.join(', ')})`); + } + const rabVersion = spimdisasm.RABBITIZER_VERSION_FOR[version]; + const rab = rabMod.loadRabbitizerSync(rabVersion); + snapshotConfig(rab); + restoreConfig(rab); + spimdisasm.setRabbitizer(rab); + spimdisasm.configureVersion(version); + return { spimdisasm, rabbitizer: rab, spimdisasmVersion: version, rabbitizerVersion: rabVersion }; +} + +export function setBackend(b) { backend = b; } +export function getBackend() { return backend; } + +export function spim() { + if (!backend) throw new Error('splat: no disassembler backend loaded'); + return backend.spimdisasm; +} + +export function rabbitizer() { + if (!backend) throw new Error('splat: no disassembler backend loaded'); + return backend.rabbitizer; +} diff --git a/packages/romdev-splat/src/ext/index.js b/packages/romdev-splat/src/ext/index.js new file mode 100644 index 00000000..15379d18 --- /dev/null +++ b/packages/romdev-splat/src/ext/index.js @@ -0,0 +1,137 @@ +// Ports of the splat extension segtypes (extensions_path/*.py) shipped by the +// projects romdev targets. Python splat imports `/.py` +// and takes the class `Seg`; romdev cannot run Python, so each +// known file is identified by its sha256 and mapped to a JS port here. A file +// with any other content is reported as unsupported, never guessed. +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import { abs } from '../runtime.js'; +import { P } from '../util/pypath.js'; +import { mkdirp, writeBytes } from '../runtime.js'; +import { opts } from '../util/options.js'; +import { parent } from '../util/pypath.js'; +import { Segment } from '../segtypes/segment.js'; +import { CommonSegHasm, CommonSegData } from '../segtypes/common.js'; +import { N64SegCi4, N64SegI4, N64SegRgba16, N64SegPalette, N64SegImg, ceil255 } from '../segtypes/platform.js'; +import * as n64img from '../n64img/image.js'; +import { SplatError, isFile } from '../runtime.js'; + +// ---------------------------------------------------------------- an N64 decomp project: hcode.py / hdata.py + +/** "Authored assembly code in src; preserve source during ROM extraction." */ +class N64SegHcode extends CommonSegHasm { + asm_out_path() { return P(opts.src_path, this.dir, `${this.name}.s`); } + split() { + if (!isFile(this.asm_out_path())) { + throw new SplatError(`FileNotFoundError: Missing authored code source: ${this.asm_out_path()}`, 1); + } + } +} + +/** "Authored assembly data: analyze/link as data, never regenerate its source." */ +class N64SegHdata extends CommonSegData { + asm_out_path() { return P(opts.src_path, this.dir, `${this.name}.s`); } + split() { + if (!isFile(this.asm_out_path())) { + throw new SplatError(`FileNotFoundError: Missing authored data source: ${this.asm_out_path()}`, 1); + } + } +} + +// ---------------------------------------------------------------- PS1 decomp project: tools/splat_ext + +class PSXSegCi4 extends N64SegCi4 { + constructor(...a) { super(...a); this.n64img.little_endian = true; } +} + +class PSXSegI4 extends N64SegI4 { + constructor(...a) { super(...a); this.n64img.little_endian = true; } +} + +class PSXSegRgba16 extends N64SegRgba16 {} + +// ABBBBBGG GGGRRRRR +function psxUnpackColor(a, b) { + const s = a | (b << 8); + const r = s & 0x1F; const g = (s >> 5) & 0x1F; const bl = (s >> 10) & 0x1F; + const al = (s >> 15) * 0xFF; + return [ceil255(r), ceil255(g), ceil255(bl), al]; +} + +class PSXSegPalette extends N64SegPalette { + parse_palette(romBytes) { + const data = romBytes.subarray(this.rom_start, this.rom_end); + const palette = []; + for (let i = 0; i < data.length; i += 2) { + if (i + 1 >= data.length) throw new TypeError("unsupported operand type(s) for <<: 'NoneType' and 'int'"); + palette.push(psxUnpackColor(data[i], data[i + 1])); + } + return palette; + } +} + +function greyPalette() { + const out = []; + for (let i = 0; i < 16; i++) out.push([i * 0x11, i * 0x11, i * 0x11, 255]); + return out; +} + +class PSXSegGrey4 extends N64SegImg { + split(romBytes) { + const path = this.out_path(); + mkdirp(parent(path)); + this.n64img.palette = greyPalette(); + this.n64img.data = romBytes.subarray(this.rom_start, this.rom_end); + this.n64img.little_endian = true; + this.n64img.write(path); + this.log(`Wrote ${this.name} to ${path}`); + } +} +PSXSegGrey4.IMG_CLS = n64img.CI4; + +class PSXSegRaw extends Segment { + out_path() { return P(opts.asset_path, this.dir, this.name); } + src_path() { return P(opts.asset_path, this.dir, `${this.name}.bin`); } + split(romBytes) { + const path = this.src_path(); + mkdirp(parent(path)); + writeBytes(path, romBytes.subarray(this.rom_start, this.rom_end)); + } +} + +// sha256 of the .py file -> { className: class } +export const PORTED_EXTENSIONS = { + // an N64 project's authored-source segtypes + '86257f3454baab37422c65128811ee6e638d6544923126f495c963b87587e46a': { file: 'hcode.py', classes: { N64SegHcode } }, + 'cc51424f8f64dfa403f08f227e3d7823e06443c2e1a052214627da50ef07d702': { file: 'hdata.py', classes: { N64SegHdata } }, + // PS1 project tools/splat_ext + '5d4efa9e428e51f674e4cbb2094358902cc95e3230166c812074153fd3ef1ade': { file: 'ci4.py', classes: { PSXSegCi4 } }, + '5c17771ba298a89ecb2221fa2a2dd72a19f85fdaab7a9febd90814929e5454b6': { file: 'i4.py', classes: { PSXSegI4 } }, + '822f24eab1a4145bce9967031299a343dd208f29cb509cb00b8609765ee9fb65': { file: 'rgba16.py', classes: { PSXSegRgba16 } }, + '065d07f8650b7051c7ad7c94c7cdd95371aed06755e38e9eb72e1049290fe0fc': { file: 'palette.py', classes: { PSXSegPalette } }, + '8cfb7861b6150d1558fd2b0b9c2edaf065a6eaa9f66198ce60a88a7967f32d23': { file: 'grey4.py', classes: { PSXSegGrey4 } }, + '52c275dea2e3431070f16e92305a873e63442de08c8fe9e66baa7faaab087a68': { file: 'raw.py', classes: { PSXSegRaw } }, +}; + +/** Report of every extension file the run looked at: [{ path, sha256, ported }]. */ +export const extensionReport = []; + +export function loadExtension(extPath, segType, platform) { + const file = P(extPath, `${segType}.py`); + let bytes; + try { + bytes = fs.readFileSync(abs(file)); + } catch { + return null; // Python: the import fails and get_extension_segment_class returns None + } + const sha = crypto.createHash('sha256').update(bytes).digest('hex'); + const port = PORTED_EXTENSIONS[sha]; + extensionReport.push({ path: file, sha256: sha, ported: !!port }); + if (!port) { + throw new SplatError(`romdev-splat: extension ${file} (sha256 ${sha}) has no JS port; this splat extension is unsupported`, 2); + } + const clsName = `${platform.toUpperCase()}Seg${segType[0].toUpperCase()}${segType.slice(1)}`; + const cls = port.classes[clsName]; + if (!cls) throw new SplatError(`AttributeError: module '${file}' has no attribute '${clsName}'`, 1); + return cls; +} diff --git a/packages/romdev-splat/src/index.js b/packages/romdev-splat/src/index.js new file mode 100644 index 00000000..b9cfed14 --- /dev/null +++ b/packages/romdev-splat/src/index.js @@ -0,0 +1,96 @@ +// romdev-splat: a JavaScript port of splat (https://github.com/ethteck/splat), +// the binary splitting tool used by N64/PS1 decompilation projects. +// +// import { split } from 'romdev-splat'; +// const r = await split(['config/us/game.us.yaml'], { cwd: '/path/to/project' }); +// +// Runs never touch process.cwd(): relative config paths, and every relative +// path splat derives from them, resolve against `cwd`. +import path from 'node:path'; +import { rt, SplatError } from './runtime.js'; +import { main } from './split.js'; +import { loadBackend, setBackend } from './disassembler/spim.js'; +import { DEFAULT_SPLAT_VERSION, detectProjectVersions, parseVersion, SUPPORTED_SPLAT_VERSIONS } from './versions.js'; +import { extensionReport, PORTED_EXTENSIONS } from './ext/index.js'; + +export { detectProjectVersions, SUPPORTED_SPLAT_VERSIONS, DEFAULT_SPLAT_VERSION, PORTED_EXTENSIONS, SplatError }; + +let queue = Promise.resolve(); + +/** + * Run `splat split`. + * + * @param {string|string[]} configPaths yaml config(s), merged in order (relative to `cwd`). + * @param {object} [o] + * @param {string[]} [o.modes] default ['all']. + * @param {boolean} [o.verbose] + * @param {boolean} [o.useCache] --use-cache + * @param {boolean} [o.skipVersionCheck] + * @param {boolean} [o.stdoutOnly] + * @param {boolean} [o.disassembleAll] + * @param {boolean} [o.makeFullDisasmForCode] + * @param {string} [o.cwd] directory the invocation runs from (default process.cwd(), read only). + * @param {string} [o.basePath] overrides the resolved `base_path` option. + * @param {string} [o.splatVersion] '0.37.1' (default) or '0.34.1'; 'auto' reads the project's pins. + * @param {string} [o.spimdisasmVersion] backend version; 'auto' reads the project's pins. + * @param {string} [o.projectDir] where 'auto' looks for pins (default cwd). + * @param {object} [o.backend] {spimdisasm, rabbitizer} to use instead of romdev-spimdisasm. + * @param {(stream: 'stdout'|'stderr', text: string) => void} [o.onOutput] + * @returns {Promise<{exitCode:number, stdout:string, stderr:string, error:Error|null, + * splatVersion:string, spimdisasmVersion:string|null, extensions:object[]}>} + */ +export function split(configPaths, o = {}) { + const run = queue.then(() => runSplit(configPaths, o)); + queue = run.catch(() => {}); + return run; +} + +async function runSplit(configPaths, o) { + const cwd = path.resolve(o.cwd || process.cwd()); + const projectDir = o.projectDir ? path.resolve(cwd, o.projectDir) : cwd; + let splatVersion = o.splatVersion || DEFAULT_SPLAT_VERSION; + let spimdisasmVersion = o.spimdisasmVersion || (splatVersion === 'auto' ? 'auto' : null); + if (splatVersion === 'auto' || spimdisasmVersion === 'auto') { + const pins = detectProjectVersions(projectDir); + if (splatVersion === 'auto') splatVersion = pins.splat || DEFAULT_SPLAT_VERSION; + if (spimdisasmVersion === 'auto') spimdisasmVersion = pins.spimdisasm; + } + const version = parseVersion(splatVersion); + + const stdout = []; + const stderr = []; + const prev = { cwd: rt.cwd, version: rt.version, sink: rt.sink }; + rt.cwd = cwd; + rt.version = version; + rt.sink = (stream, text) => { + (stream === 'stderr' ? stderr : stdout).push(text); + if (o.onOutput) o.onOutput(stream, text); + }; + extensionReport.length = 0; + let exitCode = 0; + let error = null; + try { + const backend = o.backend || await loadBackend({ spimdisasmVersion }); + setBackend(backend); + const paths = (Array.isArray(configPaths) ? configPaths : [configPaths]).map(String); + main(paths, o.modes && o.modes.length ? o.modes : null, !!o.verbose, !!o.useCache, !!o.skipVersionCheck, + !!o.stdoutOnly, !!o.disassembleAll, !!o.makeFullDisasmForCode, { basePath: o.basePath ?? null }); + } catch (e) { + error = e; + exitCode = e instanceof SplatError ? e.exitCode : 1; + if (!(e instanceof SplatError)) rt.sink('stderr', `${e && e.stack ? e.stack : e}\n`); + } finally { + rt.cwd = prev.cwd; + rt.version = prev.version; + rt.sink = prev.sink; + } + return { + exitCode, + stdout: stdout.join(''), + stderr: stderr.join(''), + error, + splatVersion, + spimdisasmVersion, + extensions: [...extensionReport], + }; +} diff --git a/packages/romdev-splat/src/n64img/image.js b/packages/romdev-splat/src/n64img/image.js new file mode 100644 index 00000000..c7fd159f --- /dev/null +++ b/packages/romdev-splat/src/n64img/image.js @@ -0,0 +1,173 @@ +// Port of n64img 0.3.3 (n64img/image.py + iter.py, MIT, ethteck). +import { writeBytes } from '../runtime.js'; +import { Writer } from './png.js'; + +function* iterImageIndexes(width, height, bytesPerPixel = 1, flipH = false, flipV = false) { + const w = Math.trunc(width * bytesPerPixel); + const h = Math.trunc(height * 1); + const step = Math.ceil(bytesPerPixel); + const xs = []; + if (flipH) for (let x = w - step; x > -1; x -= step) xs.push(x); + else for (let x = 0; x < w; x += step) xs.push(x); + const ys = []; + if (flipV) for (let y = h - 1; y > -1; y--) ys.push(y); + else for (let y = 0; y < h; y++) ys.push(y); + for (const y of ys) for (const x of xs) yield [x, y, y * w + x]; +} + +function at(data, i) { + if (i < 0 || i >= data.length) throw new RangeError('IndexError: index out of range'); + return data[i]; +} + +export class Image { + constructor(data, width, height) { + this.data = data; + this.width = width; + this.height = height; + this.depth = 1; + this.greyscale = false; + this.alpha = false; + this.flip_h = false; + this.flip_v = false; + this.little_endian = false; + this.palette = null; + } + + get_writer() { + return new Writer(this.width, this.height, { greyscale: this.greyscale, alpha: this.alpha, palette: this.palette }); + } + + parse() { + if (!this.flip_h && !this.flip_v) return this.data; + const img = []; + for (const [, , i] of iterImageIndexes(this.width, this.height, this.depth, this.flip_h, this.flip_v)) img.push(at(this.data, i)); + return Uint8Array.from(img); + } + + write(outpath) { + const pixels = this.parse(); + writeBytes(outpath, this.get_writer().writeArray(pixels)); + } + + size() { return Math.ceil(this.width * this.height * this.depth); } +} + +export class CI4 extends Image { + constructor(d, w, h) { super(d, w, h); this.depth = 0.5; } + parse() { + const img = []; + for (const [, , i] of iterImageIndexes(this.width, this.height, this.depth, this.flip_h, this.flip_v)) { + const b = at(this.data, i); + if (this.little_endian) img.push(b & 0xF, b >> 4); + else img.push(b >> 4, b & 0xF); + } + return Uint8Array.from(img); + } +} + +export class CI8 extends Image {} + +export class I1 extends Image { + constructor(d, w, h) { super(d, w, h); this.depth = 0.125; this.greyscale = true; } + parse() { + if (this.flip_h) throw new Error('I1 images cannot be flipped horizontally.'); + if (this.flip_v) throw new Error('I1 images cannot be flipped vertically.'); + const img = []; + for (const b of this.data) for (let j = 8; j > 0; j--) img.push(((b >> (j - 1)) & 1) * 0xFF); + return Uint8Array.from(img); + } +} + +export class I4 extends Image { + constructor(d, w, h) { super(d, w, h); this.depth = 0.5; this.greyscale = true; } + parse() { + const img = []; + for (const [, , i] of iterImageIndexes(this.width, this.height, this.depth, this.flip_h, this.flip_v)) { + const b = at(this.data, i); + let i1; let i2; + if (this.little_endian) { i1 = b & 0xF; i2 = (b >> 4) & 0xF; } else { i1 = (b >> 4) & 0xF; i2 = b & 0xF; } + img.push((i1 << 4) | i1, (i2 << 4) | i2); + } + return Uint8Array.from(img); + } +} + +export class I8 extends Image { + constructor(d, w, h) { super(d, w, h); this.greyscale = true; } +} + +export class IA4 extends Image { + constructor(d, w, h) { super(d, w, h); this.depth = 0.5; this.greyscale = true; this.alpha = true; } + parse() { + const img = []; + for (const [, , i] of iterImageIndexes(this.width, this.height, this.depth, this.flip_h, this.flip_v)) { + const b = at(this.data, i); + let h; let l; + if (this.little_endian) { h = b & 0xF; l = (b >> 4) & 0xF; } else { h = (b >> 4) & 0xF; l = b & 0xF; } + let i1 = h & 0xE; i1 = (i1 << 4) | (i1 << 1) | (i1 >> 2); + const a1 = (h & 1) * 0xFF; + let i2 = l & 0xE; i2 = (i2 << 4) | (i2 << 1) | (i2 >> 2); + const a2 = (l & 1) * 0xFF; + img.push(i1 & 0xFF, a1, i2 & 0xFF, a2); + } + return Uint8Array.from(img); + } +} + +export class IA8 extends Image { + constructor(d, w, h) { super(d, w, h); this.greyscale = true; this.alpha = true; } + parse() { + const img = []; + for (const [, , idx] of iterImageIndexes(this.width, this.height, 1, this.flip_h, this.flip_v)) { + const b = at(this.data, idx); + let i = (b >> 4) & 0xF; let a = b & 0xF; + i = (i << 4) | i; a = (a << 4) | a; + img.push(i, a); + } + return Uint8Array.from(img); + } +} + +export class IA16 extends Image { + constructor(d, w, h) { super(d, w, h); this.depth = 2; this.greyscale = true; this.alpha = true; } + parse() { + if (!this.flip_h && !this.flip_v) return this.data; + const img = []; + for (const [, , i] of iterImageIndexes(this.width, this.height, this.depth, this.flip_h, this.flip_v)) { + img.push(at(this.data, i), at(this.data, i + 1)); + } + return Uint8Array.from(img); + } +} + +export class RGBA16 extends Image { + constructor(d, w, h) { super(d, w, h); this.depth = 2; this.greyscale = false; this.alpha = true; } + parse() { + const img = []; + for (const [, , i] of iterImageIndexes(this.width, this.height, this.depth, this.flip_h, this.flip_v)) { + // int.from_bytes(data[i:i+2], "big"): a short slice at the end reads fewer bytes + const hi = this.data[i]; const lo = this.data[i + 1]; + let s; + if (hi === undefined) s = 0; + else if (lo === undefined) s = hi; + else s = (hi << 8) | lo; + let r = (s >> 11) & 0x1F; let g = (s >> 6) & 0x1F; let b = (s >> 1) & 0x1F; + r = (r << 3) | (r >> 2); g = (g << 3) | (g >> 2); b = (b << 3) | (b >> 2); + img.push(r, g, b, 255 * (s & 1)); + } + return Uint8Array.from(img); + } +} + +export class RGBA32 extends Image { + constructor(d, w, h) { super(d, w, h); this.depth = 4; this.greyscale = false; this.alpha = true; } + parse() { + if (!this.flip_h && !this.flip_v) return this.data; + const img = []; + for (const [, , i] of iterImageIndexes(this.width, this.height, this.depth, this.flip_h, this.flip_v)) { + img.push(at(this.data, i), at(this.data, i + 1), at(this.data, i + 2), at(this.data, i + 3)); + } + return Uint8Array.from(img); + } +} diff --git a/packages/romdev-splat/src/n64img/png.js b/packages/romdev-splat/src/n64img/png.js new file mode 100644 index 00000000..6ab391a5 --- /dev/null +++ b/packages/romdev-splat/src/n64img/png.js @@ -0,0 +1,116 @@ +// The pypng (png.py 0.20220715.0, MIT, David Jones et al.) Writer code +// paths n64img uses: Writer(width, height, greyscale, alpha, palette, +// bitdepth=8).write_array(). Same chunk layout, same IDAT chunking +// (1 MiB chunk_limit), same zlib calls. +import { compressobj, crc32 } from '../zlib.js'; + +class ProtocolError extends Error {} + +const SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); + +function checkPalette(palette) { + if (palette === null || palette === undefined) return null; + const p = [...palette]; + if (!(p.length > 0 && p.length <= 256)) { + throw new ProtocolError('a palette must have between 1 and 256 entries, see https://www.w3.org/TR/PNG/#11PLTE'); + } + let seenTriple = false; + p.forEach((t, i) => { + if (t.length !== 3 && t.length !== 4) throw new ProtocolError(`palette entry ${i}: entries must be 3- or 4-tuples.`); + if (t.length === 3) seenTriple = true; + if (seenTriple && t.length === 4) throw new ProtocolError(`palette entry ${i}: all 4-tuples must precede all 3-tuples`); + for (const x of t) { + if (!Number.isInteger(x) || x < 0 || x > 255) throw new ProtocolError(`palette entry ${i}: values must be integer: 0 <= x <= 255`); + } + }); + return p; +} + +function writeChunk(out, tag, data = new Uint8Array(0)) { + const len = Buffer.alloc(4); len.writeUInt32BE(data.length); + out.push(len); + const tagB = Buffer.from(tag, 'latin1'); + out.push(tagB); + out.push(Buffer.from(data)); + let c = crc32(tagB); + c = crc32(data, c); + const cb = Buffer.alloc(4); cb.writeUInt32BE(c >>> 0); + out.push(cb); +} + +export class Writer { + constructor(width, height, { greyscale = null, alpha = false, bitdepth = 8, palette = null, compression = null, chunkLimit = 2 ** 20 } = {}) { + if (!Number.isInteger(width) || !Number.isInteger(height)) throw new ProtocolError('width and height must be integers'); + if (width <= 0 || height <= 0) throw new ProtocolError('width and height must be greater than zero'); + palette = checkPalette(palette); + alpha = !!alpha; + const colormap = !!(palette && palette.length); + if (greyscale === null && colormap) greyscale = false; + greyscale = !!greyscale; + const planes = colormap ? 1 : (greyscale ? 1 : 3) + (alpha ? 1 : 0); + if (colormap) { + if (![1, 2, 4, 8].includes(bitdepth)) throw new ProtocolError('with palette, bitdepth must be 1, 2, 4, or 8'); + if (alpha) throw new ProtocolError('alpha and palette not compatible'); + if (greyscale) throw new ProtocolError('greyscale and palette not compatible'); + } + if (bitdepth !== 8) throw new Error('romdev-splat: only bitdepth 8 is implemented (the depth n64img writes)'); + this.width = width; + this.height = height; + this.greyscale = greyscale; + this.alpha = alpha; + this.colormap = colormap; + this.bitdepth = bitdepth; + this.compression = compression; + this.chunk_limit = chunkLimit; + this.palette = palette; + this.planes = planes; + this.color_type = 4 * (alpha ? 1 : 0) + 2 * (greyscale ? 0 : 1) + (colormap ? 1 : 0); + } + + /** write_array(outfile, pixels) with a flat pixel array; returns the PNG bytes. */ + writeArray(pixels) { + const out = [SIGNATURE]; + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(this.width, 0); + ihdr.writeUInt32BE(this.height, 4); + ihdr[8] = this.bitdepth; ihdr[9] = this.color_type; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; + writeChunk(out, 'IHDR', ihdr); + if (this.palette) { + const p = []; const t = []; + for (const x of this.palette) { + p.push(...x.slice(0, 3)); + if (x.length > 3) t.push(x[3]); + } + writeChunk(out, 'PLTE', Uint8Array.from(p)); + if (t.length) writeChunk(out, 'tRNS', Uint8Array.from(t)); + } + + const compressor = this.compression !== null ? compressobj(this.compression) : compressobj(); + const vpr = this.width * this.planes; + let data = []; + let dataLen = 0; + const flushData = () => { + const buf = Buffer.concat(data, dataLen); + data = []; dataLen = 0; + return buf; + }; + let stop = 0; + for (let y = 0; y < this.height; y++) { + const start = stop; + stop = start + vpr; + // pixels[start:stop] (Python slicing clamps; bytearray.extend of values) + const row = pixels.subarray(Math.min(start, pixels.length), Math.min(stop, pixels.length)); + data.push(Buffer.from([0]), Buffer.from(row)); + dataLen += 1 + row.length; + if (dataLen > this.chunk_limit) { + const compressed = compressor.compress(flushData()); + if (compressed.length) writeChunk(out, 'IDAT', compressed); + } + } + const compressed = compressor.compress(flushData()); + const flushed = compressor.flush(); + if (compressed.length || flushed.length) writeChunk(out, 'IDAT', Buffer.concat([compressed, flushed])); + writeChunk(out, 'IEND'); + return Buffer.concat(out); + } +} diff --git a/packages/romdev-splat/src/runtime.js b/packages/romdev-splat/src/runtime.js new file mode 100644 index 00000000..872f989c --- /dev/null +++ b/packages/romdev-splat/src/runtime.js @@ -0,0 +1,90 @@ +// Per-run state that Python splat keeps in the process: the working +// directory (virtual here: nothing ever calls process.chdir), the splat +// behaviour version, and the output streams. + +import fs from 'node:fs'; +import nodePath from 'node:path'; +import { isAbs, normpath } from './util/pypath.js'; + +export class SplatError extends Error { + constructor(message, exitCode = 2) { + super(message); + this.name = 'SplatError'; + this.exitCode = exitCode; + } +} + +export const rt = { + cwd: '/', + /** splat version whose behaviour is reproduced, [major, minor, patch]. */ + version: [0, 37, 1], + /** (stream: 'stdout'|'stderr', text) sink; text includes its trailing newline. */ + sink: null, +}; + +export function atLeast(v) { + const want = String(v).split('.').map(Number); + for (let i = 0; i < 3; i++) { + const a = rt.version[i] || 0; const b = want[i] || 0; + if (a !== b) return a > b; + } + return true; +} + +export function abs(p) { + p = String(p); + return isAbs(p) ? p : nodePath.join(rt.cwd, p); +} + +export function exists(p) { return fs.existsSync(abs(p)); } +export function isFile(p) { + try { return fs.statSync(abs(p)).isFile(); } catch { return false; } +} + +/** Python text-mode read (UTF-8, universal newlines). */ +export function readText(p) { + return fs.readFileSync(abs(p), 'utf8').replace(/\r\n?/g, '\n'); +} + +export function readBytes(p) { return fs.readFileSync(abs(p)); } + +export function mkdirp(dir) { fs.mkdirSync(abs(dir), { recursive: true }); } + +/** Python open(p, "w", newline=nl).write(text). newline null/undefined/"" = no translation on posix. */ +export function writeText(p, text, newline = '\n') { + let out = text; + if (newline && newline !== '\n') out = text.replace(/\n/g, newline); + fs.writeFileSync(abs(p), out, 'utf8'); +} + +export function writeBytes(p, bytes) { fs.writeFileSync(abs(p), bytes); } + +/** A Python text file object opened for writing: collects write() calls. */ +export class TextFile { + constructor(p, newline = '\n') { this.path = p; this.newline = newline; this.parts = []; } + write(s) { this.parts.push(s); return s.length; } + close() { writeText(this.path, this.parts.join(''), this.newline); } +} + +/** Python pathlib.Path.resolve(): absolute, symlinks resolved where they exist. */ +export function resolvePath(p) { + const a = normpath(abs(p)); + // Resolve the longest existing prefix, then append the rest. + const parts = a.split('/').filter(Boolean); + for (let i = parts.length; i >= 0; i--) { + const head = '/' + parts.slice(0, i).join('/'); + let real; + try { real = fs.realpathSync(head); } catch { continue; } + const rest = parts.slice(i); + return normpath(rest.length ? real + '/' + rest.join('/') : real); + } + return a; +} + +export function print(...args) { + emit('stdout', args.map(String).join(' ') + '\n'); +} + +export function emit(stream, text) { + if (rt.sink) rt.sink(stream, text); +} diff --git a/packages/romdev-splat/src/segtypes/common.js b/packages/romdev-splat/src/segtypes/common.js new file mode 100644 index 00000000..968e0346 --- /dev/null +++ b/packages/romdev-splat/src/segtypes/common.js @@ -0,0 +1,1366 @@ +// splat.segtypes.common.* +import { atLeast, exists, mkdirp, readText, writeText, writeBytes, TextFile, print } from '../runtime.js'; +import * as log from '../util/log.js'; +import { opts } from '../util/options.js'; +import * as symbols from '../util/symbols.js'; +import { P, parent, relativeTo, relpath, suffix, withSuffix, name as pathName } from '../util/pypath.js'; +import { hex, isDict, isList, truthy, ljust } from '../util/pyfmt.js'; +import { rt } from '../runtime.js'; +import { Segment, parseSegmentAlign, parseSegmentVram, emptyStatistics, statGet } from './segment.js'; +import { LinkerEntry, LinkerWriter } from './linker_entry.js'; +import { makeTextSection, makeDataSection, makeRodataSection, makeBssSection } from '../disassembler/disassembler_section.js'; +import { spim, rabbitizer } from '../disassembler/spim.js'; + +const has = (o, k) => isDict(o) && Object.prototype.hasOwnProperty.call(o, k); +const get = (o, k, d = null) => (has(o, k) ? o[k] : d); + +export class CommonSegment extends Segment {} + +// ---------------------------------------------------------------- group + +/** CommonSegGroup behaviour, shared with CommonSegData (Python multiple inheritance). */ +const GroupMixin = { + get_next_seg_start(i, subsegmentYamls) { + for (let j = i + 1; j < subsegmentYamls.length; j++) { + const [ret] = Segment.parse_segment_start(subsegmentYamls[j]); + if (ret !== null) return ret; + } + return this.rom_end; + }, + + group_parse_subsegments(yaml) { + const ret = []; + if (!truthy(yaml) || !has(yaml, 'subsegments')) return ret; + let prevStart = -1; + let lastRomEnd = 0; + const subs = yaml.subsegments; + for (let i = 0; i < subs.length; i++) { + const subYaml = subs[i]; + if (isList(subYaml) && subYaml.length === 1) continue; + const typ = Segment.parse_segment_type(subYaml); + let [start, isAutoSegment] = Segment.parse_segment_start(subYaml); + const cls = Segment.get_class_for_type(typ); + if (start === null) start = i === 0 ? this.rom_start : lastRomEnd; + + let end = null; + if (i < subs.length - 1) [end] = Segment.parse_segment_start(subs[i + 1]); + if (start !== null && end === null) { + const est = cls.estimate_size(subYaml); + if (est !== null) end = start + est; + } + if (end === null) end = this.get_next_seg_start(i, subs); + + if (start !== null && prevStart !== null && start < prevStart) { + log.error(`Error: Group segment ${this.name} contains subsegments which are out of ascending rom order (0x${hex(prevStart)} followed by 0x${hex(start)})`); + } + + let vram = null; + if (start !== null) { + const mp = this.get_most_parent(); + if (mp.vram_start !== null && mp.rom_start !== null) vram = mp.vram_start + start - mp.rom_start; + } + if (cls.is_noload()) { start = lastRomEnd; end = lastRomEnd; } + + const segment = Segment.from_yaml(cls, subYaml, start, end, this, vram); + if (segment.special_vram_segment) this.special_vram_segment = true; + segment.is_auto_segment = isAutoSegment; + segment.index_within_group = ret.length; + ret.push(segment); + prevStart = start; + if (end !== null) lastRomEnd = end; + } + ret.forEach((s, i) => { s.index_within_group = i; }); + return ret; + }, + + group_statistics() { + const stats = emptyStatistics(); + for (const sub of this.subsegments) { + for (const [ty, info] of sub.statistics) stats.set(ty, statGet(stats, ty).merge(info)); + } + return stats; + }, + + group_scan(romBytes) { + for (const sub of this.subsegments) if (sub.should_scan()) sub.scan(romBytes); + }, + + group_split(romBytes) { + for (const sub of this.subsegments) if (sub.should_split()) sub.split(romBytes); + }, + + group_cache() { return this.subsegments.map((s) => s.cache()); }, + + get_subsegment_for_ram(addr) { + for (const sub of this.subsegments) if (sub.contains_vram(addr)) return sub; + if (this.paired_segment && this.paired_segment.isGroup) { + for (const sub of this.paired_segment.subsegments) if (sub.contains_vram(addr)) return sub; + } + return null; + }, + + get_next_subsegment_for_ram(addr, currentSubsegIndex) { + const start = currentSubsegIndex !== null ? currentSubsegIndex : 0; + for (const sub of this.subsegments.slice(start)) { + if (sub.vram_start === null) continue; + if (sub.vram_start > addr) return sub; + } + return null; + }, + + pair_subsegments_to_other_segment(other) { + for (const segment of this.subsegments) { + for (const sibling of other.subsegments) { + if (segment.name === sibling.name) { + segment.siblings.set(sibling.get_linker_section_linksection(), sibling); + sibling.siblings.set(segment.get_linker_section_linksection(), segment); + if (segment.is_text()) sibling.sibling = segment; + else if (sibling.is_text()) segment.sibling = sibling; + break; + } + } + } + }, +}; + +export class CommonSegGroup extends CommonSegment { + constructor(...a) { + super(...a); + this.subsegments = this.parse_subsegments(this.yaml); + } + + get isGroup() { return true; } + parse_subsegments(yaml) { return this.group_parse_subsegments(yaml); } + + get needs_symbols() { return this.subsegments.some((s) => s.needs_symbols); } + get statistics() { return this.group_statistics(); } + get_linker_entries() { return this.subsegments.flatMap((s) => s.get_linker_entries()); } + scan(romBytes) { this.group_scan(romBytes); } + split(romBytes) { this.group_split(romBytes); } + should_split() { return this.extract; } + should_scan() { return this.extract; } + cache() { return this.group_cache(); } +} +Object.assign(CommonSegGroup.prototype, GroupMixin); + +// ---------------------------------------------------------------- code + +function listIndex(l, v) { const i = l.indexOf(v); return i === -1 ? null : i; } + +export class CommonSegCode extends CommonSegGroup { + constructor(...a) { + super(...a); + this.reported_file_split = false; + this.align = parseSegmentAlign(this.yaml); + if (this.align === null) this.align = 0x10; + } + + get isCode() { return true; } + + // Python sets this before CommonSegGroup.__init__ parses the subsegments. + get bss_size() { return isDict(this.yaml) ? get(this.yaml, 'bss_size', 0) : 0; } + + get needs_symbols() { return true; } + + get vram_end() { + if (this.vram_start !== null && this.size !== null) return this.vram_start + this.size + this.bss_size; + return null; + } + + _generate_segment_from_all(repType, ReplaceClass, baseName, baseSeg, romStart = null, romEnd = null, vramStart = null) { + const rep = new ReplaceClass(romStart, romEnd, repType, baseName, vramStart, [], {}); + rep.extract = false; + rep.given_subalign = this.given_subalign; + rep.exclusive_ram_id = this.get_exclusive_ram_id(); + rep.given_dir = this.given_dir; + rep.given_symbol_name_format = this.symbol_name_format; + rep.given_symbol_name_format_no_rom = this.symbol_name_format_no_rom; + if (rep === baseSeg) throw new Error('AssertionError'); + rep.sibling = baseSeg; + rep.parent = this; + rep.is_generated = true; + rep.is_auto_segment = true; + if (rep.special_vram_segment) this.special_vram_segment = true; + rep.bss_contains_common = this.bss_contains_common; + return rep; + } + + _insert_all_auto_sections(ret, baseSegments, readonlyBefore) { + const als = opts.auto_link_sections; + if (als.length === 0) return ret; + const baseList = [...baseSegments.entries()]; + + let lastInsertedIndex = baseList.length - 1; + ret.forEach((seg, i) => { + if (seg.is_text()) lastInsertedIndex = i; + else if (readonlyBefore && seg.is_rodata()) lastInsertedIndex = i; + }); + + for (let i = 0; i < als.length; i++) { + const sect = als[i]; + for (const [, seg] of baseList) { + const linkSection = seg.get_linker_section_order(); + if (linkSection === sect || linkSection === '') { + lastInsertedIndex = ret.indexOf(seg); + continue; + } + let sibling = seg.siblings.get(sect); + if (sibling === undefined || sibling === null) { + const ReplaceClass = Segment.get_class_for_type(sect); + sibling = this._generate_segment_from_all(sect, ReplaceClass, seg.name, seg); + seg.siblings.set(sect, sibling); + lastInsertedIndex += 1; + ret.splice(lastInsertedIndex < 0 ? Math.max(0, ret.length + lastInsertedIndex) : lastInsertedIndex, 0, sibling); + } + lastInsertedIndex = ret.indexOf(sibling); + } + while (lastInsertedIndex < ret.length) { + const linkSection = ret.at(lastInsertedIndex).get_linker_section_order(); // Python negative indexing + if (linkSection !== '' && !als.slice(0, i + 1).includes(linkSection)) { + lastInsertedIndex -= 1; + if (lastInsertedIndex < 0) lastInsertedIndex = 0; + break; + } + lastInsertedIndex += 1; + } + } + return ret; + } + + parse_subsegments(segmentYaml) { + if (!has(segmentYaml, 'subsegments')) { + if (!this.parent) throw new Error(`No subsegments provided in top-level code segment ${this.name}`); + return []; + } + const baseSegments = new Map(); + let ret = []; + let prevStart = -1; + let prevVram = -1; + let lastRomEnd = null; + + let readonlyBefore = false; + const textIndex = listIndex(this.section_order, '.text'); + if (textIndex !== null) { + const rodataIndex = listIndex(this.section_order, '.rodata'); + if (rodataIndex !== null) readonlyBefore = rodataIndex < textIndex; + else { + const rdataIndex = listIndex(this.section_order, '.rdata'); + if (rdataIndex !== null) readonlyBefore = rdataIndex < textIndex; + } + } + + const subs = segmentYaml.subsegments; + for (let i = 0; i < subs.length; i++) { + const subYaml = subs[i]; + if (isList(subYaml) && subYaml.length === 1) continue; + const typ = Segment.parse_segment_type(subYaml); + let [start, isAutoSegment] = Segment.parse_segment_start(subYaml); + const cls = Segment.get_class_for_type(typ); + if (start === null) start = i === 0 ? this.rom_start : lastRomEnd; + + let end = null; + if (i < subs.length - 1) [end] = Segment.parse_segment_start(subs[i + 1]); + if (start !== null && end === null) { + const est = cls.estimate_size(subYaml); + if (est !== null) end = start + est; + } + if (end === null) end = this.get_next_seg_start(i, subs); + + if (start !== null && prevStart !== null && start < prevStart) { + log.error(`Error: Group segment '${this.name}' contains subsegments which are out of ascending rom order (0x${hex(prevStart)} followed by 0x${hex(start)})`); + } + + let vram = null; + if (start !== null) vram = this.get_most_parent().rom_to_ram(start); + + if (cls.is_noload() && lastRomEnd !== null) { start = lastRomEnd; end = lastRomEnd; } + + const segment = Segment.from_yaml(cls, subYaml, start, end, this, vram); + segment.is_auto_segment = isAutoSegment; + + if (segment.vram_start !== null && prevVram !== null && segment.vram_start < prevVram) { + log.error(`Error: Group segment '${this.name}' contains subsegments which are out of ascending vram order (0x${hex(prevVram)} followed by 0x${hex(segment.vram_start)}).\n` + + `Detected when processing file '${segment.name}' of type '${segment.type}'`); + } + + ret.push(segment); + if (segment.is_text()) baseSegments.set(segment.name, segment); + if (readonlyBefore && segment.is_rodata() && segment.sibling === null) baseSegments.set(segment.name, segment); + if (segment.special_vram_segment) this.special_vram_segment = true; + segment.bss_contains_common = this.bss_contains_common; + prevStart = start; + prevVram = segment.vram_start; + if (end !== null) lastRomEnd = end; + } + + for (const segment of ret) { + let sibling = baseSegments.has(segment.name) ? baseSegments.get(segment.name) : null; + if (sibling === segment) sibling = null; + segment.sibling = sibling; + if (sibling !== null) { + segment.siblings.set(sibling.get_linker_section_linksection(), sibling); + sibling.siblings.set(segment.get_linker_section_linksection(), segment); + } + } + + ret = this._insert_all_auto_sections(ret, baseSegments, readonlyBefore); + ret.forEach((s, i) => { s.index_within_group = i; }); + return ret; + } + + scan(romBytes) { + for (const sub of this.subsegments) if (sub.is_text() && sub.should_scan()) sub.scan(romBytes); + for (const sub of this.subsegments) if (!sub.is_text() && sub.should_scan()) sub.scan(romBytes); + } +} + +// ---------------------------------------------------------------- codesubsegment + +export class CommonSegCodeSubsegment extends Segment { + constructor(...a) { + super(...a); + this.init_code_subsegment(); + } + + init_code_subsegment() { + const vram = parseSegmentVram(this.yaml); + if (vram !== null) this.vram_start = vram; + this.str_encoding = isDict(this.yaml) ? get(this.yaml, 'str_encoding', null) : null; + this.spim_section = null; + const IC = rabbitizer().InstrCategory; + this.instr_category = IC.CPU; + if (opts.platform === 'ps2') this.instr_category = IC.R5900; + else if (opts.platform === 'psx') this.instr_category = IC.R3000GTE; + else if (opts.platform === 'psp') this.instr_category = IC.R4000ALLEGREX; + this.detect_redundant_function_end = isDict(this.yaml) ? get(this.yaml, 'detect_redundant_function_end', null) : null; + this.is_hasm = false; + this.use_gp_rel_macro = opts.use_gp_rel_macro; + } + + get isCodeSubsegment() { return true; } + get needs_symbols() { return true; } + get_linker_section() { return '.text'; } + + configure_disassembler_section(ds) { + const section = ds.get_section(); + section.isHandwritten = this.is_hasm; + section.instrCat = this.instr_category; + section.detectRedundantFunctionEnd = this.detect_redundant_function_end; + section.setGpRelHack(!this.use_gp_rel_macro); + } + + scan_code(romBytes, isHasm = false) { + this.is_hasm = isHasm; + if (this.is_auto_segment) return; + if (!Number.isInteger(this.rom_start)) { + log.error(`Segment '${this.name}' (type '${this.type}') requires a rom_start. Got '${this.rom_start === null ? 'None' : this.rom_start}'`); + } + const segmentRomStart = this.get_most_parent().rom_start; + if (!Number.isInteger(this.vram_start)) { + log.error(`Segment '${this.name}' (type '${this.type}') requires a vram address. Got '${this.vram_start === null ? 'None' : this.vram_start}'`); + } + this.spim_section = makeTextSection(this.rom_start, this.rom_end, this.vram_start, this.name, romBytes, + segmentRomStart, this.get_exclusive_ram_id()); + this.configure_disassembler_section(this.spim_section); + this.spim_section.analyze(); + this.spim_section.set_comment_offset(this.rom_start); + for (const func of this.spim_section.get_section().symbolList) this.process_insns(func); + } + + process_insns(funcSpim) { + const section = this.spim_section.get_section(); + symbols.createSymbolFromSpimSymbol(this.get_most_parent(), funcSpim.contextSym, false); + for (const referencedVram of funcSpim.referencedVrams) { + const cs = section.getSymbol(referencedVram, undefined, false); + if (cs !== null && cs !== undefined) symbols.createSymbolFromSpimSymbol(this.get_most_parent(), cs, false); + } + const instrs = funcSpim.instructions; + const symOff = funcSpim.instrAnalyzer.symbolInstrOffset; + for (let i = 0; i < instrs.length; i++) { + const insn = instrs[i]; + if (opts.platform === 'ps2') { + const TV = rabbitizer().TrinaryValue; + insn.flag_r5900UseDollar = this instanceof CommonSegC ? TV.FALSE : TV.TRUE; + insn.flag_r5900DisasmAsData = TV.TRUE; + } + const off = i * 4; + const symAddress = symOff instanceof Map ? symOff.get(off) : symOff[off]; + if (symAddress !== undefined) { + const cs = section.getSymbol(symAddress); + if (cs !== null && cs !== undefined) symbols.createSymbolFromSpimSymbol(this.get_most_parent(), cs, false); + } + } + } + + print_file_boundaries() { + if (!this.show_file_boundaries || !this.spim_section) return; + const section = this.spim_section.get_section(); + for (const inFileOffset of section.fileBoundaries) { + if (!this.parent.reported_file_split) { + this.parent.reported_file_split = true; + let symAddr = 0; + for (const sym of section.symbolList) { + const symOffset = sym.inFileOffset - section.inFileOffset; + if (inFileOffset === symOffset) break; + symAddr = sym.vram; + } + print(`\nSegment ${this.name}, symbol at vram ${hex(symAddr)} ends with extra nops, indicating a likely file split.`); + print('File split suggestions for this segment will follow in config yaml format:'); + } + print(` - [0x${hex(this.rom_start + inFileOffset)}, ${this.type}]`); + } + } + + should_scan() { + return opts.is_mode_active('code') && this.rom_start !== null && this.rom_end !== null; + } + + should_split() { return this.extract && opts.is_mode_active('code') && this.should_scan(); } + should_self_split() { return this.should_split(); } + + get_asm_file_header() { + const ret = ['.include "macro.inc"', '']; + ret.push(...this.get_asm_file_extra_directives()); + const preamble = opts.generated_s_preamble; + if (preamble) { ret.push(preamble); ret.push(''); } + ret.push(this.get_section_asm_line()); + ret.push(''); + return ret; + } + + get_asm_file_extra_directives() { + const ret = ['.set noat', '.set noreorder']; + if (opts.add_set_gp_64) ret.push('.set gp=64'); + ret.push(''); + return ret; + } + + asm_out_path() { return P(opts.asm_path, this.dir, `${this.name}.s`); } + out_path() { return this.asm_out_path(); } + + split_as_asm_file(outPath) { + if (this.spim_section === null) return; + if (!outPath) return; + mkdirp(parent(outPath)); + this.print_file_boundaries(); + const f = new TextFile(outPath, '\n'); + for (const line of this.get_asm_file_header()) f.write(line + '\n'); + f.write(this.spim_section.disassemble()); + f.close(); + } + + split_as_asmtu_file(outPath) { + const modern = atLeast('0.35.0'); + if (!modern) { + if (this.spim_section === null) return; + if (!outPath) return; + } + mkdirp(parent(outPath)); + this.print_file_boundaries(); + const f = new TextFile(outPath, '\n'); + if (this.spim_section !== null) { + for (const line of this.get_asm_file_header()) f.write(line + '\n'); + f.write(this.spim_section.disassemble()); + } + const wanted = (sibling) => sibling && sibling.isCodeSubsegment && sibling.spim_section !== null + && (!sibling.should_self_split() || (modern && opts.make_full_disasm_for_code)); + for (const sect of this.section_order) { + if (sect === this.get_linker_section_linksection()) continue; + const sibling = this.siblings.get(sect); + if (!sibling) continue; + if (wanted(sibling)) { + f.write('\n'); + f.write(`${sibling.get_section_asm_line()}\n\n`); + f.write(sibling.spim_section.disassemble()); + } + } + for (const [sect, sibling] of this.siblings) { + if (sect === this.get_linker_section_linksection()) continue; + if (this.section_order.includes(sect)) continue; + if (wanted(sibling)) { + f.write('\n'); + f.write(`${sibling.get_section_asm_line()}\n\n`); + f.write(sibling.spim_section.disassemble()); + } + } + f.close(); + } +} + +// ---------------------------------------------------------------- asm / hasm / asmtu + +export class CommonSegAsm extends CommonSegCodeSubsegment { + static is_text() { return true; } + get_section_flags() { return 'ax'; } + scan(romBytes) { + if (this.rom_start !== null && this.rom_end !== null && this.rom_start !== this.rom_end) this.scan_code(romBytes); + } + split() { + if (this.rom_start === this.rom_end) return; + this.split_as_asm_file(this.out_path()); + } +} + +export class CommonSegAsmtu extends CommonSegAsm { + split() { + if (this.rom_start === this.rom_end) return; + if (this.spim_section === null) return; + const outPath = this.out_path(); + this.split_as_asmtu_file(outPath); + } +} + +export class CommonSegHasm extends CommonSegAsm { + asm_out_path() { + if (opts.hasm_in_src_path) return P(opts.src_path, this.dir, `${this.name}.s`); + return super.asm_out_path(); + } + scan(romBytes) { + if (this.rom_start !== null && this.rom_end !== null && this.rom_start !== this.rom_end) this.scan_code(romBytes, true); + } + split() { + if (this.rom_start === this.rom_end) return; + const outPath = this.out_path(); + if (outPath && !exists(outPath)) this.split_as_asm_file(outPath); + } +} + +// ---------------------------------------------------------------- c / cpp + +// Python re: r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"' with DOTALL|MULTILINE +const STRIP_C_COMMENTS_RE = /\/\/[\s\S]*?(?=\n|$(?![\s\S]))|\/\*[\s\S]*?\*\/|'(?:\\[\s\S]|[^\\'])*'|"(?:\\[\s\S]|[^\\"])*"/g; +// r"^(?:static\s+)?[^\s]+\s+([^\s(]+)\(([^;)]*)\)[^;]+?{" MULTILINE +const C_FUNC_RE = /^(?:static\s+)?[^\s]+\s+([^\s(]+)\(([^;)]*)\)[^;]+?\{/gm; +// r"GLOBAL_ASM\(\"(\w+\/)*(\w+)\.s\"\)" MULTILINE +const C_GLOBAL_ASM_IDO_RE = /GLOBAL_ASM\("(\w+\/)*(\w+)\.s"\)/gm; + +export class CommonSegC extends CommonSegCodeSubsegment { + constructor(...a) { + super(...a); + this.defined_funcs = new Set(); + this.global_asm_funcs = new Set(); + this.global_asm_rodata_syms = new Set(); + this.file_extension = 'c'; + this.use_gp_rel_macro = opts.use_gp_rel_macro_nonmatching; + } + + static strip_c_comments(text) { + return text.replace(STRIP_C_COMMENTS_RE, (s) => (s.startsWith('/') ? ' ' : s)); + } + + static get_funcs_defined_in_c(cFile) { + const text = CommonSegC.strip_c_comments(readText(cFile)); + const out = new Set(); + for (const m of text.matchAll(C_FUNC_RE)) out.add(m[1]); + return out; + } + + static *find_all_instances(string, sub) { + let start = 0; + for (;;) { + start = string.indexOf(sub, start); + if (start === -1) return; + yield start; + start += sub.length; + } + } + + static get_close_parenthesis(string, pos) { + let count = 0; + for (;;) { + const c = string[pos]; + if (c === undefined) throw new Error('IndexError: string index out of range'); + if (c === '(') count += 1; + else if (c === ')') { + if (count === 0) return pos + 1; + count -= 1; + } + pos += 1; + } + } + + static *find_include_macro(text, macroName) { + for (const pos of CommonSegC.find_all_instances(text, `${macroName}(`)) { + const close = CommonSegC.get_close_parenthesis(text, pos + `${macroName}(`.length); + const contents = text.slice(pos, close); + const args = contents.split(','); + const strip = (s) => s.replace(/^[ )]+|[ )]+$/g, ''); + if (opts.use_legacy_include_asm) { + if (args.length >= 3) yield strip(args[2]); + } else if (args.length >= 2) yield strip(args[1]); + } + } + + static get_global_asm_funcs(cFile) { + const text = CommonSegC.strip_c_comments(readText(cFile)); + if (opts.compiler.name === 'IDO') return new Set([...text.matchAll(C_GLOBAL_ASM_IDO_RE)].map((m) => m[2])); + return new Set(CommonSegC.find_include_macro(text, 'INCLUDE_ASM')); + } + + static get_global_asm_rodata_syms(cFile) { + const text = CommonSegC.strip_c_comments(readText(cFile)); + if (opts.compiler.name === 'IDO') return new Set([...text.matchAll(C_GLOBAL_ASM_IDO_RE)].map((m) => m[2])); + return new Set(CommonSegC.find_include_macro(text, 'INCLUDE_RODATA')); + } + + static is_text() { return true; } + get_section_flags() { return 'ax'; } + + out_path() { return P(opts.src_path, this.dir, `${this.name}.${this.file_extension}`); } + + scan(romBytes) { + if (this.rom_start !== null && this.rom_end !== null && this.rom_start !== this.rom_end) { + const path = this.out_path(); + if (path && opts.do_c_func_detection && exists(path)) { + this.defined_funcs = CommonSegC.get_funcs_defined_in_c(path); + this.global_asm_funcs = CommonSegC.get_global_asm_funcs(path); + this.global_asm_rodata_syms = CommonSegC.get_global_asm_rodata_syms(path); + for (const s of this.defined_funcs) symbols.state.to_mark_as_defined.add(s); + for (const s of this.global_asm_funcs) symbols.state.to_mark_as_defined.add(s); + for (const s of this.global_asm_rodata_syms) symbols.state.to_mark_as_defined.add(s); + } + this.scan_code(romBytes); + } + } + + split() { + const modern = atLeast('0.35.0'); + if (this.is_auto_segment) { + if (modern && opts.make_full_disasm_for_code) this.split_as_asmtu_file(this.asm_out_path()); + return; + } + if (this.rom_start === this.rom_end) return; + + const asmOutDir = P(opts.nonmatchings_path, this.dir); + const matchingAsmOutDir = P(opts.matchings_path, this.dir); + this.print_file_boundaries(); + + const S = spim(); + let rodataSectionType = ''; + let rodataSpimSegment = null; + if (opts.migrate_rodata_to_functions) { + for (const sect of ['.rodata', '.rdata']) { + const rs = this.siblings.get(sect); + if (!rs) continue; + if (rs.is_generated) continue; + if (!rs.type.startsWith('.')) { + log.write(`\nProblem detected with the \`${rs.type}\` section of the \`${rs.name}\` file during rodata migration.`, { status: 'warn' }); + log.write(`\t The \`${rs.type}\` section was not prefixed with a dot, which is required for the rodata migration feature to work properly and avoid build errors due to duplicated symbols at link-time.`); + log.error(`\t To fix this, please prefix the section type with a dot (like \`.${rs.type}\`).`); + } + rodataSectionType = rs.get_linker_section_linksection(); + rodataSpimSegment = rs.spim_section.get_section(); + break; + } + } + + const nameOf = (s) => (modern ? s.getNameUnquoted() : s.getName()); + + const entries = S.mips.FunctionRodataEntry.getAllEntriesFromSections(this.spim_section.get_section(), rodataSpimSegment); + + let isNewCFile = false; + const cPath = this.out_path(); + if (cPath) { + if (!exists(cPath) && opts.create_c_files) { + this.create_c_file(asmOutDir, cPath, entries); + isNewCFile = true; + } + this.create_asm_dependencies_file(cPath, asmOutDir, isNewCFile, entries); + } + + for (const entry of entries) { + entry.sectionText = this.get_linker_section_linksection(); + entry.sectionRodata = rodataSectionType; + if (entry.function !== null && entry.function !== undefined) { + const fname = nameOf(entry.function); + if (this.global_asm_funcs.has(fname) || isNewCFile || opts.disassemble_all) { + const funcSym = this.get_symbol(entry.function.vram, { in_segment: true, type: 'func', local_only: true }); + if (!funcSym) throw new Error('AssertionError'); + if (!this.global_asm_funcs.has(fname) && opts.disassemble_all && !isNewCFile) { + this.create_c_asm_file(entry, matchingAsmOutDir, funcSym); + } else { + this.create_c_asm_file(entry, asmOutDir, funcSym); + } + } + } else { + for (const rsym of entry.rodataSyms) { + if (this.global_asm_rodata_syms.has(nameOf(rsym)) || isNewCFile || opts.disassemble_all) { + const rodataSym = this.get_symbol(rsym.vram, { in_segment: true, local_only: true }); + if (!rodataSym) throw new Error('AssertionError'); + this.create_unmigrated_rodata_file(rsym, asmOutDir, rodataSym); + } + } + } + } + + if (opts.make_full_disasm_for_code) { + const section = this.spim_section.get_section(); + const oldValue = section.getGpRelHack(); + section.setGpRelHack(false); + const TV = modern && opts.platform === 'ps2' ? rabbitizer().TrinaryValue : null; + if (TV) for (const func of section.symbolList) for (const inst of func.instructions) inst.flag_r5900UseDollar = TV.TRUE; + this.split_as_asmtu_file(this.asm_out_path()); + if (TV) for (const func of section.symbolList) for (const inst of func.instructions) inst.flag_r5900UseDollar = TV.FALSE; + section.setGpRelHack(oldValue); + } + } + + get_c_preamble() { return [opts.generated_c_preamble, '']; } + + check_gaps_in_migrated_rodata(func, rodataList) { + const modern = atLeast('0.35.0'); + const nameOf = (s) => (modern ? s.getNameUnquoted() : s.getName()); + for (let i = 0; i < rodataList.length - 1; i++) { + const a = rodataList[i]; + const b = rodataList[i + 1]; + if (a.vramEnd !== b.vram) { + log.write('\nA gap was detected in migrated rodata symbols!', { status: 'warn' }); + log.write(`\t In function '${nameOf(func)}' (0x${hex(func.vram, 8)}), gap detected between '${nameOf(a)}' (0x${hex(a.vram, 8)}) and '${nameOf(b)}' (0x${hex(b.vram, 8)})`); + log.write(`\t The address of the missing rodata symbol is 0x${hex(a.vramEnd, 8)}`); + log.write('\t Try to force the migration of that symbol with `force_migration:True` in the symbol_addrs.txt file; or avoid the migration of symbols around this address with `force_not_migration:True`'); + } + } + } + + create_c_asm_file(entry, outDir, funcSym) { + const outpath = P(outDir, this.name, `${funcSym.filename}.s`); + if (exists(outpath) && !funcSym.extract) return; + mkdirp(parent(outpath)); + const f = new TextFile(outpath, '\n'); + if (opts.asm_inc_header) f.write(opts.asm_inc_header.split('\n').join(opts.c_newline)); + const R = rabbitizer(); + const named = R.config.regNames_namedRegisters; + R.config.regNames_namedRegisters = opts.named_regs_for_c_funcs; + try { + entry.writeToFile(f); + } finally { + R.config.regNames_namedRegisters = named; + } + if (entry.function !== null && entry.function !== undefined) { + this.check_gaps_in_migrated_rodata(entry.function, entry.rodataSyms); + this.check_gaps_in_migrated_rodata(entry.function, entry.lateRodataSyms); + } + f.close(); + this.log(`Disassembled ${funcSym.filename} to ${outpath}`); + } + + create_unmigrated_rodata_file(spimRodataSym, outDir, rodataSym) { + const outpath = P(outDir, this.name, `${rodataSym.filename}.s`); + if (exists(outpath) && !rodataSym.extract) return; + mkdirp(parent(outpath)); + const f = new TextFile(outpath, '\n'); + const preamble = opts.generated_s_preamble; + if (preamble) f.write(preamble + '\n'); + if (rodataSym.linker_section === null) throw new Error(`AssertionError: ${rodataSym.name}`); + f.write(`.section ${rodataSym.linker_section}\n\n`); + f.write(spimRodataSym.disassemble()); + f.close(); + this.log(`Disassembled ${rodataSym.filename} to ${outpath}`); + } + + get_c_line_include_macro(sym, asmOutDir, macroName) { + if (opts.compiler.name === 'IDO') { + const asmOutpath = P(asmOutDir, this.name, `${sym.filename}.s`); + const rel = relpath(asmOutpath, opts.base_path, rt.cwd); + return `#pragma GLOBAL_ASM("${P(rel)}")`; + } + if (opts.use_legacy_include_asm) { + const relDir = relativeTo(asmOutDir, opts.nonmatchings_path); + return `${macroName}(const s32, "${P(relDir, this.name)}", ${sym.filename});`; + } + return `${macroName}("${P(asmOutDir, this.name)}", ${sym.filename});`; + } + + get_c_lines_for_function(sym, spimSym, asmOutDir) { + const lines = []; + const modern = atLeast('0.35.0'); + const ins = spimSym.instructions; + if (opts.auto_decompile_empty_functions && ins.length === 2 && ins[0].isReturn() && ins[1].isNop()) { + lines.push(`void ${modern ? spimSym.getNameUnquoted() : spimSym.getName()}(void) {`); + lines.push('}'); + } else { + lines.push(this.get_c_line_include_macro(sym, asmOutDir, 'INCLUDE_ASM')); + } + lines.push(''); + return lines; + } + + get_c_lines_for_rodata_sym(sym, asmOutDir) { + return [this.get_c_line_include_macro(sym, asmOutDir, 'INCLUDE_RODATA'), '']; + } + + create_c_file(asmOutDir, cPath, entries) { + let lines = this.get_c_preamble(); + for (const entry of entries) { + if (entry.function !== null && entry.function !== undefined) { + const funcSym = this.get_symbol(entry.function.vram, { in_segment: true, type: 'func', local_only: true }); + lines = lines.concat(this.get_c_lines_for_function(funcSym, entry.function, asmOutDir)); + } else { + for (const rsym of entry.rodataSyms) { + const rodataSym = this.get_symbol(rsym.vram, { in_segment: true, local_only: true }); + lines = lines.concat(this.get_c_lines_for_rodata_sym(rodataSym, asmOutDir)); + } + } + } + mkdirp(parent(cPath)); + writeText(cPath, lines.join('\n'), opts.c_newline); + log.write(`Wrote ${this.name} to ${cPath}`); + } + + create_asm_dependencies_file(cPath, asmOutDir, isNewCFile, entries) { + if (!opts.create_asm_dependencies) return; + if (this.global_asm_funcs.size + this.global_asm_rodata_syms.size === 0 && !isNewCFile) return; + const modern = atLeast('0.35.0'); + const nameOf = (s) => (modern ? s.getNameUnquoted() : s.getName()); + const buildPath = opts.build_path; + const depPath = P(buildPath, withSuffix(cPath, '.asmproc.d')); + mkdirp(parent(depPath)); + const f = new TextFile(depPath, opts.c_newline); + const oPath = opts.use_o_as_suffix + ? P(buildPath, withSuffix(cPath, '.o')) + : P(buildPath, withSuffix(cPath, suffix(cPath) + '.o')); + f.write(`${oPath}:`); + const dependList = []; + for (const entry of entries) { + if (entry.function !== null && entry.function !== undefined) { + const funcName = nameOf(entry.function); + if (this.global_asm_funcs.has(funcName) || isNewCFile) { + const outpath = P(asmOutDir, this.name, funcName + '.s'); + mkdirp(parent(outpath)); + dependList.push(outpath); + f.write(` \\\n ${outpath}`); + } + } else { + for (const rsym of entry.rodataSyms) { + const rodataName = nameOf(rsym); + if (this.global_asm_rodata_syms.has(rodataName) || isNewCFile) { + const outpath = P(asmOutDir, this.name, rodataName + '.s'); + mkdirp(parent(outpath)); + dependList.push(outpath); + f.write(` \\\n ${outpath}`); + } + } + } + } + f.write('\n'); + for (const d of dependList) f.write(`${d}:\n`); + f.close(); + } +} + +export class CommonSegCpp extends CommonSegC { + constructor(...a) { super(...a); this.file_extension = 'cpp'; } +} + +// ---------------------------------------------------------------- data / rodata / bss + +export class CommonSegData extends CommonSegCodeSubsegment { + constructor(...a) { + super(...a); + // CommonSegGroup.__init__ (next in the Python MRO) parses subsegments. + this.subsegments = this.group_parse_subsegments(this.yaml); + } + + get isGroup() { return true; } + static is_data() { return true; } + + asm_out_path() { + let typ = this.type; + if (typ.startsWith('.')) typ = typ.slice(1); + return P(opts.data_path, this.dir, `${this.name}.${typ}.s`); + } + + out_path() { + if (this.type.startsWith('.')) { + if (this.sibling) return this.sibling.out_path(); + return P(opts.src_path, this.dir, `${this.name}.c`); + } + return this.asm_out_path(); + } + + scan(romBytes) { + this.group_scan(romBytes); + if (this.rom_start !== null && this.rom_end !== null) this.disassemble_data(romBytes); + } + + get_asm_file_extra_directives() { return []; } + + split(romBytes) { + this.group_split(romBytes); + if (this.spim_section === null || !this.should_self_split()) return; + this.split_as_asm_file(this.asm_out_path()); + } + + should_self_split() { + return opts.is_mode_active('data') && (!this.type.startsWith('.') || opts.disassemble_all); + } + + should_scan() { return true; } + should_split() { return true; } + cache() { return [Segment.prototype.cache.call(this), this.group_cache()]; } + get_linker_section() { return '.data'; } + get_section_flags() { return 'wa'; } + get_linker_entries() { return Segment.prototype.get_linker_entries.call(this); } + get statistics() { return this.group_statistics(); } + + configure_disassembler_section(ds) { + const section = ds.get_section(); + if (opts.data_string_encoding !== null) section.stringEncoding = opts.data_string_encoding; + if (this.str_encoding !== null) section.stringEncoding = this.str_encoding; + } + + check_disasm_preconditions() { + if (!Number.isInteger(this.rom_start)) { + log.error(`Segment '${this.name}' (type '${this.type}') requires a rom_start. Got '${this.rom_start === null ? 'None' : this.rom_start}'`); + } + if (!Number.isInteger(this.rom_end)) throw new Error(`AssertionError: ${this.rom_end}`); + const segmentRomStart = this.get_most_parent().rom_start; + if (!Number.isInteger(segmentRomStart)) throw new Error(`AssertionError: ${segmentRomStart}`); + if (!Number.isInteger(this.vram_start)) { + log.error(`Segment '${this.name}' (type '${this.type}') requires a vram address. Got '${this.vram_start === null ? 'None' : this.vram_start}'`); + } + return segmentRomStart; + } + + disassemble_data(romBytes) { + if (this.is_auto_segment) return; + const segmentRomStart = this.check_disasm_preconditions(); + this.spim_section = makeDataSection(this.rom_start, this.rom_end, this.vram_start, this.name, romBytes, + segmentRomStart, this.get_exclusive_ram_id()); + this.configure_disassembler_section(this.spim_section); + this.spim_section.analyze(); + this.spim_section.set_comment_offset(this.rom_start); + + let rodataEncountered = false; + const section = this.spim_section.get_section(); + for (const symbol of section.symbolList) { + symbols.createSymbolFromSpimSymbol(this.get_most_parent(), symbol.contextSym, true); + for (const referencedVram of symbol.referencedVrams) { + const cs = section.getSymbol(referencedVram, undefined, false); + if (cs !== null && cs !== undefined) symbols.createSymbolFromSpimSymbol(this.get_most_parent(), cs, false); + } + if (this.suggestion_rodata_section_start && !rodataEncountered && this.get_most_parent().rodata_follows_data) { + if (symbol.contextSym.isJumpTable()) { + rodataEncountered = true; + print(`\n\nData segment ${this.name}, symbol at vram ${hex(symbol.contextSym.vram)} is a jumptable, indicating the start of the rodata section _may_ be near here.`); + print('Please note the real start of the rodata section may be way before this point.'); + if (symbol.contextSym.vromAddress !== null) print(` - [0x${hex(symbol.contextSym.vromAddress)}, rodata]`); + } + } + } + } +} +Object.assign(CommonSegData.prototype, { + get_next_seg_start: GroupMixin.get_next_seg_start, + group_parse_subsegments: GroupMixin.group_parse_subsegments, + group_statistics: GroupMixin.group_statistics, + group_scan: GroupMixin.group_scan, + group_split: GroupMixin.group_split, + group_cache: GroupMixin.group_cache, + get_subsegment_for_ram: GroupMixin.get_subsegment_for_ram, + get_next_subsegment_for_ram: GroupMixin.get_next_subsegment_for_ram, + pair_subsegments_to_other_segment: GroupMixin.pair_subsegments_to_other_segment, +}); + +export class CommonSegRodata extends CommonSegData { + get_linker_section() { return '.rodata'; } + get_section_flags() { return 'a'; } + static is_data() { return false; } + static is_rodata() { return true; } + + get_possible_text_subsegment_for_symbol(rodataSym) { + if (this.sibling !== null || !opts.pair_rodata_to_text) return null; + if (!rodataSym.shouldMigrate()) return null; + const refs = rodataSym.contextSym.referenceFunctions; + const list = refs instanceof Set ? [...refs] : [...refs]; + if (list.length !== 1) return null; + const func = list[0]; + const textSegment = this.parent.get_subsegment_for_ram(func.vram); + if (textSegment === null || !textSegment.is_text()) return null; + return [textSegment, func]; + } + + configure_disassembler_section(ds) { + const section = ds.get_section(); + if (opts.string_encoding !== null) section.stringEncoding = opts.string_encoding; + if (this.str_encoding !== null) section.stringEncoding = this.str_encoding; + } + + disassemble_data(romBytes) { + if (this.is_auto_segment) return; + const segmentRomStart = this.check_disasm_preconditions(); + this.spim_section = makeRodataSection(this.rom_start, this.rom_end, this.vram_start, this.name, romBytes, + segmentRomStart, this.get_exclusive_ram_id()); + this.configure_disassembler_section(this.spim_section); + this.spim_section.analyze(); + this.spim_section.set_comment_offset(this.rom_start); + + const modern = atLeast('0.35.0'); + const nameOf = (s) => (modern ? s.getNameUnquoted() : s.getName()); + const possibleTextSegments = new Set(); + let lastJumptableAddrRemainder = 0; + const misaligned = []; + const section = this.spim_section.get_section(); + for (const symbol of section.symbolList) { + const generated = symbols.createSymbolFromSpimSymbol(this.get_most_parent(), symbol.contextSym, true); + generated.linker_section = this.get_linker_section_linksection(); + for (const referencedVram of symbol.referencedVrams) { + const cs = section.getSymbol(referencedVram, undefined, false); + if (cs !== null && cs !== undefined) symbols.createSymbolFromSpimSymbol(this.get_most_parent(), cs, false); + } + const possible = this.get_possible_text_subsegment_for_symbol(symbol); + if (possible !== null) { + const [textSegment, refFunc] = possible; + if (!possibleTextSegments.has(textSegment)) { + print(`\nRodata segment '${this.name}' may belong to the text segment '${textSegment.name}'`); + print(` Based on the usage from the function ${nameOf(refFunc)} to the symbol ${nameOf(symbol)}`); + possibleTextSegments.add(textSegment); + } + } + if (opts.platform === 'psx' || opts.platform === 'ps2') { + if (generated.type === 'jtbl') { + const vramDiff = generated.vram_start - this.vram_start; + const rem = ((vramDiff % 8) + 8) % 8; + if (rem !== lastJumptableAddrRemainder) { + lastJumptableAddrRemainder = rem; + misaligned.push(this.rom_start + vramDiff); + } + } + } + } + if (misaligned.length > 0) { + print(`\nThe rodata segment '${this.name}' has jumptables that are not aligned properly file-wise, indicating one or more likely file split.`); + print('File split suggestions for this segment will follow in config yaml format:'); + for (const off of misaligned) print(` - [0x${hex(off)}, ${this.type}]`); + print(); + } + } +} + +export class CommonSegRdata extends CommonSegRodata { + get_linker_section() { return '.rdata'; } +} + +export class CommonSegSdata extends CommonSegData { + get_linker_section() { return '.sdata'; } +} + +export class CommonSegBss extends CommonSegData { + get isBss() { return true; } + get_linker_section() { return '.bss'; } + get_section_flags() { return 'wa'; } + static is_data() { return !opts.ld_bss_is_noload; } + static is_noload() { return !!opts.ld_bss_is_noload; } + + configure_disassembler_section() {} + + disassemble_data(romBytes) { + if (!opts.ld_bss_is_noload) { super.disassemble_data(romBytes); return; } + if (this.is_auto_segment) return; + const segmentRomStart = this.check_disasm_preconditions(); + const next = this.parent.get_next_subsegment_for_ram(this.vram_start, this.index_within_group); + const bssEnd = next === null ? this.get_most_parent().vram_end : next.vram_start; + if (!Number.isInteger(bssEnd)) throw new Error(`AssertionError: ${this.name} ${bssEnd}`); + this.spim_section = makeBssSection(this.rom_start, this.rom_end, this.vram_start, bssEnd, this.name, + segmentRomStart, this.get_exclusive_ram_id()); + this.configure_disassembler_section(this.spim_section); + this.spim_section.analyze(); + this.spim_section.set_comment_offset(this.rom_start); + for (const s of this.spim_section.get_section().symbolList) { + symbols.createSymbolFromSpimSymbol(this.get_most_parent(), s.contextSym, true); + } + } + + should_scan() { + if (!opts.ld_bss_is_noload) return super.should_scan(); + return opts.is_mode_active('code') && this.vram_start !== null; + } +} + +export class CommonSegSbss extends CommonSegBss { + get_linker_section() { return '.sbss'; } +} + +// ---------------------------------------------------------------- bin family + +export class CommonSegBin extends CommonSegment { + static is_data() { return true; } + out_path() { return P(opts.asset_path, this.dir, `${this.name}.bin`); } + + split(romBytes) { + const path = this.out_path(); + mkdirp(parent(path)); + if (this.rom_end === null) log.error(`segment ${this.name} needs to know where it ends; add a position marker [0xDEADBEEF] after it`); + if (this.size === null || this.size <= 0) log.error(`Segment ${this.name} has zero size.`); + writeBytes(path, romBytes.subarray(this.rom_start, this.rom_end)); + this.log(`Wrote ${this.name} to ${path}`); + } + + get statistics_type() { return this.is_name_default() ? 'unk' : this.type; } +} + +const REGEX_SYM_NAME_NORMALIZER = /[^0-9a-zA-Z_]/g; + +export class CommonSegTextbin extends CommonSegment { + constructor(...a) { + super(...a); + this.use_src_path = isDict(this.yaml) ? get(this.yaml, 'use_src_path', false) : false; + } + + static is_text() { return true; } + get_linker_section() { return '.text'; } + get_section_flags() { return 'ax'; } + + out_path() { + if (truthy(this.use_src_path)) return P(opts.src_path, this.dir, `${this.name}.s`); + return P(opts.data_path, this.dir, `${this.name}.s`); + } + + bin_path() { + let typ = this.type; + if (typ.startsWith('.')) typ = typ.slice(1); + return P(opts.asset_path, this.dir, `${this.name}.${typ}.bin`); + } + + write_bin(romBytes) { + const binpath = this.bin_path(); + mkdirp(parent(binpath)); + writeBytes(binpath, romBytes.subarray(this.rom_start, this.rom_end)); + this.log(`Wrote ${this.name} to ${binpath}`); + } + + write_asm_contents(romBytes, f) { + if (!atLeast('0.35.0')) { this.write_asm_contents_0_34(romBytes, f); return; } + const binpath = this.bin_path(); + let asmLabel = opts.asm_function_macro; + if (!this.is_text()) asmLabel = opts.asm_data_macro; + + f.write(`${this.get_section_asm_line()}\n\n`); + let symName = null; let symNameEnd = null; let symSizeMatches = null; + const vram = this.rom_to_ram(this.rom_start); + if (vram !== null) { + const sym = this.get_symbol(vram, { in_segment: true }); + if (sym !== null) { + sym.defined = true; + symName = sym.name; + symNameEnd = sym.given_name_end; + if (sym.given_size === null || sym.given_size === this.rom_end - this.rom_start) symSizeMatches = this.rom_end - this.rom_start; + } + } + if (symName === null) { + const n = this.name.replace(REGEX_SYM_NAME_NORMALIZER, '_'); + let sfx; + if (this.is_text()) sfx = 'textbin'; + else if (this.is_data()) sfx = 'databin'; + else if (this.is_rodata()) sfx = 'rodatabin'; + else sfx = 'incbin'; + symName = `__${n}_${sfx}`; + } + if (opts.asm_nonmatching_label_macro !== '') { + const siz = symSizeMatches !== null ? `, 0x${hex(symSizeMatches)}` : ''; + f.write(`${opts.asm_nonmatching_label_macro} ${symName}${siz}\n\n`); + } + f.write(`${asmLabel} ${symName}\n`); + if (asmLabel === '.globl') { + if (this.is_text()) f.write(`.ent ${symName}\n`); + f.write(`${symName}:\n`); + } + f.write(`.incbin "${binpath}"\n`); + if (opts.asm_emit_size_directive) f.write(`.size ${symName}, . - ${symName}\n`); + if (this.is_text() && opts.asm_end_label !== '') f.write(`${opts.asm_end_label} ${symName}\n`); + else if (opts.asm_data_end_label !== '') f.write(`${opts.asm_data_end_label} ${symName}\n`); + if (symNameEnd !== null && symSizeMatches !== null) { + f.write(`${asmLabel} ${symNameEnd}\n`); + if (asmLabel === '.globl') f.write(`${symNameEnd}:\n`); + if (this.is_text() && opts.asm_end_label !== '') f.write(`${opts.asm_end_label} ${symNameEnd}\n`); + else if (opts.asm_data_end_label !== '') f.write(`${opts.asm_data_end_label} ${symNameEnd}\n`); + } + } + + write_asm_contents_0_34(romBytes, f) { + const binpath = this.bin_path(); + let asmLabel = opts.asm_function_macro; + if (!this.is_text()) asmLabel = opts.asm_data_macro; + f.write(`${this.get_section_asm_line()}\n\n`); + let sym = null; + const vram = this.rom_to_ram(this.rom_start); + if (vram !== null) sym = this.get_symbol(vram, { in_segment: true }); + if (sym !== null) { + f.write(`${asmLabel} ${sym.name}\n`); + if (asmLabel === '.globl') { + if (this.is_text()) f.write(`.ent ${sym.name}\n`); + f.write(`${sym.name}:\n`); + } + sym.defined = true; + } + f.write(`.incbin "${binpath}"\n`); + if (sym !== null) { + if (this.is_text() && opts.asm_end_label !== '') f.write(`${opts.asm_end_label} ${sym.name}\n`); + if (sym.given_name_end !== null) { + if (sym.given_size === null || sym.given_size === this.rom_end - this.rom_start) { + f.write(`${asmLabel} ${sym.given_name_end}\n`); + if (asmLabel === '.globl') f.write(`${sym.given_name_end}:\n`); + } + } + } + } + + split(romBytes) { + if (this.rom_end === null) log.error(`segment ${this.name} needs to know where it ends; add a position marker [0xDEADBEEF] after it`); + this.write_bin(romBytes); + const sPath = this.out_path(); + if (exists(sPath)) return; + mkdirp(parent(sPath)); + const f = new TextFile(sPath, null); + f.write('.include "macro.inc"\n\n'); + const preamble = opts.generated_s_preamble; + if (preamble) f.write(preamble + '\n'); + this.write_asm_contents(romBytes, f); + for (const sect of this.section_order) { + if (sect === this.get_linker_section_linksection()) continue; + const sibling = this.siblings.get(sect); + if (!sibling) continue; + if (sibling instanceof CommonSegTextbin) { + f.write('\n'); + sibling.write_asm_contents(romBytes, f); + } + } + f.close(); + } + + should_scan() { return this.rom_start !== null && this.rom_end !== null; } + should_split() { return this.extract && this.should_scan(); } +} + +function incbinSplit(self, romBytes) { + if (self.rom_end === null) log.error(`segment ${self.name} needs to know where it ends; add a position marker [0xDEADBEEF] after it`); + self.write_bin(romBytes); + if (self.sibling === null) { + const sPath = self.out_path(); + mkdirp(parent(sPath)); + const f = new TextFile(sPath, null); + f.write('.include "macro.inc"\n\n'); + const preamble = opts.generated_s_preamble; + if (preamble) f.write(preamble + '\n'); + self.write_asm_contents(romBytes, f); + f.close(); + } +} + +export class CommonSegDatabin extends CommonSegTextbin { + static is_text() { return false; } + static is_data() { return true; } + get_linker_section() { return '.data'; } + get_section_flags() { return 'wa'; } + split(romBytes) { incbinSplit(this, romBytes); } +} + +export class CommonSegRodatabin extends CommonSegTextbin { + static is_text() { return false; } + static is_rodata() { return true; } + get_linker_section() { return '.rodata'; } + get_section_flags() { return 'a'; } + split(romBytes) { incbinSplit(this, romBytes); } +} + +// ---------------------------------------------------------------- header / lib / pad / linker_offset + +export class CommonSegHeader extends CommonSegment { + static is_data() { return true; } + should_split() { return this.extract && opts.is_mode_active('code'); } + + static get_line(typ, data, comment) { + let dstr; + if (typ === 'ascii') { + // bytes.decode("ASCII").strip() + for (const b of data) if (b > 0x7f) throw new Error("UnicodeDecodeError: 'ascii' codec can't decode byte"); + let text = Buffer.from(data).toString('latin1').replace(/^[\s\x1c-\x1f]+|[\s\x1c-\x1f]+$/g, ''); + text = text.replaceAll('\x00', '\\0'); + dstr = '"' + text + '"'; + } else { + dstr = '0x' + Buffer.from(data).toString('hex').toUpperCase(); + } + dstr = ljust(dstr, 20 - typ.length); + return `.${typ} ${dstr} /* ${comment} */`; + } + + get_line(typ, data, comment) { return this.constructor.get_line(typ, data, comment); } + + out_path() { return P(opts.asm_path, this.dir, `${this.name}.s`); } + parse_header() { return []; } + + split(romBytes) { + const lines = this.parse_header(romBytes); + const srcPath = this.out_path(); + mkdirp(parent(srcPath)); + writeText(srcPath, lines.join('\n'), '\n'); + this.log(`Wrote ${this.name} to ${srcPath}`); + } + + static get_default_name() { return 'header'; } +} + +export class LinkerEntryLib extends LinkerEntry { + constructor(segment, srcPaths, objectPath, sectionOrder, sectionLink, noload) { + super(segment, srcPaths, objectPath, sectionOrder, sectionLink, noload); + this.object_path = objectPath; + } + emit_entry(w) { this.emit_path(w); } +} + +export class CommonSegLib extends CommonSegment { + constructor(...a) { + super(...a); + const vram = parseSegmentVram(this.yaml); + if (vram !== null) this.vram_start = vram; + if (isDict(this.yaml)) { + this.object = get(this.yaml, 'object', null); + this.section = get(this.yaml, 'section', '.text'); + if (this.object === null) log.error(`Error: ${this.name} is missing object file`); + } else { + if (this.args.length < 1) log.error(`Error: ${this.name} is missing object file`); + if (this.args.length > 1) [this.object, this.section] = [this.args[0], this.args[1]]; + else [this.object, this.section] = [this.args[0], '.text']; + } + this.extract = false; + } + + get_linker_section() { return this.section; } + + get_linker_entries() { + const path = P(opts.lib_path, this.name); + const objectPath = P(`${path}.a:${this.object}.o`); + return [new LinkerEntryLib(this, [path], objectPath, this.get_linker_section_order(), + this.get_linker_section_linksection(), this.is_noload())]; + } +} + +export class LinkerEntryPad extends LinkerEntry { + constructor(segment) { + super(segment, [], '.', 'pad', 'pad', false); + this.object_path = null; + } + emit_entry(w) { w._writeln(`. += 0x${hex(this.segment.size)};`); } +} + +export class CommonSegPad extends CommonSegment { + get_linker_section_order() { return ''; } + get_linker_section_linksection() { return ''; } + get_linker_entries() { return [new LinkerEntryPad(this)]; } +} + +export class LinkerEntryOffset extends LinkerEntry { + constructor(segment) { + super(segment, [], '.', 'linker_offset', 'linker_offset', false); + this.object_path = null; + } + emit_entry(w) { w._write_symbol(`${this.segment.get_cname()}_OFFSET`, '.'); } +} + +export class CommonSegLinker_offset extends Segment { + get_linker_section_order() { return ''; } + get_linker_section_linksection() { return ''; } + get_linker_entries() { return [new LinkerEntryOffset(this)]; } +} + +export { LinkerWriter, pathName, readText }; diff --git a/packages/romdev-splat/src/segtypes/index.js b/packages/romdev-splat/src/segtypes/index.js new file mode 100644 index 00000000..544b66d7 --- /dev/null +++ b/packages/romdev-splat/src/segtypes/index.js @@ -0,0 +1,71 @@ +// Registers the segment types by platform, mirroring splat's module lookup +// (segtypes.., then segtypes.common.). +import { registry } from './registry.js'; +import { LinkerEntry } from './linker_entry.js'; +import * as C from './common.js'; +import * as N from './platform.js'; +import { loadExtension } from '../ext/index.js'; + +registry.LinkerEntry = LinkerEntry; +registry.loadExtension = loadExtension; + +Object.assign(registry.common, { + asm: C.CommonSegAsm, + asmtu: C.CommonSegAsmtu, + bin: C.CommonSegBin, + bss: C.CommonSegBss, + c: C.CommonSegC, + code: C.CommonSegCode, + cpp: C.CommonSegCpp, + data: C.CommonSegData, + databin: C.CommonSegDatabin, + group: C.CommonSegGroup, + hasm: C.CommonSegHasm, + header: C.CommonSegHeader, + lib: C.CommonSegLib, + linker_offset: C.CommonSegLinker_offset, + pad: C.CommonSegPad, + rdata: C.CommonSegRdata, + rodata: C.CommonSegRodata, + rodatabin: C.CommonSegRodatabin, + sbss: C.CommonSegSbss, + sdata: C.CommonSegSdata, + textbin: C.CommonSegTextbin, +}); + +Object.assign(registry.platform.n64, { + ci: N.N64SegCi, + ci4: N.N64SegCi4, + ci8: N.N64SegCi8, + header: N.N64SegHeader, + i1: N.N64SegI1, + i4: N.N64SegI4, + i8: N.N64SegI8, + ia16: N.N64SegIa16, + ia4: N.N64SegIa4, + ia8: N.N64SegIa8, + img: N.N64SegImg, + ipl3: N.N64SegIpl3, + palette: N.N64SegPalette, + rgba16: N.N64SegRgba16, + rgba32: N.N64SegRgba32, + rsp: N.N64SegRsp, + vtx: N.N64SegVtx, +}); + +Object.assign(registry.platform.psx, { + header: N.PsxSegHeader, +}); + +// splat segment types this port does not implement (no romdev target uses +// them): resolve them so the lookup order stays the same as splat's, then refuse. +function notPorted(name) { + return class { + constructor() { throw new Error(`romdev-splat: segment type '${name}' is not ported`); } + static is_noload() { return false; } + static estimate_size() { return null; } + }; +} +for (const t of ['eh_frame', 'gcc_except_table']) registry.common[t] = notPorted(t); +for (const t of ['gfx', 'mio0', 'yay0', 'decompressor']) registry.platform.n64[t] = notPorted(t); +for (const t of ['ctor', 'lit4', 'lit8', 'vtables']) registry.platform.ps2[t] = notPorted(t); diff --git a/packages/romdev-splat/src/segtypes/linker_entry.js b/packages/romdev-splat/src/segtypes/linker_entry.js new file mode 100644 index 00000000..45971233 --- /dev/null +++ b/packages/romdev-splat/src/segtypes/linker_entry.js @@ -0,0 +1,467 @@ +// splat.segtypes.linker_entry +import { atLeast, exists, readText, mkdirp, writeText, resolvePath, rt } from '../runtime.js'; +import * as log from '../util/log.js'; +import { opts } from '../util/options.js'; +import { toCname } from '../util/symbols.js'; +import { P, parent, relativeTo, suffix, suffixes, withSuffix } from '../util/pypath.js'; +import { hex } from '../util/pyfmt.js'; + +const cleanCache = new Map(); + +export function resetCleanUpCache() { cleanCache.clear(); } + +// clean 'foo/../bar' to 'bar' +export function cleanUpPath(path) { + const key = path; + if (cleanCache.has(key)) return cleanCache.get(key); + const resolved = resolvePath(path); + const base = resolvePath(opts.base_path); + let out; + try { + out = relativeTo(resolved, base); + } catch { + try { + out = relativeTo(resolved, resolvePath(rt.cwd)); + } catch { + out = path; + } + } + cleanCache.set(key, out); + return out; +} + +export function pathToObjectPath(path) { + path = cleanUpPath(path); + const fullSuffix = opts.use_o_as_suffix ? '.o' : suffix(path) + '.o'; + if (!String(path).startsWith(String(opts.build_path))) path = P(opts.build_path, path); + return cleanUpPath(withSuffix(path, fullSuffix)); +} + +export function writeFileIfDifferent(path, newContent) { + const old = exists(path) ? readText(path) : ''; + if (old !== newContent) { + mkdirp(parent(path)); + writeText(path, newContent, opts.c_newline); + } +} + +const style = () => opts.segment_symbols_style; +export const getSegmentRomStart = (c) => (style() === 'makerom' ? `_${c}SegmentRomStart` : `${c}_ROM_START`); +export const getSegmentRomEnd = (c) => (style() === 'makerom' ? `_${c}SegmentRomEnd` : `${c}_ROM_END`); +export const getSegmentVramStart = (c) => (style() === 'makerom' ? `_${c}SegmentStart` : `${c}_VRAM`); +export const getSegmentVramEnd = (c) => (style() === 'makerom' ? `_${c}SegmentEnd` : `${c}_VRAM_END`); + +function pyCapitalize(s) { return s ? s[0].toUpperCase() + s.slice(1).toLowerCase() : s; } + +export function convertSectionNameToLinkerFormat(sectionType) { + if (!sectionType.startsWith('.')) throw new Error('AssertionError'); + if (style() === 'makerom') { + if (sectionType === '.rodata') return 'RoData'; + return pyCapitalize(sectionType.slice(1)); + } + return toCname(sectionType.toUpperCase()); +} + +export function getSegmentSectionStart(segName, sectionType) { + const sec = convertSectionNameToLinkerFormat(sectionType); + return style() === 'makerom' ? `_${segName}Segment${sec}Start` : `${segName}${sec}_START`; +} +export function getSegmentSectionEnd(segName, sectionType) { + const sec = convertSectionNameToLinkerFormat(sectionType); + return style() === 'makerom' ? `_${segName}Segment${sec}End` : `${segName}${sec}_END`; +} +export function getSegmentSectionSize(segName, sectionType) { + const sec = convertSectionNameToLinkerFormat(sectionType); + return style() === 'makerom' ? `_${segName}Segment${sec}Size` : `${segName}${sec}_SIZE`; +} + +export function getSegmentVramEndSymbolName(segment) { return getSegmentVramEnd(segment.get_cname()); } + +export class LinkerEntry { + constructor(segment, srcPaths, objectPath, sectionOrder, sectionLink, noload = false) { + this.segment = segment; + this.src_paths = srcPaths.map((p) => cleanUpPath(p)); + this.section_order = sectionOrder; + this.section_link = sectionLink; + this.noload = noload; + this.bss_contains_common = segment.bss_contains_common; + this.object_path = pathToObjectPath(objectPath); + } + + get section_order_type() { return this.section_order === '.rdata' ? '.rodata' : this.section_order; } + get section_link_type() { return this.section_link === '.rdata' ? '.rodata' : this.section_link; } + + emit_symbol_for_data(w) { + if (!opts.ld_generate_symbol_per_data_segment) return; + if (this.object_path && this.section_link_type === '.data') { + // str(dir / name) + ".".join(object_path.suffixes[:-1]) + const sfx = suffixes(this.object_path).slice(0, -1).join('.'); + const pathCname = (P(this.segment.dir, this.segment.name) + sfx).replace(/[^0-9a-zA-Z_]/g, '_'); + w._write_symbol(pathCname, '.'); + } + } + + emit_path(w) { + if (this.object_path === null) throw new Error(`AssertionError: ${this.segment.name}, ${this.segment.rom_start}`); + if (this.noload && this.bss_contains_common) { + w._write_object_path_section(this.object_path, `${this.section_link} COMMON .scommon`); + } else { + const wildcard = opts.ld_wildcard_sections ? '*' : ''; + w._write_object_path_section(this.object_path, `${this.section_link}${wildcard}`); + } + } + + emit_entry(w) { + this.emit_symbol_for_data(w); + this.emit_path(w); + } +} + +export class LinkerWriter { + constructor(isPartial = false) { + this.linker_discard_section = opts.ld_discard_section; + this.sections_allowlist = opts.ld_sections_allowlist; + this.sections_denylist = opts.ld_sections_denylist; + this.entries = []; + this.dependencies_entries = []; + this.buffer = []; + this.header_symbols = new Set(); + this.is_partial = isPartial; + this._indent_level = 0; + + this._writeln('SECTIONS'); + this._begin_block(); + if (!this.is_partial) { + this._writeln(`__romPos = ${opts.ld_rom_start};`); + if (atLeast('0.35.0') && opts.ld_gp_expression !== null) this._writeln(`_gp = ${opts.ld_gp_expression};`); + else if (opts.gp !== null) this._writeln(`_gp = 0x${hex(opts.gp)};`); + } + } + + write_max_vram_end_sym(symbol, overlays) { + for (const segment of overlays) { + if (segment === overlays[0]) this._writeln(`${symbol} = ${getSegmentVramEndSymbolName(segment)};`); + else this._writeln(`${symbol} = MAX(${symbol}, ${getSegmentVramEndSymbolName(segment)});`); + } + } + + add(segment, maxVramSyms) { + const entries = segment.get_linker_entries(); + this.entries.push(...entries); + this.dependencies_entries.push(...entries); + const segName = segment.get_cname(); + for (const [sym, segs] of maxVramSyms) this.write_max_vram_end_sym(sym, segs); + + if (opts.ld_legacy_generation) { + this.add_legacy(segment, entries); + return; + } + + const sectionEntries = new Map(); + for (const sectionName of segment.section_order) { + if (opts.section_order.includes(sectionName)) sectionEntries.set(sectionName, []); + } + + let prevEntry = null; + for (const entry of entries) { + if (sectionEntries.has(entry.section_order_type)) { prevEntry = entry.section_order_type; break; } + } + + let anyLoad = false; + let anyNoload = false; + for (const entry of entries) { + if (sectionEntries.has(entry.section_order_type)) { + sectionEntries.get(entry.section_order_type).push(entry); + } else if (prevEntry !== null) { + if (!sectionEntries.has(prevEntry)) { + log.error(`\nError on linker script generation: section '${prevEntry}' not found.\n Make sure the section '${prevEntry}' is listed on 'section_order' of the yaml options.`); + } + sectionEntries.get(prevEntry).push(entry); + } + anyLoad = anyLoad || !entry.noload; + anyNoload = anyNoload || entry.noload; + prevEntry = entry.section_order_type; + } + + if (segment.ld_align_segment_start) { + this._write_symbol('__romPos', `ALIGN(__romPos, 0x${hex(segment.ld_align_segment_start)})`); + this._write_symbol('.', `ALIGN(., 0x${hex(segment.ld_align_segment_start)})`); + } + + this._write_symbol(getSegmentRomStart(segName), '__romPos'); + + let isFirst = true; + if (anyLoad) { + this._write_segment_sections(segment, segName, sectionEntries, false, isFirst); + isFirst = false; + } + if (anyNoload) { + this._write_segment_sections(segment, segName, sectionEntries, true, isFirst); + isFirst = false; + } + this._end_segment(segment, !anyLoad); + } + + add_legacy(segment, entries) { + const segName = segment.get_cname(); + const started = new Map(opts.section_order.map((s) => [s, false])); + + // entry -> section, for the last entry of each section type + const lastSeen = new Map(); + const lastSeenValues = new Set(); + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]; + if (opts.section_order.includes(entry.section_order_type) && !lastSeenValues.has(entry.section_order_type)) { + lastSeen.set(entry, entry.section_order_type); + lastSeenValues.add(entry.section_order_type); + } + } + + if (segment.ld_align_segment_start) { + this._write_symbol('__romPos', `ALIGN(__romPos, 0x${hex(segment.ld_align_segment_start)})`); + this._write_symbol('.', `ALIGN(., 0x${hex(segment.ld_align_segment_start)})`); + } + + this._write_symbol(getSegmentRomStart(segName), '__romPos'); + this._begin_segment(segment, segName, false, true); + + let i = 0; + for (const entry of entries) { + if (entry.noload) break; + const st = started.has(entry.section_order_type) ? started.get(entry.section_order_type) : true; + if (!st) { + this._begin_section(segName, entry.section_order_type); + started.set(entry.section_order_type, true); + } + entry.emit_entry(this); + if (lastSeen.has(entry)) this._end_section(segName, entry.section_order_type, segment); + i++; + } + + if (entries.some((e) => e.noload)) { + this._end_block(); + this._begin_segment(segment, segName, true, false); + for (const entry of entries.slice(i)) { + const st = started.has(entry.section_order_type) ? started.get(entry.section_order_type) : true; + if (!st) { + this._begin_section(segName, entry.section_order_type); + started.set(entry.section_order_type, true); + } + entry.emit_entry(this); + if (lastSeen.has(entry)) this._end_section(segName, entry.section_order_type, segment); + } + } + this._end_segment(segment, false); + } + + add_referenced_partial_segment(segment, maxVramSyms) { + const entries = segment.get_linker_entries(); + this.entries.push(...entries); + const segmentsPath = opts.ld_partial_build_segments_path; + const segName = segment.get_cname(); + for (const [sym, segs] of maxVramSyms) this.write_max_vram_end_sym(sym, segs); + + if (segment.ld_align_segment_start) { + this._write_symbol('__romPos', `ALIGN(__romPos, 0x${hex(segment.ld_align_segment_start)})`); + this._write_symbol('.', `ALIGN(., 0x${hex(segment.ld_align_segment_start)})`); + } + this._write_symbol(getSegmentRomStart(segName), '__romPos'); + + const anyLoad = entries.some((e) => !e.noload); + let isFirst = true; + if (anyLoad) { + this._begin_segment(segment, segName, false, isFirst); + for (const sectionName of segment.section_order) { + if (!opts.section_order.includes(sectionName)) continue; + if (sectionName === '.bss') continue; + const entry = new LinkerEntry(segment, [], P(segmentsPath, `${segName}.o`), sectionName, sectionName, false); + this.dependencies_entries.push(entry); + entry.emit_entry(this); + } + isFirst = false; + } + if (entries.some((e) => e.noload)) { + if (!isFirst) this._end_block(); + this._begin_segment(segment, segName, true, isFirst); + let bssContainsCommon = false; + for (const entry of entries) { + if (entry.segment.bss_contains_common) { bssContainsCommon = true; break; } + } + const entry = new LinkerEntry(segment, [], P(segmentsPath, `${segName}.o`), '.bss', '.bss', true); + entry.bss_contains_common = bssContainsCommon; + this.dependencies_entries.push(entry); + entry.emit_entry(this); + } + this._end_segment(segment, !anyLoad); + } + + add_partial_segment(segment) { + const entries = segment.get_linker_entries(); + this.entries.push(...entries); + this.dependencies_entries.push(...entries); + const segName = segment.get_cname(); + + const sectionEntries = new Map(); + for (const sectionName of segment.section_order) { + if (opts.section_order.includes(sectionName)) sectionEntries.set(sectionName, []); + } + let prevEntry = null; + for (const entry of entries) { + if (sectionEntries.has(entry.section_order_type)) { + sectionEntries.get(entry.section_order_type).push(entry); + } else if (prevEntry !== null) { + if (!sectionEntries.has(prevEntry)) { + log.error(`\nError on linker script generation: section '${prevEntry}' not found.\n Make sure the section '${prevEntry}' is listed on 'section_order' of the yaml options.`); + } + sectionEntries.get(prevEntry).push(entry); + } + prevEntry = entry.section_order_type; + } + + for (const [sectionName, ents] of sectionEntries) { + if (ents.length === 0) continue; + this._begin_partial_segment(sectionName, segment, ents[0].noload); + this._begin_section(segName, sectionName); + for (const entry of ents) entry.emit_entry(this); + this._end_section(segName, sectionName, segment); + this._end_partial_segment(sectionName); + } + } + + save_linker_script(outputPath) { + if (this.sections_allowlist.length > 0) { + const address = this.is_partial ? '' : ' 0'; + for (const sect of this.sections_allowlist) { + this._writeln(`${sect}${address} :`); + this._begin_block(); + this._writeln(`*(${sect});`); + this._end_block(); + } + this._writeln(''); + } + if (this.linker_discard_section || this.sections_denylist.length > 0) { + this._writeln('/DISCARD/ :'); + this._begin_block(); + for (const sect of this.sections_denylist) this._writeln(`*(${sect});`); + if (this.linker_discard_section) this._writeln('*(*);'); + this._end_block(); + } + this._end_block(); + if (this._indent_level !== 0) throw new Error('AssertionError'); + writeFileIfDifferent(outputPath, this.buffer.join('\n') + '\n'); + } + + save_symbol_header() { + const path = opts.ld_symbol_header_path; + if (path) { + const syms = [...this.header_symbols].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + writeFileIfDifferent(path, + '#ifndef _HEADER_SYMBOLS_H_\n#define _HEADER_SYMBOLS_H_\n\n#include "common.h"\n\n' + + syms.map((s) => `extern Addr ${s};\n`).join('') + + '\n#endif\n'); + } + } + + save_dependencies_file(outputPath, targetElfPath) { + const target = atLeast('0.35.0') ? cleanUpPath(targetElfPath) : targetElfPath; + let output = `${target}:`; + for (const entry of this.dependencies_entries) { + if (entry.object_path === null) continue; + output += ` \\\n ${entry.object_path}`; + } + output += '\n'; + for (const entry of this.dependencies_entries) { + if (entry.object_path === null) continue; + output += `${entry.object_path}:\n`; + } + writeFileIfDifferent(outputPath, output); + } + + _writeln(line) { + if (line.length === 0) this.buffer.push(line); + else this.buffer.push(' '.repeat(this._indent_level) + line); + } + + _begin_block() { this._writeln('{'); this._indent_level += 1; } + _end_block() { this._indent_level -= 1; this._writeln('}'); } + + _write_symbol(symbol, value) { + symbol = toCname(symbol); + if (typeof value === 'number') value = `0x${hex(value)}`; + this._writeln(`${symbol} = ${value};`); + this.header_symbols.add(symbol); + } + + _write_object_path_section(objectPath, section) { this._writeln(`${objectPath}(${section});`); } + + _begin_segment(segment, segName, noload, isFirst) { + let vramStr; + if (opts.ld_use_symbolic_vram_addresses && segment.vram_symbol !== null) vramStr = segment.vram_symbol + ' '; + else vramStr = Number.isInteger(segment.vram_start) ? `0x${hex(segment.vram_start)} ` : ''; + + let addrStr = ' '; + if (isFirst) addrStr += vramStr; + if (noload) { segName += '_bss'; addrStr += '(NOLOAD) '; } + + this._write_symbol(getSegmentVramStart(segName), `ADDR(.${segName})`); + let line = `.${segName}${addrStr}:`; + if (!noload) line += ` AT(${getSegmentRomStart(segName)})`; + if (opts.emit_subalign && segment.subalign !== null) line += ` SUBALIGN(${segment.subalign})`; + this._writeln(line); + this._begin_block(); + if (segment.ld_fill_value !== null) this._writeln(`FILL(0x${hex(segment.ld_fill_value, 8)});`); + } + + _end_segment(segment, allBss = false) { + this._end_block(); + const name = segment.get_cname(); + if (!allBss) this._writeln(`__romPos += SIZEOF(.${name});`); + if (!opts.segment_end_before_align && segment.align) { + this._writeln(`__romPos = ALIGN(__romPos, ${segment.align});`); + if (opts.ld_align_segment_vram_end) this._writeln(`. = ALIGN(., ${segment.align});`); + } + this._write_symbol(getSegmentRomEnd(name), '__romPos'); + this._write_symbol(getSegmentVramEndSymbolName(segment), '.'); + if (opts.segment_end_before_align && segment.align) { + this._writeln(`__romPos = ALIGN(__romPos, ${segment.align});`); + if (opts.ld_align_segment_vram_end) this._writeln(`. = ALIGN(., ${segment.align});`); + } + this._writeln(''); + } + + _begin_partial_segment(sectionName, segment, noload) { + let line = `${sectionName}`; + if (noload) line += ' (NOLOAD)'; + line += ' :'; + if (opts.emit_subalign && segment.subalign !== null) line += ` SUBALIGN(${segment.subalign})`; + this._writeln(line); + this._begin_block(); + } + + _end_partial_segment() { this._end_block(); this._writeln(''); } + + _begin_section(segName, curSection) { + this._write_symbol(getSegmentSectionStart(segName, curSection), '.'); + } + + _end_section(segName, curSection, segment) { + const start = getSegmentSectionStart(segName, curSection); + const end = getSegmentSectionEnd(segName, curSection); + const size = getSegmentSectionSize(segName, curSection); + if (opts.ld_align_section_vram_end && segment.align !== null) this._writeln(`. = ALIGN(., ${segment.align});`); + this._write_symbol(end, '.'); + this._write_symbol(size, `ABSOLUTE(${end} - ${start})`); + } + + _write_segment_sections(segment, segName, sectionEntries, noload, isFirst) { + if (!isFirst) this._end_block(); + this._begin_segment(segment, segName, noload, isFirst); + for (const [sectionName, ents] of sectionEntries) { + if (ents.length === 0) continue; + if (ents[0].noload !== noload) continue; + this._begin_section(segName, sectionName); + for (const entry of ents) entry.emit_entry(this); + this._end_section(segName, sectionName, segment); + } + } +} diff --git a/packages/romdev-splat/src/segtypes/platform.js b/packages/romdev-splat/src/segtypes/platform.js new file mode 100644 index 00000000..506bf12e --- /dev/null +++ b/packages/romdev-splat/src/segtypes/platform.js @@ -0,0 +1,347 @@ +// splat.segtypes.n64.* and splat.segtypes.psx.* +import { atLeast, mkdirp, writeText } from '../runtime.js'; +import * as log from '../util/log.js'; +import { opts } from '../util/options.js'; +import { P, parent, name as pathName } from '../util/pypath.js'; +import { hex, isDict, pyInt, rjust, ljust, truthy } from '../util/pyfmt.js'; +import { Segment } from './segment.js'; +import { registry } from './registry.js'; +import { CommonSegHeader, CommonSegHasm, CommonSegCodeSubsegment } from './common.js'; +import * as n64img from '../n64img/image.js'; +import { rabbitizer } from '../disassembler/spim.js'; +import { decodeText } from '../util/codecs.js'; + +const has = (o, k) => isDict(o) && Object.prototype.hasOwnProperty.call(o, k); +const get = (o, k, d = null) => (has(o, k) ? o[k] : d); + +// ---------------------------------------------------------------- headers + +export class N64SegHeader extends CommonSegHeader { + parse_header(romBytes) { + const encoding = opts.header_encoding; + const L = []; + const w = (a, b, c) => L.push(this.get_line('word', romBytes.subarray(a, b), c)); + L.push('.section .data\n'); + w(0x00, 0x04, 'PI BSB Domain 1 register'); + w(0x04, 0x08, 'Clockrate setting'); + w(0x08, 0x0C, 'Entrypoint address'); + w(0x0C, 0x10, 'Revision'); + w(0x10, 0x14, 'Checksum 1'); + w(0x14, 0x18, 'Checksum 2'); + w(0x18, 0x1C, 'Unknown 1'); + w(0x1C, 0x20, 'Unknown 2'); + if (encoding !== 'word') { + const text = decodeText(romBytes.subarray(0x20, 0x34), encoding).replace(/^\s+|\s+$/g, ''); + L.push('.ascii "' + ljust(text, 20) + '" /* Internal name */'); + } else { + for (let i = 0x20; i < 0x34; i += 4) w(i, i + 4, 'Internal name'); + } + w(0x34, 0x38, 'Unknown 3'); + w(0x38, 0x3C, 'Cartridge'); + L.push(this.get_line('ascii', romBytes.subarray(0x3C, 0x3E), 'Cartridge ID')); + L.push(this.get_line('ascii', romBytes.subarray(0x3E, 0x3F), 'Country code')); + L.push(this.get_line('byte', romBytes.subarray(0x3F, 0x40), 'Version')); + L.push(''); + return L; + } +} + +export class PsxSegHeader extends CommonSegHeader { + parse_header(romBytes) { + const L = []; + const rev = (a, b) => Uint8Array.from(romBytes.subarray(a, b)).reverse(); + L.push('.section .data\n'); + L.push(this.get_line('ascii', romBytes.subarray(0x00, 0x08), 'Magic number')); + L.push(this.get_line('word', rev(0x08, 0x0C), '.text vram address')); + L.push(this.get_line('word', rev(0x0C, 0x10), '.data vram address')); + L.push(this.get_line('word', rev(0x10, 0x14), 'Initial PC')); + L.push(this.get_line('word', rev(0x14, 0x18), 'Initial $gp/r28')); + L.push(this.get_line('word', rev(0x18, 0x1C), '.text start')); + L.push(this.get_line('word', rev(0x1C, 0x20), '.text size')); + L.push(this.get_line('word', rev(0x20, 0x24), '.data start')); + L.push(this.get_line('word', rev(0x24, 0x28), '.data size')); + L.push(this.get_line('word', rev(0x28, 0x2C), '.bss start')); + L.push(this.get_line('word', rev(0x2C, 0x30), '.bss size')); + L.push(this.get_line('word', rev(0x30, 0x34), 'Initial $sp/r29 & $fp/r30 base')); + L.push(this.get_line('word', rev(0x34, 0x38), 'Initial $sp/r29 & $fp/r30 offset')); + for (const a of [0x38, 0x3C, 0x40, 0x44, 0x48]) L.push(this.get_line('word', romBytes.subarray(a, a + 4), 'Reserved')); + L.push(this.get_line('ascii', romBytes.subarray(0x4C, this.rom_end), 'Sony Inc')); + L.push(''); + return L; + } +} + +// ---------------------------------------------------------------- ipl3 / rsp + +export class N64SegIpl3 extends CommonSegHasm { + constructor(...a) { super(...a); this.special_vram_segment = true; } +} + +export class N64SegRsp extends CommonSegHasm { + constructor(...a) { super(...a); this.instr_category = rabbitizer().InstrCategory.RSP; } +} + +// ---------------------------------------------------------------- images + +export class N64SegImg extends Segment { + static parse_dimensions(yaml) { + if (isDict(yaml)) { + if (!has(yaml, 'width')) throw new Error("KeyError: 'width'"); + if (!has(yaml, 'height')) throw new Error("KeyError: 'height'"); + return [yaml.width, yaml.height]; + } + if (yaml.length < 5) log.error(`Error: ${JSON.stringify(yaml)} is missing width and height parameters`); + return [yaml[3], yaml[4]]; + } + + /** Subclasses pass the n64img class via the static IMG_CLS. */ + constructor(romStart, romEnd, type, name, vramStart, args, yaml) { + super(romStart, romEnd, type, name, vramStart, args, yaml); + if (romStart === null) log.error(`Error: ${type} segment ${name} rom start could not be determined`); + const ImgCls = this.constructor.IMG_CLS; + this.n64img = new ImgCls(new Uint8Array(0), 0, 0); + if (isDict(yaml)) { + this.n64img.flip_h = truthy(get(yaml, 'flip_x', false)); + this.n64img.flip_v = truthy(get(yaml, 'flip_y', false)); + } + [this.width, this.height] = N64SegImg.parse_dimensions(yaml); + this.n64img.width = this.width; + this.n64img.height = this.height; + this.image_type_in_extension = opts.image_type_in_extension; + } + + check_len() { + const expected = this.n64img.size(); + const actual = this.rom_end - this.rom_start; + if (actual > expected) { + log.error(`Error: ${this.name} should end at 0x${hex(this.rom_start + expected)}, but it ends at 0x${hex(this.rom_end)}\n(hint: add a 'bin' segment after it)`); + } else if (atLeast('0.35.0') && actual < expected) { + log.error(`Error: ${this.name} should end at 0x${hex(this.rom_start + expected)}, but it ends at 0x${hex(this.rom_end)}`); + } + } + + out_path() { + const typeExt = this.image_type_in_extension ? `.${this.type}` : ''; + return P(opts.asset_path, this.dir, `${this.name}${typeExt}.png`); + } + + should_split() { return opts.is_mode_active('img'); } + + split(romBytes) { + this.check_len(); + const path = this.out_path(); + mkdirp(parent(path)); + if (this.n64img.data.length === 0) this.n64img.data = romBytes.subarray(this.rom_start, this.rom_end); + this.n64img.write(path); + this.log(`Wrote ${this.name} to ${path}`); + } + + static estimate_size(yaml) { + const [width, height] = N64SegImg.parse_dimensions(yaml); + const typ = Segment.parse_segment_type(yaml); + if (typ === 'ci4' || typ === 'i4' || typ === 'ia4') return Math.floor((width * height) / 2); + if (typ === 'ia16' || typ === 'rgba16') return width * height * 2; + if (typ === 'rgba32') return width * height * 4; + return width * height; + } +} + +export class N64SegCi extends N64SegImg { + parse_palette_names(yaml, args) { + let ret = [this.name]; + if (isDict(yaml)) { + if (has(yaml, 'palettes')) ret = yaml.palettes; + } else if (args.length > 2) { + ret = args[2]; + } + if (typeof ret === 'string') ret = [ret]; + return ret; + } + + constructor(...a) { + super(...a); + this.palettes = []; + this.palette_names = this.parse_palette_names(this.yaml, this.args); + } + + scan(romBytes) { this.n64img.data = romBytes.subarray(this.rom_start, this.rom_end); } + + out_path_pal(palName) { + const typeExt = opts.image_type_in_extension ? `.${this.type}` : ''; + let outName; + if (this.palettes.length === 1) outName = this.name; + else if (palName.startsWith(this.name)) outName = palName; + else outName = `${this.name}_${palName}`; + return P(opts.asset_path, this.dir, `${outName}${typeExt}.png`); + } + + split(romBytes) { + if (atLeast('0.35.0')) this.check_len(); + if (this.palettes.length === 0) { + log.error(`no palettes have been mapped to ci segment \`${this.name}\`\n(hint: add a palette segment with the same name or use the \`palettes:\` field of this segment to specify palettes by name')`); + } + this.n64img.data = romBytes.subarray(this.rom_start, this.rom_end); + for (const palette of this.palettes) { + const path = this.out_path_pal(palette.name); + mkdirp(parent(path)); + this.n64img.palette = palette.parse_palette(romBytes); + this.n64img.write(path); + this.log(`Wrote ${pathName(path)} to ${path}`); + } + } +} + +const imgClass = (Base, Img, extra = {}) => { + const C = class extends Base {}; + C.IMG_CLS = Img; + Object.assign(C, extra); + return C; +}; + +export const N64SegCi4 = imgClass(N64SegCi, n64img.CI4); +export const N64SegCi8 = imgClass(N64SegCi, n64img.CI8); +export const N64SegI1 = imgClass(N64SegImg, n64img.I1); +export const N64SegI4 = imgClass(N64SegImg, n64img.I4); +export const N64SegI8 = imgClass(N64SegImg, n64img.I8); +export const N64SegIa4 = imgClass(N64SegImg, n64img.IA4); +export const N64SegIa8 = imgClass(N64SegImg, n64img.IA8); +export const N64SegIa16 = imgClass(N64SegImg, n64img.IA16); +export const N64SegRgba16 = imgClass(N64SegImg, n64img.RGBA16); +export const N64SegRgba32 = imgClass(N64SegImg, n64img.RGBA32); + +// RRRRRGGG GGBBBBBA +export function unpackColor(data) { + const s = opts.endianness === 'big' ? (data[0] << 8) | data[1] : data[0] | (data[1] << 8); + const r = (s >> 11) & 0x1F; const g = (s >> 6) & 0x1F; const b = (s >> 1) & 0x1F; + const a = (s & 1) * 0xFF; + return [ceil255(r), ceil255(g), ceil255(b), a]; +} + +/** math.ceil(0xFF * (v / 31)) with Python float semantics. */ +export function ceil255(v) { return Math.ceil(0xFF * (v / 31)); } + +const VALID_SIZES = [0x20, 0x40, 0x80, 0x100, 0x200]; + +export class N64SegPalette extends Segment { + static require_unique_name = false; + + constructor(...a) { + super(...a); + const modern = atLeast('0.35.0'); + let size; + if (this.extract) { + if (this.rom_end === null) log.error(`segment ${this.name} needs to know where it ends; add a position marker [0xDEADBEEF] after it`); + if (modern && has(this.yaml, 'size')) { + const yamlSize = this.yaml.size; + if (Number.isInteger(this.rom_start) && Number.isInteger(this.rom_end)) { + const romLen = this.rom_end - this.rom_start; + if (romLen < yamlSize) { + log.error(`Error: ${this.name} has a \`size\` value of 0x${hex(yamlSize)}, but this is smaller than the actual rom size of the palette (0x${hex(romLen)}, start: 0x${hex(this.rom_start)}, end: 0x${hex(this.rom_end)})`); + } else if (romLen > yamlSize) { + log.error(`Warning: ${this.name} has a \`size\` value of 0x${hex(yamlSize)}, but this is larger than the end of the palette (0x${hex(romLen)}, start: 0x${hex(this.rom_start)}, end: 0x${hex(this.rom_end)})\n(hint add a 'bin' segment after this palette with address 0x${hex(this.rom_end)})`); + } + } + size = yamlSize; + } else if (!has(this.yaml, 'size')) { + const actualLen = this.rom_end - this.rom_start; + const hint = "(hint: add a 'bin' segment after it or specify the size in the segment)"; + if (actualLen > VALID_SIZES[VALID_SIZES.length - 1]) { + log.error(`Error: ${this.name} (0x${hex(actualLen)} bytes) is too long, max 0x${hex(VALID_SIZES[VALID_SIZES.length - 1])})\n${hint}`); + } + if (!VALID_SIZES.includes(actualLen)) { + log.error(`Error: ${this.name} (0x${hex(actualLen)} bytes) is not a valid palette size (${VALID_SIZES.map((s) => '0x' + s.toString(16)).join(', ')})\n${hint}`); + } + size = actualLen; + } + } else { + size = 0; + } + this.palette_size = size; + this.global_id = isDict(this.yaml) ? get(this.yaml, 'global_id', null) : null; + } + + get_cname() { return super.get_cname() + '_pal'; } + + static parse_palette_bytes(data) { + const palette = []; + for (let i = 0; i < data.length; i += 2) { + // zip_longest(fillvalue=None): an odd trailing byte pairs with None + if (i + 1 >= data.length) throw new TypeError("unsupported operand type(s) for <<: 'NoneType' and 'int'"); + palette.push(unpackColor([data[i], data[i + 1]])); + } + return palette; + } + + parse_palette(romBytes) { + const data = atLeast('0.35.0') + ? romBytes.subarray(this.rom_start, this.rom_start + this.palette_size) + : romBytes.subarray(this.rom_start, this.rom_end); + return N64SegPalette.parse_palette_bytes(data); + } + + should_split() { return this.extract && opts.is_mode_active('img'); } + out_path() { return P(opts.asset_path, this.dir, `${this.name}.png`); } + + get_linker_entries() { + return [new registry.LinkerEntry(this, [P(opts.asset_path, this.dir, `${this.name}.png`)], + P(opts.asset_path, this.dir, `${this.name}.pal`), this.get_linker_section_order(), + this.get_linker_section_linksection(), this.is_noload())]; + } + + static estimate_size(yaml) { + if (isDict(yaml) && has(yaml, 'size')) return pyInt(yaml.size); + return 0x20; + } +} + +// ---------------------------------------------------------------- vtx + +export class N64SegVtx extends CommonSegCodeSubsegment { + constructor(...a) { + super(...a); + this.file_text = null; + this.data_only = isDict(this.yaml) ? get(this.yaml, 'data_only', false) : false; + } + + format_sym_name(sym) { return sym.name; } + get_linker_section() { return '.data'; } + out_path() { return P(opts.asset_path, this.dir, `${this.name}.vtx.inc.c`); } + scan(romBytes) { this.file_text = this.disassemble_data(romBytes); } + + disassemble_data(romBytes) { + const data = romBytes.subarray(this.rom_start, this.rom_end); + if (data.length % 16 !== 0) log.error(`Error: Vtx segment ${this.name} length (${data.length}) is not a multiple of 16!`); + const lines = []; + if (!truthy(this.data_only)) { lines.push(opts.generated_c_preamble); lines.push(''); } + const count = Math.floor(data.length / 16); + const sym = this.create_symbol(this.vram_start, true, { type: 'data', define: true }); + if (!truthy(this.data_only)) lines.push(`Vtx ${this.format_sym_name(sym)}[${count}] = {`); + const dv = new DataView(data.buffer, data.byteOffset, data.byteLength); + for (let o = 0; o + 16 <= data.length; o += 16) { + const x = dv.getInt16(o); const y = dv.getInt16(o + 2); const z = dv.getInt16(o + 4); + const flg = dv.getUint16(o + 6); + const t = dv.getInt16(o + 8); const c = dv.getInt16(o + 10); + const r = data[o + 12]; const g = data[o + 13]; const b = data[o + 14]; const a = data[o + 15]; + lines.push(` {{{ ${rjust(x, 5)}, ${rjust(y, 5)}, ${rjust(z, 5)} }, ${flg}, { ${rjust(t, 5)}, ${rjust(c, 5)} }, { ${rjust(r, 3)}, ${rjust(g, 3)}, ${rjust(b, 3)}, ${rjust(a, 3)} }}},`); + if (flg !== 0) this.warn(`Non-zero flag found in vertex data ${this.name}!`); + } + if (!truthy(this.data_only)) lines.push('};'); + lines.push(''); + return lines.join('\n'); + } + + split() { + if (this.file_text && this.out_path()) { + mkdirp(parent(this.out_path())); + writeText(this.out_path(), this.file_text, '\n'); + } + } + + should_scan() { return opts.is_mode_active('vtx'); } + should_split() { return this.extract && opts.is_mode_active('vtx'); } + + static estimate_size(yaml) { + if (isDict(yaml) && has(yaml, 'length')) return yaml.length * 0x10; + return null; + } +} diff --git a/packages/romdev-splat/src/segtypes/registry.js b/packages/romdev-splat/src/segtypes/registry.js new file mode 100644 index 00000000..aa12b953 --- /dev/null +++ b/packages/romdev-splat/src/segtypes/registry.js @@ -0,0 +1,8 @@ +// Segment type lookup tables (filled in by segtypes/index.js) and the +// extension loader hook; kept separate so segment.js has no import cycles. +export const registry = { + common: {}, + platform: { n64: {}, psx: {}, ps2: {}, psp: {} }, + LinkerEntry: null, + loadExtension: () => null, +}; diff --git a/packages/romdev-splat/src/segtypes/segment.js b/packages/romdev-splat/src/segtypes/segment.js new file mode 100644 index 00000000..ebe7b8ce --- /dev/null +++ b/packages/romdev-splat/src/segtypes/segment.js @@ -0,0 +1,571 @@ +// splat.segtypes.segment +import { atLeast } from '../runtime.js'; +import * as log from '../util/log.js'; +import { opts } from '../util/options.js'; +import * as vramClasses from '../util/vram_classes.js'; +import * as symbols from '../util/symbols.js'; +import { Symbol, toCname } from '../util/symbols.js'; +import { IntervalTree } from '../util/intervaltree.js'; +import { P } from '../util/pypath.js'; +import { hex, isDict, isList, pyInt, pyStr, truthy } from '../util/pyfmt.js'; +import { registry } from './registry.js'; + +const has = (o, k) => isDict(o) && Object.prototype.hasOwnProperty.call(o, k); +const get = (o, k, d = null) => (has(o, k) ? o[k] : d); + +export function parseSegmentVram(segment) { + if (has(segment, 'vram')) return pyInt(segment.vram); + return null; +} + +export function parseSegmentVramSymbol(segment) { + if (has(segment, 'vram_symbol')) return pyStr(segment.vram_symbol); + return null; +} + +export function parseSegmentVramClass(segment) { + if (has(segment, 'vram_class')) return vramClasses.resolve(segment.vram_class); + return null; +} + +export function parseSegmentFollowsVram(segment) { + if (isDict(segment)) return get(segment, 'follows_vram', null); + return null; +} + +export function parseSegmentAlign(segment) { + if (has(segment, 'align')) return pyInt(segment.align); + return null; +} + +export function parseSegmentSubalign(segment) { + const def = opts.subalign; + if (isDict(segment)) { + let subalign = get(segment, 'subalign', def); + if (subalign !== null) subalign = pyInt(subalign); + return subalign; + } + return def; +} + +export function parseSegmentSectionOrder(segment) { + const def = opts.section_order; + if (isDict(segment)) return get(segment, 'section_order', def); + return def; +} + +export class SegmentStatisticsInfo { + constructor(size, count) { this.size = size; this.count = count; } + merge(o) { return new SegmentStatisticsInfo(this.size + o.size, this.count + o.count); } +} + +/** defaultdict(lambda: SegmentStatisticsInfo(0, 0)) */ +export function emptyStatistics() { return new Map(); } +export function statGet(stats, k) { + if (!stats.has(k)) stats.set(k, new SegmentStatisticsInfo(0, 0)); + return stats.get(k); +} + +export class Segment { + static require_unique_name = true; + + static get_class_for_type(segType) { + if (segType.startsWith('.')) segType = segType.slice(1); + let cls; + if (opts.allow_segment_overrides) { + cls = Segment.get_extension_segment_class(segType); + if (cls === null) cls = Segment.get_base_segment_class(segType); + } else { + cls = Segment.get_base_segment_class(segType); + if (cls === null) cls = Segment.get_extension_segment_class(segType); + } + if (cls === null) { + log.error(`could not load segment type '${segType}'\n(hint: confirm your extension directory is configured correctly)`); + } + return cls; + } + + static get_base_segment_class(segType) { + const platform = opts.platform; + const p = registry.platform[platform]; + if (p && Object.prototype.hasOwnProperty.call(p, segType)) return p[segType]; + if (Object.prototype.hasOwnProperty.call(registry.common, segType)) return registry.common[segType]; + return null; + } + + static get_extension_segment_class(segType) { + const extPath = opts.extensions_path; + if (!extPath) { + log.error(`could not load presumed extended segment type '${segType}' because no extensions path is configured`); + } + return registry.loadExtension(extPath, segType, opts.platform); + } + + /** -> [start|null, isAuto] */ + static parse_segment_start(segment) { + const s = isDict(segment) ? get(segment, 'start', null) : segment[0]; + if (s === null || s === undefined) return [null, false]; + if (s === 'auto') return [null, true]; + return [pyInt(s), false]; + } + + static parse_segment_type(segment) { + if (isDict(segment)) { + if (!has(segment, 'type')) throw new Error("KeyError: 'type'"); + return pyStr(segment.type); + } + return pyStr(segment[1]); + } + + static parse_segment_name(cls, romStart, segment) { + if (has(segment, 'name')) return pyStr(segment.name); + if (has(segment, 'dir')) return pyStr(segment.dir); + if (isList(segment) && segment.length >= 3) return pyStr(segment[2]); + return pyStr(cls.get_default_name(romStart)); + } + + static parse_segment_symbol_name_format(segment) { + if (has(segment, 'symbol_name_format')) return pyStr(segment.symbol_name_format); + return opts.symbol_name_format; + } + + static parse_segment_symbol_name_format_no_rom(segment) { + if (has(segment, 'symbol_name_format_no_rom')) return pyStr(segment.symbol_name_format_no_rom); + return opts.symbol_name_format_no_rom; + } + + static parse_segment_file_path(segment) { + if (has(segment, 'path')) return P(segment.path); + return null; + } + + static parse_segment_bss_contains_common(segment, def) { + if (has(segment, 'bss_contains_common')) return truthy(segment.bss_contains_common); + return def; + } + + static parse_linker_section_order(yaml) { + if (has(yaml, 'linker_section_order')) return pyStr(yaml.linker_section_order); + return null; + } + + static parse_linker_section(yaml) { + if (has(yaml, 'linker_section')) return pyStr(yaml.linker_section); + return null; + } + + static parse_ld_fill_value(yaml, def) { + if (has(yaml, 'ld_fill_value')) return yaml.ld_fill_value; + return def; + } + + static parse_ld_align_segment_start(yaml) { + if (has(yaml, 'ld_align_segment_start')) return yaml.ld_align_segment_start; + return opts.ld_align_segment_start; + } + + static parse_suggestion_rodata_section_start(yaml) { + if (isDict(yaml)) { + const v = get(yaml, 'suggestion_rodata_section_start', null); + if (v !== null) { + if (typeof v !== 'boolean') throw new Error('AssertionError'); + return v; + } + } + return null; + } + + static parse_pair_segment(yaml) { + if (!atLeast('0.35.0')) return null; + if (has(yaml, 'pair_segment')) return yaml.pair_segment; + return null; + } + + constructor(romStart, romEnd, type, name, vramStart, args, yaml) { + this.rom_start = romStart; + this.rom_end = romEnd; + this.type = type; + this.name = name; + this.vram_start = vramStart; + + this.align = null; + this.given_subalign = opts.subalign; + this.exclusive_ram_id = null; + this.given_dir = '.'; + this.given_find_file_boundaries = null; + this.given_seg_symbols = new Map(); + this.symbol_ranges_ram = new IntervalTree(); + this.symbol_ranges_rom = new IntervalTree(); + this.given_section_order = opts.section_order; + this.vram_class = null; + this.given_follows_vram = null; + this.given_vram_symbol = null; + this.given_symbol_name_format = opts.symbol_name_format; + this.given_symbol_name_format_no_rom = opts.symbol_name_format_no_rom; + this.parent = null; + this.sibling = null; + this.siblings = new Map(); + this.pair_segment_name = Segment.parse_pair_segment(yaml); + this.paired_segment = null; + this.file_path = null; + this.args = args; + this.yaml = yaml; + + this.extract = true; + this.has_linker_entry = true; + if (this.rom_start === null) this.extract = false; + else if (this.type.startsWith('.')) this.extract = false; + + this.warnings = []; + this.did_run = false; + this.bss_contains_common = Segment.parse_segment_bss_contains_common(yaml, opts.ld_bss_contains_common); + this.special_vram_segment = false; + this.linker_section_order = Segment.parse_linker_section_order(yaml); + this.linker_section = Segment.parse_linker_section(yaml); + this.ld_fill_value = Segment.parse_ld_fill_value(yaml, opts.ld_fill_value); + this.ld_align_segment_start = Segment.parse_ld_align_segment_start(yaml); + this.is_generated = false; + this.given_suggestion_rodata_section_start = Segment.parse_suggestion_rodata_section_start(yaml); + this.is_auto_segment = false; + this.index_within_group = null; + + if (this.rom_start !== null && this.rom_end !== null && this.rom_start !== undefined && this.rom_end !== undefined) { + if (this.rom_start > this.rom_end) { + log.error(`Error: segments out of order - (${this.name} starts at 0x${hex(this.rom_start)}, but next segment starts at 0x${hex(this.rom_end)})`); + } + } + } + + static from_yaml(cls, yaml, romStart, romEnd, parent, vram = null) { + const type = Segment.parse_segment_type(yaml); + const name = Segment.parse_segment_name(cls, romStart, yaml); + const vramClass = parseSegmentVramClass(yaml); + let vramStart; + if (vram !== null && vram !== undefined) vramStart = vram; + else if (vramClass) vramStart = vramClass.vram; + else vramStart = parseSegmentVram(yaml); + + const args = isDict(yaml) ? [] : yaml.slice(3); + + const ret = new cls(romStart, romEnd, type, name, vramStart, args, yaml); + if (parent !== null) { + // Python `"subalign" in yaml` works for dicts (keys) and lists (items). + const inYaml = (k) => (isDict(yaml) ? has(yaml, k) : yaml.includes(k)); + if (inYaml('subalign')) { + log.error(`Non top-level segment '${name}' (rom address 0x${hex(romStart)}) specified a \`subalign\`. \`subalign\` is valid only for top-level segments`); + } + if (inYaml('ld_fill_value')) { + log.error(`Non top-level segment '${name}' (rom address 0x${hex(romStart)}) specified a \`ld_fill_value\`. \`ld_fill_value\` is valid only for top-level segments`); + } + } + ret.parent = parent; + + if (atLeast('0.35.0') && opts.ld_bss_is_noload && ret.isBss) { + if (parent && parent.isCode) { + if (parent.bss_size <= 0) { + log.error(`Top-level segment '${parent.name}' is missing a \`bss_size\` value.\n A non-zero \`bss_size\` value must be defined on the top-level segments that contain '${ret.type}' sections (produced by the '${ret.name}' section).`); + } + if (Number.isInteger(ret.vram_start) && Number.isInteger(parent.vram_end) && ret.vram_start >= parent.vram_end) { + log.error(`The section '${ret.name}' (vram 0x${hex(ret.vram_start, 8)}) is outside its parent's address range '${parent.name}' (0x${hex(parent.vram_start, 8)} ~ 0x${hex(parent.vram_end, 8)}).\n This may happen when the specified \`bss_size\` value is too small.`); + } + } + } + + ret.given_section_order = parseSegmentSectionOrder(yaml); + ret.given_subalign = parseSegmentSubalign(yaml); + + if (isDict(yaml)) { + ret.extract = truthy(get(yaml, 'extract', ret.extract)); + ret.exclusive_ram_id = get(yaml, 'exclusive_ram_id', null); + ret.given_dir = P(get(yaml, 'dir', '')); + ret.has_linker_entry = truthy(get(yaml, 'linker_entry', true)); + ret.given_find_file_boundaries = get(yaml, 'find_file_boundaries', null); + } + + ret.given_symbol_name_format = Segment.parse_segment_symbol_name_format(yaml); + ret.given_symbol_name_format_no_rom = Segment.parse_segment_symbol_name_format_no_rom(yaml); + ret.file_path = Segment.parse_segment_file_path(yaml); + ret.bss_contains_common = Segment.parse_segment_bss_contains_common(yaml, opts.ld_bss_contains_common); + ret.given_follows_vram = parseSegmentFollowsVram(yaml); + ret.given_vram_symbol = parseSegmentVramSymbol(yaml); + + if (vramClass) { + ret.vram_class = vramClass; + if (ret.given_follows_vram) log.error(`Error: segment ${ret.name} has both a vram class and a follows_vram property`); + if (ret.given_vram_symbol) log.error(`Error: segment ${ret.name} has both a vram class and a vram_symbol property`); + } + + if (!ret.align) ret.align = parseSegmentAlign(yaml); + return ret; + } + + static is_text() { return false; } + static is_data() { return false; } + static is_rodata() { return false; } + static is_noload() { return false; } + static estimate_size() { return null; } + static get_default_name(addr) { return hex(addr); } + + is_text() { return this.constructor.is_text(); } + is_data() { return this.constructor.is_data(); } + is_rodata() { return this.constructor.is_rodata(); } + is_noload() { return this.constructor.is_noload(); } + get_default_name(addr) { return this.constructor.get_default_name(addr); } + + // isinstance() markers (avoid circular imports between segment classes) + get isBss() { return false; } + get isCode() { return false; } + get isGroup() { return false; } + get isCodeSubsegment() { return false; } + + get needs_symbols() { return false; } + + get dir() { + if (this.parent) return P(this.parent.dir, this.given_dir); + return this.given_dir; + } + + get show_file_boundaries() { + if (this.given_find_file_boundaries !== null && this.given_find_file_boundaries !== undefined) { + return this.given_find_file_boundaries; + } + if (!this.parent) return opts.find_file_boundaries; + return this.parent.show_file_boundaries; + } + + get symbol_name_format() { return this.given_symbol_name_format; } + get symbol_name_format_no_rom() { return this.given_symbol_name_format_no_rom; } + + get subalign() { + if (this.parent !== null) throw new Error(`AssertionError: subalign is not valid for non-top-level segments. (${this})`); + return this.given_subalign; + } + + get vram_symbol() { + if (this.vram_class && this.vram_class.vram_symbol) return this.vram_class.vram_symbol; + if (this.given_vram_symbol) return this.given_vram_symbol; + return null; + } + + get_exclusive_ram_id() { + if (this.parent) return this.parent.get_exclusive_ram_id(); + return this.exclusive_ram_id; + } + + add_symbol(symbol) { + let l = this.given_seg_symbols.get(symbol.vram_start); + if (!l) { l = []; this.given_seg_symbols.set(symbol.vram_start, l); } + l.push(symbol); + if (symbol.size > 4) { + this.symbol_ranges_ram.addi(symbol.vram_start, symbol.vram_end, symbol); + if (symbol.rom !== null) this.symbol_ranges_rom.addi(symbol.rom, symbol.rom_end, symbol); + } + } + + get seg_symbols() { + if (this.parent) return this.parent.seg_symbols; + return this.given_seg_symbols; + } + + get size() { + if (this.rom_start !== null && this.rom_end !== null && this.rom_start !== undefined && this.rom_end !== undefined) { + return this.rom_end - this.rom_start; + } + return null; + } + + get statistics() { + const stats = emptyStatistics(); + if (this.size !== null) stats.set(this.statistics_type, new SegmentStatisticsInfo(this.size, 1)); + return stats; + } + + get statistics_type() { return this.type; } + + get vram_end() { + if (this.vram_start !== null && this.vram_start !== undefined && this.size !== null) return this.vram_start + this.size; + return null; + } + + get section_order() { return this.given_section_order; } + + get rodata_follows_data() { + const so = this.section_order; + if (!so.includes('.rodata') || !so.includes('.data')) return false; + return so.indexOf('.rodata') - so.indexOf('.data') === 1; + } + + get suggestion_rodata_section_start() { + if (this.given_suggestion_rodata_section_start !== null) return this.given_suggestion_rodata_section_start; + if (this.parent !== null) return this.parent.suggestion_rodata_section_start; + return opts.suggestion_rodata_section_start; + } + + get_cname() { + let name = this.name; + if (this.parent) name = this.parent.name + '_' + name; + return toCname(name); + } + + contains_vram(vram) { + const vs = this.vram_start; const ve = this.vram_end; + if (vs !== null && vs !== undefined && ve !== null && ve !== undefined) return vram >= vs && vram < ve; + return false; + } + + contains_rom(rom) { + if (this.rom_start !== null && this.rom_start !== undefined && this.rom_end !== null && this.rom_end !== undefined) { + return rom >= this.rom_start && rom < this.rom_end; + } + return false; + } + + rom_to_ram(romAddr) { + if (this.vram_start !== null && this.vram_start !== undefined && this.rom_start !== null && this.rom_start !== undefined) { + return this.vram_start + romAddr - this.rom_start; + } + return null; + } + + ram_to_rom(ramAddr) { + if (!this.contains_vram(ramAddr) && ramAddr !== this.vram_end) return null; + if (this.vram_start !== null && this.vram_start !== undefined && this.rom_start !== null && this.rom_start !== undefined) { + return this.rom_start + ramAddr - this.vram_start; + } + return null; + } + + should_scan() { return this.should_split(); } + should_split() { return this.extract && opts.is_mode_active(this.type); } + scan() {} + split() {} + cache() { return [this.yaml, this.rom_end]; } + + get_linker_section() { return '.data'; } + + get_linker_section_order() { + if (this.linker_section_order !== null) return this.linker_section_order; + return this.get_linker_section(); + } + + get_linker_section_linksection() { + if (this.linker_section !== null) return this.linker_section; + return this.get_linker_section(); + } + + get_section_flags() { return null; } + + get_section_asm_line() { + let line = `.section ${this.get_linker_section_linksection()}`; + const flags = this.get_section_flags(); + if (flags) line += `, "${flags}"`; + return line; + } + + out_path() { return null; } + + get_most_parent() { + let seg = this; + while (seg.parent) seg = seg.parent; + return seg; + } + + get_linker_entries() { + if (!this.has_linker_entry) return []; + const path = this.out_path(); + if (path) { + return [new registry.LinkerEntry(this, [path], path, this.get_linker_section_order(), + this.get_linker_section_linksection(), this.is_noload())]; + } + return []; + } + + log(msg) { + if (opts.verbose) log.write(`${this.type} ${this.name}: ${msg}`); + } + + warn(msg) { this.warnings.push(msg); } + + is_name_default() { return this.name === this.get_default_name(this.rom_start); } + + unique_id() { + const s = this.parent ? this.parent.unique_id() + '_' : ''; + return s + this.type + '_' + this.name; + } + + static visible_ram(seg1, seg2) { + if (seg1.get_most_parent() === seg2.get_most_parent()) return true; + if (seg1.get_exclusive_ram_id() === null || seg2.get_exclusive_ram_id() === null) return true; + return seg1.get_exclusive_ram_id() !== seg2.get_exclusive_ram_id(); + } + + retrieve_symbol(syms, addr) { + const all = syms.get(addr); + if (!all) return null; + const items = all.filter((i) => i.segment === null || Segment.visible_ram(this, i.segment)); + if (items.length === 0) return null; + return items[0]; + } + + retrieve_sym_type(syms, addr, type) { + const all = syms.get(addr); + if (!all) return null; + const items = all.filter((i) => (i.segment === null || Segment.visible_ram(this, i.segment)) && type === i.type); + return items.length ? items[0] : null; + } + + get_symbol(addr, { in_segment = false, type = null, create = false, define = false, reference = false, search_ranges = false, local_only = false } = {}) { + let ret = null; + let rom = null; + const mostParent = this.get_most_parent(); + + if (in_segment) { + rom = mostParent.ram_to_rom(addr); + ret = mostParent.retrieve_symbol(mostParent.seg_symbols, addr); + if (!ret && search_ranges) { + if (rom !== null) { + const c = mostParent.symbol_ranges_rom.at(rom); + if (c.length) ret = c[0].data; + } + if (!ret) { + const c = mostParent.symbol_ranges_ram.at(addr); + if (c.length) ret = c[0].data; + } + } + } else if (!local_only) { + ret = mostParent.retrieve_symbol(symbols.state.all_symbols_dict, addr); + if (!ret && search_ranges) { + const c = symbols.state.all_symbols_ranges.at(addr); + if (c.length) ret = c[0].data; + } + } + + if (!ret && create) { + ret = new Symbol(addr, { rom, type }); + symbols.addSymbol(ret); + if (in_segment) { + ret.segment = mostParent; + let l = mostParent.seg_symbols.get(addr); + if (!l) { l = []; mostParent.seg_symbols.set(addr, l); } + l.push(ret); + } + } + + if (ret) { + if (define) ret.defined = true; + if (reference) ret.referenced = true; + if (ret.type === null) ret.type = type; + if (ret.rom === null) ret.rom = rom; + if (in_segment && ret.segment === null) ret.segment = mostParent; + } + return ret; + } + + create_symbol(addr, inSegment, { type = null, define = false, reference = false, search_ranges = false, local_only = false } = {}) { + const ret = this.get_symbol(addr, { in_segment: inSegment, type, create: true, define, reference, search_ranges, local_only }); + if (!ret) throw new Error('AssertionError'); + return ret; + } + + toString() { return `${this.name} (${this.type})`; } +} diff --git a/packages/romdev-splat/src/split.js b/packages/romdev-splat/src/split.js new file mode 100644 index 00000000..60071003 --- /dev/null +++ b/packages/romdev-splat/src/split.js @@ -0,0 +1,387 @@ +// splat.scripts.split +import crypto from 'node:crypto'; +import { rt, atLeast, readBytes, mkdirp, writeText, TextFile, exists, abs } from './runtime.js'; +import * as log from './util/log.js'; +import * as conf from './util/conf.js'; +import * as options from './util/options.js'; +import * as symbols from './util/symbols.js'; +import * as relocs from './util/relocs.js'; +import * as palettes from './util/palettes.js'; +import * as vramClasses from './util/vram_classes.js'; +import * as filePresets from './util/file_presets.js'; +import { Statistics } from './util/statistics.js'; +import { Cache } from './util/cache.js'; +import { IntervalTree } from './util/intervaltree.js'; +import { P, parent, withSuffix } from './util/pypath.js'; +import { hex, pyStr } from './util/pyfmt.js'; +import { Segment } from './segtypes/segment.js'; +import { LinkerWriter, getSegmentVramEndSymbolName, resetCleanUpCache } from './segtypes/linker_entry.js'; +import { CommonSegCode } from './segtypes/common.js'; +import * as disassemblerInstance from './disassembler/disassembler_instance.js'; +import { spim } from './disassembler/spim.js'; +import './segtypes/index.js'; + +const S = { segmentRoms: new IntervalTree(), segmentRams: new IntervalTree(), config: null }; + +export function initializeSegments(configSegments) { + S.segmentRoms = new IntervalTree(); + S.segmentRams = new IntervalTree(); + const segmentsByName = new Map(); + const ret = []; + let doCrossSegmentPairing = false; + let lastRomEnd = 0; + + for (let i = 0; i < configSegments.length; i++) { + const segYaml = configSegments[i]; + if (Array.isArray(segYaml) && segYaml.length === 1) continue; + + const segType = Segment.parse_segment_type(segYaml); + const segmentClass = Segment.get_class_for_type(segType); + let [thisStart] = Segment.parse_segment_start(segYaml); + + let nextStart = null; + for (let j = i + 1; j < configSegments.length; j++) { + [nextStart] = Segment.parse_segment_start(configSegments[j]); + if (nextStart !== null) break; + } + if (nextStart === null) { + log.error('Next segment address could not be found. Segments list must end with a rom end pos marker ([0x10000000])'); + } + + if (segmentClass.is_noload()) { + thisStart = lastRomEnd; + nextStart = lastRomEnd; + } + + const segment = Segment.from_yaml(segmentClass, segYaml, thisStart, nextStart, null); + + if (segment.constructor.require_unique_name) { + if (segmentsByName.has(segment.name)) log.error(`segment name '${segment.name}' is not unique`); + segmentsByName.set(segment.name, segment); + } + if (segment.pair_segment_name !== null) doCrossSegmentPairing = true; + + ret.push(segment); + if (Number.isInteger(segment.rom_start) && Number.isInteger(segment.rom_end) && segment.rom_start !== segment.rom_end) { + S.segmentRoms.addi(segment.rom_start, segment.rom_end, segment); + } + const ve = segment.vram_end; + if (Number.isInteger(segment.vram_start) && Number.isInteger(ve) && segment.vram_start !== ve) { + S.segmentRams.addi(segment.vram_start, ve, segment); + } + if (nextStart !== null) lastRomEnd = nextStart; + } + + for (const segment of ret) { + if (segment.given_follows_vram) { + if (!segmentsByName.has(segment.given_follows_vram)) { + log.error(`segment '${segment.given_follows_vram}', the 'follows_vram' value for segment '${segment.name}', does not exist`); + } + segment.given_vram_symbol = getSegmentVramEndSymbolName(segmentsByName.get(segment.given_follows_vram)); + } + } + + if (ret[ret.length - 1].type === 'pad') { + log.error('Last segment in config cannot be a pad segment; see https://github.com/ethteck/splat/wiki/Segments#pad'); + } + + if (doCrossSegmentPairing) { + for (const seg of ret) { + if (seg.pair_segment_name === null) continue; + let found = false; + for (const other of ret) { + if (seg === other) continue; + if (seg.pair_segment_name === other.name && other.isGroup) { + if (other.pair_segment_name !== null) { + log.error(`Both segments '${seg.name}' and '${other.name}' have a \`pair_segment\` value, when only at most one of the cross-paired segments can have this attribute.`); + } + found = true; + seg.paired_segment = other; + other.paired_segment = seg; + if (seg.isGroup && other.isGroup) seg.pair_subsegments_to_other_segment(other); + break; + } + } + if (!found) { + log.error(`Segment '${seg.pair_segment_name}' not found.\n It is referenced by segment '${seg.name}', because of the \`pair_segment\` attribute.`); + } + } + } + return ret; +} + +function assignSymbolsToSegments() { + for (const symbol of symbols.state.all_symbols) { + if (symbol.segment) continue; + if (symbol.rom) { + const cands = S.segmentRoms.at(symbol.rom); + if (cands.length > 1) log.error(`multiple segments rom overlap symbol ${symbol}`); + else if (cands.length === 0) log.error(`no segment rom overlaps symbol ${symbol}`); + else cands[0].data.add_symbol(symbol); + } else { + for (const cand of S.segmentRams.at(symbol.vram_start)) { + const seg = cand.data; + if (!seg.get_exclusive_ram_id()) seg.add_symbol(symbol); + } + } + } +} + +function calcSegmentDependences(allSegments) { + const vramClassToSegments = new Map(); + for (const seg of allSegments) { + if (seg.vram_class !== null) { + if (!vramClassToSegments.has(seg.vram_class.name)) vramClassToSegments.set(seg.vram_class.name, []); + vramClassToSegments.get(seg.vram_class.name).push(seg); + } + } + const out = new Map(); + for (const vc of vramClasses.state.vramClasses.values()) { + if (vc.follows_classes.length) { + out.set(vc, []); + for (const fc of vc.follows_classes) { + if (vramClassToSegments.has(fc)) out.get(vc).push(...vramClassToSegments.get(fc)); + } + } + } + return out; +} + +function readTargetBinary() { + const romBytes = readBytes(options.opts.target_path); + const config = S.config; + if ('sha1' in config) { + const sha1 = crypto.createHash('sha1').update(romBytes).digest('hex'); + const expected = String(config.sha1).toLowerCase(); + if (expected !== sha1) log.error(`sha1 mismatch: expected ${expected}, was ${sha1}`); + } else { + log.write('Warning: no sha1 in config'); + } + return romBytes; +} + +function initializePlatform() { + const o = options.opts; + if (o.platform === 'n64') { + const ctx = symbols.state.spim_context; + ctx.fillDefaultBannedSymbols(); + if (o.libultra_symbols) ctx.globalSegment.fillLibultraSymbols(); + if (o.ique_symbols) ctx.globalSegment.fillIQueSymbols(); + if (o.hardware_regs) ctx.globalSegment.fillHardwareRegs(true); + } else if (o.platform === 'psx') { + // nothing + } else if (o.platform === 'ps2') { + throw new Error('romdev-splat: the ps2 platform is not ported'); + } else if (o.platform === 'psp') { + throw new Error('romdev-splat: the psp platform is not ported'); + } +} + +function initializeAllSymbols(allSegments) { + symbols.initialize(allSegments); + relocs.initialize(); + assignSymbolsToSegments(); + if (options.opts.is_mode_active('code')) { + symbols.initializeSpimContext(allSegments, CommonSegCode); + relocs.initializeSpimContext(); + } +} + +function doScan(allSegments, romBytes, stats, cache) { + const processed = []; + for (const segment of allSegments) { + for (const [ty, sub] of segment.statistics) stats.add_size(ty, sub.size); + if (segment.should_scan()) { + if (cache.check_cache_hit(segment, false)) continue; + segment.did_run = true; + segment.scan(romBytes); + processed.push(segment); + for (const [ty, sub] of segment.statistics) stats.count_split(ty, sub.count); + } + } + symbols.markCFuncsAsDefined(); + return processed; +} + +function doSplit(allSegments, romBytes, stats, cache) { + for (const segment of allSegments) { + if (cache.check_cache_hit(segment, true)) { + for (const [ty, sub] of segment.statistics) stats.count_cached(ty, sub.count); + continue; + } + if (segment.should_split()) { + let segmentBytes = romBytes; + if (segment.file_path) segmentBytes = readBytes(segment.file_path); + segment.split(segmentBytes); + } + } +} + +function writeLinkerScript(allSegments) { + const o = options.opts; + const deps = calcSegmentDependences(allSegments); + const toSearch = new Set(deps.keys()); + const maxVramEndInsertionPoints = new Map(); + for (let i = allSegments.length - 1; i >= 0; i--) { + const seg = allSegments[i]; + if (seg.vram_class !== null && toSearch.has(seg.vram_class)) { + if (!maxVramEndInsertionPoints.has(seg)) maxVramEndInsertionPoints.set(seg, []); + maxVramEndInsertionPoints.get(seg).push([seg.vram_class.vram_symbol, deps.get(seg.vram_class)]); + toSearch.delete(seg.vram_class); + } + } + + const linkerWriter = new LinkerWriter(); + const partialScriptsPath = o.ld_partial_scripts_path; + const segmentsPath = o.ld_partial_build_segments_path; + if (o.ld_partial_linking) { + if (partialScriptsPath === null) log.error('Partial linking is enabled but `ld_partial_scripts_path` has not been set'); + if (segmentsPath === null) log.error('Partial linking is enabled but `ld_partial_build_segments_path` has not been set'); + } + + for (const segment of allSegments) { + const maxVramSyms = maxVramEndInsertionPoints.get(segment) || []; + if (o.ld_partial_linking) { + linkerWriter.add_referenced_partial_segment(segment, maxVramSyms); + const sub = new LinkerWriter(true); + sub.add_partial_segment(segment); + const segName = segment.get_cname(); + sub.save_linker_script(P(partialScriptsPath, `${segName}.ld`)); + if (o.ld_dependencies) sub.save_dependencies_file(P(partialScriptsPath, `${segName}.d`), P(segmentsPath, `${segName}.o`)); + } else { + linkerWriter.add(segment, maxVramSyms); + } + } + + linkerWriter.save_linker_script(o.ld_script_path); + linkerWriter.save_symbol_header(); + writeLdDependencies(linkerWriter); + return linkerWriter; +} + +function writeLdDependencies(linkerWriter) { + const o = options.opts; + if (o.ld_dependencies) { + if (o.elf_path === null) { + log.error('Generation of dependency file for linker script requested but `elf_path` was not provided in the yaml options'); + } + linkerWriter.save_dependencies_file(withSuffix(o.ld_script_path, '.d'), o.elf_path); + } +} + +function writeElfSectionsFile(allSegments) { + const o = options.opts; + if (o.elf_section_list_path) { + let list = ''; + for (const segment of allSegments) list += '.' + segment.get_cname() + '\n'; + mkdirp(parent(o.elf_section_list_path)); + writeText(o.elf_section_list_path, list, '\n'); + } +} + +function writeUndefinedAuto(toWrite, filePath) { + mkdirp(parent(filePath)); + writeText(filePath, toWrite.map((s) => `${s.name} = 0x${hex(s.vram_start)};\n`).join(''), '\n'); +} + +/** list.sort(key=...) is stable; Array.prototype.sort is stable too. */ +function sortByVram(list) { return list.sort((a, b) => a.vram_start - b.vram_start); } + +function writeUndefinedFuncsAuto() { + const o = options.opts; + if (o.create_undefined_funcs_auto) { + const toWrite = sortByVram(symbols.state.all_symbols.filter((s) => s.referenced && !s.defined && s.type === 'func')); + writeUndefinedAuto(toWrite, o.undefined_funcs_auto_path); + } +} + +function writeUndefinedSymsAuto() { + const o = options.opts; + if (o.create_undefined_syms_auto) { + const toWrite = sortByVram(symbols.state.all_symbols.filter((s) => s.referenced && !s.defined + && !['func', 'label', 'jtbl_label'].includes(s.type))); + writeUndefinedAuto(toWrite, o.undefined_syms_auto_path); + } +} + +function printSegmentWarnings(allSegments) { + for (const segment of allSegments) { + if (segment.warnings.length > 0) { + log.write(`\x1b[2m0x${hex(segment.rom_start, 6)}\x1b[0m ${segment.type} \x1b[1m${segment.name}\x1b[0m:`); + for (const w of segment.warnings) log.write('warning: ' + w, { status: 'warn' }); + log.write(''); + } + } +} + +function dumpSymbols() { + const o = options.opts; + if (!o.dump_symbols) return; + const hidden = P(o.base_path, '.splat'); + mkdirp(hidden); + const f = new TextFile(P(hidden, 'splat_symbols.csv'), null); + f.write('vram_start,given_name,name,type,given_size,size,rom,defined,user_declared,referenced,extract\n'); + for (const s of sortByVram([...symbols.state.all_symbols])) { + f.write(`${hex(s.vram_start)},${pyStr(s.given_name)},${s.name},${pyStr(s.type)},`); + f.write(s.given_size !== null ? `0x${hex(s.given_size)},` : 'None,'); + f.write(`${s.size},`); + f.write(s.rom !== null ? `0x${hex(s.rom)},` : 'None,'); + f.write(`${pyStr(s.defined)},${pyStr(s.user_declared)},${pyStr(s.referenced)},${pyStr(s.extract)}\n`); + } + f.close(); + symbols.state.spim_context.saveContextToFile(abs(P(hidden, 'spim_context.csv'))); +} + +export function splatVersionString() { return rt.version.join('.'); } + +/** splat.scripts.split.main, synchronous once the backend is loaded. */ +export function main(configPaths, modes, verbose, useCache = true, skipVersionCheck = false, stdoutOnly = false, + disassembleAll = false, makeFullDisasmForCode = false, overrides = {}) { + if (stdoutOnly) log.write('--stdout-only flag is deprecated', { status: 'warn' }); + + resetCleanUpCache(); + disassemblerInstance.reset(); + symbols.resetSymbols(); + relocs.reset(); + + S.config = conf.load(configPaths, modes, verbose, disassembleAll, makeFullDisasmForCode, overrides); + const o = options.opts; + + disassemblerInstance.createDisassemblerInstance(skipVersionCheck, splatVersionString()); + + const romBytes = readTargetBinary(); + mkdirp(o.base_path); + + const stats = new Statistics(); + const cache = new Cache(S.config, useCache, verbose); + + if (!o.is_unsupported_platform) initializePlatform(); + + const allSegments = initializeSegments(S.config.segments); + initializeAllSymbols(allSegments); + + if (o.is_mode_active('img')) palettes.initialize(allSegments); + + doScan(allSegments, romBytes, stats, cache); + doSplit(allSegments, romBytes, stats, cache); + + if (o.is_mode_active('ld')) { + const lw = writeLinkerScript(allSegments); + writeLdDependencies(lw); + writeElfSectionsFile(allSegments); + } + + writeUndefinedFuncsAuto(); + writeUndefinedSymsAuto(); + printSegmentWarnings(allSegments); + stats.print_statistics(romBytes.length); + cache.save(verbose); + + if (o.is_mode_active('code')) { + dumpSymbols(); + if (atLeast('0.35.0')) filePresets.writeAllFiles(); + } + return { segments: allSegments, symbols: symbols.state.all_symbols, spim }; +} + +export { exists }; diff --git a/packages/romdev-splat/src/util/cache.js b/packages/romdev-splat/src/util/cache.js new file mode 100644 index 00000000..2806d0ad --- /dev/null +++ b/packages/romdev-splat/src/util/cache.js @@ -0,0 +1,47 @@ +// splat.util.cache_handler. Python splat pickles the cache; this port keeps +// the same keys and comparison rules in a JSON file at the same path. +import { exists, readText, mkdirp, writeText } from '../runtime.js'; +import * as log from './log.js'; +import { opts } from './options.js'; +import { parent } from './pypath.js'; + +const enc = (v) => JSON.stringify(v, (k, x) => (x instanceof Map ? [...x] : x)); + +export class Cache { + constructor(config, useCache, verbose) { + this.use_cache = useCache; + this.cache = {}; + if (useCache && exists(opts.cache_path)) { + try { + this.cache = JSON.parse(readText(opts.cache_path)); + if (verbose) log.write(`Loaded cache (${Object.keys(this.cache).length} items)`); + } catch { + log.write('Not able to load cache file. Discarding old cache', { status: 'warn' }); + this.cache = {}; + } + } + const optsKey = enc(config.options === undefined ? null : config.options); + if (useCache && this.cache.__options__ !== optsKey) { + if (verbose) log.write('Options changed, invalidating cache'); + this.cache = { __options__: optsKey }; + } + } + + save(verbose) { + if (Object.keys(this.cache).length && this.use_cache) { + if (verbose) log.write('Writing cache'); + mkdirp(parent(opts.cache_path)); + writeText(opts.cache_path, JSON.stringify(this.cache), '\n'); + } + } + + check_cache_hit(segment, updateOnMiss) { + if (this.use_cache) { + const cached = enc(segment.cache()); + const id = segment.unique_id(); + if (cached === this.cache[id]) return true; + if (updateOnMiss) this.cache[id] = cached; + } + return false; + } +} diff --git a/packages/romdev-splat/src/util/codecs.js b/packages/romdev-splat/src/util/codecs.js new file mode 100644 index 00000000..1a78ce9d --- /dev/null +++ b/packages/romdev-splat/src/util/codecs.js @@ -0,0 +1,22 @@ +// Python codec names -> decoders, for the few text encodings splat decodes +// itself (the N64 header's internal name). +function pyCodecName(name) { return String(name).toLowerCase().replace(/_/g, '-'); } + +export function decodeText(bytes, encoding) { + const n = pyCodecName(encoding); + if (n === 'ascii' || n === 'us-ascii' || n === '646') { + for (const b of bytes) { + if (b > 0x7f) throw new Error(`UnicodeDecodeError: 'ascii' codec can't decode byte 0x${b.toString(16)}`); + } + return Buffer.from(bytes).toString('latin1'); + } + if (n === 'latin-1' || n === 'latin1' || n === 'iso-8859-1' || n === 'iso8859-1') return Buffer.from(bytes).toString('latin1'); + const map = { + 'utf-8': 'utf-8', utf8: 'utf-8', + 'shift-jis': 'shift_jis', 'shift_jis': 'shift_jis', sjis: 'shift_jis', 's-jis': 'shift_jis', + 'euc-jp': 'euc-jp', eucjp: 'euc-jp', + }; + const label = map[n]; + if (!label) throw new Error(`romdev-splat: unsupported text encoding '${encoding}'`); + return new TextDecoder(label, { fatal: true }).decode(bytes); +} diff --git a/packages/romdev-splat/src/util/compiler.js b/packages/romdev-splat/src/util/compiler.js new file mode 100644 index 00000000..c03d3f08 --- /dev/null +++ b/packages/romdev-splat/src/util/compiler.js @@ -0,0 +1,58 @@ +// splat.util.compiler (defaults gated on the splat version: 0.37 changed the +// default label macros and added data-end / nonmatching / include_asm fields). +import { atLeast } from '../runtime.js'; + +function make(name, fields = {}) { + const modern = atLeast('0.35.0'); + const base = modern + ? { + asm_function_macro: 'glabel', asm_function_alt_macro: 'alabel', asm_jtbl_label_macro: 'jlabel', + asm_data_macro: 'dlabel', asm_end_label: 'endlabel', asm_data_end_label: 'enddlabel', + asm_ehtable_label_macro: 'ehlabel', asm_nonmatching_label_macro: 'nonmatching', + } + : { + asm_function_macro: 'glabel', asm_function_alt_macro: 'glabel', asm_jtbl_label_macro: 'glabel', + asm_data_macro: 'glabel', asm_end_label: '', asm_data_end_label: '', + asm_ehtable_label_macro: 'ehlabel', asm_nonmatching_label_macro: '', + }; + return { + name, + ...base, + c_newline: '\n', + asm_inc_header: '', + asm_emit_size_directive: null, + j_as_branch: false, + uses_include_asm: true, + align_on_branch_labels: false, + ...fields, + }; +} + +/** Build the compiler table for the active splat version. */ +export function compilers() { + const modern = atLeast('0.35.0'); + const GCC = make('GCC', { + asm_inc_header: '.set noat /* allow manual use of $at */\n.set noreorder /* don\'t insert nops after branches */\n\n', + j_as_branch: true, + }); + const SN64 = make('SN64', { + asm_function_macro: '.globl', asm_function_alt_macro: '.globl', asm_jtbl_label_macro: '.globl', + asm_data_macro: '.globl', asm_end_label: '.end', + ...(modern ? { asm_data_end_label: '', asm_nonmatching_label_macro: '' } : {}), + c_newline: '\r\n', asm_emit_size_directive: false, j_as_branch: true, + }); + const IDO = make('IDO', { asm_emit_size_directive: false, uses_include_asm: !modern ? true : false }); + const KMC = make('KMC', { j_as_branch: true }); + const EGCS = make('EGCS', { j_as_branch: true }); + const PSYQ = make('PSYQ', { j_as_branch: true }); + const MWCCPS2 = make('MWCCPS2', { uses_include_asm: !modern }); + const EEGCC = make('EEGCC', { align_on_branch_labels: modern }); + const table = {}; + for (const c of [GCC, SN64, IDO, KMC, EGCS, PSYQ, MWCCPS2, EEGCC]) table[c.name] = c; + return table; +} + +export function forName(name, table) { + name = name.toUpperCase(); + return table[name] || make(name); +} diff --git a/packages/romdev-splat/src/util/conf.js b/packages/romdev-splat/src/util/conf.js new file mode 100644 index 00000000..7ed26612 --- /dev/null +++ b/packages/romdev-splat/src/util/conf.js @@ -0,0 +1,37 @@ +// splat.util.conf: load and merge the yaml config files. +import { readText } from '../runtime.js'; +import { loadYaml } from './yaml11.js'; +import * as options from './options.js'; +import * as vramClasses from './vram_classes.js'; +import { isDict, pyTypeName } from './pyfmt.js'; + +function sameType(a, b) { return pyTypeName(a) === pyTypeName(b); } + +export function mergeConfigs(main, additional, additionalPath) { + for (const key of Object.keys(additional)) { + if (!(key in main)) { + main[key] = additional[key]; + } else if (!sameType(main[key], additional[key])) { + throw new TypeError(`Could not merge ${additionalPath}: type for key '${key}' in configs does not match`); + } else if (Array.isArray(main[key])) { + // Python `+=` extends the existing list object in place. + main[key].push(...additional[key]); + } else if (isDict(main[key])) { + main[key] = mergeConfigs(main[key], additional[key], additionalPath); + } else { + main[key] = additional[key]; + } + } + return main; +} + +export function load(configPaths, modes = null, verbose = false, disassembleAll = false, makeFullDisasmForCode = false, overrides = {}) { + let config = {}; + for (const entry of configPaths) { + const additional = loadYaml(readText(entry)); + config = mergeConfigs(config, additional, entry); + } + vramClasses.initialize(config.vram_classes === undefined ? null : config.vram_classes); + options.initialize(config, configPaths, modes, verbose, disassembleAll, makeFullDisasmForCode, overrides); + return config; +} diff --git a/packages/romdev-splat/src/util/file_presets.js b/packages/romdev-splat/src/util/file_presets.js new file mode 100644 index 00000000..1caed820 --- /dev/null +++ b/packages/romdev-splat/src/util/file_presets.js @@ -0,0 +1,317 @@ +// splat.util.file_presets (splat >= 0.35): include/include_asm.h, +// include/macro.inc, include/labels.inc and include/gte_macros.inc. +import { exists, mkdirp, readText, writeText } from '../runtime.js'; +import * as log from './log.js'; +import { opts } from './options.js'; +import { parent } from './pypath.js'; +import { GTE_MACROS } from './gte_macros.js'; + +export function writeAllFiles() { + if (!opts.generate_asm_macros_files) return; + writeIncludeAsmH(); + writeAssemblyIncFiles(); +} + +function write(filepath, contents) { + mkdirp(parent(filepath)); + if (exists(filepath)) { + if (readText(filepath) === contents) return; + } + writeText(filepath, contents, '\n'); +} + +function writeIncludeAsmH() { + if (!opts.compiler.uses_include_asm) return; + const directory = opts.generated_asm_macros_directory; + let includeAsmMacro; + if (opts.include_asm_macro_style === 'maspsx_hack') { + includeAsmMacro = `\ +#define INCLUDE_ASM(FOLDER, NAME) \\ + void __maspsx_include_asm_hack_##NAME() { \\ + __asm__( \\ + ".text # maspsx-keep \\n" \\ + " .align 2 # maspsx-keep\\n" \\ + " .set noat # maspsx-keep\\n" \\ + " .set noreorder # maspsx-keep\\n" \\ + " .include \\"" FOLDER "/" #NAME ".s\\" # maspsx-keep\\n" \\ + " .set reorder # maspsx-keep\\n" \\ + " .set at # maspsx-keep\\n" \\ + ); \\ + } +`; + } else { + includeAsmMacro = `\ +#define INCLUDE_ASM(FOLDER, NAME) \\ + __asm__( \\ + ".section .text\\n" \\ + " .set noat\\n" \\ + " .set noreorder\\n" \\ + " .include \\"" FOLDER "/" #NAME ".s\\"\\n" \\ + " .set reorder\\n" \\ + " .set at\\n" \\ + ) +`; + } + const includeRodataMacro = `\ +#define INCLUDE_RODATA(FOLDER, NAME) \\ + __asm__( \\ + ".section .rodata\\n" \\ + " .include \\"" FOLDER "/" #NAME ".s\\"\\n" \\ + ".section .text" \\ + ) +`; + const fileData = `\ +#ifndef INCLUDE_ASM_H +#define INCLUDE_ASM_H + +#if !defined(M2CTX) && !defined(PERMUTER) + +#ifndef INCLUDE_ASM +${includeAsmMacro}\ +#endif +#ifndef INCLUDE_RODATA +${includeRodataMacro}\ +#endif + +#if INCLUDE_ASM_USE_MACRO_INC +__asm__(".include \\"${directory}/macro.inc\\"\\n"); +#else +__asm__(".include \\"${directory}/labels.inc\\"\\n"); +#endif + +#else + +#ifndef INCLUDE_ASM +#define INCLUDE_ASM(FOLDER, NAME) +#endif +#ifndef INCLUDE_RODATA +#define INCLUDE_RODATA(FOLDER, NAME) +#endif + +#endif /* !defined(M2CTX) && !defined(PERMUTER) */ + +#endif /* INCLUDE_ASM_H */ +`; + write(`${directory}/include_asm.h`, fileData); +} + +const COP0_AND_FLOAT_ALIASES = ` +# COP0 register aliases + +.set Index, $0 +.set Random, $1 +.set EntryLo0, $2 +.set EntryLo1, $3 +.set Context, $4 +.set PageMask, $5 +.set Wired, $6 +.set Reserved07, $7 +.set BadVaddr, $8 +.set Count, $9 +.set EntryHi, $10 +.set Compare, $11 +.set Status, $12 +.set Cause, $13 +.set EPC, $14 +.set PRevID, $15 +.set Config, $16 +.set LLAddr, $17 +.set WatchLo, $18 +.set WatchHi, $19 +.set XContext, $20 +.set Reserved21, $21 +.set Reserved22, $22 +.set Reserved23, $23 +.set Reserved24, $24 +.set Reserved25, $25 +.set PErr, $26 +.set CacheErr, $27 +.set TagLo, $28 +.set TagHi, $29 +.set ErrorEPC, $30 +.set Reserved31, $31 + +# Float register aliases + +.set $fv0, $f0 +.set $fv0f, $f1 +.set $fv1, $f2 +.set $fv1f, $f3 +.set $ft0, $f4 +.set $ft0f, $f5 +.set $ft1, $f6 +.set $ft1f, $f7 +.set $ft2, $f8 +.set $ft2f, $f9 +.set $ft3, $f10 +.set $ft3f, $f11 +.set $fa0, $f12 +.set $fa0f, $f13 +.set $fa1, $f14 +.set $fa1f, $f15 +.set $ft4, $f16 +.set $ft4f, $f17 +.set $ft5, $f18 +.set $ft5f, $f19 +.set $fs0, $f20 +.set $fs0f, $f21 +.set $fs1, $f22 +.set $fs1f, $f23 +.set $fs2, $f24 +.set $fs2f, $f25 +.set $fs3, $f26 +.set $fs3f, $f27 +.set $fs4, $f28 +.set $fs4f, $f29 +.set $fs5, $f30 +.set $fs5f, $f31 +`; + +function writeAssemblyIncFiles() { + const directory = opts.generated_asm_macros_directory; + const o = opts; + + let funcMacros = `\ +# A function symbol. +.macro ${o.asm_function_macro} label, visibility=global + .\\visibility \\label + .type \\label, @function + \\label: + .ent \\label +.endm +`; + if (o.asm_end_label !== '') { + funcMacros += ` +# The end of a function symbol. +.macro ${o.asm_end_label} label + .size \\label, . - \\label + .end \\label +.endm +`; + } + if (o.asm_function_alt_macro !== '' && o.asm_function_alt_macro !== o.asm_function_macro) { + funcMacros += ` +# An alternative entry to a function. +.macro ${o.asm_function_alt_macro} label, visibility=global + .\\visibility \\label + .type \\label, @function + \\label: + .aent \\label +.endm +`; + } + if (o.asm_ehtable_label_macro !== '' && o.asm_ehtable_label_macro !== o.asm_function_macro) { + funcMacros += ` +# A label referenced by an error handler table. +.macro ${o.asm_ehtable_label_macro} label, visibility=global + .\\visibility \\label + \\label: +.endm +`; + } + + let jlabelMacroLabelsinc = ''; + let jlabelMacroMacroinc = ''; + if (o.asm_jtbl_label_macro !== '' && o.asm_jtbl_label_macro !== o.asm_function_macro) { + jlabelMacroMacroinc = ` +# A label referenced by a jumptable. +.macro ${o.asm_jtbl_label_macro} label, visibility=global + .\\visibility \\label + \\label: +.endm +`; + if (o.migrate_rodata_to_functions) { + jlabelMacroLabelsinc = ` +# A label referenced by a jumptable. +.macro ${o.asm_jtbl_label_macro} label, visibility=local + .\\visibility \\label + \\label: +.endm +`; + } else { + jlabelMacroLabelsinc = jlabelMacroMacroinc; + } + } + + let dataMacros = ''; + if (o.asm_data_macro !== '' && o.asm_data_macro !== o.asm_function_macro) { + dataMacros += ` +# A data symbol. +.macro ${o.asm_data_macro} label, visibility=global + .\\visibility \\label + .type \\label, @object + \\label: +.endm +`; + } + if (o.asm_data_end_label !== '') { + dataMacros += ` +# End of a data symbol. +.macro ${o.asm_data_end_label} label + .size \\label, . - \\label +.endm +`; + } + + let nmMacros = ''; + if (o.asm_nonmatching_label_macro !== '') { + nmMacros = ` +# Label to signal the symbol haven't been matched yet. +.macro ${o.asm_nonmatching_label_macro} label, size=1 + .global \\label\\().NON_MATCHING + .type \\label\\().NON_MATCHING, @object + .size \\label\\().NON_MATCHING, \\size + \\label\\().NON_MATCHING: +.endm +`; + } + + const macrosInc = `\ +${funcMacros} +${jlabelMacroMacroinc} +${dataMacros} +${nmMacros}\ +`; + + if (o.compiler.uses_include_asm) { + let preamble = '# This file is used by the original compiler/assembler.\n# Defines the expected assembly macros.\n'; + if (o.platform === 'psx') preamble += '\n.include "gte_macros.inc"\n'; + const labelsInc = `\ +${preamble} +${funcMacros} +${jlabelMacroLabelsinc} +${dataMacros} +${nmMacros}\ +`; + write(`${directory}/labels.inc`, labelsInc); + } + + let gas; + if (o.platform === 'n64' || o.platform === 'psx') gas = macrosInc; + else if (o.platform === 'ps2' || o.platform === 'psp') { + gas = macrosInc.replaceAll('\\label', '"\\label"').replaceAll('"\\label"\\().NON_MATCHING', '"\\label\\().NON_MATCHING"'); + } else if (!o.is_unsupported_platform) { + log.error(`Unknown platform '${o.platform}'`); + } else gas = macrosInc; + + if (o.platform === 'n64') { + gas += COP0_AND_FLOAT_ALIASES; + } else if (o.platform === 'psx') { + gas += '\n.include "gte_macros.inc"\n'; + write(`${directory}/gte_macros.inc`, GTE_MACROS); + } + + if (o.generated_macro_inc_content !== null) gas += `\n${o.generated_macro_inc_content}\n`; + + const preamble = '# This file is used by modern gas.\n# Defines the expected assembly macros\n'; + gas = `\ +# Evaluate this file only once in case it's included more than once +.ifndef _MACRO_INC_GUARD +.internal _MACRO_INC_GUARD +.set _MACRO_INC_GUARD, 1 + +${gas} +.endif +`; + write(`${directory}/macro.inc`, `${preamble}\n${gas}`); +} diff --git a/packages/romdev-splat/src/util/gte_macros.js b/packages/romdev-splat/src/util/gte_macros.js new file mode 100644 index 00000000..b32b9501 --- /dev/null +++ b/packages/romdev-splat/src/util/gte_macros.js @@ -0,0 +1,3 @@ +// gte_macros.inc as written by splat 0.37.1 (util/file_presets.py), taken +// from rabbitizer docs/r3000gte/gte_macros.s. +export const GTE_MACROS = ".ifndef .L_GTE_MACRO_INC\n.L_GTE_MACRO_INC:\n\n## GTE instruction macros\n## These are meant for use with GAS and replace DMPSX\n\n.macro cop2op fake_op, op, gbg = 0, sf = 1, mx = 0, v = 0, cv = 0, lm = 0\n cop2 \\fake_op << 20 | \\gbg << 20 | \\sf << 19 | \\mx << 17 | \\v << 15 | \\cv << 13 | \\lm << 10 | \\op\n.endm\n\n/* RTPS 15 0x4A180001 Perspective transform */\n.macro rtps\n cop2op 0x01, 0x01\n.endm\n\n/* RTPT 23 0x4A280030 Perspective transform on 3 points */\n.macro rtpt\n cop2op 0x02, 0x30\n.endm\n\n/* DPCL 8 0x4A680029 Depth Cue Color light */\n.macro dpcl\n cop2op 0x06, 0x29\n.endm\n\n/* DPCS 8 0x4A780010 Depth Cueing */\n.macro dpcs\n cop2op 0x07, 0x10\n.endm\n\n/* DPCT 17 0x4AF8002A Depth cue color RGB0,RGB1,RGB2 */\n.macro dpct\n cop2op 0x0F, 0x2A\n.endm\n\n/* INTPL 8 0x4A980011 Interpolation of vector and far color */\n.macro intpl\n cop2op 0x09, 0x11\n.endm\n\n/* NCS 14 0x4AC8041E Normal color v0 */\n.macro ncs\n cop2op 0x0C, 0x1E, lm = 1\n.endm\n\n/* NCT 30 0x4AD80420 Normal color v0, v1, v2 */\n.macro nct\n cop2op 0x0D, 0x20, lm = 1\n.endm\n\n/* NCDS 19 0x4AE80413 Normal color depth cuev0 */\n.macro ncds\n cop2op 0x0E, 0x13, lm = 1\n.endm\n\n/* NCDT 44 0x4AF80416 Normal color depth cue v0, v1, v2 */\n.macro ncdt\n cop2op 0x0F, 0x16, lm = 1\n.endm\n\n/* NCCS 17 0x4B08041B Normal color col. v0 */\n.macro nccs\n cop2op 0x10, 0x1B, lm = 1\n.endm\n\n/* NCCT 39 0x4B18043F Normal color col.v0, v1, v2 */\n.macro ncct\n cop2op 0x11, 0x3F, lm = 1\n.endm\n\n/* CDP 13 0x4B280414 Color Depth Queue */\n.macro cdp\n cop2op 0x12, 0x14, lm = 1\n.endm\n\n/* CC 11 0x4B38041C Color Col. */\n.macro cc\n cop2op 0x13, 0x1C, lm = 1\n.endm\n\n/* NCLIP 8 0x4B400006 Normal clipping */\n.macro nclip\n cop2op 0x14, 0x06, sf = 0\n.endm\n\n/* AVSZ3 5 0x4B58002D Average of three Z values */\n.macro avsz3\n cop2op 0x15, 0x2D\n.endm\n\n/* AVSZ4 6 0x4B68002E Average of four Z values */\n.macro avsz4\n cop2op 0x16, 0x2E\n.endm\n\n\n## Instructions which take an argument\n# gbg: arg is 5 bit wide\n# sf : arg is 1 bit wide\n# mx : arg is 2 bit wide\n# v : arg is 2 bit wide\n# cv : arg is 2 bit wide\n# lm : arg is 1 bit wide\n\n/* mvmva 8 0x4A4nnn12 Multiply vector by matrix and vector addition. */\n.macro mvmva sf, mx, v, cv, lm\n cop2op 0x04, 0x12, sf = \\sf, mx = \\mx, v = \\v, cv = \\cv, lm = \\lm\n.endm\n\n/* SQR 5 0x4AAn0428 Square of vector */\n.macro sqr sf\n cop2op 0x0A, 0x28, sf = \\sf, lm = 1\n.endm\n\n/* OP 6 0x4B7n000C Outer Product */\n.macro op sf\n cop2op 0x17, 0x0C, sf = \\sf\n.endm\n\n/* GPF 6 0x4B9n003D General purpose interpolation */\n.macro gpf sf\n cop2op 0x19, 0x3D, sf = \\sf\n.endm\n\n/* GPL 5 0x4BAn003E general purpose interpolation */\n.macro gpl sf\n cop2op 0x1A, 0x3E, sf = \\sf\n.endm\n\n\n## Convenience macros\n\n/* rtv0 - 0x4A486012 v0 * rotmatrix */\n.macro rtv0\n # .word 0x4A486012\n mvmva 1, 0, 0, 3, 0\n.endm\n\n/* rtv1 - 0x4A48E012 v1 * rotmatrix */\n.macro rtv1\n # .word 0x4A48E012\n mvmva 1, 0, 1, 3, 0\n.endm\n\n/* rtv2 - 0x4A496012 v2 * rotmatrix */\n.macro rtv2\n # .word 0x4A496012\n mvmva 1, 0, 2, 3, 0\n.endm\n\n/* rtir12 - 0x4A49E012 ir * rotmatrix */\n.macro rtir12\n # .word 0x4A49E012\n mvmva 1, 0, 3, 3, 0\n.endm\n\n/* rtir0 - 0x4A41E012 ir * rotmatrix */\n.macro rtir0\n # .word 0x4A41E012\n mvmva 0, 0, 3, 3, 0\n.endm\n\n/* rtv0tr - 0x4A480012 v0 * rotmatrix + tr vector */\n.macro rtv0tr\n # .word 0x4A480012\n mvmva 1, 0, 0, 0, 0\n.endm\n\n/* rtv1tr - 0x4A488012 v1 * rotmatrix + tr vector */\n.macro rtv1tr\n # .word 0x4A488012\n mvmva 1, 0, 1, 0, 0\n.endm\n\n/* rtv2tr - 0x4A490012 v2 * rotmatrix + tr vector */\n.macro rtv2tr\n # .word 0x4A490012\n mvmva 1, 0, 2, 0, 0\n.endm\n\n/* rtirtr - 0x4A498012 ir * rotmatrix + tr vector */\n.macro rtirtr\n # .word 0x4A498012\n mvmva 1, 0, 3, 0, 0\n.endm\n\n/* rtv0bk - 0x4A482012 v0 * rotmatrix + bk vector */\n.macro rtv0bk\n # .word 0x4A482012\n mvmva 1, 0, 0, 1, 0\n.endm\n\n/* rtv1bk - 0x4A48A012 v1 * rotmatrix + bk vector */\n.macro rtv1bk\n # .word 0x4A48A012\n mvmva 1, 0, 1, 1, 0\n.endm\n\n/* rtv2bk - 0x4A492012 v2 * rotmatrix + bk vector */\n.macro rtv2bk\n # .word 0x4A492012\n mvmva 1, 0, 2, 1, 0\n.endm\n\n/* rtirbk - 0x4A49A012 ir * rotmatrix + bk vector */\n.macro rtirbk\n # .word 0x4A49A012\n mvmva 1, 0, 3, 1, 0\n.endm\n\n/* ll - 0x4A4A6412 v0 * light matrix. Lower limit result to 0 */\n.macro ll\n # .word 0x4A4A6412\n mvmva 1, 1, 0, 3, 1\n.endm\n\n/* llv0 - 0x4A4A6012 v0 * light matrix */\n.macro llv0\n # .word 0x4A4A6012\n mvmva 1, 1, 0, 3, 0\n.endm\n\n/* llv1 - 0x4A4AE012 v1 * light matrix */\n.macro llv1\n # .word 0x4A4AE012\n mvmva 1, 1, 1, 3, 0\n.endm\n\n/* llv2 - 0x4A4B6012 v2 * light matrix */\n.macro llv2\n # .word 0x4A4B6012\n mvmva 1, 1, 2, 3, 0\n.endm\n\n/* llvir - 0x4A4BE012 ir * light matrix */\n.macro llvir\n # .word 0x4A4BE012\n mvmva 1, 1, 3, 3, 0\n.endm\n\n/* llv0tr - 0x4A4A0012 v0 * light matrix + tr vector */\n.macro llv0tr\n # .word 0x4A4A0012\n mvmva 1, 1, 0, 0, 0\n.endm\n\n/* llv1tr - 0x4A4A8012 v1 * light matrix + tr vector */\n.macro llv1tr\n # .word 0x4A4A8012\n mvmva 1, 1, 1, 0, 0\n.endm\n\n/* llv2tr - 0x4A4B0012 v2 * light matrix + tr vector */\n.macro llv2tr\n # .word 0x4A4B0012\n mvmva 1, 1, 2, 0, 0\n.endm\n\n/* llirtr - 0x4A4B8012 ir * light matrix + tr vector */\n.macro llirtr\n # .word 0x4A4B8012\n mvmva 1, 1, 3, 0, 0\n.endm\n\n/* llv0bk - 0x4A4A2012 v0 * light matrix + bk vector */\n.macro llv0bk\n # .word 0x4A4A2012\n mvmva 1, 1, 0, 1, 0\n.endm\n\n/* llv1bk - 0x4A4AA012 v1 * light matrix + bk vector */\n.macro llv1bk\n # .word 0x4A4AA012\n mvmva 1, 1, 1, 1, 0\n.endm\n\n/* llv2bk - 0x4A4B2012 v2 * light matrix + bk vector */\n.macro llv2bk\n # .word 0x4A4B2012\n mvmva 1, 1, 2, 1, 0\n.endm\n\n/* llirbk - 0x4A4BA012 ir * light matrix + bk vector */\n.macro llirbk\n # .word 0x4A4BA012\n mvmva 1, 1, 3, 1, 0\n.endm\n\n/* lc - 0x4A4DA412 v0 * color matrix, Lower limit clamped to 0 */\n.macro lc\n # .word 0x4A4DA412\n mvmva 1, 2, 3, 1, 1\n.endm\n\n/* lcv0 - 0x4A4C6012 v0 * color matrix */\n.macro lcv0\n # .word 0x4A4C6012\n mvmva 1, 2, 0, 3, 0\n.endm\n\n/* lcv1 - 0x4A4CE012 v1 * color matrix */\n.macro lcv1\n # .word 0x4A4CE012\n mvmva 1, 2, 1, 3, 0\n.endm\n\n/* lcv2 - 0x4A4D6012 v2 * color matrix */\n.macro lcv2\n # .word 0x4A4D6012\n mvmva 1, 2, 2, 3, 0\n.endm\n\n/* lcvir - 0x4A4DE012 ir * color matrix */\n.macro lcvir\n # .word 0x4A4DE012\n mvmva 1, 2, 3, 3, 0\n.endm\n\n/* lcv0tr - 0x4A4C0012 v0 * color matrix + tr vector */\n.macro lcv0tr\n # .word 0x4A4C0012\n mvmva 1, 2, 0, 0, 0\n.endm\n\n/* lcv1tr - 0x4A4C8012 v1 * color matrix + tr vector */\n.macro lcv1tr\n # .word 0x4A4C8012\n mvmva 1, 2, 1, 0, 0\n.endm\n\n/* lcv2tr - 0x4A4D0012 v2 * color matrix + tr vector */\n.macro lcv2tr\n # .word 0x4A4D0012\n mvmva 1, 2, 2, 0, 0\n.endm\n\n/* lcirtr - 0x4A4D8012 ir * color matrix + tr vector */\n.macro lcirtr\n # .word 0x4A4D8012\n mvmva 1, 2, 3, 0, 0\n.endm\n\n/* lev0bk - 0x4A4C2012 v0 * color matrix + bk vector */\n.macro lev0bk\n # .word 0x4A4C2012\n mvmva 1, 2, 0, 1, 0\n.endm\n\n/* lev1bk - 0x4A4CA012 v1 * color matrix + bk vector */\n.macro lev1bk\n # .word 0x4A4CA012\n mvmva 1, 2, 1, 1, 0\n.endm\n\n/* lev2bk - 0x4A4D2012 v2 * color matrix + bk vector */\n.macro lev2bk\n # .word 0x4A4D2012\n mvmva 1, 2, 2, 1, 0\n.endm\n\n/* leirbk - 0x4A4DA012 ir * color matrix + bk vector */\n.macro leirbk\n # .word 0x4A4DA012\n mvmva 1, 2, 3, 1, 0\n.endm\n\n/* sqr12 - 0x4AA80428 square of ir 1,19,12 */\n# .macro sqr12\n# # .word 0x4AA80428\n# sqr 1\n# .endm\n\n/* sqr0 - 0x4AA00428 square of ir 1,31, 0 */\n# .macro sqr0\n# # .word 0x4AA00428\n# sqr 0\n# .endm\n\n/* op12 - 0x4B78000C outer product 1,19,12 */\n.macro op12\n # .word 0x4B78000C\n op 1\n.endm\n\n/* op0 - 0x4B70000C outer product 1,31, 0 */\n.macro op0\n # .word 0x4B70000C\n op 0\n.endm\n\n/* gpf12 - 0x4B98003D general purpose interpolation 1,19,12 */\n.macro gpf12\n # .word 0x4B98003D\n gpf 1\n.endm\n\n/* gpf0 - 0x4B90003D general purpose interpolation 1,31, 0 */\n.macro gpf0\n # .word 0x4B90003D\n gpf 0\n.endm\n\n/* gpl12 - 0x4BA8003E general purpose interpolation 1,19,12 */\n.macro gpl12\n # .word 0x4BA8003E\n gpl 1\n.endm\n\n/* gpl0 - 0x4BA0003E general purpose interpolation 1,31, 0 */\n.macro gpl0\n # .word 0x4BA0003E\n gpl 0\n.endm\n\n.endif\n"; diff --git a/packages/romdev-splat/src/util/intervaltree.js b/packages/romdev-splat/src/util/intervaltree.js new file mode 100644 index 00000000..b5e5ed5c --- /dev/null +++ b/packages/romdev-splat/src/util/intervaltree.js @@ -0,0 +1,33 @@ +// The subset of the intervaltree API splat uses (addi() and point queries on +// half-open [begin, end) intervals), written for this package from that +// documented behaviour. + +export class Interval { + constructor(begin, end, data) { this.begin = begin; this.end = end; this.data = data; } +} + +export class IntervalTree { + constructor() { this.items = []; this.keys = new Map(); } + + addi(begin, end, data) { + if (begin === null || end === null || begin === undefined || end === undefined) { + throw new TypeError("'>=' not supported between instances of 'int' and 'NoneType'"); + } + if (begin >= end) throw new Error(`IntervalTree: Null Interval objects not allowed in IntervalTree: Interval(${begin}, ${end})`); + const k = begin + ":" + end; + let same = this.keys.get(k); + if (!same) { same = []; this.keys.set(k, same); } + if (same.includes(data)) return; + same.push(data); + this.items.push(new Interval(begin, end, data)); + } + + /** tree[point]: the intervals containing point, in insertion order. */ + at(point) { + const out = []; + for (const it of this.items) if (it.begin <= point && point < it.end) out.push(it); + return out; + } + + get size() { return this.items.length; } +} diff --git a/packages/romdev-splat/src/util/log.js b/packages/romdev-splat/src/util/log.js new file mode 100644 index 00000000..0dd6a8d7 --- /dev/null +++ b/packages/romdev-splat/src/util/log.js @@ -0,0 +1,27 @@ +// splat.util.log: status-coloured messages; error() stops the run. +import { emit, SplatError } from '../runtime.js'; +import { pyStr } from './pyfmt.js'; + +const ANSI = { + ok: '\x1b[32m', + warn: '\x1b[33m\x1b[1m', + error: '\x1b[31m\x1b[1m', + skip: '\x1b[2m', +}; + +export function write(msg, { status = null } = {}) { + const stream = status === 'warn' || status === 'error' ? 'stderr' : 'stdout'; + emit(stream, (ANSI[status] || '') + pyStr(msg) + '\n'); +} + +export function error(msg) { + write(msg, { status: 'error' }); + throw new SplatError(pyStr(msg), 2); +} + +// line_num is zero-indexed +export function parsingErrorPreamble(path, lineNum, line) { + write(''); + write(`error reading ${path}, line ${lineNum + 1}:`, { status: 'error' }); + write(`\t${line}`); +} diff --git a/packages/romdev-splat/src/util/options.js b/packages/romdev-splat/src/util/options.js new file mode 100644 index 00000000..8fedf829 --- /dev/null +++ b/packages/romdev-splat/src/util/options.js @@ -0,0 +1,264 @@ +// splat.util.options: the yaml `options:` block, parsed and validated the way +// splat does (unknown keys are an error, types are checked, paths are +// normalised with os.path.normpath). +import { atLeast } from '../runtime.js'; +import { P, normpath, parent } from './pypath.js'; +import { compilers, forName } from './compiler.js'; +import { isList, isPyInt, pyTypeName, isDict } from './pyfmt.js'; +import { PyFloat } from './yaml11.js'; + +/** @type {any} */ +export let opts = null; + +const TYPES = { + str: (v) => typeof v === 'string', + bool: (v) => typeof v === 'boolean', + int: (v) => isPyInt(v), + list: (v) => isList(v), + float: (v) => v instanceof PyFloat, + object: () => true, +}; + +function typeErr(opt, t, v) { + return new Error(`Expected ${opt} to have type , got `); +} + +class OptParser { + constructor(yaml) { + this.yaml = yaml; + this.read = new Set(); + } + + has(opt) { return Object.prototype.hasOwnProperty.call(this.yaml, opt); } + + parseOpt(opt, t, def = null) { + if (!this.has(opt)) { + if (def !== null && def !== undefined) return def; + throw new Error(`Missing required option ${opt}`); + } + this.read.add(opt); + const value = this.yaml[opt]; + if (TYPES[t](value)) return value; + if (t === 'float' && isPyInt(value)) return new PyFloat(Number(value)); + throw typeErr(opt, t, value); + } + + parseOptionalOpt(opt, t) { + if (!this.has(opt)) return null; + return this.parseOpt(opt, t); + } + + parseOptionalOptWithDefault(opt, t, def) { + if (!this.has(opt)) return def; + this.read.add(opt); + const value = this.yaml[opt]; + if (value === null || TYPES[t](value)) return value; + if (t === 'float' && isPyInt(value)) return new PyFloat(Number(value)); + throw typeErr(opt, t, value); + } + + parseOptWithin(opt, t, within, def = null) { + const value = this.parseOpt(opt, t, def); + if (!within.includes(value)) throw new Error(`Invalid value for ${opt}: ${value}`); + return value; + } + + parsePath(basePath, opt, def = null) { + return normpath(P(basePath, this.parseOpt(opt, 'str', def))); + } + + parseOptionalPath(basePath, opt) { + if (!this.has(opt)) return null; + return this.parsePath(basePath, opt); + } + + parsePathList(basePath, opt, def) { + const paths = this.parseOpt(opt, 'object', def); + if (typeof paths === 'string') return [P(basePath, paths)]; + if (isList(paths)) return paths.map((p) => P(basePath, p)); + throw new Error(`Expected str or list for '${opt}', got `); + } + + checkNoUnreadOpts() { + const unread = Object.keys(this.yaml).filter((o) => !this.read.has(o)); + if (unread.length) throw new Error(`Unrecognized YAML option(s): ${unread.join(', ')}`); + } +} + +function parseYaml(yaml, configPaths, modes, verbose, disasmAll, makeFullDisasmForCode, overrides) { + if (!isDict(yaml)) throw new Error('options must be a mapping'); + const p = new OptParser(yaml); + const modern = atLeast('0.35.0'); + + const basename = p.parseOpt('basename', 'str'); + const isUnsupportedPlatform = p.parseOpt('is_unsupported_platform', 'bool', false); + const platform = isUnsupportedPlatform + ? p.parseOpt('platform', 'str') + : p.parseOptWithin('platform', 'str', ['n64', 'psx', 'ps2', 'psp']); + + const table = compilers(); + const comp = forName(p.parseOpt('compiler', 'str', 'IDO'), table); + + let basePath = normpath(P(parent(configPaths[0]), p.parseOpt('base_path', 'str'))); + if (overrides.basePath != null) basePath = normpath(overrides.basePath); + const asmPath = p.parsePath(basePath, 'asm_path', 'asm'); + + let asmEmitSizeDirective = p.parseOptionalOpt('asm_emit_size_directive', 'bool'); + if (asmEmitSizeDirective === null) asmEmitSizeDirective = comp.asm_emit_size_directive; + + let alignOnBranchLabels = false; + if (modern) { + alignOnBranchLabels = p.parseOptionalOpt('align_on_branch_labels', 'bool'); + if (alignOnBranchLabels === null) alignOnBranchLabels = comp.align_on_branch_labels; + } + + const endianness = p.parseOptWithin('endianness', 'str', ['big', 'little'], + ['psx', 'ps2', 'psp'].includes(platform) ? 'little' : 'big'); + + let includeAsmMacroStyle = 'default'; + if (modern) { + includeAsmMacroStyle = p.parseOptWithin('include_asm_macro_style', 'str', ['default', 'maspsx_hack'], 'default'); + } + + const defaultLdBssIsNoload = platform !== 'psx'; + const defaultAddSetGp64 = !(platform === 'psx' || platform === 'ps2'); + + const ret = { + verbose, + dump_symbols: p.parseOpt('dump_symbols', 'bool', false), + modes, + base_path: basePath, + target_path: p.parsePath(basePath, 'target_path'), + elf_path: p.parseOptionalPath(basePath, 'elf_path'), + platform, + is_unsupported_platform: isUnsupportedPlatform, + allow_segment_overrides: p.parseOpt('allow_segment_overrides', 'bool', false), + compiler: comp, + compilers: table, + endianness, + section_order: p.parseOpt('section_order', 'list', ['.text', '.data', '.rodata', '.bss']), + generated_c_preamble: p.parseOpt('generated_c_preamble', 'str', '#include "common.h"'), + generated_s_preamble: p.parseOpt('generated_s_preamble', 'str', ''), + }; + if (modern) { + ret.generated_macro_inc_content = p.parseOptionalOpt('generated_macro_inc_content', 'str'); + ret.generate_asm_macros_files = p.parseOpt('generate_asm_macros_files', 'bool', true); + } else { + ret.generated_macro_inc_content = null; + ret.generate_asm_macros_files = false; + } + ret.include_asm_macro_style = includeAsmMacroStyle; + ret.generated_asm_macros_directory = modern ? p.parsePath(basePath, 'generated_asm_macros_directory', 'include') : P(basePath, 'include'); + Object.assign(ret, { + use_o_as_suffix: p.parseOpt('o_as_suffix', 'bool', false), + gp: p.parseOptionalOpt('gp_value', 'int'), + check_consecutive_segment_types: p.parseOpt('check_consecutive_segment_types', 'bool', true), + asset_path: p.parsePath(basePath, 'asset_path', 'assets'), + symbol_addrs_paths: p.parsePathList(basePath, 'symbol_addrs_path', 'symbol_addrs.txt'), + reloc_addrs_paths: p.parsePathList(basePath, 'reloc_addrs_path', 'reloc_addrs.txt'), + build_path: p.parsePath(basePath, 'build_path', 'build'), + src_path: p.parsePath(basePath, 'src_path', 'src'), + asm_path: asmPath, + data_path: p.parsePath(asmPath, 'data_path', 'data'), + nonmatchings_path: p.parsePath(asmPath, 'nonmatchings_path', 'nonmatchings'), + matchings_path: p.parsePath(asmPath, 'matchings_path', 'matchings'), + cache_path: p.parsePath(basePath, 'cache_path', '.splache'), + hasm_in_src_path: p.parseOpt('hasm_in_src_path', 'bool', false), + create_undefined_funcs_auto: p.parseOpt('create_undefined_funcs_auto', 'bool', true), + undefined_funcs_auto_path: p.parsePath(basePath, 'undefined_funcs_auto_path', 'undefined_funcs_auto.txt'), + create_undefined_syms_auto: p.parseOpt('create_undefined_syms_auto', 'bool', true), + undefined_syms_auto_path: p.parsePath(basePath, 'undefined_syms_auto_path', 'undefined_syms_auto.txt'), + extensions_path: p.parseOptionalPath(basePath, 'extensions_path'), + lib_path: p.parsePath(basePath, 'lib_path', 'lib'), + elf_section_list_path: p.parseOptionalPath(basePath, 'elf_section_list_path'), + subalign: p.parseOptionalOptWithDefault('subalign', 'int', 16), + emit_subalign: p.parseOpt('emit_subalign', 'bool', true), + auto_link_sections: p.parseOpt('auto_link_sections', 'list', ['.data', '.rodata', '.bss']), + ld_script_path: p.parsePath(basePath, 'ld_script_path', `${basename}.ld`), + ld_symbol_header_path: p.parseOptionalPath(basePath, 'ld_symbol_header_path'), + ld_discard_section: p.parseOpt('ld_discard_section', 'bool', true), + ld_sections_allowlist: p.parseOpt('ld_sections_allowlist', 'list', []), + ld_sections_denylist: p.parseOpt('ld_sections_denylist', 'list', []), + ld_wildcard_sections: p.parseOpt('ld_wildcard_sections', 'bool', false), + ld_use_symbolic_vram_addresses: p.parseOpt('ld_use_symbolic_vram_addresses', 'bool', true), + ld_partial_linking: p.parseOpt('ld_partial_linking', 'bool', false), + ld_partial_scripts_path: p.parseOptionalPath(basePath, 'ld_partial_scripts_path'), + ld_partial_build_segments_path: p.parseOptionalPath(basePath, 'ld_partial_build_segments_path'), + ld_dependencies: p.parseOpt('ld_dependencies', 'bool', false), + ld_legacy_generation: p.parseOpt('ld_legacy_generation', 'bool', false), + segment_end_before_align: p.parseOpt('segment_end_before_align', 'bool', false), + segment_symbols_style: p.parseOptWithin('segment_symbols_style', 'str', ['splat', 'makerom'], 'splat'), + ld_rom_start: p.parseOpt('ld_rom_start', 'int', 0), + ld_fill_value: p.parseOptionalOptWithDefault('ld_fill_value', 'int', 0), + ld_bss_is_noload: p.parseOpt('ld_bss_is_noload', 'bool', defaultLdBssIsNoload), + ld_align_segment_start: p.parseOptionalOptWithDefault('ld_align_segment_start', 'int', null), + ld_align_segment_vram_end: p.parseOpt('ld_align_segment_vram_end', 'bool', true), + ld_align_section_vram_end: p.parseOpt('ld_align_section_vram_end', 'bool', true), + ld_generate_symbol_per_data_segment: p.parseOpt('ld_generate_symbol_per_data_segment', 'bool', false), + ld_bss_contains_common: p.parseOpt('ld_bss_contains_common', 'bool', false), + }); + ret.ld_gp_expression = modern ? p.parseOptionalOptWithDefault('ld_gp_expression', 'str', null) : null; + Object.assign(ret, { + create_c_files: p.parseOpt('create_c_files', 'bool', true), + auto_decompile_empty_functions: p.parseOpt('auto_decompile_empty_functions', 'bool', true), + do_c_func_detection: p.parseOpt('do_c_func_detection', 'bool', true), + c_newline: p.parseOpt('c_newline', 'str', comp.c_newline), + symbol_name_format: p.parseOpt('symbol_name_format', 'str', '$VRAM'), + symbol_name_format_no_rom: p.parseOpt('symbol_name_format_no_rom', 'str', '$VRAM_$SEG'), + find_file_boundaries: p.parseOpt('find_file_boundaries', 'bool', true), + pair_rodata_to_text: p.parseOpt('pair_rodata_to_text', 'bool', true), + migrate_rodata_to_functions: p.parseOpt('migrate_rodata_to_functions', 'bool', true), + asm_inc_header: p.parseOpt('asm_inc_header', 'str', comp.asm_inc_header), + asm_function_macro: p.parseOpt('asm_function_macro', 'str', comp.asm_function_macro), + asm_function_alt_macro: p.parseOpt('asm_function_alt_macro', 'str', comp.asm_function_alt_macro), + asm_jtbl_label_macro: p.parseOpt('asm_jtbl_label_macro', 'str', comp.asm_jtbl_label_macro), + asm_data_macro: p.parseOpt('asm_data_macro', 'str', comp.asm_data_macro), + asm_end_label: p.parseOpt('asm_end_label', 'str', comp.asm_end_label), + }); + ret.asm_data_end_label = modern ? p.parseOpt('asm_data_end_label', 'str', comp.asm_data_end_label) : ''; + ret.asm_ehtable_label_macro = p.parseOpt('asm_ehtable_label_macro', 'str', comp.asm_ehtable_label_macro); + ret.asm_nonmatching_label_macro = modern + ? p.parseOpt('asm_nonmatching_label_macro', 'str', comp.asm_nonmatching_label_macro) : ''; + Object.assign(ret, { + asm_emit_size_directive: asmEmitSizeDirective, + mnemonic_ljust: p.parseOpt('mnemonic_ljust', 'int', 11), + rom_address_padding: p.parseOpt('rom_address_padding', 'bool', false), + mips_abi_gpr: p.parseOptWithin('mips_abi_gpr', 'str', ['numeric', '32', 'o32', 'n32', 'n64'], 'o32'), + mips_abi_float_regs: p.parseOptWithin('mips_abi_float_regs', 'str', ['numeric', '32', 'o32', 'n32', 'n64'], 'numeric'), + named_regs_for_c_funcs: p.parseOpt('named_regs_for_c_funcs', 'bool', true), + add_set_gp_64: p.parseOpt('add_set_gp_64', 'bool', defaultAddSetGp64), + create_asm_dependencies: p.parseOpt('create_asm_dependencies', 'bool', false), + string_encoding: p.parseOptionalOpt('string_encoding', 'str'), + data_string_encoding: p.parseOptionalOpt('data_string_encoding', 'str'), + rodata_string_guesser_level: p.parseOptionalOpt('rodata_string_guesser_level', 'int'), + data_string_guesser_level: p.parseOptionalOpt('data_string_guesser_level', 'int'), + allow_data_addends: p.parseOpt('allow_data_addends', 'bool', true), + header_encoding: p.parseOpt('header_encoding', 'str', 'ASCII'), + gfx_ucode: p.parseOptWithin('gfx_ucode', 'str', ['f3d', 'f3db', 'f3dex', 'f3dexb', 'f3dex2'], 'f3dex2'), + libultra_symbols: p.parseOpt('libultra_symbols', 'bool', false), + ique_symbols: p.parseOpt('ique_symbols', 'bool', false), + hardware_regs: p.parseOpt('hardware_regs', 'bool', false), + image_type_in_extension: p.parseOpt('image_type_in_extension', 'bool', false), + use_legacy_include_asm: p.parseOpt('use_legacy_include_asm', 'bool', false), + align_on_branch_labels: alignOnBranchLabels, + disasm_unknown: p.parseOpt('disasm_unknown', 'bool', false), + detect_redundant_function_end: p.parseOpt('detect_redundant_function_end', 'bool', true), + disassemble_all: p.parseOpt('disassemble_all', 'bool', false) || disasmAll, + make_full_disasm_for_code: p.parseOpt('make_full_disasm_for_code', 'bool', false) || makeFullDisasmForCode, + global_vram_start: p.parseOptionalOpt('global_vram_start', 'int'), + global_vram_end: p.parseOptionalOpt('global_vram_end', 'int'), + use_gp_rel_macro_nonmatching: p.parseOpt('use_gp_rel_macro_nonmatching', 'bool', true), + use_gp_rel_macro: p.parseOpt('use_gp_rel_macro', 'bool', true), + suggestion_rodata_section_start: p.parseOpt('suggestion_rodata_section_start', 'bool', true), + }); + p.checkNoUnreadOpts(); + + ret.is_mode_active = (mode) => ret.modes.includes(mode) || ret.modes.includes('all'); + return ret; +} + +export function initialize(config, configPaths, modes, verbose = false, disasmAll = false, makeFullDisasmForCode = false, overrides = {}) { + if (!modes || modes.length === 0) modes = ['all']; + opts = parseYaml(config.options, configPaths, modes, verbose, disasmAll, makeFullDisasmForCode, overrides); + return opts; +} diff --git a/packages/romdev-splat/src/util/palettes.js b/packages/romdev-splat/src/util/palettes.js new file mode 100644 index 00000000..1f1ec1ff --- /dev/null +++ b/packages/romdev-splat/src/util/palettes.js @@ -0,0 +1,65 @@ +// splat.util.palettes: resolve Raster#palette and Palette#raster links. +import * as log from './log.js'; + +function isPalette(s) { return typeof s.parse_palette === 'function' && 'global_id' in s; } +function isCi(s) { return Array.isArray(s.palette_names); } + +export function initialize(allSegments) { + const globalIds = new Map(); + + const collectGlobalIds = (segments) => { + for (const segment of segments) { + if (isPalette(segment) && segment.global_id !== null) globalIds.set(segment.global_id, segment); + if (segment.isGroup) collectGlobalIds(segment.subsegments); + } + }; + + const globalIdsNotSeen = new Set(); + + const process = (segments) => { + const rasterMap = new Map(); + const paletteMap = new Map(); + for (const segment of segments) { + if (isPalette(segment)) paletteMap.set(segment.name, segment); + if (isCi(segment)) rasterMap.set(segment.name, segment); + if (segment.isGroup) process(segment.subsegments); + } + const palettesSeen = new Set(paletteMap.keys()); + for (const raster of rasterMap.values()) { + for (const palName of raster.palette_names) { + let pal = globalIds.has(palName) ? globalIds.get(palName) : null; + if (pal !== null) { + globalIdsNotSeen.delete(palName); + palettesSeen.delete(palName); + raster.palettes.push(pal); + } else { + pal = paletteMap.has(palName) ? paletteMap.get(palName) : null; + if (pal !== null) { + palettesSeen.delete(palName); + raster.palettes.push(pal); + } else { + log.error('Could not find palette: ' + palName + ', referenced by raster: ' + raster.name); + } + } + } + for (const palName of paletteMap.keys()) { + if (palName.startsWith(raster.name + '.')) { + raster.palettes.push(paletteMap.get(palName)); + palettesSeen.delete(palName); + } + } + if (raster.palettes.length === 0) log.error(`Raster ${raster.name} has no linked palettes`); + } + for (const palName of palettesSeen) { + const pal = paletteMap.get(palName); + if (pal.global_id === null) log.error(`Palette ${pal.name} has no linked rasters`); + } + }; + + collectGlobalIds(allSegments); + for (const k of globalIds.keys()) globalIdsNotSeen.add(k); + process(allSegments); + if (globalIdsNotSeen.size > 0) { + log.error(`Found no ci links to palettes with global_ids: ${[...globalIdsNotSeen].join(', ')}`); + } +} diff --git a/packages/romdev-splat/src/util/pyfmt.js b/packages/romdev-splat/src/util/pyfmt.js new file mode 100644 index 00000000..8bbaccc4 --- /dev/null +++ b/packages/romdev-splat/src/util/pyfmt.js @@ -0,0 +1,119 @@ +// Python formatting and conversion helpers. +import { PyFloat } from './yaml11.js'; + +/** f"{v:X}" / f"{v:0{width}X}" */ +export function hex(v, width = 0) { + if (typeof v !== 'number' && typeof v !== 'bigint') throw new TypeError(`cannot hex-format ${v}`); + const neg = v < 0; + let s = (neg ? -v : v).toString(16).toUpperCase(); + if (s.length < width - (neg ? 1 : 0)) s = s.padStart(width - (neg ? 1 : 0), '0'); + return (neg ? '-' : '') + s; +} + +/** f"{v:x}" */ +export function hexl(v, width = 0) { return hex(v, width).toLowerCase(); } + +/** Python hex(v) */ +export function pyHex(v) { return (v < 0 ? '-0x' : '0x') + Math.abs(v).toString(16); } + +export function isInt(v) { return typeof v === 'number' && Number.isInteger(v) || typeof v === 'boolean'; } +export function isPyInt(v) { return (typeof v === 'number' && Number.isInteger(v)) || typeof v === 'boolean'; } +export function isStr(v) { return typeof v === 'string'; } +export function isDict(v) { return v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof PyFloat); } +export function isList(v) { return Array.isArray(v); } + +/** Python int(v) for the value kinds splat feeds it. */ +export function pyInt(v) { + if (typeof v === 'boolean') return v ? 1 : 0; + if (typeof v === 'number') return Math.trunc(v); + if (v instanceof PyFloat) return Math.trunc(v.value); + if (typeof v === 'string') { + const s = v.trim().replace(/_/g, ''); + if (!/^[-+]?\d+$/.test(s)) throw new Error(`invalid literal for int() with base 10: '${v}'`); + return parseInt(s, 10); + } + throw new TypeError(`int() argument must be a string or a number, not '${pyTypeName(v)}'`); +} + +/** Python int(s, 0). */ +export function pyInt0(s) { + const t = String(s).trim(); + const m = /^([-+]?)(0[xX][0-9a-fA-F_]+|0[oO][0-7_]+|0[bB][01_]+|0+|[1-9][0-9_]*)$/.exec(t); + if (!m || /__|_$|^[-+]?_/.test(m[2]) || /^0[xXoObB]_*$/.test(m[2])) { + throw new Error(`invalid literal for int() with base 0: '${s}'`); + } + const body = m[2].replace(/_/g, ''); + let v; + if (/^0[xX]/.test(body)) v = parseInt(body.slice(2), 16); + else if (/^0[oO]/.test(body)) v = parseInt(body.slice(2), 8); + else if (/^0[bB]/.test(body)) v = parseInt(body.slice(2), 2); + else v = parseInt(body, 10); + return m[1] === '-' ? -v : v; +} + +export function pyTypeName(v) { + if (v === null || v === undefined) return 'NoneType'; + if (typeof v === 'boolean') return 'bool'; + if (typeof v === 'number') return Number.isInteger(v) ? 'int' : 'float'; + if (v instanceof PyFloat) return 'float'; + if (typeof v === 'string') return 'str'; + if (Array.isArray(v)) return 'list'; + return 'dict'; +} + +/** Python str(v) for the values splat prints. */ +export function pyStr(v) { + if (v === null || v === undefined) return 'None'; + if (v === true) return 'True'; + if (v === false) return 'False'; + if (typeof v === 'string') return v; + if (typeof v === 'number') return String(v); + if (v instanceof PyFloat) return pyFloatRepr(v.value); + if (Array.isArray(v) || (typeof v === 'object' && v.constructor === Object)) return pyRepr(v); + if (v instanceof Set) return pyRepr(v); + return String(v); +} + +function pyFloatRepr(f) { + if (Number.isInteger(f)) return f.toFixed(1); + if (f === Infinity) return 'inf'; + if (f === -Infinity) return '-inf'; + if (Number.isNaN(f)) return 'nan'; + return String(f); +} + +export function pyRepr(v) { + if (v === null || v === undefined) return 'None'; + if (v === true) return 'True'; + if (v === false) return 'False'; + if (typeof v === 'string') { + const q = v.includes("'") && !v.includes('"') ? '"' : "'"; + let s = v.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t'); + if (q === "'") s = s.replace(/'/g, "\\'"); + return q + s + q; + } + if (typeof v === 'number') return String(v); + if (v instanceof PyFloat) return pyFloatRepr(v.value); + if (Array.isArray(v)) return '[' + v.map(pyRepr).join(', ') + ']'; + if (v instanceof Set) return v.size ? '{' + [...v].map(pyRepr).join(', ') + '}' : 'set()'; + if (typeof v === 'object') { + return '{' + Object.entries(v).map(([k, x]) => pyRepr(k) + ': ' + pyRepr(x)).join(', ') + '}'; + } + return String(v); +} + +/** str.ljust */ +export function ljust(s, n) { return s.length >= n ? s : s + ' '.repeat(n - s.length); } + +/** Python bool(v) truthiness. */ +export function truthy(v) { + if (v === null || v === undefined || v === false || v === 0 || v === '') return false; + if (v instanceof PyFloat) return v.value !== 0; + if (Array.isArray(v)) return v.length > 0; + if (v instanceof Set || v instanceof Map) return v.size > 0; + if (typeof v === 'object') return Object.keys(v).length > 0; + return true; +} + +/** f"{n:5}" for ints (right aligned). */ +export function rjust(v, n) { const s = String(v); return s.length >= n ? s : ' '.repeat(n - s.length) + s; } diff --git a/packages/romdev-splat/src/util/pypath.js b/packages/romdev-splat/src/util/pypath.js new file mode 100644 index 00000000..dfcdd21d --- /dev/null +++ b/packages/romdev-splat/src/util/pypath.js @@ -0,0 +1,120 @@ +// Python pathlib.PurePosixPath / os.path semantics on plain strings. +// +// splat builds every output path (and many strings written into outputs, +// like `.incbin "..."` and INCLUDE_ASM paths) from pathlib objects, so the +// exact normalisation rules matter: "." parts vanish, ".." parts stay, +// Path("") is ".", joining an absolute path replaces the left side. +// Filesystem access goes through runtime.abs(), which resolves a (possibly +// relative) Python-style path against the run's virtual cwd. + +/** Normalise like pathlib's parser: drop "" and "." parts, keep "..". */ +export function P(...parts) { + let abs = false; + let segs = []; + for (const partRaw of parts) { + if (partRaw == null) throw new TypeError('path part is null'); + const part = String(partRaw); + if (part.startsWith('/')) { abs = true; segs = []; } + for (const s of part.split('/')) { + if (s === '' || s === '.') continue; + segs.push(s); + } + } + if (abs) return '/' + segs.join('/'); + return segs.length ? segs.join('/') : '.'; +} + +/** os.path.normpath (posix). */ +export function normpath(p) { + p = String(p); + if (p === '') return '.'; + const initialSlashes = p.startsWith('//') && !p.startsWith('///') ? 2 : (p.startsWith('/') ? 1 : 0); + const comps = p.split('/'); + const out = []; + for (const c of comps) { + if (c === '' || c === '.') continue; + if (c !== '..' || (!initialSlashes && out.length === 0) || (out.length && out[out.length - 1] === '..')) { + out.push(c); + } else if (out.length) { + out.pop(); + } + } + let r = out.join('/'); + if (initialSlashes) r = '/'.repeat(initialSlashes) + r; + return r || '.'; +} + +export function isAbs(p) { return String(p).startsWith('/'); } + +export function name(p) { + p = P(p); + if (p === '.' || p === '/') return ''; + const i = p.lastIndexOf('/'); + return i === -1 ? p : p.slice(i + 1); +} + +export function parent(p) { + p = P(p); + if (p === '.' || p === '/') return p; + const i = p.lastIndexOf('/'); + if (i === -1) return '.'; + if (i === 0) return '/'; + return p.slice(0, i); +} + +/** PurePath.suffix (CPython 3.12 rule: a leading dot is not a suffix, nor a trailing one). */ +export function suffix(p) { + const n = name(p); + const i = n.lastIndexOf('.'); + if (0 < i && i < n.length - 1) return n.slice(i); + return ''; +} + +export function suffixes(p) { + const n = name(p); + if (n.endsWith('.')) return []; + const stripped = n.replace(/^\.+/, ''); + const parts = stripped.split('.').slice(1); + return parts.map((s) => '.' + s); +} + +export function stem(p) { + const n = name(p); + const s = suffix(p); + return s ? n.slice(0, -s.length) : n; +} + +export function withSuffix(p, suf) { + if (suf && (!suf.startsWith('.') || suf === '.')) throw new Error(`Invalid suffix ${suf}`); + const n = name(p); + if (!n) throw new Error(`${p} has an empty name`); + const s = suffix(p); + const newName = (s ? n.slice(0, -s.length) : n) + suf; + const par = parent(p); + return par === '.' ? newName : P(par, newName); +} + +/** PurePath.relative_to (no ".." walking); throws like ValueError. */ +export function relativeTo(p, base) { + p = P(p); base = P(base); + if (base === '.') { + if (isAbs(p)) throw new Error(`${p} is not in the subpath of ${base}`); + return p; + } + if (p === base) return '.'; + const prefix = base === '/' ? '/' : base + '/'; + if (p.startsWith(prefix)) return p.slice(prefix.length); + throw new Error(`${p} is not in the subpath of ${base}`); +} + +/** os.path.relpath(path, start) with both resolved against cwd. */ +export function relpath(path, start, cwd) { + const a = normpath(isAbs(path) ? path : cwd + '/' + path); + const b = normpath(isAbs(start) ? start : cwd + '/' + start); + const as = a.split('/').filter(Boolean); + const bs = b.split('/').filter(Boolean); + let i = 0; + while (i < as.length && i < bs.length && as[i] === bs[i]) i++; + const rel = [...Array(bs.length - i).fill('..'), ...as.slice(i)]; + return rel.length ? rel.join('/') : '.'; +} diff --git a/packages/romdev-splat/src/util/relocs.js b/packages/romdev-splat/src/util/relocs.js new file mode 100644 index 00000000..d10e9a6c --- /dev/null +++ b/packages/romdev-splat/src/util/relocs.js @@ -0,0 +1,74 @@ +// splat.util.relocs +import { exists } from '../runtime.js'; +import * as log from './log.js'; +import { opts } from './options.js'; +import { hex, pyInt0 } from './pyfmt.js'; +import { readLines, state as symbolsState } from './symbols.js'; +import { spim } from '../disassembler/spim.js'; + +export let allRelocs = new Map(); + +export function reset() { allRelocs = new Map(); } + +export function initialize() { + allRelocs = new Map(); + for (const path of opts.reloc_addrs_paths) { + if (!exists(path)) continue; + const lines = readLines(path); + for (let lineNum = 0; lineNum < lines.length; lineNum++) { + const line = lines[lineNum].split('//')[0].trim(); + if (line === '') continue; + let romAddr = null; let relocType = null; let symbolName = null; let addend = null; + for (const info of line.split(' ')) { + if (!info.includes(':')) continue; + if (info.split(':').length - 1 > 1) { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Too many ':'s in '${info}'`); + log.error(''); + } + const [attrName, attrVal] = info.split(':'); + if (attrName === '') { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Missing attribute name in '${info}', is there extra whitespace?`); + log.error(''); + } + if (attrVal === '') { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Missing attribute value in '${info}', is there extra whitespace?`); + log.error(''); + } + try { + if (attrName === 'rom') { romAddr = pyInt0(attrVal); continue; } + if (attrName === 'reloc') { relocType = attrVal; continue; } + if (attrName === 'symbol') { symbolName = attrVal; continue; } + if (attrName === 'addend') { addend = pyInt0(attrVal); continue; } + } catch (e) { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`value of attribute '${attrName}' could not be read:`); + log.write(''); + throw e; + } + } + if (romAddr === null) { log.parsingErrorPreamble(path, lineNum, line); log.error("Missing required 'rom' attribute for reloc"); } + if (relocType === null) { log.parsingErrorPreamble(path, lineNum, line); log.error("Missing required 'reloc' attribute for reloc"); } + if (symbolName === null) { log.parsingErrorPreamble(path, lineNum, line); log.error("Missing required 'symbol' attribute for reloc"); } + const reloc = { rom_address: romAddr, reloc_type: relocType, symbol_name: symbolName, addend: addend !== null ? addend : 0 }; + if (allRelocs.has(romAddr)) { + log.parsingErrorPreamble(path, lineNum, line); + log.error(`Duplicated 'rom' address for reloc: 0x${hex(romAddr)}`); + } + allRelocs.set(romAddr, reloc); + } + } +} + +export function initializeSpimContext() { + const S = spim(); + for (const [romAddress, reloc] of allRelocs) { + const relocType = S.common.RelocType.fromStr(reloc.reloc_type); + if (relocType === null || relocType === undefined) { + log.error(`Reloc type '${reloc.reloc_type}' is not valid. Rom address: 0x${hex(romAddress)}`); + } + symbolsState.spim_context.addGlobalReloc(romAddress, relocType, reloc.symbol_name, reloc.addend); + } +} diff --git a/packages/romdev-splat/src/util/statistics.js b/packages/romdev-splat/src/util/statistics.js new file mode 100644 index 00000000..36cef068 --- /dev/null +++ b/packages/romdev-splat/src/util/statistics.js @@ -0,0 +1,30 @@ +// splat.util.statistics +import * as log from './log.js'; + +function fmtSize(size) { + if (size > 1000000) return String(Math.floor(size / 1000000)) + ' MB'; + if (size > 1000) return String(Math.floor(size / 1000)) + ' KB'; + return String(size) + ' B'; +} + +const pct = (r) => (r * 100).toFixed(2) + '%'; +const rj = (s, n) => (s.length >= n ? s : ' '.repeat(n - s.length) + s); + +export class Statistics { + constructor() { this.seg_sizes = new Map(); this.seg_split = new Map(); this.seg_cached = new Map(); } + add_size(typ, size) { this.seg_sizes.set(typ, (this.seg_sizes.get(typ) || 0) + (size === null ? 0 : size)); } + count_split(typ, count = 1) { this.seg_split.set(typ, (this.seg_split.get(typ) || 0) + count); } + count_cached(typ, count = 1) { this.seg_cached.set(typ, (this.seg_cached.get(typ) || 0) + count); } + + print_statistics(totalSize) { + const unkSize = this.seg_sizes.get('unk') || 0; + let restSize = 0; + for (const [typ, size] of this.seg_sizes) if (typ !== 'unk') restSize += size; + log.write(`Split ${fmtSize(restSize)} (${pct(restSize / totalSize)}) in defined segments`); + for (const [typ, size] of this.seg_sizes) { + if (typ === 'unk') continue; + log.write(`${rj(typ, 20)}: ${rj(fmtSize(size), 8)} (${pct(size / totalSize)}) \x1b[32m${this.seg_split.get(typ) || 0} split\x1b[0m, \x1b[2m${this.seg_cached.get(typ) || 0} cached`); + } + log.write(`${rj('unknown', 20)}: ${rj(fmtSize(unkSize), 8)} (${pct(unkSize / totalSize)}) from unknown bin files`); + } +} diff --git a/packages/romdev-splat/src/util/symbols.js b/packages/romdev-splat/src/util/symbols.js new file mode 100644 index 00000000..874407be --- /dev/null +++ b/packages/romdev-splat/src/util/symbols.js @@ -0,0 +1,529 @@ +// splat.util.symbols +import { atLeast } from '../runtime.js'; +import * as log from './log.js'; +import { opts } from './options.js'; +import { IntervalTree } from './intervaltree.js'; +import { hex, pyInt0, pyRepr } from './pyfmt.js'; +import { stem } from './pypath.js'; +import { readText, exists } from '../runtime.js'; +import { spim } from '../disassembler/spim.js'; +import * as disassemblerInstance from '../disassembler/disassembler_instance.js'; + +export const state = { + all_symbols: [], + all_symbols_dict: new Map(), + all_symbols_ranges: new IntervalTree(), + ignored_addresses: new Set(), + to_mark_as_defined: new Set(), + spim_context: null, +}; + +export const TRUEY_VALS = ['true', 'on', 'yes', 'y']; +export const FALSEY_VALS = ['false', 'off', 'no', 'n']; +export const splat_sym_types = new Set(['func', 'jtbl', 'jtbl_label', 'label']); +const ILLEGAL_FILENAME_CHARS = ['<', '>', ':', '"', '/', '\\', '|', '?', '*']; + +export function resetSymbols() { + state.all_symbols = []; + state.all_symbols_dict = new Map(); + state.all_symbols_ranges = new IntervalTree(); + state.ignored_addresses = new Set(); + state.to_mark_as_defined = new Set(); + state.spim_context = new (spim().common.Context)(); +} + +function checkValidType(typename) { + if (typename[0] !== typename[0].toLowerCase() && typename[0] === typename[0].toUpperCase()) return true; + if (splat_sym_types.has(typename)) return true; + if (disassemblerInstance.getInstance().known_types().has(typename)) return true; + return false; +} + +const isTruey = (s) => TRUEY_VALS.includes(s.toLowerCase()); +const isFalsey = (s) => FALSEY_VALS.includes(s.toLowerCase()); + +export function addSymbol(sym) { + state.all_symbols.push(sym); + if (sym.vram_start !== null && sym.vram_start !== undefined) { + let l = state.all_symbols_dict.get(sym.vram_start); + if (!l) { l = []; state.all_symbols_dict.set(sym.vram_start, l); } + l.push(sym); + } + if (sym.size > 4) state.all_symbols_ranges.addi(sym.vram_start, sym.vram_end, sym); +} + +export function toCname(symbolName) { + symbolName = symbolName.replace(/[^0-9a-zA-Z_]/g, '_'); + if ('0123456789'.includes(symbolName[0])) symbolName = '_' + symbolName; + return symbolName; +} + +function pyStrip(s) { return s.replace(/^[\s\x1c-\x1f\x85\xa0]+|[\s\x1c-\x1f\x85\xa0]+$/g, ''); } + +// Python str.split(" ") keeps empty strings between consecutive spaces. +function handleSymAddrs(path, lines, allSegments) { + const getSegForName = (n) => allSegments.find((s) => s.name === n) || null; + const getSegForRom = (rom) => allSegments.find((s) => s.contains_rom(rom)) || null; + + const seen = new Map(); + for (let lineNum = 0; lineNum < lines.length; lineNum++) { + const line = pyStrip(lines[lineNum]); + if (line === '' || line.startsWith('//')) continue; + const commentLoc = line.indexOf('//'); + let lineMain = line; + let lineExt = ''; + if (commentLoc !== -1) { + lineExt = pyStrip(line.slice(commentLoc + 2)); + lineMain = pyStrip(line.slice(0, commentLoc)); + } + + let name; let addr; + try { + if ((line.match(/;/g) || []).length !== 1) throw new Error('Line must contain a single semi-colon'); + const lineSplit = lineMain.split('='); + name = pyStrip(lineSplit[0]); + if (lineSplit.length < 2) throw new Error('list index out of range'); + addr = pyInt0(pyStrip(lineSplit[1]).slice(0, -1)); + } catch (e) { + log.parsingErrorPreamble(path, lineNum, line); + log.write('Line must be of the form'); + log.write(' =
; // attr0:val0 attr1:val1 [...]'); + log.write('with
in hex preceded by 0x, or dec'); + log.write(''); + throw e; + } + + const sym = new Symbol(addr, { given_name: name }); + let ignoreSym = false; + if (lineExt) { + for (const info of lineExt.split(' ')) { + if (!info.includes(':')) continue; + if (info.split(':').length - 1 > 1) { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Too many ':'s in '${info}'`); + log.error(''); + } + const [attrName, attrVal] = info.split(':'); + if (attrName === '') { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Missing attribute name in '${info}', is there extra whitespace?`); + log.error(''); + } + if (attrVal === '') { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Missing attribute value in '${info}', is there extra whitespace?`); + log.error(''); + } + + try { + if (attrName === 'type') { + if (!checkValidType(attrVal)) { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Unrecognized symbol type in '${info}', it should be one of`); + log.write(pyRepr([...splat_sym_types, ...spim().common.gKnownTypes])); + log.write('You may use a custom type that starts with a capital letter'); + log.error(''); + } + sym.type = attrVal; + continue; + } + if (attrName === 'size') { sym.given_size = pyInt0(attrVal); continue; } + if (attrName === 'rom') { sym.rom = pyInt0(attrVal); continue; } + if (attrName === 'segment') { + const seg = getSegForName(attrVal); + if (seg === null) { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Cannot find segment '${attrVal}'`); + log.error(''); + } else { + sym.segment = seg; + } + continue; + } + if (attrName === 'name_end') { sym.given_name_end = attrVal; continue; } + if (attrName === 'filename') { sym.given_filename = attrVal; continue; } + if (attrName === 'visibility') { sym.given_visibility = attrVal; continue; } + if (attrName === 'function_owner') { sym.function_owner = attrVal; continue; } + if (attrName === 'align' && atLeast('0.35.0')) { + const align = pyInt0(attrVal); + if (align < 0) { + log.parsingErrorPreamble(path, lineNum, line); + log.error(`The given alignment for '${sym.name}' (0x${hex(sym.vram_start, 8)}) is negative.`); + } + // (align & -align).bit_length() - 1 + const low = align & -align; + const shift = low === 0 ? -1 : Math.log2(low); + if (shift < 0 || 2 ** shift !== align) { + log.parsingErrorPreamble(path, lineNum, line); + log.error(`The given alignment '0x${hex(align)}' for symbol '${sym.name}' (0x${hex(sym.vram_start, 8)}) is not a power of two.`); + } + if (sym.vram_start % align !== 0) { + log.parsingErrorPreamble(path, lineNum, line); + log.error(`The symbol '${sym.name}' (0x${hex(sym.vram_start, 8)}) is not aligned already to the given alignment '0x${hex(align)}'.`); + } + sym.given_align = align; + continue; + } + } catch (e) { + if (e && e.name === 'SplatError') throw e; + log.parsingErrorPreamble(path, lineNum, line); + log.write(`value of attribute '${attrName}' could not be read:`); + log.write(''); + throw e; + } + + const tfVal = isTruey(attrVal) ? true : (isFalsey(attrVal) ? false : null); + if (tfVal === null) { + log.parsingErrorPreamble(path, lineNum, line); + log.write(`Invalid Boolean value '${attrVal}' for attribute '${attrName}', should be one of`); + log.write(pyRepr([...TRUEY_VALS, ...FALSEY_VALS])); + log.error(''); + } else { + switch (attrName) { + case 'defined': sym.defined = tfVal; break; + case 'extract': sym.extract = tfVal; break; + case 'ignore': ignoreSym = tfVal; break; + case 'force_migration': sym.force_migration = tfVal; break; + case 'force_not_migration': sym.force_not_migration = tfVal; break; + case 'allow_addend': sym.allow_addend = tfVal; break; + case 'dont_allow_addend': sym.dont_allow_addend = tfVal; break; + case 'can_reference': sym.can_reference = tfVal; break; + case 'can_be_referenced': sym.can_be_referenced = tfVal; break; + case 'allow_duplicated': sym.allow_duplicated = true; break; + default: break; + } + } + } + } + + if (ignoreSym) { + if (sym.given_size === null || sym.given_size === 0) { + state.ignored_addresses.add(sym.vram_start); + } else { + state.spim_context.addBannedSymbolRangeBySize(sym.vram_start, sym.given_size); + } + continue; + } + + if (sym.segment === null && sym.rom !== null) sym.segment = getSegForRom(sym.rom); + if (sym.segment) sym.segment.add_symbol(sym); + + sym.user_declared = true; + + if (seen.has(sym.name)) { + const item = seen.get(sym.name); + if (!sym.allow_duplicated || !item.allow_duplicated) { + log.parsingErrorPreamble(path, lineNum, line); + log.error(`Duplicate symbol detected! ${sym.name} has already been defined at vram 0x${hex(item.vram_start, 8)}`); + } + } + + const items = state.all_symbols_dict.get(addr); + if (items) { + for (const item of items) { + if (sym.rom === item.rom && sym.segment === item.segment) { + if (!sym.allow_duplicated || !item.allow_duplicated) { + log.parsingErrorPreamble(path, lineNum, line); + log.error(`Duplicate symbol detected! ${sym.name} clashes with ${item.name} defined at vram 0x${hex(addr, 8)}.\n If this is intended, specify either a segment or a rom address for this symbol`); + } + } + } + } + + const fname = sym.filename; + if ([...fname].length > 253 || ILLEGAL_FILENAME_CHARS.some((c) => fname.includes(c))) { + log.parsingErrorPreamble(path, lineNum, line); + log.error('Ilegal symbol filename detected!\n' + + ' The symbol\n' + + ` ${sym.name}\n` + + ' exceeds the 255 bytes filename limit that most OS imposes or uses illegal characters,\n' + + ' which will be a problem when writing the symbol to its own file.\n' + + ` To fix this specify a \`filename\` for this symbol, like \`filename:func_${hex(sym.vram_start, 8)}\`.\n` + + ' Make sure the filename does not exceed 253 bytes nor it contains any of the following characters:\n' + + ` ${pyRepr(ILLEGAL_FILENAME_CHARS)}`); + } + + seen.set(sym.name, sym); + addSymbol(sym); + } +} + +/** Python file.readlines() over universal-newline text. */ +function readLines(p) { + const text = readText(p); + const lines = text.split('\n'); + const out = lines.map((l, i) => (i < lines.length - 1 ? l + '\n' : l)); + if (out.length && out[out.length - 1] === '') out.pop(); + return out; +} + +export function initialize(allSegments) { + state.all_symbols = []; + state.all_symbols_dict = new Map(); + state.all_symbols_ranges = new IntervalTree(); + for (const path of opts.symbol_addrs_paths) { + if (exists(path)) handleSymAddrs(path, readLines(path), allSegments); + } +} + +export { readLines, stem }; + +export function initializeSpimContext(allSegments, CommonSegCode) { + let globalVromStart = null; + let globalVromEnd = null; + let globalVramStart = opts.global_vram_start; + let globalVramEnd = opts.global_vram_end; + const overlaySegments = []; // insertion-ordered set + + const ctx = state.spim_context; + for (const a of state.ignored_addresses) ctx.bannedSymbols.add(a); + + const globalSegmentsAfterOverlays = []; + + for (const segment of allSegments) { + if (!(segment instanceof CommonSegCode)) continue; + if (segment.special_vram_segment) continue; + if (!Number.isInteger(segment.vram_start) || !Number.isInteger(segment.vram_end) + || !Number.isInteger(segment.rom_start) || !Number.isInteger(segment.rom_end)) continue; + + const ramId = segment.get_exclusive_ram_id(); + if (ramId === null) { + if (globalVramStart === null) globalVramStart = segment.vram_start; + else if (segment.vram_start < globalVramStart) globalVramStart = segment.vram_start; + + if (globalVramEnd === null) globalVramEnd = segment.vram_end; + else if (globalVramEnd < segment.vram_end) { + globalVramEnd = segment.vram_end; + if (overlaySegments.length > 0) globalSegmentsAfterOverlays.push(segment); + } + + if (globalVromStart === null) globalVromStart = segment.rom_start; + else if (segment.rom_start < globalVromStart) globalVromStart = segment.rom_start; + + if (globalVromEnd === null) globalVromEnd = segment.rom_end; + else if (globalVromEnd < segment.rom_end) globalVromEnd = segment.rom_end; + } else if (segment.vram_start !== segment.vram_end) { + const spimSegment = ctx.addOverlaySegment(ramId, segment.rom_start, segment.rom_end, segment.vram_start, segment.vram_end); + for (const list of segment.seg_symbols.values()) { + for (const sym of list) addSymbolToSpimSegment(spimSegment, sym); + } + if (!overlaySegments.includes(spimSegment)) overlaySegments.push(spimSegment); + } + } + + if (globalVramStart !== null && globalVramEnd !== null && globalVromStart !== null && globalVromEnd !== null) { + ctx.changeGlobalSegmentRanges(globalVromStart, globalVromEnd, globalVramStart, globalVramEnd); + + let overlapsFound = false; + for (const ovl of overlaySegments) { + if (ovl.vramEnd > globalVramStart && globalVramEnd > ovl.vramStart) { + log.write(`Error: the vram range ([0x${hex(ovl.vramStart, 8)}, 0x${hex(ovl.vramEnd, 8)}]) of the non-global segment at rom address 0x${hex(ovl.vromStart)} overlaps with the global vram range ([0x${hex(globalVramStart, 8)}, 0x${hex(globalVramEnd, 8)}])`, { status: 'warn' }); + overlapsFound = true; + } + } + if (overlapsFound) { + log.write('Many overlaps between non-global and global segments were found.'); + log.write('This is usually caused by missing `exclusive_ram_id` tags on segments that have a higher vram address than other `exclusive_ram_id`-tagged segments'); + if (globalSegmentsAfterOverlays.length > 0) { + log.write('These segments are the main suspects for missing a `exclusive_ram_id` tag:', { status: 'warn' }); + for (const seg of globalSegmentsAfterOverlays) log.write(` '${seg.name}', rom: 0x${hex(seg.rom_start, 6)}`); + } else { + log.write('No suspected segments??', { status: 'warn' }); + } + log.error('Stopping due to the above errors'); + } + } + + for (const segment of allSegments) { + if (!(segment instanceof CommonSegCode)) continue; + if (segment.get_exclusive_ram_id() !== null) continue; + for (const list of segment.seg_symbols.values()) { + for (const sym of list) addSymbolToSpimSegment(ctx.globalSegment, sym); + } + } + + if (globalVramStart && globalVramEnd) { + for (const sym of state.all_symbols) { + if (sym.segment !== null) continue; + if (sym.vram_start < globalVramStart || sym.vram_end > globalVramEnd) continue; + addSymbolToSpimSegment(ctx.globalSegment, sym); + } + } +} + +function applyCommonAttrs(contextSym, sym, withAddendAttrs) { + if (sym.user_declared) contextSym.isUserDeclared = true; + if (sym.defined) contextSym.isDefined = true; + if (sym.rom !== null) contextSym.vromAddress = sym.rom; + if (sym.given_size !== null) contextSym.size = sym.size; + if (sym.force_migration) contextSym.forceMigration = true; + if (sym.force_not_migration) contextSym.forceNotMigration = true; + contextSym.functionOwnerForMigration = sym.function_owner; + if (withAddendAttrs) { + if (sym.allow_addend) contextSym.allowedToReferenceAddends = true; + if (sym.dont_allow_addend) contextSym.notAllowedToReferenceAddends = true; + if (sym.can_reference !== null) contextSym.allowedToReferenceSymbols = sym.can_reference; + if (sym.can_be_referenced !== null) contextSym.allowedToBeReferenced = sym.can_be_referenced; + } + contextSym.setNameGetCallbackIfUnset(() => sym.name); + if (sym.given_name_end) contextSym.nameEnd = sym.given_name_end; + if (sym.given_visibility) contextSym.visibility = sym.given_visibility; + if (sym.given_align && atLeast('0.35.0')) contextSym.setAlignment(sym.given_align); + return contextSym; +} + +export function addSymbolToSpimSegment(segment, sym) { + const auto = !sym.user_declared; + let contextSym; + // SymbolsSegment.addX(address, isAutogenerated, vromAddress); addSymbol has sectionType second. + if (sym.type === 'func') contextSym = segment.addFunction(sym.vram_start, auto, sym.rom); + else if (sym.type === 'jtbl') contextSym = segment.addJumpTable(sym.vram_start, auto, sym.rom); + else if (sym.type === 'jtbl_label') contextSym = segment.addJumpTableLabel(sym.vram_start, auto, sym.rom); + else if (sym.type === 'label') contextSym = segment.addBranchLabel(sym.vram_start, auto, sym.rom); + else { + contextSym = segment.addSymbol(sym.vram_start, undefined, auto, sym.rom); + if (sym.type !== null) contextSym.type = sym.type; + } + return applyCommonAttrs(contextSym, sym, true); +} + +export function addSymbolToSpimSection(section, sym) { + const auto = !sym.user_declared; + let contextSym; + // ElementBase.addX(vramAddress, *, isAutogenerated, symbolVrom); addSymbol has sectionType first. + if (sym.type === 'func') contextSym = section.addFunction(sym.vram_start, auto, sym.rom); + else if (sym.type === 'jtbl') contextSym = section.addJumpTable(sym.vram_start, auto, sym.rom); + else if (sym.type === 'jtbl_label') contextSym = section.addJumpTableLabel(sym.vram_start, auto, sym.rom); + else if (sym.type === 'label') contextSym = section.addBranchLabel(sym.vram_start, auto, sym.rom); + else { + contextSym = section.addSymbol(sym.vram_start, undefined, auto, sym.rom); + if (sym.type !== null) contextSym.type = sym.type; + } + return applyCommonAttrs(contextSym, sym, false); +} + +// force_in_segment=true when the symbol belongs to this specific segment, +// false when it is just a reference. splat 0.34 had no such parameter. +export function createSymbolFromSpimSymbol(segment, contextSym, forceInSegment) { + const S = spim().common.SymbolSpecialType; + let inSegment = false; + let symType = null; + if (contextSym.type === S.jumptable) { inSegment = true; symType = 'jtbl'; } + else if (contextSym.type === S.function) { symType = 'func'; } + else if (contextSym.type === S.branchlabel) { inSegment = true; symType = 'label'; } + else if (contextSym.type === S.jumptablelabel) { inSegment = true; symType = 'jtbl_label'; } + + if (!inSegment) { + const ramId = segment.get_exclusive_ram_id(); + if (contextSym.overlayCategory === null && ramId === null) { + inSegment = segment.contains_vram(contextSym.vram); + } else if (contextSym.overlayCategory === ramId) { + if (contextSym.vromAddress !== null) inSegment = segment.contains_rom(contextSym.vromAddress); + else inSegment = segment.contains_vram(contextSym.vram); + } + } + + const force = atLeast('0.35.0') ? forceInSegment : false; + const sym = segment.create_symbol(contextSym.vram, force || inSegment, { type: symType, reference: true }); + + if (sym.given_name === null && contextSym.name !== null) sym.given_name = contextSym.name; + + contextSym.setNameGetCallback(() => sym.name); + + if (contextSym.size !== null) sym.given_size = contextSym.getSize(); + if (contextSym.vromAddress !== null) sym.rom = contextSym.getVrom(); + if (contextSym.isDefined) sym.defined = true; + if (contextSym.referenceCounter > 0) sym.referenced = true; + return sym; +} + +export function markCFuncsAsDefined() { + for (const symbol of state.all_symbols) { + if (state.to_mark_as_defined.size === 0) return; + const n = symbol.name; + if (state.to_mark_as_defined.has(n)) { + symbol.defined = true; + state.to_mark_as_defined.delete(n); + } + } +} + +export class Symbol { + constructor(vramStart, fields = {}) { + this.vram_start = vramStart; + this.given_name = null; + this.given_name_end = null; + this.rom = null; + this.type = null; + this.given_size = null; + this.segment = null; + this.defined = false; + this.referenced = false; + this.extract = true; + this.user_declared = false; + this.force_migration = false; + this.force_not_migration = false; + this.function_owner = null; + this.allow_addend = false; + this.dont_allow_addend = false; + this.can_reference = null; + this.can_be_referenced = null; + this.linker_section = null; + this.allow_duplicated = false; + this.given_filename = null; + this.given_visibility = null; + this.given_align = null; + this._generated_default_name = null; + this._last_type = null; + Object.assign(this, fields); + } + + toString() { return this.name; } + + format_name(format) { + let ret = format.replaceAll('$VRAM', hex(this.vram_start, 8)); + if (ret.includes('$ROM')) { + if (!Number.isInteger(this.rom)) { + log.error(`Attempting to rom-name a symbol with no ROM address: ${hex(this.vram_start, 8)} typed ${this.type === null ? 'None' : this.type}`); + } + ret = ret.replaceAll('$ROM', hex(this.rom)); + } + if (ret.includes('$SEG')) { + if (this.segment === null) return hex(this.vram_start); + ret = ret.replaceAll('$SEG', this.segment.name); + } + return ret; + } + + get default_name() { + if (this._generated_default_name !== null && this.type === this._last_type) { + return this._generated_default_name; + } + let suffix; + if (this.segment) { + suffix = Number.isInteger(this.rom) + ? this.format_name(this.segment.symbol_name_format) + : this.format_name(this.segment.symbol_name_format_no_rom); + } else { + suffix = Number.isInteger(this.rom) + ? this.format_name(opts.symbol_name_format) + : this.format_name(opts.symbol_name_format_no_rom); + } + let prefix; + if (this.type === 'func') prefix = 'func'; + else if (this.type === 'jtbl') prefix = 'jtbl'; + else if (this.type === 'jtbl_label' || this.type === 'label') return `.L${suffix}`; + else prefix = 'D'; + this._last_type = this.type; + this._generated_default_name = `${prefix}_${suffix}`; + return this._generated_default_name; + } + + get rom_end() { return !this.rom ? null : this.rom + this.size; } + get vram_end() { return this.vram_start + this.size; } + get name() { return this.given_name ? this.given_name : this.default_name; } + get size() { return this.given_size !== null ? this.given_size : 4; } + get filename() { return this.given_filename !== null ? this.given_filename : this.name; } + contains_vram(o) { return o >= this.vram_start && o < this.vram_end; } + contains_rom(o) { return o >= this.rom && o < this.rom_end; } +} diff --git a/packages/romdev-splat/src/util/vram_classes.js b/packages/romdev-splat/src/util/vram_classes.js new file mode 100644 index 00000000..83201dd7 --- /dev/null +++ b/packages/romdev-splat/src/util/vram_classes.js @@ -0,0 +1,76 @@ +// splat.util.vram_classes +import * as log from './log.js'; +import { isDict, isList, isPyInt, pyStr, pyTypeName } from './pyfmt.js'; + +export class VramClass { + constructor(name, vram, givenVramSymbol = null, followsClasses = []) { + this.name = name; + this.vram = vram; + this.given_vram_symbol = givenVramSymbol; + this.follows_classes = followsClasses; + } + + get vram_symbol() { + if (this.given_vram_symbol !== null) return this.given_vram_symbol; + if (this.follows_classes.length) return this.name + '_CLASS_VRAM'; + return null; + } +} + +export const state = { vramClasses: new Map() }; + +export function initialize(yaml) { + state.vramClasses = new Map(); + if (yaml === null || yaml === undefined) return; + if (!isList(yaml)) log.error('vram_classes must be a list'); + + const classNames = new Set(); + for (const vc of yaml) { + if (isDict(vc)) { + if (!('name' in vc)) log.error(`vram_class (${pyStr(vc)}) must have a name`); + classNames.add(vc.name); + } else if (isList(vc)) { + classNames.add(vc[0]); + } + } + + for (const vc of yaml) { + let name; let vram; let vramSymbol = null; let followsClasses = []; + if (isDict(vc)) { + if (!('name' in vc)) log.error(`vram_class (${pyStr(vc)}) must have a name`); + name = vc.name; + if (!('vram' in vc)) log.error(`vram_class (${pyStr(vc)}) must have a vram`); + vram = vc.vram; + if ('vram_symbol' in vc) { + vramSymbol = vc.vram_symbol; + if (typeof vramSymbol !== 'string') { + log.error(`vram_symbol (${pyStr(vramSymbol)})must be a string, got `); + } + } + if ('follows_classes' in vc) { + followsClasses = vc.follows_classes; + if (!isList(followsClasses)) { + log.error(`vram_symbol (${pyStr(followsClasses)})must be a list, got `); + } + for (const fc of followsClasses) { + if (!classNames.has(fc)) log.error(`follows_class (${pyStr(fc)}) not found in vram_classes`); + } + } + } else if (isList(vc)) { + if (vc.length !== 2) log.error(`vram_class (${pyStr(vc)}) must have 2 elements, got ${vc.length}`); + name = vc[0]; + vram = vc[1]; + } else { + log.error(`vram_class must be a dict or list, got `); + } + if (typeof name !== 'string') log.error(`vram_class name (${pyStr(name)}) must be a string, got `); + if (!isPyInt(vram)) log.error(`vram_class vram (${pyStr(vram)}) must be an int, got `); + if (state.vramClasses.has(name)) log.error(`Duplicate vram class name '${name}'`); + state.vramClasses.set(name, new VramClass(name, vram, vramSymbol, followsClasses)); + } +} + +export function resolve(name) { + if (!state.vramClasses.has(name)) log.error(`Unknown vram class '${pyStr(name)}'`); + return state.vramClasses.get(name); +} diff --git a/packages/romdev-splat/src/util/yaml11.js b/packages/romdev-splat/src/util/yaml11.js new file mode 100644 index 00000000..d7ae83e4 --- /dev/null +++ b/packages/romdev-splat/src/util/yaml11.js @@ -0,0 +1,184 @@ +// YAML loading with PyYAML SafeLoader semantics (YAML 1.1 implicit typing, +// merge keys, shared aliases, last-duplicate-key-wins). +// +// The `yaml` package parses the document structure (failsafe schema, so every +// scalar arrives as its source string); this module then resolves plain +// scalars with PyYAML's own implicit resolver regexes and constructors +// (yaml/resolver.py + yaml/constructor.py SafeConstructor). + +import { parseDocument, isMap, isSeq, isScalar, isAlias } from 'yaml'; + +/** A YAML float (Python float), kept distinct from ints. */ +export class PyFloat { + constructor(value) { this.value = value; } + valueOf() { return this.value; } + toString() { return String(this.value); } +} + +const RE_BOOL = /^(?:yes|Yes|YES|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)$/; +const RE_FLOAT = /^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?|\.[0-9][0-9_]*(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$/; +const RE_INT = /^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?(?:0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$/; +const RE_MERGE = /^(?:<<)$/; +const RE_NULL = /^(?:~|null|Null|NULL|)$/; +const RE_TIMESTAMP = /^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]?(?:[Tt]|[ \t]+)[0-9][0-9]?:[0-9][0-9]:[0-9][0-9](?:\.[0-9]*)?(?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$/; + +// PyYAML registers resolvers per first character; the lists are checked in +// registration order (bool, float, int, merge, null, timestamp). +const RESOLVERS = [ + ['bool', RE_BOOL, 'yYnNtTfFoO'], + ['float', RE_FLOAT, '-+0123456789.'], + ['int', RE_INT, '-+0123456789'], + ['merge', RE_MERGE, '<'], + ['null', RE_NULL, '~nN\0'], + ['timestamp', RE_TIMESTAMP, '0123456789'], +]; + +function resolvePlain(value) { + const first = value === '' ? '\0' : value[0]; + for (const [kind, re, firsts] of RESOLVERS) { + if (!firsts.includes(first)) continue; + if (re.test(value)) return kind; + } + return 'str'; +} + +function constructInt(src) { + let value = src.replace(/_/g, ''); + let sign = 1n; + if (value[0] === '-') sign = -1n; + if ('+-'.includes(value[0])) value = value.slice(1); + let big; + if (value === '0') big = 0n; + else if (value.startsWith('0b')) big = BigInt('0b' + value.slice(2)); + else if (value.startsWith('0x')) big = BigInt('0x' + value.slice(2)); + else if (value[0] === '0') big = BigInt('0o' + value.slice(1)); + else if (value.includes(':')) { + const digits = value.split(':').map((d) => BigInt(d)).reverse(); + let base = 1n; big = 0n; + for (const d of digits) { big += d * base; base *= 60n; } + } else big = BigInt(value); + const r = sign * big; + if (r > BigInt(Number.MAX_SAFE_INTEGER) || r < -BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error(`YAML integer ${src} exceeds the safe integer range`); + } + return Number(r); +} + +function constructFloat(src) { + let value = src.replace(/_/g, '').toLowerCase(); + let sign = 1; + if (value[0] === '-') sign = -1; + if ('+-'.includes(value[0])) value = value.slice(1); + if (value === '.inf') return new PyFloat(sign * Infinity); + if (value === '.nan') return new PyFloat(NaN); + if (value.includes(':')) { + const digits = value.split(':').map((d) => parseFloat(d)).reverse(); + let base = 1; let r = 0; + for (const d of digits) { r += d * base; base *= 60; } + return new PyFloat(sign * r); + } + return new PyFloat(sign * parseFloat(value)); +} + +function constructBool(src) { + return { yes: true, no: false, true: true, false: false, on: true, off: false }[src.toLowerCase()]; +} + +const TAG = 'tag:yaml.org,2002:'; + +function scalarValue(node) { + const src = node.value == null ? '' : String(node.value); + let kind; + if (node.tag && node.tag !== '!') { + const t = node.tag.startsWith(TAG) ? node.tag.slice(TAG.length) : node.tag; + kind = t; + } else if (node.type === 'PLAIN' && node.tag !== '!') { + kind = resolvePlain(src); + } else { + kind = 'str'; + } + switch (kind) { + case 'str': return src; + case 'int': return constructInt(src); + case 'float': return constructFloat(src); + case 'bool': return constructBool(src); + case 'null': return null; + case 'merge': return MERGE_KEY; + case 'timestamp': return src; + default: throw new Error(`unsupported YAML tag ${node.tag}`); + } +} + +const MERGE_KEY = Symbol('merge'); + +/** Python-dict-like key used for JS object properties. */ +function keyString(k) { + if (k === null) return 'None'; + if (k === true) return 'True'; + if (k === false) return 'False'; + if (k instanceof PyFloat) return String(k.value); + return String(k); +} + +function convert(node, doc, anchors) { + if (node == null) return null; + if (isAlias(node)) { + if (!anchors.has(node.source)) throw new Error(`found undefined alias ${node.source}`); + return anchors.get(node.source); + } + if (isScalar(node)) { + const v = scalarValue(node); + if (node.anchor) anchors.set(node.anchor, v); + return v; + } + if (isSeq(node)) { + const out = []; + if (node.anchor) anchors.set(node.anchor, out); + for (const it of node.items) out.push(convert(it, doc, anchors)); + return out; + } + if (isMap(node)) { + const out = {}; + if (node.anchor) anchors.set(node.anchor, out); + // PyYAML flatten_mapping: merge entries are collected first (a list merges + // each map in order, earlier maps winning), then explicit keys override. + const merged = []; + const explicit = []; + for (const pair of node.items) { + const kNode = pair.key; + const isMergeKey = isScalar(kNode) && kNode.type === 'PLAIN' && !kNode.tag && kNode.value === '<<'; + if (isMergeKey) { + const val = convert(pair.value, doc, anchors); + const maps = Array.isArray(val) ? val : [val]; + const submerge = []; + for (const m of maps) { + if (m === null || typeof m !== 'object' || Array.isArray(m)) { + throw new Error('expected a mapping or list of mappings for merging'); + } + submerge.push(Object.entries(m)); + } + // PyYAML: submerge.reverse(); for value in submerge: merge.extend(value) + submerge.reverse(); + for (const e of submerge) merged.push(...e); + } else { + const k = convert(kNode, doc, anchors); + explicit.push([keyString(k), convert(pair.value, doc, anchors)]); + } + } + for (const [k, v] of merged) out[k] = v; + for (const [k, v] of explicit) out[k] = v; + return out; + } + throw new Error('unsupported YAML node'); +} + +/** Parse one YAML document with PyYAML SafeLoader semantics. */ +export function loadYaml(text) { + const doc = parseDocument(text, { + schema: 'failsafe', uniqueKeys: false, merge: false, version: '1.1', strict: false, prettyErrors: false, + }); + if (doc.errors && doc.errors.length) throw doc.errors[0]; + return convert(doc.contents, doc, new Map()); +} + +export const _internals = { resolvePlain, constructInt }; diff --git a/packages/romdev-splat/src/versions.js b/packages/romdev-splat/src/versions.js new file mode 100644 index 00000000..29a6611b --- /dev/null +++ b/packages/romdev-splat/src/versions.js @@ -0,0 +1,90 @@ +// Which splat / spimdisasm / rabbitizer versions a project pins. +// +// splat behaviour is reproduced for the versions romdev's targets use: +// 0.37.1 (default) and 0.34.1. spimdisasm/rabbitizer versions are passed to +// the disassembler backend. +import fs from 'node:fs'; +import path from 'node:path'; + +export const SUPPORTED_SPLAT_VERSIONS = ['0.34.1', '0.37.1']; +export const DEFAULT_SPLAT_VERSION = '0.37.1'; + +function readIf(p) { try { return fs.readFileSync(p, 'utf8'); } catch { return null; } } + +function fromUvLock(text) { + const out = {}; + const re = /\[\[package\]\]\s*\nname = "([^"]+)"\s*\nversion = "([^"]+)"/g; + for (const m of text.matchAll(re)) out[m[1]] = m[2]; + return out; +} + +function fromRequirements(text) { + const out = {}; + for (const line of text.split('\n')) { + const m = /^\s*([A-Za-z0-9_.-]+)\s*==\s*([0-9][^\s;#]*)/.exec(line); + if (m) out[m[1].toLowerCase()] = m[2]; + } + return out; +} + +function fromVenv(dir) { + const out = {}; + const lib = path.join(dir, '.venv', 'lib'); + let pys = []; + try { pys = fs.readdirSync(lib).filter((d) => d.startsWith('python')); } catch { return out; } + for (const py of pys) { + const sp = path.join(lib, py, 'site-packages'); + let names = []; + try { names = fs.readdirSync(sp); } catch { continue; } + for (const n of names) { + const m = /^([A-Za-z0-9_.]+)-([0-9][^-]*)\.dist-info$/.exec(n); + if (m) out[m[1].toLowerCase().replace(/_/g, '-')] = m[2]; + } + } + return out; +} + +/** + * Detect the pinned versions for a project checkout. Sources, first match + * wins per package: uv.lock, tools/requirements-python.txt, + * requirements.txt, a vendored tools/splat/src/splat/__init__.py, then the + * project's .venv (installed dist-info). Returns {splat, spimdisasm, + * rabbitizer, n64img, sources}; missing entries are null. + */ +export function detectProjectVersions(projectDir) { + const found = { splat: null, spimdisasm: null, rabbitizer: null, n64img: null }; + const sources = {}; + const take = (map, src) => { + const pick = (key, names) => { + if (found[key]) return; + for (const n of names) { + if (map[n]) { found[key] = map[n]; sources[key] = src; return; } + } + }; + pick('splat', ['splat64']); + pick('spimdisasm', ['spimdisasm']); + pick('rabbitizer', ['rabbitizer']); + pick('n64img', ['n64img']); + }; + const uv = readIf(path.join(projectDir, 'uv.lock')); + if (uv) take(fromUvLock(uv), 'uv.lock'); + for (const req of ['tools/requirements-python.txt', 'requirements.txt']) { + const t = readIf(path.join(projectDir, req)); + if (t) take(fromRequirements(t), req); + } + const vendored = readIf(path.join(projectDir, 'tools/splat/src/splat/__init__.py')); + if (vendored && !found.splat) { + const m = /__version__\s*=\s*"([^"]+)"/.exec(vendored); + if (m) { found.splat = m[1]; sources.splat = 'tools/splat/src/splat/__init__.py'; } + } + take(fromVenv(projectDir), '.venv'); + return { ...found, sources }; +} + +export function parseVersion(v) { + const s = String(v); + if (!SUPPORTED_SPLAT_VERSIONS.includes(s)) { + throw new Error(`romdev-splat reproduces splat ${SUPPORTED_SPLAT_VERSIONS.join(' and ')}; ${s} is not supported`); + } + return s.split('.').map(Number); +} diff --git a/packages/romdev-splat/src/wasm/zlib-stream.wasm b/packages/romdev-splat/src/wasm/zlib-stream.wasm new file mode 100755 index 00000000..56d373a6 Binary files /dev/null and b/packages/romdev-splat/src/wasm/zlib-stream.wasm differ diff --git a/packages/romdev-splat/src/zlib.js b/packages/romdev-splat/src/zlib.js new file mode 100644 index 00000000..3ec37230 --- /dev/null +++ b/packages/romdev-splat/src/zlib.js @@ -0,0 +1,62 @@ +// Vanilla zlib (WASM) with CPython zlib-module call semantics: +// compressobj(level, DEFLATED, wbits, memLevel, strategy).compress()/flush() +// and crc32(). See src/wasm/zlib-stream.wasm (scripts/build-zlib-wasm.sh). +import fs from 'node:fs'; + +let inst = null; + +function wasm() { + if (inst) return inst; + const bytes = fs.readFileSync(new URL('./wasm/zlib-stream.wasm', import.meta.url)); + const mod = new WebAssembly.Module(bytes); + inst = new WebAssembly.Instance(mod, { env: { emscripten_notify_memory_growth() {} } }).exports; + if (inst._initialize) inst._initialize(); + return inst; +} + +const Z_NO_FLUSH = 0; +const Z_FINISH = 4; + +function withInput(e, data, fn) { + const n = data.length; + const p = e.zs_malloc(n); + new Uint8Array(e.memory.buffer, p, n).set(data); + try { return fn(p, n); } finally { e.zs_mfree(p); } +} + +export class Compress { + /** zlib.compressobj(level=-1, method=DEFLATED, wbits=15, memLevel=8, strategy=0) */ + constructor(level = -1, wbits = 15, memLevel = 8, strategy = 0) { + const e = wasm(); + this.h = e.zs_new(level, wbits, memLevel, strategy); + if (!this.h) throw new Error('zlib: deflateInit2 failed'); + } + + _run(data, flush) { + const e = wasm(); + const rc = withInput(e, data, (p, n) => e.zs_compress(this.h, p, n, flush)); + if (rc !== 0) throw new Error(`zlib: deflate error ${rc}`); + const ptr = e.zs_out_ptr(this.h); + const len = e.zs_out_len(this.h); + return Buffer.from(new Uint8Array(e.memory.buffer, ptr, len)); + } + + compress(data) { return this._run(data, Z_NO_FLUSH); } + + flush() { + const out = this._run(new Uint8Array(0), Z_FINISH); + wasm().zs_free(this.h); + this.h = 0; + return out; + } +} + +export function compressobj(level = -1, wbits = 15, memLevel = 8, strategy = 0) { + return new Compress(level, wbits, memLevel, strategy); +} + +/** zlib.crc32(data, value=0) */ +export function crc32(data, value = 0) { + const e = wasm(); + return withInput(e, data, (p, n) => e.zs_crc32(value >>> 0, p, n) >>> 0); +} diff --git a/packages/romdev-splat/test/helpers/fake-backend.mjs b/packages/romdev-splat/test/helpers/fake-backend.mjs new file mode 100644 index 00000000..df3e96c8 --- /dev/null +++ b/packages/romdev-splat/test/helpers/fake-backend.mjs @@ -0,0 +1,81 @@ +// A stand-in for romdev-spimdisasm/romdev-rabbitizer with just enough of the +// API for splat runs that never disassemble (no `code` mode): context, +// GlobalConfig, enums. Any disassembly call throws. + +class SymbolsSegment { + constructor(vromStart = null, vromEnd = null, vramStart = null, vramEnd = null) { + this.vromStart = vromStart; this.vromEnd = vromEnd; this.vramStart = vramStart; this.vramEnd = vramEnd; + this.symbols = new Map(); + } + _add(vram, type) { + let s = this.symbols.get(vram); + if (!s) { + s = { + vram, type, name: null, size: null, vromAddress: null, isDefined: false, referenceCounter: 0, + overlayCategory: null, setNameGetCallbackIfUnset() {}, setNameGetCallback() {}, setAlignment() {}, + }; + this.symbols.set(vram, s); + } + return s; + } + addFunction(v) { return this._add(v, 'function'); } + addJumpTable(v) { return this._add(v, 'jumptable'); } + addJumpTableLabel(v) { return this._add(v, 'jumptablelabel'); } + addBranchLabel(v) { return this._add(v, 'branchlabel'); } + addSymbol(v) { return this._add(v, null); } + fillLibultraSymbols() {} + fillIQueSymbols() {} + fillHardwareRegs() {} +} + +class Context { + constructor() { + this.globalSegment = new SymbolsSegment(); + this.bannedSymbols = new Set(); + this.overlays = []; + this.relocs = []; + } + fillDefaultBannedSymbols() {} + addBannedSymbolRangeBySize() {} + addOverlaySegment(cat, a, b, c, d) { const s = new SymbolsSegment(a, b, c, d); this.overlays.push(s); return s; } + changeGlobalSegmentRanges(a, b, c, d) { Object.assign(this.globalSegment, { vromStart: a, vromEnd: b, vramStart: c, vramEnd: d }); } + addGlobalReloc(...a) { this.relocs.push(a); } + saveContextToFile() { throw new Error('fake backend: saveContextToFile'); } +} + +class FakeSection { + constructor(...a) { this.args = a; this.symbolList = []; this.fileBoundaries = []; this.gpRelHack = false; } + analyze() {} + setCommentOffset() {} + setGpRelHack(v) { this.gpRelHack = v; } + getGpRelHack() { return this.gpRelHack; } + getSymbol() { return null; } + disassemble() { throw new Error("fake backend: disassemble"); } +} + +const enumFromStr = (names) => ({ fromStr: (s) => (names.includes(s) ? s : null) }); + +export function makeFakeBackend() { + const spimdisasm = { + __version__: '1.39.3', + __version_info__: [1, 39, 3], + common: { + Context, + GlobalConfig: {}, + Compiler: enumFromStr(['IDO', 'GCC', 'SN64', 'PSYQ', 'KMC', 'EGCS', 'MWCCPS2', 'EEGCC']), + compilerOptions: {}, + InputEndian: { BIG: 'big', LITTLE: 'little' }, + RelocType: enumFromStr(['MIPS_HI16', 'MIPS_LO16', 'MIPS_32', 'MIPS_26', 'MIPS_GPREL16']), + SymbolSpecialType: { function: 'function', jumptable: 'jumptable', branchlabel: 'branchlabel', jumptablelabel: 'jumptablelabel' }, + gKnownTypes: new (class extends Set { has() { return true; } })(['s32']), + }, + mips: { sections: { SectionText: FakeSection, SectionData: FakeSection, SectionRodata: FakeSection, SectionBss: FakeSection } }, + }; + const rabbitizer = { + config: {}, + Abi: { fromStr: (s) => s }, + InstrCategory: { CPU: 'CPU', RSP: 'RSP', R3000GTE: 'R3000GTE', R4000ALLEGREX: 'R4000ALLEGREX', R5900: 'R5900' }, + TrinaryValue: { TRUE: 1, FALSE: 0 }, + }; + return { spimdisasm, rabbitizer }; +} diff --git a/packages/romdev-splat/test/helpers/synthetic.mjs b/packages/romdev-splat/test/helpers/synthetic.mjs new file mode 100644 index 00000000..d7231a28 --- /dev/null +++ b/packages/romdev-splat/test/helpers/synthetic.mjs @@ -0,0 +1,80 @@ +// A small synthetic N64 project (no real ROM data) for the ROM-less tests. +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import crypto from 'node:crypto'; + +export function makeRom() { + const rom = Buffer.alloc(0x1200); + rom.write('\x80\x37\x12\x40', 0, 'latin1'); + rom.write('SYNTHETIC TEST ROM ', 0x20, 'latin1'); + rom.write('NSXE', 0x3B, 'latin1'); + for (let i = 0x40; i < 0x1000; i++) rom[i] = (i * 7) & 0xFF; + for (let i = 0x1000; i < 0x1100; i++) rom[i] = i & 0xFF; + // rgba16 4x4 at 0x1100: a gradient, alternate alpha + for (let p = 0; p < 16; p++) rom.writeUInt16BE(((p * 2) << 11) | ((31 - p) << 6) | (p << 1) | (p & 1), 0x1100 + p * 2); + // ci4 4x4 at 0x1120: indices 0..15 + for (let p = 0; p < 8; p++) rom[0x1120 + p] = ((p * 2) << 4) | (p * 2 + 1); + // palette at 0x1128: 16 colours + for (let c = 0; c < 16; c++) rom.writeUInt16BE((c << 11) | (c << 6) | ((15 - c) << 1) | (c > 0 ? 1 : 0), 0x1128 + c * 2); + return rom; +} + +export const SYMBOLS = `// symbols +blob_start = 0x80001000; // type:u8 size:0x100 rom:0x1000 +tex_rgba = 0x80001100; // size:0x20 + func_80001200 = 0x80001200; // type:func defined:True +hwreg = 0xA4000000; +`; + +export function makeYaml(sha1, extra = '') { + return `name: Synthetic +sha1: ${sha1} +options: + basename: testrom + target_path: rom.z64 + elf_path: build/testrom.elf + base_path: . + platform: n64 + compiler: GCC + ld_script_path: out/testrom.ld + ld_dependencies: True + undefined_funcs_auto_path: out/undefined_funcs_auto.txt + undefined_syms_auto_path: out/undefined_syms_auto.txt + symbol_addrs_path: symbols.txt + asset_path: assets + asm_path: asm + image_type_in_extension: True + ld_wildcard_sections: True + ld_sections_allowlist: [.pdr] + ld_sections_denylist: [.reginfo] + o_as_suffix: True +${extra}segments: + - name: header + type: header + start: 0x0 + - [0x40, bin, boot] + - name: main + type: code + start: 0x1000 + vram: 0x80001000 + bss_size: 0x100 + subsegments: + - [0x1000, databin, blob] + - [0x1100, rgba16, tex, 4, 4] + - [0x1120, ci4, sprite, 4, 4] + - [0x1128, palette, sprite] + - { start: 0x1148, type: bss, vram: 0x80001148, name: heap } + - [0x1200] +`; +} + +export function makeProject(extra = '') { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'romdev-splat-test-')); + const rom = makeRom(); + fs.writeFileSync(path.join(dir, 'rom.z64'), rom); + fs.writeFileSync(path.join(dir, 'symbols.txt'), SYMBOLS); + const sha1 = crypto.createHash('sha1').update(rom).digest('hex'); + fs.writeFileSync(path.join(dir, 'splat.yaml'), makeYaml(sha1, extra)); + return dir; +} diff --git a/packages/romdev-splat/test/rom-gated.test.mjs b/packages/romdev-splat/test/rom-gated.test.mjs new file mode 100644 index 00000000..d8f12066 --- /dev/null +++ b/packages/romdev-splat/test/rom-gated.test.mjs @@ -0,0 +1,54 @@ +// Differential test against a Python splat reference tree. Needs a checkout +// of an N64 decomp project that uses splat 0.37.1 with its baserom, and the +// output tree Python splat produced from it; skips cleanly otherwise. +// +// ROMDEV_SPLAT_PROJECT=/path/to/checkout (its yaml + baserom) +// ROMDEV_SPLAT_CONFIG=config/us/game.us.yaml (relative to the checkout) +// ROMDEV_SPLAT_REF=/path/to/reference/tree (Python splat's outputs) +// ROMDEV_SPLAT_COMPARE=asm,bin,.splat (subtrees to compare) +// ROMDEV_SPLAT_EXCLUDE=regex (paths not written by splat) +// ROMDEV_SPLAT_COPY=config,src,lib,include,tools/splat_ext +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { split, detectProjectVersions } from '../src/index.js'; + +const env = process.env; +const project = env.ROMDEV_SPLAT_PROJECT; +const ref = env.ROMDEV_SPLAT_REF; +const config = env.ROMDEV_SPLAT_CONFIG; +const ready = project && ref && config && fs.existsSync(path.join(project, config)) && fs.existsSync(ref); + +function walk(root, rel, acc) { + const d = path.join(root, rel); + if (!fs.existsSync(d)) return acc; + if (fs.statSync(d).isFile()) { acc.push(rel); return acc; } + for (const e of fs.readdirSync(d)) walk(root, path.join(rel, e), acc); + return acc; +} + +test('split output is byte-identical to the Python splat reference tree', { skip: ready ? false : 'set ROMDEV_SPLAT_PROJECT/CONFIG/REF to run' }, async () => { + const work = fs.mkdtempSync(path.join(env.ROMDEV_SPLAT_TMP || os.tmpdir(), 'romdev-splat-ref-')); + try { + for (const p of (env.ROMDEV_SPLAT_COPY || 'config,src,lib,include,tools/splat_ext').split(',')) { + const from = path.join(project, p); + if (fs.existsSync(from)) fs.cpSync(from, path.join(work, p), { recursive: true }); + } + const pins = detectProjectVersions(project); + const r = await split([config], { cwd: work, splatVersion: pins.splat || '0.37.1', spimdisasmVersion: pins.spimdisasm || undefined }); + assert.equal(r.exitCode, 0, r.stderr); + const subs = (env.ROMDEV_SPLAT_COMPARE || 'asm,bin,.splat').split(','); + const ex = env.ROMDEV_SPLAT_EXCLUDE ? new RegExp(env.ROMDEV_SPLAT_EXCLUDE) : null; + const list = (root) => subs.flatMap((s) => walk(root, s, [])).filter((p) => !ex || !ex.test(p)).sort(); + const want = list(ref); + const got = list(work); + assert.ok(want.length > 0, 'reference tree is empty'); + assert.deepEqual(got, want); + const differing = want.filter((p) => !fs.readFileSync(path.join(ref, p)).equals(fs.readFileSync(path.join(work, p)))); + assert.deepEqual(differing, []); + } finally { + fs.rmSync(work, { recursive: true, force: true }); + } +}); diff --git a/packages/romdev-splat/test/synthetic.test.mjs b/packages/romdev-splat/test/synthetic.test.mjs new file mode 100644 index 00000000..b5b72229 --- /dev/null +++ b/packages/romdev-splat/test/synthetic.test.mjs @@ -0,0 +1,257 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { split } from '../src/index.js'; +import { makeFakeBackend } from './helpers/fake-backend.mjs'; +import { makeProject, makeRom } from './helpers/synthetic.mjs'; +import { compressobj, crc32 } from '../src/zlib.js'; + +const MODES = ['ld', 'bin', 'databin', 'img', 'rgba16', 'ci4', 'palette']; + +async function run(extra = '') { + const dir = makeProject(extra); + const r = await split(['splat.yaml'], { cwd: dir, backend: makeFakeBackend(), modes: MODES }); + return { dir, r, read: (p) => fs.readFileSync(path.join(dir, p)) }; +} + +const EXPECTED_LD = `SECTIONS +{ + __romPos = 0; + header_ROM_START = __romPos; + header_VRAM = ADDR(.header); + .header : AT(header_ROM_START) SUBALIGN(16) + { + FILL(0x00000000); + header_DATA_START = .; + build/asm/header.o(.data*); + header_DATA_END = .; + header_DATA_SIZE = ABSOLUTE(header_DATA_END - header_DATA_START); + } + __romPos += SIZEOF(.header); + header_ROM_END = __romPos; + header_VRAM_END = .; + + boot_ROM_START = __romPos; + boot_VRAM = ADDR(.boot); + .boot : AT(boot_ROM_START) SUBALIGN(16) + { + FILL(0x00000000); + boot_DATA_START = .; + build/assets/boot.o(.data*); + boot_DATA_END = .; + boot_DATA_SIZE = ABSOLUTE(boot_DATA_END - boot_DATA_START); + } + __romPos += SIZEOF(.boot); + boot_ROM_END = __romPos; + boot_VRAM_END = .; + + main_ROM_START = __romPos; + main_VRAM = ADDR(.main); + .main 0x80001000 : AT(main_ROM_START) SUBALIGN(16) + { + FILL(0x00000000); + main_DATA_START = .; + build/asm/data/blob.o(.data*); + build/assets/tex.rgba16.o(.data*); + build/assets/sprite.ci4.o(.data*); + build/assets/sprite.o(.data*); + . = ALIGN(., 16); + main_DATA_END = .; + main_DATA_SIZE = ABSOLUTE(main_DATA_END - main_DATA_START); + } + main_bss_VRAM = ADDR(.main_bss); + .main_bss (NOLOAD) : SUBALIGN(16) + { + FILL(0x00000000); + main_BSS_START = .; + build/asm/data/heap.bss.o(.bss*); + . = ALIGN(., 16); + main_BSS_END = .; + main_BSS_SIZE = ABSOLUTE(main_BSS_END - main_BSS_START); + } + __romPos += SIZEOF(.main); + __romPos = ALIGN(__romPos, 16); + . = ALIGN(., 16); + main_ROM_END = __romPos; + main_VRAM_END = .; + + .pdr 0 : + { + *(.pdr); + } + + /DISCARD/ : + { + *(.reginfo); + *(*); + } +} +`; + +test('linker script, dependency file and databin asm', async () => { + const { dir, r, read } = await run(); + try { + assert.equal(r.exitCode, 0, r.stderr); + assert.equal(read('out/testrom.ld').toString(), EXPECTED_LD); + assert.equal(read('out/testrom.d').toString(), [ + 'build/testrom.elf: \\', ' build/asm/header.o \\', ' build/assets/boot.o \\', ' build/asm/data/blob.o \\', + ' build/assets/tex.rgba16.o \\', ' build/assets/sprite.ci4.o \\', ' build/assets/sprite.o \\', + ' build/asm/data/heap.bss.o', 'build/asm/header.o:', 'build/assets/boot.o:', 'build/asm/data/blob.o:', + 'build/assets/tex.rgba16.o:', 'build/assets/sprite.ci4.o:', 'build/assets/sprite.o:', 'build/asm/data/heap.bss.o:', '', + ].join('\n')); + // blob_start from symbols.txt names the databin; its size matches, so nonmatching carries it + assert.equal(read('asm/data/blob.s').toString(), '.include "macro.inc"\n\n.section .data, "wa"\n\n' + + 'nonmatching blob_start, 0x100\n\ndlabel blob_start\n.incbin "assets/blob.databin.bin"\nenddlabel blob_start\n'); + const rom = makeRom(); + assert.ok(read('assets/boot.bin').equals(rom.subarray(0x40, 0x1000))); + assert.ok(read('assets/blob.databin.bin').equals(rom.subarray(0x1000, 0x1100))); + assert.equal(read('out/undefined_syms_auto.txt').length, 0); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +}); + +test('legacy linker script generation and wildcard-off paths', async () => { + const { dir, r, read } = await run(' ld_legacy_generation: True\n'); + try { + assert.equal(r.exitCode, 0, r.stderr); + const ld = read('out/testrom.ld').toString(); + // legacy mode opens the NOLOAD block with the section symbols of the data run already closed + assert.match(ld, /main_DATA_SIZE = ABSOLUTE\(main_DATA_END - main_DATA_START\);\n \}\n main_bss_VRAM = ADDR\(\.main_bss\);/); + assert.match(ld, /\.main_bss \(NOLOAD\) : SUBALIGN\(16\)/); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +}); + +function chunks(png) { + assert.ok(png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))); + const out = []; + for (let o = 8; o < png.length;) { + const len = png.readUInt32BE(o); + const tag = png.subarray(o + 4, o + 8).toString('latin1'); + const data = png.subarray(o + 8, o + 8 + len); + assert.equal(png.readUInt32BE(o + 8 + len), crc32(Buffer.concat([Buffer.from(tag, 'latin1'), data]))); + out.push([tag, data]); + o += 12 + len; + } + return out; +} + +test('image segments: PNG bytes built by hand from the ROM data', async () => { + const { dir, r, read } = await run(); + try { + assert.equal(r.exitCode, 0, r.stderr); + const rom = makeRom(); + const ceil = (v) => Math.ceil(0xFF * (v / 31)); + + // rgba16 -> 8-bit RGBA, colour type 6 + const rows = []; + for (let y = 0; y < 4; y++) { + const row = [0]; + for (let x = 0; x < 4; x++) { + const s = rom.readUInt16BE(0x1100 + (y * 4 + x) * 2); + const c = (v) => (v << 3) | (v >> 2); + row.push(c((s >> 11) & 31), c((s >> 6) & 31), c((s >> 1) & 31), 255 * (s & 1)); + } + rows.push(...row); + } + const raw = Buffer.from(rows); + const z = compressobj(); + const idat = Buffer.concat([z.compress(raw), z.flush()]); + const ihdr = Buffer.from([0, 0, 0, 4, 0, 0, 0, 4, 8, 6, 0, 0, 0]); + const build = (list) => { + const parts = [Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])]; + for (const [tag, data] of list) { + const len = Buffer.alloc(4); len.writeUInt32BE(data.length); + const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(Buffer.concat([Buffer.from(tag), data]))); + parts.push(len, Buffer.from(tag), data, crc); + } + return Buffer.concat(parts); + }; + const expectedRgba = build([['IHDR', ihdr], ['IDAT', idat], ['IEND', Buffer.alloc(0)]]); + const gotRgba = read('assets/tex.rgba16.png'); + assert.ok(gotRgba.equals(expectedRgba)); + // and the stream is a valid zlib stream of exactly those scanlines + assert.ok(zlib.inflateSync(chunks(gotRgba)[1][1]).equals(raw)); + + // ci4 with a 16-entry palette: PLTE + tRNS, colour type 3, one index byte per pixel + const plte = []; const trns = []; + for (let c = 0; c < 16; c++) { + const s = rom.readUInt16BE(0x1128 + c * 2); + plte.push(ceil((s >> 11) & 31), ceil((s >> 6) & 31), ceil((s >> 1) & 31)); + trns.push((s & 1) * 255); + } + const ciRaw = []; + for (let y = 0; y < 4; y++) { + ciRaw.push(0); + for (let b = 0; b < 2; b++) { const v = rom[0x1120 + y * 2 + b]; ciRaw.push(v >> 4, v & 15); } + } + const z2 = compressobj(); + const idat2 = Buffer.concat([z2.compress(Buffer.from(ciRaw)), z2.flush()]); + const expectedCi = build([['IHDR', Buffer.from([0, 0, 0, 4, 0, 0, 0, 4, 8, 3, 0, 0, 0])], + ['PLTE', Buffer.from(plte)], ['tRNS', Buffer.from(trns)], ['IDAT', idat2], ['IEND', Buffer.alloc(0)]]); + assert.ok(read('assets/sprite.ci4.png').equals(expectedCi)); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +}); + +test('vanilla zlib stream: level 6 default, known bytes', () => { + // Regression bytes of vanilla zlib 1.3.1 (the same module wrote 1000+ PNGs + // byte-identical to CPython zlib output); also a valid zlib stream. + const z = compressobj(); + const out = Buffer.concat([z.compress(Buffer.from('hello hello hello')), z.flush()]); + assert.equal(out.toString('hex'), '789ccb48cdc9c957c84090003a2e067d'); + assert.equal(zlib.inflateSync(out).toString(), 'hello hello hello'); + assert.equal(crc32(Buffer.from('123456789')), 0xCBF43926); +}); + +test('symbol file parsing: attributes, whitespace, comments', async () => { + const { dir, r } = await run(); + try { + assert.equal(r.exitCode, 0, r.stderr); + const { symbols: syms } = await import('../src/util/symbols.js').then((m) => ({ symbols: m.state.all_symbols })); + const byName = new Map(syms.map((s) => [s.name, s])); + const blob = byName.get('blob_start'); + assert.equal(blob.vram_start, 0x80001000); + assert.equal(blob.type, 'u8'); + assert.equal(blob.given_size, 0x100); + assert.equal(blob.rom, 0x1000); + assert.equal(blob.user_declared, true); + assert.equal(blob.defined, true); // the databin defines it + assert.equal(blob.segment.name, 'main'); + const f = byName.get('func_80001200'); + assert.equal(f.type, 'func'); + assert.equal(f.defined, true); + assert.equal(byName.get('tex_rgba').size, 0x20); + assert.equal(byName.get('hwreg').segment, null); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +}); + +test('bad symbol lines and unknown options are reported as errors', async () => { + const dir = makeProject(' not_an_option: 1\n'); + try { + const r = await split(['splat.yaml'], { cwd: dir, backend: makeFakeBackend(), modes: MODES }); + assert.notEqual(r.exitCode, 0); + assert.match(String(r.error), /Unrecognized YAML option\(s\): not_an_option/); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } + const dir2 = makeProject(); + try { + fs.appendFileSync(path.join(dir2, 'symbols.txt'), 'broken = 0x80001300; // defined:maybe\n'); + const r = await split(['splat.yaml'], { cwd: dir2, backend: makeFakeBackend(), modes: MODES }); + assert.equal(r.exitCode, 2); + assert.match(r.stdout + r.stderr, /Invalid Boolean value 'maybe' for attribute 'defined'/); + } finally { fs.rmSync(dir2, { recursive: true, force: true }); } +}); + +test('splat 0.34.1 behaviour: newer options are unknown, textbin/databin asm has no nonmatching label', async () => { + const dir = makeProject(); + try { + const r = await split(['splat.yaml'], { cwd: dir, backend: makeFakeBackend(), modes: MODES, splatVersion: '0.34.1' }); + assert.equal(r.exitCode, 0, r.stderr); + assert.equal(fs.readFileSync(path.join(dir, 'asm/data/blob.s'), 'utf8'), + '.include "macro.inc"\n\n.section .data, "wa"\n\nglabel blob_start\n.incbin "assets/blob.databin.bin"\n'); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } + const dir2 = makeProject(' ld_gp_expression: foo\n'); + try { + const r = await split(['splat.yaml'], { cwd: dir2, backend: makeFakeBackend(), modes: MODES, splatVersion: '0.34.1' }); + assert.match(String(r.error), /Unrecognized YAML option\(s\): ld_gp_expression/); + } finally { fs.rmSync(dir2, { recursive: true, force: true }); } +}); diff --git a/packages/romdev-splat/test/yaml11.test.mjs b/packages/romdev-splat/test/yaml11.test.mjs new file mode 100644 index 00000000..1ebb0bff --- /dev/null +++ b/packages/romdev-splat/test/yaml11.test.mjs @@ -0,0 +1,94 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { loadYaml, PyFloat } from '../src/util/yaml11.js'; + +test('YAML 1.1 implicit scalars follow PyYAML SafeLoader', () => { + const y = loadYaml(` +hex: 0x80000400 +hexu: 0x8000_0400 +oct: 017 +dec: 1_000 +zero: 0 +neg: -12 +bin: 0b1010 +sexa: 1:30 +notint: 08 +float: 1.5 +floatexp: 1.0e+3 +notfloat: 1e5 +inf: .inf +yes: yes +No: No +on: ON +off: off +y: y +n: n +null1: ~ +null2: null +empty: +str: "0x10" +single: '017' +text: hello world +`); + assert.equal(y.hex, 0x80000400); + assert.equal(y.hexu, 0x80000400); + assert.equal(y.oct, 15); + assert.equal(y.dec, 1000); + assert.equal(y.zero, 0); + assert.equal(y.neg, -12); + assert.equal(y.bin, 10); + assert.equal(y.sexa, 90); + assert.equal(y.notint, '08'); + assert.ok(y.float instanceof PyFloat); + assert.equal(y.float.value, 1.5); + assert.equal(y.floatexp.value, 1000); + assert.equal(y.notfloat, '1e5'); + assert.equal(y.inf.value, Infinity); + // keys go through the same resolver: `yes`/`on`/`off` keys become True/False + assert.equal(y.True, true); + assert.equal(y.False, false); + assert.equal(y.y, 'y'); + assert.equal(y.n, 'n'); + assert.equal(y.null1, null); + assert.equal(y.null2, null); + assert.equal(y.empty, null); + assert.equal(y.str, '0x10'); + assert.equal(y.single, '017'); + assert.equal(y.text, 'hello world'); +}); + +test('merge keys: explicit keys win, earlier merged maps win over later ones', () => { + const y = loadYaml(` +a: &a {x: 1, y: 2} +b: &b {y: 3, z: 4} +c: + <<: [*a, *b] + x: 9 +d: + <<: *b +`); + assert.deepEqual(y.c, { x: 9, y: 2, z: 4 }); + assert.deepEqual(y.d, { y: 3, z: 4 }); + // aliases share the object, as PyYAML does + assert.equal(y.d.y, 3); +}); + +test('aliases resolve to the same object and duplicate keys keep the last value', () => { + const y = loadYaml('a: &l [1, 2]\nb: *l\nk: 1\nk: 2\n'); + assert.equal(y.a, y.b); + assert.equal(y.k, 2); +}); + +test('segment list entries keep their shapes', () => { + const y = loadYaml(` +segments: + - [0x1000, c, boot/main] + - { type: bss, vram: 0x80001000, name: heap } + - [auto, .data, x] + - [0x2000] +`); + assert.deepEqual(y.segments[0], [0x1000, 'c', 'boot/main']); + assert.deepEqual(y.segments[1], { type: 'bss', vram: 0x80001000, name: 'heap' }); + assert.deepEqual(y.segments[2], ['auto', '.data', 'x']); + assert.deepEqual(y.segments[3], [0x2000]); +}); diff --git a/packages/romdev-toolchain-cc65/README.md b/packages/romdev-toolchain-cc65/README.md index 5baeb67c..e4a193eb 100644 --- a/packages/romdev-toolchain-cc65/README.md +++ b/packages/romdev-toolchain-cc65/README.md @@ -2,19 +2,21 @@ cc65 - 6502 C compiler + ca65/ld65/da65, plus the cc65 target share tree, as WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **cc65**. +Bundles: **cc65**, https://github.com/cc65/cc65. **License:** Zlib -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-cc65.sh` (no patch - built clean). See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-cc65.sh` with patch `cc65-reproducible-debug-info.patch` (deterministic object files). See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-toolchain-cc65/package.json b/packages/romdev-toolchain-cc65/package.json index 3d79a669..41c345e8 100644 --- a/packages/romdev-toolchain-cc65/package.json +++ b/packages/romdev-toolchain-cc65/package.json @@ -1,6 +1,6 @@ { "name": "romdev-toolchain-cc65", - "version": "0.1.4", + "version": "0.1.5", "description": "cc65 toolchain (cc65 / ca65 / ld65 / da65) + target share files for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/atari7800-mono.o b/packages/romdev-toolchain-cc65/share/cc65/lib/atari7800-mono.o index 905066fb..4cb7f510 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/atari7800-mono.o and b/packages/romdev-toolchain-cc65/share/cc65/lib/atari7800-mono.o differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/atari7800.lib b/packages/romdev-toolchain-cc65/share/cc65/lib/atari7800.lib index b7a3912a..08297b34 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/atari7800.lib and b/packages/romdev-toolchain-cc65/share/cc65/lib/atari7800.lib differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/c64-soft80.o b/packages/romdev-toolchain-cc65/share/cc65/lib/c64-soft80.o index c088c0ed..ee88294c 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/c64-soft80.o and b/packages/romdev-toolchain-cc65/share/cc65/lib/c64-soft80.o differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/c64-soft80mono.o b/packages/romdev-toolchain-cc65/share/cc65/lib/c64-soft80mono.o index 5988bb99..aed15c36 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/c64-soft80mono.o and b/packages/romdev-toolchain-cc65/share/cc65/lib/c64-soft80mono.o differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/c64-tgimousedata.o b/packages/romdev-toolchain-cc65/share/cc65/lib/c64-tgimousedata.o index 9f40d45d..1457075c 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/c64-tgimousedata.o and b/packages/romdev-toolchain-cc65/share/cc65/lib/c64-tgimousedata.o differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/c64.lib b/packages/romdev-toolchain-cc65/share/cc65/lib/c64.lib index ce6da9cb..67f5b60e 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/c64.lib and b/packages/romdev-toolchain-cc65/share/cc65/lib/c64.lib differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/lynx.lib b/packages/romdev-toolchain-cc65/share/cc65/lib/lynx.lib index eff0b9fb..ed17e9f1 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/lynx.lib and b/packages/romdev-toolchain-cc65/share/cc65/lib/lynx.lib differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/nes.lib b/packages/romdev-toolchain-cc65/share/cc65/lib/nes.lib index cda1e358..6379e108 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/nes.lib and b/packages/romdev-toolchain-cc65/share/cc65/lib/nes.lib differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/none.lib b/packages/romdev-toolchain-cc65/share/cc65/lib/none.lib index a120493b..05db13b7 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/none.lib and b/packages/romdev-toolchain-cc65/share/cc65/lib/none.lib differ diff --git a/packages/romdev-toolchain-cc65/share/cc65/lib/pce.lib b/packages/romdev-toolchain-cc65/share/cc65/lib/pce.lib index e98d533c..0c6e811b 100644 Binary files a/packages/romdev-toolchain-cc65/share/cc65/lib/pce.lib and b/packages/romdev-toolchain-cc65/share/cc65/lib/pce.lib differ diff --git a/packages/romdev-toolchain-decomp-gcc/README.md b/packages/romdev-toolchain-decomp-gcc/README.md new file mode 100644 index 00000000..de574f1f --- /dev/null +++ b/packages/romdev-toolchain-decomp-gcc/README.md @@ -0,0 +1,81 @@ +# romdev-toolchain-decomp-gcc + +The gcc toolchains that N64 and PS1 matching-decompilation projects pin, and the +command-line tools their builds run, as WebAssembly, for romdevtools' `decomp` +tool. + +- `wasm/kmc-2.7.2/`: gcc 2.7.2 as shipped in the N64 SDK (KMC): the driver + `gcc`, the preprocessor `cpp` (cccp) and `cc1`, with the binutils 2.6 + assembler `as` it pairs with (including `--force-n64align`). Built from + [decompals/mips-gcc-2.7.2](https://github.com/decompals/mips-gcc-2.7.2) and + [decompals/mips-binutils-2.6](https://github.com/decompals/mips-binutils-2.6) + (GPL-2.0) with `kmc-gcc-2.7.2-wasm.patch` (the driver runs its passes through + romdev's spawn hook instead of fork/exec) and `kmc-binutils-2.6-wasm.patch` + (lays out obstack chunks and frags as the reference x86_64 build does, so gas + splits frags at the same places). +- `wasm/egcs-1.1.2/`: EGCS 1.1.2 (gcc 2.91.66) for mips-linux (`gcc`, `cpp` + (cccp), `cc1`) with its binutils 2.9.5 assembler `as`: the compiler N64 + decomp projects build their iQue (China) versions with. Built from + [decompals/mips-gcc-egcs-2.91.66](https://github.com/decompals/mips-gcc-egcs-2.91.66) + and [decompals/mips-binutils-egcs-2.9.5](https://github.com/decompals/mips-binutils-egcs-2.9.5) + (GPL-2.0) with `egcs-1.1.2-wasm.patch` and `egcs-binutils-2.9.5-wasm.patch`. +- `wasm/psx-gcc-2.6.3/`: gcc 2.6.3 for the PlayStation (`gcc`, `cc1`, `cpp`), + built with the steps of [decompals/old-gcc](https://github.com/decompals/old-gcc)'s + `gcc-2.6.3-psx` recipe (the `cc1-psx-26` that PS1 decomp projects run + directly), plus the driver with `psx-gcc-2.6.3-wasm.patch` (spawn hook, a + `sys_errlist` built from strerror, `-EL` for its mips-linux-gnu `as` step). + The build's generators are compiled with emcc too and run under Node. The + projects' assembly post-processor, maspsx, is ported to JS in romdevtools. +- `wasm/mips-linux-gnu-14.2/`: gcc 14.2.0 for target mips-linux-gnu (`gcc`, + `cpp`, `cc1`), configured like Debian's `gcc-mips-linux-gnu` (trixie, + 14.2.0-13cross1): the modern cross gcc projects use for data-only translation + units, `.s` preprocessing and linker scripts. It assembles with + `mips-linux-gnu-as` from `romdev-toolchain-mips-gcc`. Built with + `gcc-14-driver-wasm-spawn.patch` and Debian's distro specs + (`gcc-14-debian-distro-specs.patch`). Like Debian's cross cpp it pre-includes + glibc's `stdc-predef.h`, shipped at `mips-linux-gnu/include/` from Debian's + libc6-dev-mips-cross (LGPL-2.1-or-later). romdev runs the driver with + `GCC_EXEC_PREFIX=/lib/gcc/`. +- `wasm/tools/`: decompals' [slinky](https://github.com/decompals/slinky) + (`slinky-cli`), [pigment64](https://github.com/decompals/pigment64) and + [crunch64](https://github.com/decompals/crunch64) command-line tools (MIT), + and `raw-deflate`, vanilla zlib's raw deflate (zlib license). +- `wasm/tools/psx-str`, `psx-disk`, `psx-assets`: a PS1 decomp project's own + setup tools (a string encoder in Rust, a disc image extractor and an asset + tool in Go), built from that project's repository at the commit pinned in + `versions.json` (AGPL-3.0). The Go tools are wasip1 modules run under + `node:wasi`. romdev builds all three from a rewritten copy of the source + that carries none of the game's text: names the tools need (project file + paths, env vars, the console-port file lists, the disc's volume + identifiers) are read at run time from the project and its original disc + image, and objdiff progress labels are the overlay codes. Extracted and + built assets and rebuilt disc images are unchanged. + +Objects these compilers emit are compared byte for byte against the natively +built compilers over full project builds. romdev drives the modules from its +isolated WASM worker; they are not a general-purpose CLI. You normally install +`romdevtools` (`npx romdevtools`), not this package directly. + +## Upstream and license + +GPL-2.0-or-later (the old gcc and binutils trees), GPL-3.0-or-later (gcc 14.2), +LGPL-2.1-or-later (`stdc-predef.h`), AGPL-3.0-only (the PS1 project's setup +tools), MIT (slinky, pigment64, crunch64) and Zlib (`raw-deflate`). The +upstream commits and tarballs are pinned in +`packages/romdevtools/scripts/versions.json` in the romdev repo; the patches +are in `packages/romdevtools/scripts/patches/`, and the source rewrites +in `packages/romdevtools/scripts/src/decomp-go-wasip1/` (Go tools) and +`packages/romdevtools/scripts/src/psx-str/` (string encoder). + +**Built by** (all in `packages/romdevtools/scripts/`): + +- `build-decomp-gcc.sh` (`kmc`, `egcs` and `psx` targets) for the old gcc + toolchains; +- `build-mips-linux-gcc-wasm.sh` for gcc 14.2; +- `build-decomp-rust-tools.sh` for slinky, pigment64, crunch64, raw-deflate and + the Rust string encoder; +- `build-decomp-go-tools.sh` for the Go setup tools. + +See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-toolchain-decomp-gcc/index.js b/packages/romdev-toolchain-decomp-gcc/index.js new file mode 100644 index 00000000..3ebf8ee7 --- /dev/null +++ b/packages/romdev-toolchain-decomp-gcc/index.js @@ -0,0 +1,36 @@ +// romdev-toolchain-decomp-gcc - binary package: the gcc toolchains N64 +// and PS1 matching-decompilation projects pin, as WASM, one directory per family, and +// the command-line tools their builds run: +// wasm/kmc-2.7.2/ gcc (driver), cpp (cccp), cc1, as (binutils 2.6) +// wasm/egcs-1.1.2/ gcc (driver), cpp (cccp), cc1, as (binutils 2.9.5) +// wasm/psx-gcc-2.6.3/ cc1, cpp (cccp): PS1 gcc 2.6.3-psx +// wasm/mips-linux-gnu-14.2/ gcc (driver), cpp, cc1 (assembles with +// romdev-toolchain-mips-gcc's mips-linux-gnu-as) +// wasm/tools/ slinky-cli, pigment64, crunch64, raw-deflate, +// psx-str (emscripten); psx-disk, psx-assets (wasip1): +// a PS1 decomp project's string encoder, CD image +// extractor and asset extractor/builder +// Every module is linked with NODERAWFS (it reads and writes the real +// filesystem); romdevtools' decomp domain (src/decomp/toolchain.js) runs them in +// its WASM worker and supplies the spawn hook the driver runs its passes with. +import { fileURLToPath } from "node:url"; +import path from "node:path"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export const wasmDir = path.join(__dirname, "wasm"); +export const families = { + "kmc-2.7.2": ["gcc", "cpp", "cc1", "as"], + "egcs-1.1.2": ["gcc", "cpp", "cc1", "as"], + "psx-gcc-2.6.3": ["cc1", "cpp"], + "mips-linux-gnu-14.2": ["gcc", "cpp", "cc1"], +}; +export const tools = ["slinky-cli", "pigment64", "crunch64", "raw-deflate", "psx-str"]; +/** wasip1 modules in wasm/tools/, run under node:wasi rather than as emscripten glue. */ +export const wasiTools = ["psx-disk", "psx-assets"]; + +/** Directory of one family's modules. */ +export function familyDir(family) { + if (!families[family]) throw new Error(`no decomp gcc family '${family}' (have ${Object.keys(families).join(", ")})`); + return path.join(wasmDir, family); +} diff --git a/packages/romdev-toolchain-decomp-gcc/package.json b/packages/romdev-toolchain-decomp-gcc/package.json new file mode 100644 index 00000000..cf664810 --- /dev/null +++ b/packages/romdev-toolchain-decomp-gcc/package.json @@ -0,0 +1,30 @@ +{ + "name": "romdev-toolchain-decomp-gcc", + "version": "0.1.0", + "description": "The gcc toolchains N64 and PS1 matching-decompilation projects pin (KMC gcc 2.7.2 with binutils 2.6 as; EGCS 1.1.2 with binutils 2.9.5 as; gcc 2.6.3-psx cc1; gcc 14.2 for mips-linux-gnu) and the build tools they run (slinky, pigment64, crunch64), bundled as WASM for romdev's decomp domain.", + "type": "module", + "main": "index.js", + "exports": { + ".": "./index.js", + "./wasm/*": "./wasm/*" + }, + "files": [ + "index.js", + "wasm", + "README.md" + ], + "engines": { + "node": ">=24" + }, + "license": "GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-2.1-or-later AND AGPL-3.0-only AND MIT AND Zlib", + "repository": { + "type": "git", + "url": "git+https://github.com/monteslu/romdev.git", + "directory": "packages/romdev-toolchain-decomp-gcc" + }, + "homepage": "https://github.com/monteslu/romdev#readme", + "bugs": { + "url": "https://github.com/monteslu/romdev/issues" + }, + "author": "Luis Montes" +} diff --git a/packages/romdev-toolchain-ido/README.md b/packages/romdev-toolchain-ido/README.md new file mode 100644 index 00000000..936ad3a8 --- /dev/null +++ b/packages/romdev-toolchain-ido/README.md @@ -0,0 +1,36 @@ +# romdev-toolchain-ido + +**Not published.** IDO is SGI's proprietary IRIX C compiler. romdev does not +distribute it, and no romdev npm package contains it. This package is marked +private, so npm will not publish it; it exists in the romdev repository only as +the folder a local build writes into. + +## What a local build produces + +The IRIX IDO 5.3 and 7.1 C compilers that N64 matching-decompilation projects +build with, as WebAssembly, for romdevtools' `decomp` tool: + +- `wasm/5.3/` and `wasm/7.1/`: one module per IRIX program (`cc`, `acpp`, + `cfe`, `uopt`, `ugen`, `as0`, `as1`, `ujoin`, `uld`, `umerge`, `usplit`), + plus the compiler's message catalog `err.english.cc`. + +## Getting IDO + +Build it yourself from a romdev checkout with +`packages/romdevtools/scripts/build-ido.sh`. The script fetches the pinned +[ido-static-recomp](https://github.com/decompals/ido-static-recomp) (MIT), +which statically recompiles each IRIX executable to C, then compiles that C +with emcc and romdev's patch `ido-static-recomp-wasm.patch` (the WASM memory +model and a vfork-style fork so `cc` can run its passes as sibling modules). + +A romdev checkout finds the built modules in this folder on its own. An +installed `romdevtools` finds them through `ROMDEV_IDO_DIR`, set to a directory +holding the `5.3/` and `7.1/` folders. + +## License + +This package grants no rights to IDO. The IRIX programs are SGI's proprietary +software and remain the property of their owners; nothing produced here is +redistributable. See `ido//LICENSE.md` in the ido-static-recomp +repository. The recompiler itself is MIT, and romdev's build script and patch +are MIT. diff --git a/packages/romdev-toolchain-ido/index.js b/packages/romdev-toolchain-ido/index.js new file mode 100644 index 00000000..efb48501 --- /dev/null +++ b/packages/romdev-toolchain-ido/index.js @@ -0,0 +1,20 @@ +// romdev-toolchain-ido - binary package: IRIX IDO 5.3 / 7.1 compiler programs +// as WASM, one module per IRIX program under wasm//. Every module is +// linked with NODERAWFS (it reads and writes the real filesystem) and expects +// romdev's driver (romdevtools src/decomp/wasm-run.js) to supply the spawn hook +// cc uses to run its passes. err.english.cc sits beside the modules: cc finds +// it, and its passes, through the USR_LIB environment variable. +import { fileURLToPath } from "node:url"; +import path from "node:path"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export const wasmDir = path.join(__dirname, "wasm"); +export const versions = ["5.3", "7.1"]; +export const programs = ["cc", "acpp", "cfe", "uopt", "ugen", "as0", "as1", "ujoin", "uld", "umerge", "usplit"]; + +/** Directory of one IDO version's modules. */ +export function versionDir(version) { + if (!versions.includes(version)) throw new Error(`IDO ${version} is not shipped (have ${versions.join(", ")})`); + return path.join(wasmDir, version); +} diff --git a/packages/romdev-toolchain-ido/package.json b/packages/romdev-toolchain-ido/package.json new file mode 100644 index 00000000..559bfbab --- /dev/null +++ b/packages/romdev-toolchain-ido/package.json @@ -0,0 +1,31 @@ +{ + "name": "romdev-toolchain-ido", + "version": "0.1.0", + "private": true, + "description": "IRIX IDO 5.3 and 7.1 C compilers (cc, cfe, uopt, ugen, as1 and the other passes), statically recompiled by ido-static-recomp and bundled as WASM for romdev's N64 matching-decompilation domain.", + "type": "module", + "main": "index.js", + "exports": { + ".": "./index.js", + "./wasm/*": "./wasm/*" + }, + "files": [ + "index.js", + "wasm", + "README.md" + ], + "engines": { + "node": ">=24" + }, + "license": "SEE LICENSE IN README.md", + "repository": { + "type": "git", + "url": "git+https://github.com/monteslu/romdev.git", + "directory": "packages/romdev-toolchain-ido" + }, + "homepage": "https://github.com/monteslu/romdev#readme", + "bugs": { + "url": "https://github.com/monteslu/romdev/issues" + }, + "author": "Luis Montes" +} diff --git a/packages/romdev-toolchain-m68k-gcc/README.md b/packages/romdev-toolchain-m68k-gcc/README.md index 24fe7d96..547ffcda 100644 --- a/packages/romdev-toolchain-m68k-gcc/README.md +++ b/packages/romdev-toolchain-m68k-gcc/README.md @@ -1,9 +1,12 @@ # romdev-toolchain-m68k-gcc -m68k-elf-gcc toolchain (cc1/as/ld/objcopy/objdump) for Sega Genesis C - and the -native m68k disassembler/reassembler behind `disassembleProject` - as -WebAssembly. Plus SGDK's Z80 tools (sjasm/bintos), the Genesis C library tree -(`share/genesis/lib/`: full SGDK + minimal runtime), and the full C build +The m68k-elf gcc toolchain (`cc1`, `as`, `ld`, `objcopy`, `objdump`) for Sega +Genesis C, as WebAssembly. The objdump also serves 68000 disassembly for +`disasm({target:'rom'})` and byte-exact `disasm({target:'project'})`, and the +`as`, `ld` and `objcopy` also build Genesis assembly: romdevtools translates +Motorola-syntax sources for them. The +package also carries SGDK's Z80 tools (`sjasm`, `bintos`), the Genesis C +library tree (`share/genesis/lib/`: SGDK and a minimal runtime) and the C build pipeline: ```js @@ -11,30 +14,42 @@ import { buildGenesisC, finalizeGenesisRom, parseBuildLog } from "romdev-toolchain-m68k-gcc"; const r = await buildGenesisC({ source: '#include \nint main(){ ... }' }); -const rom = finalizeGenesisRom(r.binary); // pad + $18E checksum (SGDK post-link) +const rom = finalizeGenesisRom(r.binary); // pad and write the $18E checksum (SGDK's post-link step) ``` -One dep compiles everything for the target - an SDK or tool building Genesis -ROMs needs only this package (romdev's own server builds through the same -entry, so there is exactly one pipeline). `buildGenesisC` also accepts an -injected `env` (runTool / share manifest / hash / sdkCache / loadGlue) so the -identical pipeline runs in a browser Web Worker - see +An SDK or tool that builds Genesis ROMs needs only this package; romdevtools' +`build({platform:'genesis'})` goes through the same entry point. +`buildGenesisC` also accepts an injected `env` (runTool, share manifest, hash, +sdkCache, loadGlue) so the same pipeline runs in a browser Web Worker; see `build/genesis-c/genesis-c.js` for the contract. -A binary package for [romdev](https://github.com/monteslu/romdev): it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. Install `romdev` for the full dev suite, or this package alone for the -build pipeline. +A binary package for [romdev](https://github.com/monteslu/romdev). The main +`romdevtools` package loads it on demand. Install `romdevtools` +(`npx romdevtools`) for the full tool set, or this package alone for the build +pipeline. -## Upstream & license +## Upstream and license -Bundles: **m68k-elf-gcc, binutils**. +Bundles: **gcc 14.2.0, binutils 2.42 and newlib 4.4.0** for m68k-elf, and +**SGDK** (https://github.com/Stephane-D/SGDK) with its `sjasm` and `bintos` +tools. -**License:** GPL-3.0-or-later with GCC Runtime Library Exception (does not encumber compiled ROMs). +**License:** -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +- gcc and binutils: GPL-3.0-or-later (the package's `license` field). libgcc + carries the GCC Runtime Library Exception, and newlib uses BSD-style + licences, so linking them does not place conditions on a compiled ROM. +- SGDK: MIT (`share/genesis/lib/sgdk/LICENSE`, with `COPYING.RUNTIME`). +- `sjasm` and `bintos` are built from SGDK's `tools/` tree at the pinned SGDK + commit; `sjasm` keeps its original author's licence notice there. -**Built by:** `romdevtools/scripts/build-m68k-wasm-tools.sh + build-sjasm.sh` (no patch - built clean). See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +This package redistributes the upstream source built to WebAssembly. The +upstream versions are pinned in `packages/romdevtools/scripts/versions.json` in +the romdev repo, and the repo's `NOTICE` has the full third-party inventory. + +**Built by:** `packages/romdevtools/scripts/build-m68k-wasm-tools.sh` (the +native stage is `build-m68k-toolchain.sh`, with newlib patches +`newlib-4.4.0-m68k-ldbl-eq-dbl.patch` and +`newlib-4.4.0-m68k-bare-metal-system.patch`) and `build-sjasm.sh`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-toolchain-m68k-gcc/build/_worker/pool.js b/packages/romdev-toolchain-m68k-gcc/build/_worker/pool.js index 8c204f53..95066dee 100644 --- a/packages/romdev-toolchain-m68k-gcc/build/_worker/pool.js +++ b/packages/romdev-toolchain-m68k-gcc/build/_worker/pool.js @@ -9,7 +9,7 @@ // gets a fresh one. // // This is the chokepoint that gives MCP the "one bad build can't kill -// the server" property requested in Round 11 feedback. +// the server" property. import { fork } from "node:child_process"; import os from "node:os"; diff --git a/packages/romdev-toolchain-m68k-gcc/build/_worker/wasm-worker.js b/packages/romdev-toolchain-m68k-gcc/build/_worker/wasm-worker.js index c62361da..04d6125b 100644 --- a/packages/romdev-toolchain-m68k-gcc/build/_worker/wasm-worker.js +++ b/packages/romdev-toolchain-m68k-gcc/build/_worker/wasm-worker.js @@ -223,7 +223,14 @@ process.on("message", async (msg) => { return; } if (msg.type === "run") { - const result = await runJob(msg.job); + // A job may name a handler module that runs it instead of the single- + // tool MEMFS path above (the decomp domain's NODERAWFS toolchains: IDO's + // cc spawning its passes as sibling modules, binutils over a real tree). + // It still runs HERE, in the isolated worker, so an abort cannot reach + // the server. + const result = msg.job.handler + ? await (await import(msg.job.handler)).runWorkerJob(msg.job) + : await runJob(msg.job); process.send({ type: "result", id: msg.id, result }); // After every job, signal ready again so the pool can recycle us. process.send({ type: "ready" }); diff --git a/packages/romdev-toolchain-m68k-gcc/build/common/io.js b/packages/romdev-toolchain-m68k-gcc/build/common/io.js index e10abf1d..431dee00 100644 --- a/packages/romdev-toolchain-m68k-gcc/build/common/io.js +++ b/packages/romdev-toolchain-m68k-gcc/build/common/io.js @@ -31,7 +31,7 @@ function bytesToBase64(u8) { /** Convert binary (Uint8Array / Buffer / base64 string) → InputFile spec. */ export function binaryFile(vfsPath, bytes) { // Accept EITHER raw bytes OR a base64 STRING - the same either/or contract the - // toolchain wrappers honor individually (asar/cc65/vasm68k/wladx all guard with + // toolchain wrappers honor individually (asar/cc65/wladx all guard with // `x instanceof Uint8Array ? x : Buffer.from(x, "base64")`). The MCP // `binaryIncludes` schema delivers base64 STRINGS; decoding them as UTF-8 (the // old bug) made the base64 TEXT itself the file bytes - .incbin then embedded diff --git a/packages/romdev-toolchain-m68k-gcc/build/common/share-fs.js b/packages/romdev-toolchain-m68k-gcc/build/common/share-fs.js index 41cb735d..cbf5f950 100644 --- a/packages/romdev-toolchain-m68k-gcc/build/common/share-fs.js +++ b/packages/romdev-toolchain-m68k-gcc/build/common/share-fs.js @@ -14,7 +14,7 @@ // rel paths always use "/" and are relative to the share LIB root (e.g. // "libtonc/gba_crt0.s", "sgdk/md.ld"). // -// ⚠ ORDER MATTERS: list() order feeds SDK compile order → ar member order → +// ORDER MATTERS: list() order feeds SDK compile order → ar member order → // ROM bytes, and the sdk-cache hash keys. dirShare preserves the readdir // walk order the drivers always used; buildShareManifest() materializes a // manifest with the SAME walk, so a browser host that stages its manifest diff --git a/packages/romdev-toolchain-m68k-gcc/build/common/wasm-tool.js b/packages/romdev-toolchain-m68k-gcc/build/common/wasm-tool.js index 27fdd400..bf8178b1 100644 --- a/packages/romdev-toolchain-m68k-gcc/build/common/wasm-tool.js +++ b/packages/romdev-toolchain-m68k-gcc/build/common/wasm-tool.js @@ -19,7 +19,7 @@ import path from "node:path"; /** * Resolve a single tool glue FILE from its package, falling back to a local * in-tree copy. This is the arm/m68k/mips/sh-gcc + asar + wladx + rgbds + dasm + - * vasm68k + sjasm + tcc816 shape (one .js/.mjs glue per tool). + * sjasm + tcc816 shape (one .js/.mjs glue per tool). * * @param {Object} a * @param {string} a.pkg npm package the glue ships in (e.g. "romdev-platform-gba") diff --git a/packages/romdev-toolchain-m68k-gcc/build/genesis-c/README.md b/packages/romdev-toolchain-m68k-gcc/build/genesis-c/README.md index b00fb717..f0c9ce9c 100644 --- a/packages/romdev-toolchain-m68k-gcc/build/genesis-c/README.md +++ b/packages/romdev-toolchain-m68k-gcc/build/genesis-c/README.md @@ -1,61 +1,50 @@ -# Genesis C toolchain - pipeline overview +# Genesis C build pipeline -This directory will host the JS-side glue for the Genesis C build path -once the WASM artifacts ship. Pipeline shape: +`genesis-c.js` exports `buildGenesisC()` and `finalizeGenesisRom()`, the C +build path for Sega Genesis ROMs. Each stage is a WebAssembly tool from this +package, run in its own worker, so a crash in one stage cannot take down the +caller: ``` - ┌─── cc1 (WASM) ──┐ - main.c ──────► │ m68k-elf-as (WASM)│ ──► .o ──► m68k-elf-ld (WASM) ──► ELF ──► objcopy ──► .bin - └─ JS driver orchestrates ─┘ (Genesis raw ROM) - ▲ - │ links against - libgcc.a + libc.a (newlib) + libmd.a (SGDK) - - all built natively as PURE target artifacts - and shipped as binary blobs (no native code - ever runs at user-build time). +main.c --cc1--> main.s --as--> main.o --ld--> main.elf --objcopy--> main.bin + ^ + | links against + crt0 + libmd.a (SGDK) or a minimal runtime, libc.a, libm.a (newlib), libgcc.a ``` -## Status - -- **Native cross-toolchain build (stage 1)**: in progress - - `scripts/build-m68k-toolchain.sh` produces binutils + gcc + newlib + - libgcc into `build/m68k-toolchain/install/`. -- **WASM port of cc1/as/ld (stage 2)**: pending. -- **SGDK native build against the cross-toolchain (stage 3)**: pending. -- **JS driver `buildGenesisC()`**: pending. -- **build({output:'rom'}) wiring**: pending. - -## Why a 3-stage build - -GCC's build is bootstrapping: gcc-the-binary builds libgcc.a using -gcc-the-binary, and libgcc.a is a TARGET artifact (m68k object file), -not a host one. Emscripten can't host the native gcc bootstrap because -gcc spawns its own subprocesses (cc1, as, ld) during the build. - -Solution: -1. **Stage 1 (native)** builds the cross-toolchain on the build host. - The output is a native Linux/Mac binary that produces m68k-elf - objects. Plus libgcc.a, libc.a, crt0.o, etc. - pure target artifacts. -2. **Stage 2 (WASM)** re-compiles cc1, m68k-elf-as, m68k-elf-ld via - emcc, sourcing from the same upstream gcc/binutils trees but - building only the components users invoke at runtime. Each becomes - a `Module` we can `callMain` on, identical to wla-65816 / tcc-65816 - from R15/R16/R18. -3. **Stage 3 (native against stage 1)** builds SGDK once on the build - host using the native stage-1 toolchain. Output: `libmd.a` + - `sega.s` (crt0) + `md.ld` (linker script) + the SGDK include tree. - These are TARGET artifacts - they ship as binary blobs alongside - our WASM tools and never re-build on user machines. - -User builds (stage 4, at runtime) wire it together: -- JS driver calls cc1.wasm with the user's main.c → .s -- JS driver calls as.wasm with the .s → .o -- JS driver calls ld.wasm linking [crt0.o, user .o(s), libmd.a, - libc.a, libgcc.a] against md.ld → main.elf -- JS driver calls objcopy.wasm with main.elf → main.bin (raw Genesis ROM) - -The "fork/exec" problem that historically blocked gcc-in-the-browser -goes away because **we don't ship gcc-the-driver**. The driver is JS, -running in Node, orchestrating WASM tools via our existing worker pool -(R12). Each WASM tool sees a clean MEMFS, runs a single callMain, -returns its output. +No native code runs at build time. The JS driver orchestrates the WASM tools in +place of gcc's own driver, so gcc's fork/exec of its passes is not needed. The +target libraries (`libgcc.a`, newlib's `libc.a` and `libm.a`, SGDK's runtime) +are prebuilt target artifacts under `share/genesis/lib/`. SGDK's `libmd.a` +ships as a prebuilt seed built from the bundled SGDK source; pass +`rebuildSdk: true` to compile it from source instead (cached by source hash). +If the SGDK source no longer matches the seed and no rebuild was asked for, the +result carries an `sdkEditIgnored` warning naming the changed file. + +## Two runtime modes + +- `sgdk: true` (default): links the bundled SGDK runtime (`libmd.a`, the + `sega.s` crt0, the `md.ld` linker script and the SGDK header tree), so + `#include ` works and the standard SGDK API (`VDP_drawText`, + `SYS_doVBlankProcess`, `SPR_addSprite` and the rest) is available. +- `sgdk: false`: gcc, newlib and libgcc only, with a small `sega.s` and + `genesis.ld`. The program drives the VDP registers directly. + +## Running outside Node + +Pass `env` to run the same pipeline in a browser Web Worker. Every seam is +optional; omitting `env` uses the Node defaults (worker pool and file reads): + +- `env.runTool`: runs the gcc tools (see `common/gcc-toolchain.js`, `ToolJob`). +- `env.loadGlue`: the sjasm and bintos module factories (see `sjasm/sjasm.js`). +- `env.share`: the `share/genesis/lib` tree as a `{relPath: string|Uint8Array}` + manifest; stage it with `common/share-fs.js` `buildShareManifest` so the key + order matches Node's (it determines compile order, archive member order and + so the ROM bytes). +- `env.hash`: an async `{name: text} -> hex digest` used for the SDK seed check + (required when `env` is given; in a browser, `crypto.subtle`). +- `env.sdkCache`: an optional `{get(key), put(key, bytes)}` cache for the + rebuilt SDK archive. + +`finalizeGenesisRom(binary)` pads the ROM and writes the header checksum at +`$18E`, SGDK's post-link step. diff --git a/packages/romdev-toolchain-m68k-gcc/build/genesis-c/genesis-c.js b/packages/romdev-toolchain-m68k-gcc/build/genesis-c/genesis-c.js index 98291d8b..bc6c0c31 100644 --- a/packages/romdev-toolchain-m68k-gcc/build/genesis-c/genesis-c.js +++ b/packages/romdev-toolchain-m68k-gcc/build/genesis-c/genesis-c.js @@ -6,7 +6,7 @@ // ld.wasm - link user .o + sega.o + libmd.a + libgcc → .elf // objcopy.wasm - strip ELF down to raw .bin Genesis ROM // -// Each WASM tool runs in a fresh worker (R12 subprocess isolation), so +// Each WASM tool runs in a fresh worker (subprocess isolation), so // a crash in one stage doesn't take out the server. // // ENV INJECTION (0.95.0, browser IDEs): pass `env` to run the identical @@ -507,7 +507,7 @@ export function finalizeGenesisRom(bin) { } /** - * Minimum-viable Genesis C path (no SGDK). R20 stage-1 behavior. + * Minimum-viable Genesis C path (no SGDK). * Same code path as before - only this implementation handles the * minimal sega.s / genesis.ld bundled under lib/c/. */ diff --git a/packages/romdev-toolchain-m68k-gcc/build/parse-errors.js b/packages/romdev-toolchain-m68k-gcc/build/parse-errors.js index ab9d8dd2..12520d35 100644 --- a/packages/romdev-toolchain-m68k-gcc/build/parse-errors.js +++ b/packages/romdev-toolchain-m68k-gcc/build/parse-errors.js @@ -41,8 +41,12 @@ export function parseBuildLog(log) { issues.push(...parseAsar(text)); } else if (/^rgbasm$|^rgblink$|^rgbfix$/.test(baseStage)) { issues.push(...parseRgbds(text, baseStage)); - } else if (/^vasm/.test(baseStage)) { - issues.push(...parseVasm(text)); + } else if (baseStage === "m68k-as") { + // Genesis assembly (Motorola syntax through GNU as): every diagnostic is + // already "file:line: error|warning: message" against the source line, + // plus a few location-less "error: message" lines from the link. + issues.push(...parseCc65Like(text, baseStage)); + issues.push(...parseBareSeverity(text, baseStage)); } else if (/^sdcc$|^sdasz80$|^sdasgb$|^sdld$|^mcpp$/.test(baseStage)) { // SDCC family: sdcc / sdasz80 / sdasgb / sdld / mcpp. Some diagnostics use // the cc65-style `file:line: Error: msg`; SDCC's frontend ALSO emits a @@ -65,10 +69,9 @@ export function parseBuildLog(log) { // Tag everything with the (possibly empty) actual stage name so an // assembler error doesn't mistakenly report as "asar" on a non-SNES // build. - // Try EVERY parser - some toolchains (vasm genesis-asm) emit no - // "--- stage ---" marker, so the whole log lands here unnamed; if we skip - // a parser the error is silently swallowed (issues[] empty on a real - // failure). Include vasm + sdcc + wla, which the old fallback omitted. + // Try EVERY parser - a toolchain that emits no "--- stage ---" marker + // lands here unnamed; if we skip a parser the error is silently + // swallowed (issues[] empty on a real failure). const tag = baseStage || "unknown"; issues.push(...parseCc65Like(text, tag)); issues.push(...parseLd65Linker(text, tag)); @@ -76,7 +79,6 @@ export function parseBuildLog(log) { issues.push(...parseDasm(text)); issues.push(...parseAsar(text, tag)); issues.push(...parseRgbds(text, tag)); - issues.push(...parseVasm(text)); issues.push(...parseWla(text, tag)); issues.push(...parseGnuToolchain(text, tag)); } @@ -89,7 +91,7 @@ export function parseBuildLog(log) { // banners (wlalink prints a 26k-line dump full of them) from being mistaken // for our markers and splitting the real error away from its stage. const KNOWN_STAGE_RE = - /^(cc65|ca65|ld65|dasm|asar|rgbasm|rgblink|rgbfix|vasm|sdcc|sdasz80|sdasgb|sdld|mcpp|tcc-65816|wla-65816|wla|wlalink|wladx|gcc|cc1|as|ld|objcopy|m68k|sjasm|bintos|tcc)\b/i; + /^(cc65|ca65|ld65|dasm|asar|rgbasm|rgblink|rgbfix|m68k-as|sdcc|sdasz80|sdasgb|sdld|mcpp|tcc-65816|wla-65816|wla|wlalink|wladx|gcc|cc1|as|ld|objcopy|m68k|sjasm|bintos|tcc)\b/i; function splitByStage(log) { // Markers like "--- ca65 ---" OR with parenthesized args like @@ -425,23 +427,15 @@ function parseWla(text, stage = "wla") { return out; } -// vasm example: -// error 22 in line 5 of "/work/main.s": ... -// warning 1003 in line 8 of "main.s": ... -// fatal error 13 in line 1 of "/work/main.s": could not open for input -// (← a MISSING incbin asset: the #1 thing an agent forgets to pass) -function parseVasm(text) { +// Location-less diagnostics: a line that is just "error: message" or +// "warning: message" (the m68k-as link stage reports overlapping org blocks +// this way). +function parseBareSeverity(text, stage) { const out = []; - const re = /^(?fatal error|error|warning)\s+\d+\s+in\s+line\s+(?\d+)\s+of\s+"(?[^"]+)":\s*(?.+)$/gm; + const re = /^(?error|warning): (?.+)$/gm; let m; while ((m = re.exec(text))) { - out.push({ - severity: m.groups.sev === "warning" ? "warning" : "error", - file: m.groups.file, - line: parseInt(m.groups.line, 10), - message: m.groups.msg.trim(), - stage: "vasm", - }); + out.push({ severity: m.groups.sev, message: m.groups.msg.trim(), stage }); } return out; } diff --git a/packages/romdev-toolchain-m68k-gcc/package.json b/packages/romdev-toolchain-m68k-gcc/package.json index 784f06f1..6abcfc49 100644 --- a/packages/romdev-toolchain-m68k-gcc/package.json +++ b/packages/romdev-toolchain-m68k-gcc/package.json @@ -1,7 +1,7 @@ { "name": "romdev-toolchain-m68k-gcc", - "version": "0.4.1", - "description": "m68k-elf-gcc toolchain (cc1 / as / ld / objcopy / objdump) + Z80 tools (sjasm/bintos) + the Genesis C library share/ tree (SGDK + minimal runtime) for romdev Genesis C builds + disassembly. WASM.", + "version": "0.4.2", + "description": "m68k-elf-gcc toolchain (cc1 / as / ld / objcopy / objdump) + Z80 tools (sjasm/bintos) + the Genesis C library share/ tree (SGDK + minimal runtime) for romdev Genesis C and assembly builds + disassembly. WASM.", "type": "module", "main": "index.js", "exports": { diff --git a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/README.md b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/README.md index 3c8f6afc..cc51b15f 100644 --- a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/README.md +++ b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/README.md @@ -1,7 +1,7 @@ # Genesis / Mega Drive - quickstart -The compressed version of "everything I had to learn the hard way -building a Genesis ROM with romdev." +The short list of what matters most when building a Genesis ROM in assembly +with romdev. ## Snippets shipped in this directory @@ -16,23 +16,26 @@ building a Genesis ROM with romdev." | `sprite_table.s` | Soft-OAM staging + DMA upload pattern. | | `z80_bootstrap.s` | Z80 sound CPU bring-up + bus protocol. | -Fetch any with `getStarterSnippet({platform:"genesis", name:""})`. -Pull them all at once with `getAllStarterSnippets({platform:"genesis"})`. +Fetch one with +`examples({op:'snippets', platform:'genesis', mode:'get', snippetName:''})`, +list them with `mode:'list'`, or get them all at once with `mode:'getAll'`. +`examples({op:'copySnippets', platform:'genesis', destinationDir})` copies them +into a project. -## The five gotchas that cost the most time +## Five common mistakes -### 1. vasm Motorola syntax: NO SPACES after commas +### 1. Motorola syntax: whitespace ends the operand field ```asm -move.w #$2700, sr ; ERROR: "number or identifier expected" move.w #$2700,sr ; OK +move.w d0,d1 copy it ; OK: everything after the operands is a comment +dc.w 1 + 2 ; assembles dc.w 1 - " + 2" is a comment ``` -vasm's Motorola syntax tokenizer treats the space as terminating the -operand. This applies to ALL multi-operand instructions: `move`, `add`, -`movem`, `lea`, etc. The starter snippets in this directory are all -no-space; don't add spaces when editing them even if your editor -auto-formats. +In Motorola syntax the operand field ends at the first space or tab, and the +rest of the line is a comment. A space right after a comma is skipped +(`move.w #$2700, sr` works), but a space anywhere else inside an operand or +expression cuts it short. Write expressions without spaces: `dc.w 1+2`. ### 2. WRAM variables: use `equ`, not `org` @@ -44,15 +47,15 @@ my_var equ $00FF0000 ; GOOD: pure compile-time constant ; CPU writes here at runtime; no ROM space used ``` -The "your ROM is 16 MB and will not fit on a cart" surprise is one of -the top three Genesis-newbie mistakes. See `wram.s` for the full pattern. +A ROM that comes out at 16 MB is the usual symptom. See `wram.s` for the full +pattern. ### 3. Header byte counts: notes field is 32 bytes, NOT 40 Several online references claim the "notes" field at $1D0 is 40 bytes. It is 32. ($1D0-$1EF, with region at $1F0-$1FF.) If you size it as -40, region overlaps your code section at $200 and vasm yells -"sections must not overlap." `header.s` has the authoritative layout +40, region overlaps your code section at $200 and the build fails with +"org blocks overlap." `header.s` has the authoritative layout in a prominent comment at the top. ### 4. VDP control reads: bit 3 of LOW byte, address $C00005 @@ -73,14 +76,13 @@ add.w d0, total_lines ; OK The 68000's instruction set requires at least one operand of most arithmetic ops to be a register (D0-D7 or A0-A7). Coming from cc65 or -asar (where memory-to-memory is sometimes legal) this catches you. -The "instruction not supported on selected architecture" error from -vasm is technically correct but cryptic - it means "this addressing- -mode combination is invalid for the 68000," not "your CPU is too old." +asar (where memory-to-memory is sometimes legal), this is easy to miss. +An "operands mismatch" error from the assembler means "this addressing-mode +combination is invalid for the 68000," not "your CPU is too old." ## Build + iterate workflow -The fastest loop (works for most Genesis dev): +The fastest loop for most Genesis work: ```js build({ @@ -92,8 +94,7 @@ build({ }) ``` -Returns build status + final screenshot in one call (~500 ms cold, -faster after the core is warm). +Returns the build status and a final screenshot in one call. For multi-file projects use the `sources` map: @@ -140,18 +141,18 @@ start (see `catalog({op:'categories'})` for the map): | `memory({op:'read', region:"genesis_z80_ram"})` | 8 KB Z80 sound CPU RAM | | `state({op:'dump', path})` | Full savestate blob for forensic inspection | -Pair `frame({op:'screenshot', overlayBoxes:true})` with `sprites({op:'inspect'})` for -"is the GPU rendering sprites where I think they are" visual debugging. +Compare `sprites({op:'inspect'})` with `frame({op:'screenshot'})` to check that +sprites render where the game places them (the screenshot `overlayBoxes` option +is NES and SNES only). ## ROM file extension -Default convention in this MCP: `.gen`. Genesis frontends -(Batocera, ES-DE, RetroBat, RetroPie, ROCKNIX) all accept `.gen`, -`.md`, `.bin`, `.smd`. `.gen` is unambiguous in 2026: `.md` collides -with markdown, `.bin` is generic, `.smd` implies a header format -we do not emit. +romdev writes `.gen` by default. Genesis frontends (Batocera, ES-DE, +RetroBat, RetroPie, ROCKNIX) all accept `.gen`, `.md`, `.bin` and `.smd`. +`.gen` is unambiguous: `.md` collides with Markdown, `.bin` is generic, and +`.smd` implies an interleaved header format romdev does not emit. -## Open question: live Z80 driver state +## Limitation: live Z80 driver state The YM2612 + Z80 sound CPU state is not currently as deeply introspectable as the SNES SPC700 + DSP - YM2612 in particular diff --git a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/c/sega.s b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/c/sega.s index 62afa121..547689c2 100644 --- a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/c/sega.s +++ b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/c/sega.s @@ -38,8 +38,8 @@ _rom_header: .ascii "SEGA MEGA DRIVE " | $100..$10F system name .ascii "(C)ROMDEV 2026.MAY" | $110..$121 copyright .byte 0,0 | $122..$123 pad - .ascii "ROM-DEV-MCP C BUILD " | $124..$153 domestic title (48 chars) - .ascii "ROM-DEV-MCP C BUILD " | $154..$183 overseas title (48 chars) + .ascii "ROMDEV C BUILD " | $124..$153 domestic title (48 chars) + .ascii "ROMDEV C BUILD " | $154..$183 overseas title (48 chars) .ascii "GM ROMDEV-01-00" | $184..$192 serial number (game id + revision) .byte 0,0 | $193..$194 checksum (patched later) .ascii "J " | $195..$1A4 device support (joypad) diff --git a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/header.s b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/header.s index 3eec6f1b..ff1694e1 100644 --- a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/header.s +++ b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/header.s @@ -7,9 +7,8 @@ ; isn't). ; ; Fields below are positional and must be the exact byte counts shown. -; vasm68k pads strings to their declared length with spaces if you use -; .ascii "..." inside a fixed area, but it's safer to space-pad manually -; to avoid subtle off-by-ones. +; dc.b "..." emits exactly the characters you write, so space-pad every +; string to its field width by hand. org $00000000 @@ -50,9 +49,9 @@ vector_table: ; $1D0-$1EF notes (32) ← NOT 40 ; $1F0-$1FF region (16) ; -; A label at _header_end (= $200) below would catch any miscount via -; vasm's section-overlap detection (gives a more readable error than -; "instruction at $1F8 collides with code at $200"). +; Each org starts a new block, and the build refuses blocks that overlap +; ("org blocks overlap"), so a header that runs past $200 into the code +; block is caught at build time. org $00000100 dc.b "SEGA MEGA DRIVE " ; $100 system name (16) dc.b "(C)YOU 2026.JAN " ; $110 copyright (16) diff --git a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/nmi_safe.s b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/nmi_safe.s index 356e97cd..5df0b3d6 100644 --- a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/nmi_safe.s +++ b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/nmi_safe.s @@ -10,7 +10,7 @@ ; ; Critical gotchas this skeleton handles: ; -; 1. **The vector table at $00-$0FF points at handlers.** vasm68k will +; 1. **The vector table at $00-$0FF points at handlers.** The assembler will ; happily build a ROM with random garbage at vector $78 (VINT vector) ; if you forget; the CPU will then jump to garbage on the first VBlank. ; See header.s for the vector table. diff --git a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/sgdk/libmd.seed.a b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/sgdk/libmd.seed.a index 6710549d..1e2487e8 100644 Binary files a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/sgdk/libmd.seed.a and b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/sgdk/libmd.seed.a differ diff --git a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/wram.s b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/wram.s index 43005af6..a69da65b 100644 --- a/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/wram.s +++ b/packages/romdev-toolchain-m68k-gcc/share/genesis/lib/wram.s @@ -3,7 +3,7 @@ ; Genesis has 64 KB of work RAM at $00FF0000-$00FFFFFF. To use it for ; game variables, you declare LABELS at addresses in that range. ; -; ** DO NOT use `org` for WRAM. ** vasm pads the ROM out to the +; ** DO NOT use `org` for WRAM. ** The build pads the ROM out to the ; highest `org` it sees, so `org $00FF0000` produces a 16 MB ROM file ; mostly full of zeros, and the variables you "wrote" there aren't ; actually stored anywhere - they're just labels pointing into space diff --git a/packages/romdev-toolchain-mips-gcc/README.md b/packages/romdev-toolchain-mips-gcc/README.md index f2a569f6..5e585f5b 100644 --- a/packages/romdev-toolchain-mips-gcc/README.md +++ b/packages/romdev-toolchain-mips-gcc/README.md @@ -1,8 +1,45 @@ # romdev-toolchain-mips-gcc -The `mips-elf` GCC toolchain (binutils 2.42 + gcc 14.2.0 + newlib 4.4.0) compiled -to WASM, for romdev's **N64** (R4300, big-endian) and **PS1** (R3000, little-endian) -C builds and disassembly. One toolchain emits both endiannesses via `-EB`/`-EL`. +MIPS toolchains compiled to WebAssembly, for romdev's N64 and PS1 work: -Built by `scripts/build-mips-toolchain.sh` (STAGE 1, native) + `build-mips-wasm-tools.sh` -(STAGE 2, WASM). Not vendored - fetched + built from pinned upstream (versions.json). +- **mips-elf gcc 14.2.0 and binutils 2.42** (`cc1`, `mips-elf-as`, + `mips-elf-ld`, `mips-elf-objcopy`, `mips-elf-objdump`): the C builds and + disassembly for N64 (R4300, big-endian) and PS1 (R3000, little-endian). One + toolchain emits both byte orders with `-EB` / `-EL`. +- **mips-linux-gnu binutils 2.46** (`mips-linux-gnu-as`, `-ld`, `-objcopy`, + `-objdump`): the traditional-MIPS ELF tools N64 matching-decompilation + projects assemble, link and objcopy with. The `mips-elf` tools cannot stand + in for them, because their IRIX-compatible ELF output differs byte for byte. + These modules use NODERAWFS (they read and write the real filesystem) and are + driven by romdevtools' `decomp` tool and by `romdev-permuter`. +- **armips** (`wasm/armips.{mjs,wasm}`): the assembler N64 decomp projects + rebuild their RSP microcode with, at the commit those projects pin. + +A binary package for [romdev](https://github.com/monteslu/romdev). The main +`romdevtools` package loads it on demand for `build({platform:'n64'|'ps1'})` +and the `decomp` tool. You normally install `romdevtools` (`npx romdevtools`), +not this package directly. + +## Upstream and license + +- gcc and binutils: GPL-3.0-or-later (the package's `license` field). +- armips (https://github.com/Kingcom/armips): MIT. +- This package contains the compilers, binutils and armips only. The newlib C + library (BSD-style licences) and libgcc (GPL with the GCC Runtime Library + Exception) that N64 and PS1 builds link against ship with romdevtools; + neither places conditions on a compiled ROM. + +The upstream versions and commits are pinned in +`packages/romdevtools/scripts/versions.json` in the romdev repo, and the repo's +`NOTICE` has the full third-party inventory. + +**Built by** (all in `packages/romdevtools/scripts/`): + +- `build-mips-toolchain.sh` (native stage) and `build-mips-wasm-tools.sh` + (WASM stage) for the mips-elf toolchain; +- `build-mips-linux-binutils-wasm.sh` for the mips-linux-gnu binutils; +- `build-armips.sh` with patch `armips-wasm-single-thread.patch` for armips. + +See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-toolchain-mips-gcc/index.js b/packages/romdev-toolchain-mips-gcc/index.js index fc733983..b996109b 100644 --- a/packages/romdev-toolchain-mips-gcc/index.js +++ b/packages/romdev-toolchain-mips-gcc/index.js @@ -2,6 +2,11 @@ // assembler, linker, objcopy, objdump (WASM). Big-endian (N64 R4300) and // little-endian (PS1 R3000) both emit from this one toolchain via -EB/-EL. // emcc emits ESM (EXPORT_ES6=1) so the glue uses .mjs extensions. +// +// Also: mips-linux-gnu binutils (as/ld/objcopy/objdump), the traditional-MIPS +// ELF vectors N64 decomp projects build with. Those are linked with NODERAWFS +// (they work on the real filesystem) and are driven by romdevtools' decomp +// domain from its WASM worker (src/decomp/toolchain.js). import { fileURLToPath } from "node:url"; import path from "node:path"; @@ -14,6 +19,10 @@ export const toolchain = { "mips-elf-ld": { gluePath: path.join(WASM, "mips-elf-ld.mjs") }, "mips-elf-objcopy": { gluePath: path.join(WASM, "mips-elf-objcopy.mjs") }, "mips-elf-objdump": { gluePath: path.join(WASM, "mips-elf-objdump.mjs") }, + "mips-linux-gnu-as": { gluePath: path.join(WASM, "mips-linux-gnu-as.mjs"), fs: "noderawfs" }, + "mips-linux-gnu-ld": { gluePath: path.join(WASM, "mips-linux-gnu-ld.mjs"), fs: "noderawfs" }, + "mips-linux-gnu-objcopy": { gluePath: path.join(WASM, "mips-linux-gnu-objcopy.mjs"), fs: "noderawfs" }, + "mips-linux-gnu-objdump": { gluePath: path.join(WASM, "mips-linux-gnu-objdump.mjs"), fs: "noderawfs" }, }; export const wasmDir = WASM; diff --git a/packages/romdev-toolchain-mips-gcc/package.json b/packages/romdev-toolchain-mips-gcc/package.json index 27649e13..746d9ea1 100644 --- a/packages/romdev-toolchain-mips-gcc/package.json +++ b/packages/romdev-toolchain-mips-gcc/package.json @@ -1,6 +1,6 @@ { "name": "romdev-toolchain-mips-gcc", - "version": "0.1.2", + "version": "0.1.3", "description": "mips-elf-gcc toolchain (cc1 / as / ld / objcopy / objdump) for romdev N64 + PS1 C builds + disassembly, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-toolchain-rgbds/README.md b/packages/romdev-toolchain-rgbds/README.md index 7c8019bd..d3849b9d 100644 --- a/packages/romdev-toolchain-rgbds/README.md +++ b/packages/romdev-toolchain-rgbds/README.md @@ -2,19 +2,21 @@ RGBDS (rgbasm/rgblink/rgbfix) - Game Boy / GBC assembler toolchain, as WebAssembly. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **RGBDS**. +Bundles: **RGBDS**, https://github.com/gbdev/rgbds. **License:** MIT -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the +romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-rgbds.sh` (no patch - built clean). See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-rgbds.sh` (no patches). See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-toolchain-rgbds/package.json b/packages/romdev-toolchain-rgbds/package.json index 4dd08112..68392d03 100644 --- a/packages/romdev-toolchain-rgbds/package.json +++ b/packages/romdev-toolchain-rgbds/package.json @@ -1,6 +1,6 @@ { "name": "romdev-toolchain-rgbds", - "version": "0.1.2", + "version": "0.1.3", "description": "RGBDS toolchain (rgbasm / rgblink / rgbfix) for romdev Game Boy dev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-toolchain-sdcc/README.md b/packages/romdev-toolchain-sdcc/README.md index b387973e..45587c2a 100644 --- a/packages/romdev-toolchain-sdcc/README.md +++ b/packages/romdev-toolchain-sdcc/README.md @@ -1,23 +1,33 @@ # romdev-toolchain-sdcc -SDCC (sdcc/sdasz80/sdasgb/sdld/mcpp) - Z80/SM83 C compiler, plus its target share -tree, as WebAssembly. Also ships the native **z80-elf binutils** -(as/ld/objcopy/objdump) that power Z80 + SM83 `disassembleRom` and byte-exact -`disassembleProject` - one z80-elf serves both `-m z80` and `-m gbz80`. +SDCC (`sdcc`, `sdasgb`, `sdasz80`, `sdld`, `mcpp`), the Z80 and SM83 C compiler, +plus its target share tree, as WebAssembly. The package also ships z80-elf GNU +binutils (`as`, `ld`, `objcopy`, `objdump`), which serve Z80 and SM83 +disassembly for `disasm({target:'rom'})` and byte-exact +`disasm({target:'project'})`. One z80-elf build covers both `-m z80` and +`-m gbz80`. -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. +A binary package for [romdev](https://github.com/monteslu/romdev). It ships the +prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on +demand. You normally install `romdevtools` (`npx romdevtools`), not this package +directly. -## Upstream & license +## Upstream and license -Bundles: **SDCC**, **GNU binutils** (z80-elf target). +Bundles: **SDCC 4.4.0** (https://sdcc.sourceforge.net) and **GNU binutils +2.42** (z80-elf target). -**License:** SDCC: GPL-2.0-or-later (runtime libraries: GPL with linking exception - does not encumber compiled ROMs). binutils: GPL-3.0. +**License:** SDCC: GPL-2.0-or-later; its runtime libraries are GPL with a +linking exception, so linking them does not place conditions on a compiled +ROM. binutils: GPL-3.0-or-later. -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. +This package redistributes the upstream source built to WebAssembly. The +upstream versions are pinned in `packages/romdevtools/scripts/versions.json` in +the romdev repo, and the repo's `NOTICE` has the full third-party inventory. -**Built by:** `romdevtools/scripts/build-sdcc.sh + build-z80-binutils-wasm.sh`, with `scripts/patches/sdcc-sdasgb-32bit-addresses.patch` (sdasgb links with 32-bit addresses, so all 512 MBC5 banks work). See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. +**Built by:** `packages/romdevtools/scripts/build-sdcc.sh` and +`build-z80-binutils-wasm.sh`, with `scripts/patches/sdcc-sdasgb-32bit-addresses.patch` +(sdasgb links with 32-bit addresses, so all 512 MBC5 banks work) and +`scripts/patches/sdcc-c1mode-debug-info.patch`. See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-toolchain-sh-gcc/README.md b/packages/romdev-toolchain-sh-gcc/README.md index f655d9b5..ff5f8470 100644 --- a/packages/romdev-toolchain-sh-gcc/README.md +++ b/packages/romdev-toolchain-sh-gcc/README.md @@ -1,13 +1,26 @@ # romdev-toolchain-sh-gcc -The `sh-elf` GCC toolchain (gcc 14.2.0 + binutils 2.42 + newlib 4.4.0) compiled to -WebAssembly, for romdev **Sega Dreamcast (SH-4)** C builds and disassembly. +The sh-elf gcc toolchain (gcc 14.2.0, binutils 2.42) compiled to WebAssembly, +for romdev's Sega Dreamcast (SH-4) C builds and disassembly. -Ships `cc1` (the C frontend), `sh-elf-as`, `sh-elf-ld`, `sh-elf-objcopy`, and -`sh-elf-objdump` as Emscripten ESM modules. The SH-4 is little-endian with -`m4-single-only` floating point; one toolchain emits all Dreamcast code. +It ships `cc1` (the C front end), `sh-elf-as`, `sh-elf-ld`, `sh-elf-objcopy` +and `sh-elf-objdump` as Emscripten ES modules. The SH-4 runs little-endian with +`-m4-single-only` floating point, and one toolchain emits all Dreamcast code. -Used by `romdevtools` to drive `build({platform:"dreamcast"})`: cc1 → as → ld produce -an ELF that Flycast's reios HLE BIOS boots directly (no GD-ROM image or firmware). +romdevtools uses it for `build({platform:'dreamcast'})`: cc1, as and ld produce +an ELF that the Flycast core's reios HLE BIOS boots directly, with no GD-ROM +image or firmware. You normally install `romdevtools` (`npx romdevtools`), not +this package directly. -Built from source by `romdevtools/scripts/build-sh-wasm-tools.sh`. +## License + +gcc and binutils: GPL-3.0-or-later. This package contains the compiler and +binutils only. The newlib C library (BSD-style licences) and libgcc (GPL with +the GCC Runtime Library Exception) that Dreamcast builds link against ship with +romdevtools; neither places conditions on a compiled program. + +**Built by:** `packages/romdevtools/scripts/build-sh-wasm-tools.sh` (the native +stage, which also builds newlib 4.4.0 and libgcc, is `build-sh-toolchain.sh`). +See +[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md) +for the recipe-to-package map. diff --git a/packages/romdev-toolchain-sh-gcc/package.json b/packages/romdev-toolchain-sh-gcc/package.json index 2ff69cd9..471ed826 100644 --- a/packages/romdev-toolchain-sh-gcc/package.json +++ b/packages/romdev-toolchain-sh-gcc/package.json @@ -1,6 +1,6 @@ { "name": "romdev-toolchain-sh-gcc", - "version": "0.1.2", + "version": "0.1.3", "description": "sh-elf-gcc toolchain (cc1 / as / ld / objcopy / objdump) for romdev Dreamcast (SH-4) C builds + disassembly, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdev-toolchain-vasm/README.md b/packages/romdev-toolchain-vasm/README.md deleted file mode 100644 index e27177dc..00000000 --- a/packages/romdev-toolchain-vasm/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# romdev-toolchain-vasm - -vasm (m68k, Motorola syntax) - Sega Genesis assembler, as WebAssembly. - -A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the -prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on -demand. You normally install `romdev`, not this package directly. - -## Upstream & license - -Bundles: **vasm**. - -**License:** vasm custom license - "free for any use", including commercial; see upstream. - -This package redistributes the upstream binary built to WebAssembly; the source -is fetched from a pinned upstream commit at build time (see the romdev repo's -`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the -full third-party inventory. - -**Built by:** `romdevtools/scripts/build-vasm68k.sh` (no patch - built clean). See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map. diff --git a/packages/romdev-toolchain-vasm/index.js b/packages/romdev-toolchain-vasm/index.js deleted file mode 100644 index b252714b..00000000 --- a/packages/romdev-toolchain-vasm/index.js +++ /dev/null @@ -1,14 +0,0 @@ -// romdev-toolchain-vasm - binary package: vasm m68k assembler -// (Motorola syntax, Genesis dev), bundled as WASM. -// Exports absolute paths to the bundled WASM so romdev's resolver can load -// it via the package. -import { fileURLToPath } from "node:url"; -import path from "node:path"; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const WASM = path.join(__dirname, "wasm"); - -// Assembler toolchain - vasm68k. -export const toolchain = { - vasm68k: { gluePath: path.join(WASM, "vasm68k.js") }, -}; diff --git a/packages/romdev-xgm2/README.md b/packages/romdev-xgm2/README.md index b03e311c..60043fbe 100644 --- a/packages/romdev-xgm2/README.md +++ b/packages/romdev-xgm2/README.md @@ -41,8 +41,8 @@ const c = emitC(blob, "bgm_level1"); ## In romdev -`romdev-mcp` wraps this as `encodeAudio({target:'xgm2', vgmPath, name})` - emits -the C array directly. See the Genesis MENTAL_MODEL "music how-to". +romdevtools wraps this as `encodeAudio({target:'xgm2', vgmPath, name})`, which +emits the C array directly. ## Provenance diff --git a/packages/romdev-xgm2/package.json b/packages/romdev-xgm2/package.json index ff855eb5..6d0923d1 100644 --- a/packages/romdev-xgm2/package.json +++ b/packages/romdev-xgm2/package.json @@ -1,7 +1,7 @@ { "name": "romdev-xgm2", - "version": "0.2.1", - "description": "Pure-JS VGM \u2192 XGM2 music converter for Sega Genesis / Mega Drive (SGDK XGM2 driver). A faithful port of SGDK's xgm2tool - no Java, no native binary. Parses a .vgm and emits a compiled XGM2 blob you .incbin into a ROM and play with XGM2_play().", + "version": "0.2.2", + "description": "Pure-JS VGM → XGM2 music converter for Sega Genesis / Mega Drive (SGDK XGM2 driver). A faithful port of SGDK's xgm2tool - no Java, no native binary. Parses a .vgm and emits a compiled XGM2 blob you .incbin into a ROM and play with XGM2_play().", "type": "module", "main": "src/index.js", "exports": { diff --git a/packages/romdev_game_codes/README.md b/packages/romdev_game_codes/README.md index c0c9338c..fa0c3c24 100644 --- a/packages/romdev_game_codes/README.md +++ b/packages/romdev_game_codes/README.md @@ -2,12 +2,13 @@ The bundled game-code / cheat database for [romdev](https://github.com/monteslu/romdev), split into its own package so the -main `romdev-mcp` package stays small and the database can grow and version +main `romdevtools` package stays small and the database can grow and version independently. It is a **data package** - no runtime logic of its own beyond a tiny lazy -loader. `romdev-mcp` depends on it and resolves it at runtime, then reads **one -platform's index at a time** (never the whole DB into memory). +loader. `romdevtools` depends on it, resolves it at run time and reads one +platform's index at a time (never the whole database into memory). It backs +romdevtools' `cheats({op:'lookup'})`. ## What's inside @@ -34,7 +35,8 @@ RetroArch/RetroDECK community cheats tree actually carries: | MSX | `msx` | (C64 has no entry: the community cheats tree ships no Commodore-64 cheat folder. -Raw `ADDR:VAL` pokes via `makeCheat` still work on C64 in romdev.) +Raw `ADDR:VAL` pokes made with `cheats({op:'make'})` still work on C64 in +romdev.) ## API @@ -51,6 +53,6 @@ listPlatforms(); // ["atari2600","atari7800","gb","gba",...] Cheat codes are community-aggregated data from the libretro-database / RetroArch cheats lineage (originally Game Genie code books and GameHacking.org). The index -here is **pre-parsed** (decoded + compacted) by -`romdev/scripts/build-cheat-index.mjs` rather than a redistribution of the raw -`.cht` tree. +here is pre-parsed (decoded and compacted) by +`packages/romdevtools/scripts/build-cheat-index.mjs` in the romdev repo rather +than a redistribution of the raw `.cht` tree. diff --git a/packages/romdev_game_codes/package.json b/packages/romdev_game_codes/package.json index ec548c47..601b92d7 100644 --- a/packages/romdev_game_codes/package.json +++ b/packages/romdev_game_codes/package.json @@ -1,6 +1,6 @@ { "name": "romdev_game_codes", - "version": "0.1.1", + "version": "0.1.2", "description": "Bundled game-code/cheat database for romdev - a pre-parsed per-platform labeled RAM/code map (libretro-database lineage), lazy-loaded one platform at a time.", "type": "module", "main": "index.js", diff --git a/packages/romdevtools/AGENTS.md b/packages/romdevtools/AGENTS.md index 5c0fce2c..8b6a90a0 100644 --- a/packages/romdevtools/AGENTS.md +++ b/packages/romdevtools/AGENTS.md @@ -1,1168 +1,231 @@ # romdev - Agent guide -This is romdev's GENERIC orientation - read it once. The platform-specific detail (memory maps, footguns, debug tooling) lives in each platform's docs, which you fetch on demand with `platform({op:'doc'})` as you work; this doc tells you when. +This is romdev's general orientation. Read it once. Detail lives in docs you fetch on demand with `platform({op:'doc'})`; this guide says which one to read when. ## What this server does -Drives the full homebrew ROM dev loop for 19 retro game platforms (NES, SNES, Game Boy, Game Boy Color, Game Boy Advance, Genesis, Sega Master System, Game Gear, Atari 2600/7800, Atari Lynx, Commodore 64, PC Engine / TurboGrafx-16, and MSX / MSX2, plus the open-hardware GameTank and sync32 - and the 3D consoles Nintendo 64, Sony PlayStation, and Sega Dreamcast) - plus the **PICO-8** fantasy console (via FAKE-08: a Lua VM, so its own tier - `build` PACKAGES a `.p8` from Lua, `disasm({target:'source'})` reads the cart's Lua instead of machine code, `memory({region:'system_ram'})` reads its 64 KB; cpuState/decompile/tile-inspectors are N/A). Build → run → screenshot → inspect → patch → iterate. Also a strong reverse-engineering kit: disassemble existing ROMs into byte-exact rebuildable projects (`disasm({target:'project'})`/`disasm({target:'references'})` - the workhorse for any structural hack), find a value's address with the Cheat-Engine search loop (`memory({op:'search'})`/`memory({op:'searchNext'})`), find the EXACT instruction that wrote a RAM byte (`breakpoint({on:'write'})`, a core-level write watchpoint), confirm a patch is live in the running image (`memory({op:'readCart'})`; add `findHex` to scan the whole cart for a byte pattern with every hit mapped to a CPU address - call-site hunts in one call), bound every instruction that can REACH a RAM byte including near-base indexed forms (`disasm({target:'accessScan'})` - the 'who can write this?' scan, classified read/write/rmw; on a banked cart pass **`banks:[...]`/`excludeBanks:[...]`** to scan only the CODE banks - a DATA bank decodes as fiction that still boundary-verifies, and on 6502 a zero-page target hits constantly inside tile data, so an unfiltered scan can be hundreds of junk sites. The result always carries a **`perBank`** density rollup so you can tell which banks to distrust without reading their rows, and rows are capped **per bank** (`maxSitesPerBank`, default 32) so a flooded bank can't consume the whole budget and truncate away the real hits from the code banks), decode in-game script interpreters from a declarative grammar (`disasm({target:'script'})` - level scripts/spawn lists as structured records, reproducible in the call), tell whether a "found table" is really ASCII (`memory({op:'classify'})`), trace where an on-screen graphic comes from (`watch({on:'copy'})` on the 15 classic platforms - writer PC per VRAM write; `watch({on:'dma'})` for Genesis DMA sources), drive menus by screen-change (`navigate`), and look up cheats (`cheats({op:'lookup'})`/`cheats({op:'search'})`: a free, crowd-sourced labeled RAM/code map for known ROMs), apply + create cheats, convert assets, study patterns from real games. **Doing a romhack? Start with `platform({op:'doc', platform:'romhacking', name:'playbook'})`** - the decision tree that wires all of the above together. Bundled WASM toolchains and emulator cores - no system dependencies, no installs. +romdev runs the whole retro game development and reverse-engineering loop in-process: build, run, screenshot, inspect, debug, patch, disassemble, decompile, recompile, convert assets and drive emulators. Every compiler and emulator core is bundled as WASM. + +- Platforms: 19 consoles and computers (see "Platforms"), plus the PICO-8 fantasy console and two native runtimes (wasmcart, jsgame). +- Homebrew: fork a working example game, edit it, `build({output:'run'})` to build, load, run and screenshot in one call. +- Reverse engineering: byte-exact rebuildable disassembly, value search, write/read/pc breakpoints, coverage, Rizin/Ghidra analysis and decompilation, cheat lookup, ROM patching and asset re-injection. +- Static recompilation: turn a NES, SNES, Game Boy, GBA, SMS/GG or Genesis ROM into a wasmcart and verify it against the reference core. +- Matching decompilation: recover C that compiles to the original bytes with the project's original compiler, run as WASM. + +You drive the work. The human directs: they may want a game, a disassembly, a romhack, a recompile, or anything else here. + +### Where the detail lives + +| Read | When | +|---|---| +| `platform({op:'doc', platform, name:'mental_model'})` | Before writing code or doing RE on a platform: memory map, video chip, input, build pipeline, footguns, debug regions. | +| `platform({op:'doc', platform, name:'troubleshooting'})` | The moment something on that platform is broken. | +| `platform({op:'doc', platform, name:'upstream_sources'})` | Where the bundled library and compiler sources are. | +| `platform({op:'doc', platform:'n64', name:'decomp'})` | Matching decompilation. | +| `platform({op:'doc', platform:'romhacking', name:'playbook'})` | Before any romhack or RE task: the decision tree and per-asset round trips. | +| `platform({op:'doc', platform:'guide', name:'recompile'})` | Static recompilation and its verification ops. | +| `platform({op:'doc', platform:'guide', name:'debugging'})` | Per-platform inspector coverage, memory/state tools, symbol-aware reads, input mapping, save states. | +| `platform({op:'doc', platform:'guide', name:'assets'})` | Art, tilemaps, sprite capture, audio formats, cross-platform moves. | +| `platform({op:'doc', platform:'guide', name:'music'})` | Where to get music and how to turn it into platform data. | +| `platform({op:'doc', platform:'guide', name:'wasmcart'})` | wasmcart carts: ABI, input, WebGPU, `presentWindow`, the `wasm` tool. | +| `platform({op:'doc', platform:'guide', name:'bezels'})` | Active Bezels (`.ab` companions that composite over a game). | +| `platform({op:'doc', platform:'guide', name:'sessions'})` | Sessions, eviction, many agents on one server, the playtest window, the livestream, feedback. | -You drive the work. The human is a director - they may want a game, a ROM disassembly, a tool-assisted reverse-engineering session, or anything else this server can do. +`platform({op:'docs', platform})` lists what a platform ships; `platform({op:'docs', platform:'guide'})` lists the guides. -## The one hard rule: NEVER install a compiler or emulator. romdev bundles every one. +## The one hard rule: never install a compiler or emulator + +You never need, and must never install, a compiler or emulator to build or run a ROM here. Every compiler, assembler and linker (cc65, sdcc, gcc and binutils for m68k/arm/mips/sh, tcc, wla, rgbds, asar, dasm), every SDK (SGDK, PVSnesLib, libtonc/libgba, cc65 libs) and every emulator core is bundled as WASM and runs through these tools: `build`, `loadMedia`, `frame`, the inspectors, `playtest`. + +If a compiler or emulator install is invoked or prompted (`clang`, `gcc`, Xcode or Command Line Tools, `node-gyp`, devkitPro, `brew`/`apt install `), that is a defect. Do not install it, do not investigate it with host commands, and report it ("romdev should provide this"), for example with `feedback({op:'record'})`. `platform({op:'list'})` and `platform({op:'toolchains'})` show what is bundled. + +- Native addons (the playtest window's `@kmamal/sdl`) ship prebuilt. A compile kicking off means the prebuilt is missing: do not let it compile. `playtest` self-heals by downloading the binary, or fails with `reason:"sdl-binary-missing"` and a one-line `fixCommand`. +- Content tools are fine: ImageMagick, GIMP, LibreSprite/Aseprite, Audacity, Tiled, a tracker, a quick art script. They make source PNGs, `.wav`, `.tmx`; romdev imports and packs them (see the assets guide), and often does the whole conversion itself. +- romdev itself is JavaScript and WASM only and never runs Python, make or git on the host. -Internalize this above all else: **you never need - and must never install - a compiler or an emulator to build or run a ROM here.** Every compiler/assembler/linker (cc65, sdcc, gcc, tcc, wla, rgbds, vasm, m68k-gcc, arm-none-eabi-gcc, ...), every devkit/SDK (SGDK, PVSnesLib, libtonc/libgba, cc65 libs, ...), and every emulator core (fceumm, snes9x, gpgx, gambatte, mGBA, handy, vice, prosystem, stella, ...) is **already bundled as WASM** and runs in-process through these MCP tools. The whole build → link → run → inspect loop is `build({output:'rom'})` / `build({output:'run'})` / `build({output:'project'})` / `loadMedia` / `frame({op:'screenshot'})` / `inspect*` / `playtest` - never a host `gcc` or a downloaded toolchain. +Matching decompilation also uses the original compiler as WASM. `decomp({op:'setup', root})` runs a fresh checkout's own setup and extract goals in-process (splat as the JS port romdev-splat at the versions the project pins), and `decomp({op:'import'})` registers it. Compiles use the flags the project's Makefile chooses per file (romdev reads the Makefile). Supported compilers: IDO 5.3/7.1, KMC gcc 2.7.2, EGCS 1.1.2, PS1 gcc 2.6.3 with maspsx, mips-linux-gnu gcc 14, with mips-linux-gnu binutils, armips and a JS asm-processor. IDO is SGI's proprietary compiler and is not shipped: build it with `scripts/build-ido.sh` from a romdev source checkout, or point `ROMDEV_IDO_DIR` at your build. A build step with no WASM/JS equivalent (a Python asset packer) is never run on the host: its existing output is kept and reported in `keptPrebuilt`. -**So if a build toolchain or emulator is ever invoked or prompts to install - `clang`, `gcc`, Xcode / macOS Command Line Tools, `node-gyp`, devkitPro, `brew/apt install ` - that is a DEFECT, not your cue to proceed.** Stop, do NOT install it, do NOT investigate it with host-side diagnostic commands (that just alarms the user), and surface it: "romdev should provide this - a host compiler/emulator should never be needed." Then find the romdev tool or report the gap. `platform({op:'list'})` / `platform({op:'toolchains'})` show what's bundled. +## The second rule: read your platform's docs before writing code for it -**The one exception is a registered matching-decompilation project.** `decomp({op:'import'})` registers a checkout whose OWN toolchain (an IDO static recompilation, MIPS binutils, the project's make) is the point: recovering C that compiles to the original bytes needs the original compiler, and romdev runs that project's compiler and build as-is, with the flags its Makefile chooses per file. That is user-authorized by the act of registering the project; do not refuse it because of the paragraph above, and do not substitute a romdev WASM toolchain for it. romdev still never installs anything on the machine for you - the project's docs say how its toolchain is set up. +This guide cannot hold 19 platforms of detail. Read `platform({op:'doc', platform, name:'mental_model'})` for every system you build for or reverse-engineer, before writing code. Most "why won't this work" dead ends are a documented footgun there (a C64 game that needs a key to start, an SDCC WRAM-layout trap, a render-enable order, a core that exposes `gb_vram` not `video_ram`). Read `troubleshooting` the moment something breaks, and the romhacking playbook first for any hack. +## Platforms -### Host content tools (art / audio / map editors) are totally fine +| Tier | Platforms | What works | +|---|---|---| +| Classic (15) | NES, SNES, Game Boy, Game Boy Color, GBA, Genesis, Master System, Game Gear, Atari 2600, Atari 7800, Atari Lynx, C64, PC Engine, MSX/MSX2, GameTank | Build, run, inspect, sound and music, forkable genre examples, write/read/pc breakpoints, single-step, coverage, byte-exact disassembly projects, re-inject tools, mental model and troubleshooting docs. | +| sync32 | an open RP2350-based console (Cortex-M33, `.s32`) | C carts against a function-pointer ABI, WASM toolchain, memory/cpu/palette inspection, five genre examples, cycle profiling. No PPU, OAM or tilemap. | +| 3D consoles | Nintendo 64, PlayStation, Dreamcast | Build and run examples (GPU-rendered cores), disassembly, Rizin/Ghidra analysis, memory tools; N64 breakpoints and single-step; matching decompilation projects. | +| Fantasy console | PICO-8 (FAKE-08) | `build` packages a `.p8` from Lua; `disasm({target:'source'})` reads the cart's Lua; `memory({region:'system_ram'})` is its 64 KB. CPU and tile inspectors do not apply. | +| Native runtimes | wasmcart, jsgame | Load, step, screenshot, input, `frame({op:'verify'})`, the `wasm` tool, `pack`. | -This rule is about **compilers and emulators only** - NOT about content tools. ImageMagick, GIMP, Aseprite/LibreSprite, Audacity, Tiled, a tracker (FamiStudio/Deflemask), Python for a quick art script - all fine to use, and fine for the user to install. They produce **raw source art/audio** (a PNG, a sprite sheet, a `.wav`, a `.tmx`); romdev then **imports and packs** that into platform-native data. Use them freely when they help; just don't reach for a *compiler or emulator*. +Genre examples (`shmup`, `platformer`, `puzzle`, `sports`, `racing`) ship for every classic platform except the Atari 2600, which has four (no `puzzle`: the TIA has no tilemap for a match-3 board), and for sync32, GameTank, PICO-8, N64, PlayStation and Dreamcast. The platformer side-scrolls with a hardware camera everywhere except NES and the Atari 2600, which are single-screen. Classic platforms also ship a music demo (`music_demo`) on the de-facto engine (FamiTone2, hUGEDriver, an SPC700 driver, XGM2, maxmod, PSG trackers, a SID sequencer, `lynx_snd_play`, TIA; PC Engine and MSX as `music_sfx`, plus `sprite_move`/`catch_game` projects). -## The second rule: READ YOUR TARGET PLATFORM'S DOCS BEFORE YOU WRITE CODE FOR IT +`platform({op:'list'})` is the live matrix with language defaults and quirks (`platform` filters to one row, `slim:true` drops prose). C is the default wherever a C compiler is bundled; asm-only platforms default to asm; pass `language` to override. Platform-specific inspectors, regions and traps are in each mental model; the debugging guide has the coverage matrix. -This doc is deliberately GENERIC - it can't hold 19 platforms' worth of detail without bloating every session. The knowledge that actually saves you - the memory map, the input/control quirks, the render-enable order, the codegen traps, the SDK's footguns - lives in each platform's docs, read on demand: +## Tools -- **`platform({op:'doc', platform, name:'mental_model'})`** - read this for EVERY system you're about to build or RE on, BEFORE you write code. It's a couple hundred tokens and most "why won't this work" dead-ends are a documented footgun you'd have seen there (a C64 game that needs a keyboard key to start; an SDCC WRAM-layout trap; a platform's render-enable order; gambatte exposing `gb_vram` not `video_ram`). -- **`platform({op:'doc', platform, name:'troubleshooting'})`** - the symptom→fix list; read it the moment something's broken. -- **`platform({op:'doc', platform:'romhacking', name:'playbook'})`** - read FIRST if you're doing a romhack/RE (the cross-platform decision tree). +All 38 tools are registered at session start; call any by name. Each is a verb with an operation axis. `catalog({op:'categories'})` maps them by purpose; `catalog({op:'status'})` re-orients a session (what is loaded, version, health, play and bezel state). -Skipping this is the #1 avoidable time-sink. If you find yourself flailing on platform behavior and you haven't read that platform's `mental_model`, stop and read it - the answer is almost always there. +| Tool | Axis and values | +|---|---| +| `catalog` | `op`: categories, status | +| `platform` | `op`: list, capabilities, resolve, toolchains, docs, doc | +| `examples` | `op`: list, fork, show, snippets, copySnippets | +| `build` | `output`: rom, romWithDebug, run, project, reassemble | +| `loadMedia` | load a ROM, disk, tape, program or cart (`path` or `base64`; `slot:'b'`, `core`, `firmware`, `cheats`, `coreOptions`, `useActiveBezel`, wasmcart options) | +| `host` | `op`: unload, shutdown, reset (`hard:true` power-cycles), pause, resume, play, stop | +| `frame` | `op`: step, screenshot, stepAndShot, sideBySide, compareRam, findDiverge, compareRender, portStatus, stepInstruction, stepInstructions, traceInstructions, verify, verifyRecompile, fuzzRecompile, cycles | +| `input` | `op`: set, press, sequence, timeline, navigate, layout, pressKey, typeText, joyport, pointer, wheel | +| `state` | `op`: save, load, list, export, dump, diff, exportSram, importSram, exportDisk, importDisk, putDiskFile, autoSnapshot, recoverSnapshot | +| `memory` | `op`: read, write, readCart, regions, snapshot, diff, diffRuns, classify, search, searchUnknown, searchNext, provenance | +| `symbols` | `op`: resolve, lookup, map, list, addr, analyze | +| `disasm` | `target`: bytes, rom, range, project, references, cfg, xrefs, functions, reachable, decompile, source, resolveJumptable, pointerTable, recompile, script, accessScan, sourceLookup | +| `breakpoint` | `on`: write, read, pc, jumptable | +| `watch` | `on`: mem, range, pc, dma, copy | +| `cpu` | `op`: read, setReg, call, decompress | +| `runUntil`, `recordSession` | step until a memory or framebuffer condition; record a timeline of screenshots and memory samples | +| `sprites` | `op`: inspect, group, preview, capture, render, emitC, extractScreenshot | +| `tiles` | `op`: png, pixels, fingerprints, ascii, preview | +| `background` | `view`: map, renderState, rendered | +| `palette` | `source`: live, platformMaster, lospec | +| `videoDebug`, `audioDebug` | VDP state (`chip:'vdp'`); audio chip state and traces (`op`: inspect, record) | +| `encodeArt`, `importArt` | `stage`: quantize, crop, tiles, tilemap, validate; `from`: aseprite, gif, texturepacker, tiled, rom | +| `encodeAudio` | `target`: brr, xgm2pcm, xgm2, maxmod, famitone, spc, gg, sms, c64, lynx, atari7800, gb, gbc, sync32, sync32pcm | +| `romPatch` | `op`: write, writeMany, spliceCHR, relocate, makeStored, findFree, findPointer, diff, gbHeader | +| `assembleSnippet` | assemble a few instructions to bytes at an origin (6502, 65816, 68k, Z80, SM83, HuC6280) | +| `cart` | `op`: identify, extract, wrap, packDisk | +| `cheats` | `op`: lookup, search, apply, remove, clear, make | +| `text` | `op`: learn, encode, find (custom-font text) | +| `wasm` | `op`: conformance, info, exports, debugState, events, read, write, save, command | +| `pack` | `target`: wasc, jsgame | +| `playtest` | `op`: open, stop, status, framebuffer, fps, bezel | +| `regression` | `op`: capture, check (golden checkpoint runs) | +| `decomp` | matching decompilation, about 45 ops (see "Matching decompilation") | +| `files` | `op`: read, write, list | +| `feedback` | `op`: record, list | -### romdev also packs assets in-server - reach for these first +## Making a game: fork an example, then iterate -Asset conversion is bundled too, so you often don't need the host tools at all. First-class tools: `encodeArt({stage:'tiles'})`, `encodeArt({stage:'tilemap'})`, `encodeArt({stage:'quantize'})`, `palette({source:'platformMaster'})`, `palette({source:'lospec'})`, `encodeArt({stage:'validate'})`, the loaders `importArt({from:'texturepacker'})` / `importArt({from:'aseprite'})` / `importArt({from:'gif'})` / `importArt({from:'tiled'})`, and helpers like `sprites({op:'capture'})` / `importArt({from:'rom'})`. The canonical quantize→tile→pack path lives here. Typical flow: paint pixels in a host editor (or generate a PNG), then `encodeArt({stage:'quantize'})` → `encodeArt({stage:'tiles'})` to get platform-native tiles. (You can do the whole thing in-server too when the art is procedural.) +Never start from a blank file. Fork the example whose core loop is nearest your game (even for a very different game), then change one thing at a time and re-run `build({output:'run'})`. Retro bring-up is a long chain of fragile hardware init with no partial credit; a working game is your regression oracle. -### Native-addon prompts are a packaging bug - never compile on the host +1. `examples({op:'list', platform?})`: every example with its kind (`game` or minimal `reference` such as `default`, `hello_sprite`, `tile_engine`), mechanics, hardware techniques, players and SRAM, plus genre-to-nearest-fork guidance. +2. `examples({op:'fork', example:'/', name, path, title?, overwrite?})`: copies the example into a new directory as your game (sources, runtime files, crt0, linker config, vendored library source, README, `.gitignore`), renamed throughout. It builds before you change a line. The response lists the files you edit plus `vendorFileCount` (`verbose:true` for the full list). You can pass `platform` + `template` instead of `example`. +3. `build({output:'run', path, platform})` builds the directory, loads it, runs it and returns a screenshot inline. `build({output:'project', path, outputPath})` builds the directory to a ROM. +4. `examples({op:'show', example, file?, technique?})` reads a donor example without forking; `technique` extracts one marked HARDWARE IDIOM block with its dependency header to graft. +5. `examples({op:'snippets', platform, mode:'list'|'get'|'getAll'})` and `examples({op:'copySnippets', platform, destinationDir, include?})` fetch vetted helpers (reset, read_pad, OAM DMA, palette upload); `copySnippets` writes to disk without passing bytes through your context. -A couple of optional features load a native Node addon (most notably the `playtest` SDL window, via `@kmamal/sdl`). These ship **prebuilt** - they must never compile on your machine. If you see a `clang` / Xcode / Command Line Tools / `node-gyp` build kick off while using romdev, the prebuilt binary is missing or mismatched: **do not let it compile, do not install a toolchain - report it.** `playtest` itself self-heals by downloading its prebuilt binary and, if it can't, fails with a `reason:"sdl-binary-missing"` tool error whose message carries the exact one-line `fixCommand` - it never needs a host compiler. +Want a side-scroller? Fork `/platformer`. NES scrolling needs platforms drawn into the nametables plus `ppu_scroll(camX,0)` and column streaming past 512 px; each platformer's `describe` text and the mental model's "Horizontal scrolling" section give the details. -## If a human is watching, open playtest early - -If a human is sitting next to you during this session - and that's most sessions in practice - open the playtest window as soon as your first build succeeds. `playtest()` opens a native SDL window that runs your ROM live and accepts USB gamepads (hot-plugged controllers are picked up automatically). It returns **immediately** - the render loop runs in the background, so you keep calling other tools while the human plays. Every other MCP tool keeps working against that same running ROM, and **`build({output:'run'})`/`loadMedia` rebuilds update the window in place** - the window follows your latest build, no relaunch and no crash on rebuild. A human sitting next to you should be **playing the game** while you iterate, not watching screenshots scroll past. - -**Co-driving is detected for you.** While the human is actively pressing (pad or keyboard), the window's input wins over yours and its real-time loop races your frame-stepping - and you'll KNOW: `frame`/`input` responses carry a `humanCoDriveWarning` while they pressed within the last ~2s, and `catalog({op:'status'})` / `playtest({op:'status'})` expose `humanInputActive`. When the human is idle the window leaves your `input({op:'set'})` alone. For deterministic stepping while they play, either `host({op:'pause'})` (the window keeps rendering, frozen) or use a SECOND session (a different `session` argument - or `x-romdev-session` header over HTTP - = a fully isolated emulator). - -``` -playtest() // opens the SDL window (returns immediately). op:'open' is the default; - // playtest({op:'stop'|'status'|'framebuffer'}) close / check / capture-what-the-human-sees - // playtest({op:'fps', show?}) show/hide the on-screen fps counter (or open with fpsOverlay:true) -``` - -After that, keep iterating with `build({output:'run'})` / `build({output:'rom'})` / memory({op:'read'}) / frame({op:'screenshot'}) exactly as before - they all act on the live emulator the user is playing. Because the window and `frame({op:'screenshot'})` read the **same** live host, what you capture is what the human sees. (If you ever need to be explicit - e.g. to double-check the human's exact frame - `playtest({op:'framebuffer'})` captures the window's framebuffer directly, with `source`/`loadedMediaPath`/`frameCount` metadata.) - -**No gamepad?** `playtest()`'s response includes a `keyboardControls` map and a `tellUser` note when no controller is detected - relay the keys to the human (arrows = D-pad, Z = main action, Enter = START, ESC closes) so they know how to play. - -**The mouse works on pointer carts.** For a wasmcart cart that declares FLAG_POINTER (menus, card games, touch-first games), the window forwards real mouse moves/clicks into the cart's pointer slot 0, mapped through the same letterbox the frame is drawn with - so the human can just click, including after resizing the window. Pad-only carts never see mouse movement. The scroll wheel reaches those carts too (ABI v3.1) - drive it headlessly with `input({op:'wheel', notches})`. - -**Opening a window on a GL wasmcart? Load it with `presentWindow:true`.** A GL cart otherwise has every frame dragged back to the CPU just so SDL can blit it in software - about a third of a frame budget at 1080p spent moving pixels the GPU already had. `loadMedia({platform:'wasmcart', path, presentWindow:true})` lets the window present by GPU blit + swap instead: measured `convertMs` 3.52 → 0, window cost ~7.45 ms → ~2.0 ms on a 1080p 3D cart. - -``` -loadMedia({platform:'wasmcart', path:'/carts/game.wasc', presentWindow:true}) -playtest() // window now presents GPU-direct -``` - -Three things worth knowing: -- **It must be set at LOAD time.** The cart's GL context binds when its wasm loads and cannot be swapped afterwards, so a cart already loaded without the flag keeps the slower path until you reload it. -- **Screenshots are unaffected - by contract.** `frame({op:'screenshot'})` and `playtest({op:'framebuffer'})` return the full cart frame at the cart's resolution, byte-identical to a plain load. Capture dimensions are a function of the CART only: nothing the human does to the window (drag, F11, multi-monitor) changes what you capture. If you ever measure otherwise, that's a bug worth reporting, not something to work around. -- **Skip it for headless work.** It costs one extra GL context per loaded cart and buys nothing when no window is open - the readback path is what you want there anyway. - -**"It feels slow" is a number, not a vibe.** The window's title bar always shows live fps (` | 58 fps`, the rate actually achieved). `playtest({op:'status'})` returns `perf` - rolling `fps` (60 = full speed) and `tickHz`, plus per-stage costs (`stepMs` emulation, `convertMs` framebuffer→RGBA, `presentMs` SDL blit, `audioQueuedMs` queue depth) - so YOU can say where the time goes. When the HUMAN should see the number on screen, `playtest({op:'fps', show:true})` draws a corner counter into the frame (they can also toggle it with F3). - -Skip playtest only when there's clearly no human in the loop: CI runs, automated test suites, batch reverse-engineering, or when the user has explicitly said "headless." `playtest()` needs a desktop session to draw into; if it can't open a window the call FAILS as a tool error (never a success-shaped `opened:false`) and the message tells you exactly how to fix it. Three distinct cases: `reason:"sdl-binary-missing"` means the `@kmamal/sdl` native binary isn't installed (the server tries to self-heal, but if it can't, the message gives a `fixCommand` to run + restart) - a one-time native-addon fix, NOT a display problem. `reason:"no-display"` means SDL came up on the offscreen/dummy driver - no physical screen (headless/SSH; run the server in a terminal inside the desktop session). `reason:"sdl-error"` quotes whatever SDL actually threw - READ the quoted error; the message only suggests the desktop-session fix when the error really names a display/driver problem, otherwise treat the quoted error itself as the fault to report. Either way, every other tool (build, run, screenshot, inspect) is fully headless and unaffected. When in doubt, ask once, then default to opening it. - -## Tool surface: everything is loaded - just call the tool - -**All ~32 tools are registered and callable from session init - there is no loading step.** If you see a tool name anywhere in this doc or via `catalog({op:'categories'})`, you can call it right now. Each tool is a small VERB with an operation axis - `memory({op})`, `build({output})`, `sprites({op})`, `breakpoint({on})`, `cpu({op})` - so the whole surface is a few dozen names, not a few hundred. - -(We used to lazy-load tools behind a `loadCategory` call. It caused more harm than good - agents burned round-trips re-loading categories, and dynamic registration never propagated reliably to clients anyway. The consolidation shrank the surface enough that the entire thing loads up front; the old `loadCategory`/`describeTool` discovery tools are gone.) - -`catalog({op:'categories'})` still exists as a **map of what's available, grouped by purpose** - useful for discovery, not a gate: - -- `platforms` - which platforms + languages are supported -- `run` - load ROMs, step frames, screenshot - `crop:{x,y,w,h}` returns a native-res strip (HUD counters legible at a fraction of the image tokens) - (works for existing ROMs you didn't compile) -- `input` - drive controllers, look up hardware bit layouts. `input({op:'set', ports})` is POSITIONAL: `ports[N]` IS port N (there is no `port` key), and each button is its own boolean (`{a:true, b:true}`, never `{buttons:['a','b']}`). A malformed port object is REJECTED rather than partially applied - a press that silently doesn't happen turns into a false NEGATIVE about the game, which is the most expensive wrong answer this tool can give. `navigate` walks menus by advancing on SCREEN CHANGE (not fixed frames) and reports whether each press was consumed - the fast, reliable way to script a UI. **`input({op:'pointer', x, y, left?, right?, id?, active?})`** is absolute mouse/touch for wasmcart carts that declare FLAG_POINTER: `id` selects the pointer SLOT (0 = mouse, the default; 1-9 = touch fingers - several slots at once is a multi-finger gesture), and `active:false` releases a slot the way a real host does on touchend. Use `id:1+` to test the commonest cart-side portability trap: a cart that polls only pointer[0] works perfectly with a desktop mouse and silently ignores every touch on a phone. **`input({op:'wheel', notches})`** is the scroll wheel (wasmcart ABI v3.1): one click of a detented wheel is `notches:1`, fractions are allowed (`0.25` = a trackpad nudge), and POSITIVE IS UP - the SDL/LOVE convention, not the browser's downward deltaY. `notchesX` scrolls horizontally; `dx`/`dy` are the raw 1/120-notch units if you are asserting exact ABI values. The delta belongs to the NEXT frame stepped and is CLEARED after it, so a wheel call must be followed by a frame step to be observed, and repeated calls before that step ACCUMULATE the way a real trackpad flick does. A zero delta is REFUSED rather than accepted as a no-op - the host already clears the field every frame, so scrolling by nothing can only be a units mistake. -- `state` - savestates and forensic state inspection (`state({op:'save'})`, `state({op:'load'})`, `state({op:'export'})` a slot to disk without touching the live host, `state({op:'list'})`, `state({op:'dump'})`). A restore always CLEARS active cheats - pass **`reapplyCheats:true`** to `state({op:'load'})` and they are snapshotted before the load and re-armed after (`cheatsReapplied[]`), because reading `cheatsCleared:N` does not stop you forgetting to re-arm three calls later. `state({op:'save', path})` records any active cheats in a `.cheats.json` **sidecar** so a rig shared between sessions describes its own requirements instead of relying on prose; the `.state` bytes are unchanged, so existing states keep loading. **`state({op:'autoSnapshot', enabled:true, intervalSeconds:60})`** arms an opt-in periodic background save so an unprompted SERVER RESTART costs a minute instead of the session - captures happen lazily on calls that already touch the host (no timer, nothing while idle), land in a session-scoped temp dir that can never clobber a named slot, and can never fail the call they were protecting. **`state({op:'recoverSnapshot'})`** restores the newest one after a restart. -- `memory` - read/write VRAM/OAM/CGRAM/ARAM and other regions (all 19 platforms). **`memory({op:'regions'})` lists the regions valid for the loaded platform** (generic vs platform-specific) - start there rather than guessing: there are 126 region ids across the cores and the per-platform ones (`sms_cram`, `genesis_cram`, `gba_palette`, `pce_vce_palette`, `msx_palette`, ...) are where the interesting state lives. `memory({op:'read'})` takes `offsets:[...]` to batch scattered reads in one call. **`memory({op:'search'})`/`memory({op:'searchNext'})`** = the Cheat-Engine value-search loop ("find the address of X, narrow as X changes") - relative compares (`inc`/`dec`/`changed`) work as the FIRST narrow (baselines recorded at seed), and `as:'bcd'`/`as:'digits'` search packed-BCD scores and digit-per-byte HUD buffers (any constant tile base) when stored ≠ displayed. **`memory({op:'searchUnknown'})`** is the unknown-initial-value hunt - seed the whole region with no value, then narrow by `dec`/`inc`/`changed` across events (the value you can't read off the HUD). **`memory({op:'readCart'})`** reads the loaded cart image to confirm a patch is live (pass `{cpuAddress, bank}` to read a banked CPU address on NES/SNES). **`memory({op:'classify'})`** says whether bytes look like ASCII/code/tile-data (kills the "found table that's really a string" trap). `memory({op:'snapshot'})` + `memory({op:'diff'})` answer "which bytes changed across this event?" (diff defaults to a clustered summary with stride detection; small clusters carry before/after hex, `minDelta` filters churn, and predicate filters - `changeDir:'inc'|'dec'`, `deltaEq`, `beforeMin/Max`, `afterMin/Max` - keep only the bytes that moved the way you expect; `outputPath`+`echo:false` route the full list to disk); **`memory({op:'diffRuns', portsA, portsB?})`** answers "which byte does this INPUT drive?" in one call (same start state run twice under two inputs, only the divergent bytes return); `state({op:'diff'})` is the coarse whole-machine version. Reads routed to disk take `echo:false` to skip the inline hex. -- `debug` - **`frame({op:'verify'})`** (NO-VISION render-health: one call answers "is the game actually rendering / alive?" on all 15 classic platforms AND the native runtimes (wasmcart/jsgame - pixel scan only, GL carts scanned via the offscreen-GL readback, `render.renderEnabled:null`) - fuses a framebuffer pixel scan with the per-platform render-enable/NMI decode; `{verified:true|false|null, issues[], pixels, render}`, frame-0-guarded so it never cries wolf on boot), `sprites({op:'inspect'})`, `palette({source:'live'})`, `cpu({op:'read'})` (17 of the 19 - MSX and PC Engine have no decoder yet), **`videoDebug({chip:'vdp'})`** (SMS/GG/Genesis: decoded VDP state - mode flags, the name-table / sprite-attribute / sprite-pattern bases multiplied out to real VRAM addresses, scroll, line counter, border; the control latch / status register / VRAM address are NOT exposed by the core and the response says so in `unavailable` rather than omitting them silently - for status-register behaviour use `breakpoint({on:'read'})` on the status port), `audioDebug({op:'inspect'})` (the 13 systems with a sound chip - all but Atari 2600/7800; incl. GameTank's ACP coprocessor via `chip:'acp'`; pass `frames:N` to TRACE a per-channel note-timeline for headless melody asserts), `background({view:'renderState'})`, `breakpoint({on:'write'})` (write watchpoint, all 18; EVERY hit on EVERY platform carries `registersAtHit` - the register file frozen at the hit instant, the only honest read since live regs drift after a hit - and the CPU stays frozen until the hit is cleared), **`watch({on:'dma', precision:'sampled'})`** (Genesis: which ROM offset a VRAM graphic was DMA'd from), **`watch({on:'copy'})`** (the 15 classic platforms: every write landing in a VRAM window logged with the EXECUTING instruction's PC - the generic 'which routine uploads this graphic?'; port-based video memory hooked in-core incl. the SNES DMA path, CPU-mapped VRAM via the range log), **`disasm({target:'bytes'|'rom'|'references'|'project'|'sourceLookup'})`** (`bytes`/`rom`/`references` on all 18, `project` byte-exact reassembly on the 15 classic platforms (incl. GameTank, cc65/6502) - native binutils objdump per CPU, incl. GBA ARM7/Thumb; the byte-exact `disasm({target:'project'})` reassembles through native as/ld/objcopy; banked carts - NES mappers, SNES LoROM, GB MBC, Sega mapper, MSX megaROM, 2600 F8/F6/F4, 7800 SuperGame, >32KB HuCards - are split and reference-scanned PER BANK, refs tagged `prgBank`/`romBank`; `sourceLookup` returns YOUR annotated project source lines for an address range, matched on the emitted address comment - the annotation session's most-repeated nav op; `disasm({target:'source', projectDir, startAddress})` routes here too, so either spelling works, and it matches only a line's OWN address annotation so a data table whose bytes read like the address isn't a false hit), plus the **Rizin/Ghidra RE engine** `disasm({target:'cfg'|'xrefs'|'functions'|'decompile'|'resolveJumptable'})` (ALL 18, incl. the 3D consoles' MIPS R3000/R4300 + SH-4 - control-flow graphs, deep xrefs, auto-detected functions [sorted real-code-first, `looksLikeData` flagged], and Ghidra C pseudocode; quality excellent on GBA/Genesis, rough on 6502; decompile output NAMES hardware registers [`PPUMASK` not `*0x2001`] and on the 6502 family folds SLEIGH clutter to readable C99 [`uint8_t`, `zp_FD`]; `resolveJumptable` resolves computed dispatchers live via `breakpoint({on:'jumptable'})`) + `symbols({op:'analyze'})` (one-shot structural map - pass **`summary:true`** for counts + entrypoints + top functions [~2.5K chars vs the full ~44K table on a 1MB ROM], or **`topN`** to bound the list), `symbols({op})` lookup, `background({view:'rendered'})`, plus **`cheats({op})`** (`cheats({op:'lookup'})` = a free labeled RAM/code map for known ROMs, `cheats({op:'search'})` to fuzzy-find a game by name, `cheats({op:'apply'})`/`cheats({op:'clear'})` non-destructively, `cheats({op:'make'})` to create codes) -- `assets` - convert PNGs to tiles (`encodeArt`/`importArt`), WAVs to BRR, identify ROMs (`cart({op:'identify'})`), plus the hacking toolkit (`romPatch({op})` - write/writeMany/spliceCHR/relocate/makeStored/findFree/findPointer/diff, `assembleSnippet`, `cart({op:'extract'})`, `cart({op:'wrap'})`) -- `project` - the example-game library (`examples`: list / fork / show, plus the legacy snippet ops) -- `show` - `playtest({op})`: `op:'open'` opens the live SDL window for a human, `op:'stop'` closes it, `op:'status'` reports liveness, `op:'framebuffer'` captures exactly what the human's window shows -- `advanced` - `runUntil`, **`watch({on:'mem'|'range'|'pc'})`** (LOG-ALL tracing; for a MULTI-BYTE variable - 16/32-bit distance, score, pointer, timer - set **`as:'u16le'`** (or u16be/u24/u32) on the range: without it the range is diffed per BYTE and a value whose high byte holds steady reports as its low byte alone under the range's label ($05F0 reads as 240, not 1520), while un-annotated multi-byte ranges now carry `byteIndex`/`byteLabel` and a `constantBytes[]` roll for the bytes that never moved. A watch armed while the CPU sits at an un-cleared breakpoint hit misses everything already executed in that frame, so the result carries `armedWhileHalted` - an empty window then isn't a clean negative; `range`/`pc` take **`fromState`**/`fromStatePath` to trace from a restored savestate moment), **`breakpoint({on:'write'})`** (the EXACT instruction that wrote a byte, via a core watchpoint - fixes the frame-sampled-PC problem; runs to END OF FRAME and reports the LAST matching write with `hits`=count; `condition:'increase'|'decrease'|'equals'`+`conditionValue` filters to the MEANINGFUL write - the score going UP, not the per-frame restore churn (core-level on all 19, `oldValueByte` reported); `conditionWidth:16` watches a WORD in the platform's byte order (BE on Genesis) - 'equals' arms the word's high byte, inc/dec compare the word so a carry can't lie; RAM-mirror aliases (SNES $7E low mirror, NES $0800+, GB echo, SMS/GG, Genesis $E0-$FE) are canonicalized at arm time (`armedAddress` echoed); `precision:'sampled'` is the cheap frame-PC version; on a `pressDuring` run pass **`abortIf:[{region,offset,label}]`** to stop early if the driven scenario derails - a guard byte changing returns `{aborted, abortedBy, before, after}` instead of burning all `maxFrames` on a meaningless `found:false`), **`breakpoint({on:'pc'})`** (execution breakpoint - freeze the CPU AT an instruction and read its registers; on a MISS it reports **`mainThreadPc`** - the busiest PC over ~a frame of single-stepping, i.e. the main loop, not the frame-boundary NMI/idle `pcNow` - plus a `pcHistogram`, save-state-wrapped so it has no side effects), **`breakpoint({on:'read'})`** (the EXACT instruction that read a byte), **`breakpoint({on:'jumptable'})`** (RESOLVE a computed-jump dispatcher static analysis can't follow - `JMP (table,X)` / RTS-trick state machines, script/battle VMs: break at the dispatcher, single-step through the indirect transfer, record the COMPUTED targets live across frames/inputs; the varying arms are isolated from fixed trampolines; `disasm({target:'resolveJumptable'})` points here. No static-only tool can do this - it needs the live emulator), **`frame({op:'stepInstruction'})`** (CPU single-step) - all 19 platforms (N64 since romdev-core-parallel-n64 0.3.0: the hook lives in the default cached-interpreter CPU, so `breakpoint({on:'pc'})`, single-step and the PC coverage log are real there); input recording; **`decomp({op})`** - matching decompilation for a registered splat project (import/plan/resolve/generate/compare/search/integrate/progress + trace/coverage/overlays/smoke on a live session; N64 proven, ps1 path implemented but unverified - `platform({op:'doc', platform:'n64', name:'decomp'})`) - -**"Disassemble this NES ROM"** is now just: `disasm({target:'rom', path, startAddress, length})`. No discovery step. - -### Romhacking / reverse-engineering: check `cheats({op:'lookup'})` early - it's a free RAM map - -> **Doing a romhack? Read the playbook first:** `platform({op:'doc', platform:'romhacking', name:'playbook'})` -> - the full decision tree (find a value's address with `memory({op:'search'})`, tell whether -> on-screen text is a string or a pre-rendered bitmap, confirm a patch is live with -> `memory({op:'readCart'})`, drive menus fast with `navigate`, avoid the "found table that's -> really ASCII" trap with `memory({op:'classify'})`). It encodes the traps below so you don't -> rediscover them the hard way. - -When the task is to **modify an existing game**, you have two complementary -entry tools, and which leads depends on the kind of hack: - -- **`cheats({op:'lookup', path})`** - the bundled cheat DB is a crowd-sourced **labeled - memory/code map** for thousands of known ROMs: each RAM cheat is a named address - (`"Infinite Health" → $00CD`), each Game Genie code is a named code site. It - answers *"which byte holds X?"* for free, in one call - when an entry exists. - Cheap to check, so check it early. But it only helps for **values it happens to - label**, and only for ROMs in the DB. -- **`disasm({target:'rom'})` / `disasm({target:'project'})` / `disasm({target:'references'})`** - the actual - code. This is how you understand *how* something works and the **only** path for - structural hacks: new logic/behavior, text, graphics, AI, anything no cheat - names - and for any game the cheat DB doesn't cover. - -**Don't treat one as a mere fallback for the other - they answer different -questions, and running both early is normal.** A good default: - -1. **`cart({op:'identify', path})`** → platform + title (sniffs zip-wrapped ROMs too). -2. **`cheats({op:'lookup', path})`** - a fast lookup. If it names the address you need, - you may have just skipped a long memory hunt. If it returns nothing useful (no - match, or no cheat for *your* target), that's fine - move on, no time lost. -3. **Disassemble / trace** whenever the hack is about CODE or about data the - cheats don't cover: `disasm({target:'project'})` for a rebuildable project - (then edit a region `.asm` and `build({output:'reassemble', platform, path})` to - rebuild a byte-identical ROM in one call - the "cmp before commit" gate; a - `.gitignore` is written so the kept `original.rom` can't be committed. **Large - ROM (≥512KB, e.g. a 1MB SNES/Genesis cart)? Pass `background:true`** and poll - `disasm({target:'project', job, outputDir})` - the reassemble can take minutes - and would otherwise time the call out. A uniform-fill/padding bank reports - `fill:true` + `readablePercent:null`, so "low % = data bank" isn't fooled by a - $FF pad tail), - `disasm({target:'references'})` for "what touches this address", `breakpoint({on:'write'})` for the exact - instruction that wrote a byte, `watch({on:'mem'})`/`breakpoint({on:'write',precision:'sampled'})` to find an address - empirically. For STRUCTURE - "what are the functions, how do they call each - other, what's the control flow" - use the Rizin analysis ops: `symbols({op:'analyze'})` - for a one-shot map (functions + entrypoints), `disasm({target:'functions'})` for the - auto-detected function list, `disasm({target:'cfg', address})` for a function's basic-block - graph, `disasm({target:'xrefs', address})` for every cross-reference TO an address (deeper - than the da65 `references` scan - it follows the analysis graph). A CFG's edges are TYPED: - `call` is the callee and `call_return` is where execution resumes after it returns, so both - halves of a call are walkable (a consumer that misses the return site produces code where - `ret` pops an address that was never compiled). `disasm({target:'reachable', entries})` does - that walk for you and returns the closed block set - build it from the reset/IRQ vectors, - and when the closure looks small, that is usually honest: the ROM dispatches through - computed jumps, which no static walk can follow. Resolve those with - `breakpoint({on:'jumptable'})` and pass the recovered arms back as additional `entries`. For C-like PSEUDOCODE, - `disasm({target:'decompile', address})` runs Ghidra's decompiler (carries the decompiler's - own WARNINGs; quality excellent on GBA/Genesis, good on GB/Z80, rough on 6502). All - Rizin/Ghidra analysis ops cover 18/18 platforms (incl. the 3D consoles' MIPS/SH-4). For a no-cheats game or a - logic/text/graphics change, this is where the real work is - start here, don't wait on a - cheat lookup. - - **Static recompilation (the port engine), `disasm({target:'recompile'})`.** Translates a - routine from one console's CPU to another's assembly through a shared lift→IR→emit pipeline. - Sources: `nes` (6502) and `sms`/`gg`/`msx`/`z80` (Z80 - one lifter, four machines, since they - share the ISA and differ only at the hardware seam). Targets: `snes` (65816) and `genesis` - (m68k). An unsupported source→target pair is REFUSED rather than emitting text that looks - like assembly and cannot build. Two things to expect, both by design: - - **Bulk IR for a whole cart.** `emit:'ir'` + `allOffsets:true` + `outputPath` writes JSONL - (a manifest comes back, never megabytes inline) covering every byte, including instructions - that straddle a bank edge (marked `straddlesWindow`). Add **`alignments:'all'`** for a record - at EVERY byte offset, not just the linear tiling's instruction starts - what a static - recompiler needs, since a computed jump can land mid-instruction. Secondary records overlap - by design: assert `offsetsWithRecord == romBytes`, never sum record lengths. - - **`residue` is the point.** Anything not mechanically translatable is refused and listed, - never guessed - a wrong guess in a recompiler is a silent miscompile. The common entry is a - computed jump (`jp (hl)`, `jmp (table,x)`): resolve its arms with - `breakpoint({on:'jumptable'})` and re-run with those addresses as entries. - - **Hardware is left at a SEAM.** 6502 hardware is memory-mapped (PPU/APU stubs); the Z80 - reaches hardware through a separate I/O space, so every `in`/`out` is a seam and nothing - else is (`Z80_IO_READ`/`Z80_IO_WRITE`, port in X). Wire the target's hardware there. - This is phase-1 altitude: it translates a routine and stubs out-of-slice callees. It is not a - whole-ROM port. -4. **VERIFY before patching**: `memory({op:'write'})` the address live and watch the effect - (cheat labels are *probable* - matched by name, not verified CRC; static - "matches the pattern" ≠ "actually runs"). -5. **Patch**: `romPatch({op:'write'})`/`romPatch({op:'writeMany'})` with `expect:` bytes (refuses a wrong-revision - write) - or `cheats({op:'apply'})` to prototype a value change live first. - -Rule of thumb: **cheats are a shortcut for finding a known value's address; -disassembly is how you change behavior.** Most non-trivial hacks need the -disassembler regardless - so reach for it freely, and let `cheats({op:'lookup'})` save you a -hunt when it can, not gate the work when it can't. - -**If your session ever returns a 404 "session not found"** (the server restarted), your MCP client should auto-reconnect (re-`initialize`) - and the fresh session again has every tool loaded. You don't re-arm anything. If your client does NOT auto-reconnect on 404, restart its MCP connection once; that's a client limitation, not a server step. - -**Your emulator can be evicted while your session lives on.** A loaded ROM is a live WASM core holding real memory, so the server bounds how many it keeps: a host unused for ~10 minutes is torn down, and when too many are live at once the **largest holder's** oldest idle one goes (declare `x-romdev-agent` and that means your own, not a bystander's - see below). This is not an error and not a restart - your session, tools and save states on disk are all fine. You'll see it as a "No ROM loaded" error that **names the exact `loadMedia({...})` call to get back**; re-run it and carry on (if a playtest window was open, the error also points at an auto-checkpoint holding the last ~15s of play). An open playtest window is never evicted - a human may be mid-game. `catalog({op:'status'})` reports `serverHealth {rssMb, liveHosts, maxHosts, hostIdleMs}` if you want to see where things stand. - -**Running many sessions in parallel? Say who you are.** Send a stable -`x-romdev-agent` header (REST) or `dev.romdev/agentHandle` in `_meta` -(2026-07-28 MCP) alongside your per-task session ids - one value for YOU, -across all your sessions. It is optional and purely cooperative, but it buys -you two things: at the session/host caps, eviction targets the LARGEST -holder's oldest session, so declaring yourself means your parallel burst -evicts its own idle sessions instead of another agent's - and -`catalog({op:'status'})` reports `sessionsByAgent`, so a human wondering -"who opened forty sessions?" gets your name instead of a mystery. -Undeclared sessions pool together as "(unattributed)" and share that pool's -eviction fate. When you finish a session, `host({op:'shutdown'})` releases -ALL of it - emulator, session record, livestream entry - immediately. -Declared agents also get a memory aid: the FIRST response of every new -session you open carries `agentSessionReminder` listing your other live -sessions (key, what's loaded, idle time) - that list is exactly what you -need at the end of a parallel burst to shut down every session you opened, -or to notice you already had a session for the thing you're about to redo. - -**Both protocol revisions are served on the same endpoint.** Legacy clients (`initialize` handshake + `Mcp-Session-Id`) work exactly as before. Modern clients speaking **2026-07-28** - no handshake, no session id, per-request `_meta` - are served statelessly, with `server/discover` advertising what this server supports. Since that revision has no protocol session to hold your identity, the server resolves it in this order: a `_meta["dev.romdev/sessionHandle"]` handle; **the optional `session` argument every tool accepts** - the one form you can produce from inside a tool call, so if you are on a modern client just pass one stable, descriptive slug (`session:"nes-platformer"`) on every call from the first `loadMedia` on; or, when a call names nothing, **your keep-alive connection** - the server keys the session to it and ends every result with a `session: ` line. Copy that id into `session:` if a later call ever says "No ROM loaded": a replaced connection starts empty, and the id is how you get your emulator back. A DIFFERENT `session` value is a fully isolated second emulator (deterministic stepping while a human plays in the first). Over plain HTTP the same job is done by the `x-romdev-session` header - send it on every call AND reuse one `Mcp-Session-Id`; re-initializing per call mints a fresh session even with the header set, which is how a second playtest window gets opened with the first orphaned. - -**Hit a defect, or a job that cost far more calls than it should?** `feedback({op:'record', title, body, severity})` appends one stamped line (server version, pid, loaded platform + media, time) to a local, append-only log the human collects - nothing leaves the machine. One report per distinct issue; the server instructions call a host-toolchain install "a DEFECT to report", and this is where. - -## Large output: write to a path, or ask for it inline - -Tools that can return a LARGE payload (ROM bytes, full disassembly, big memory dumps, build logs, tile blobs, **and screenshots/inspect images**) follow ONE rule so they don't silently flood your context: - -- **`inline: false` is the default → you MUST pass an output path** (`outputPath` / `outputDir` / `path`). The payload is written there and you get back just `{ path, bytes }`. Calling such a tool with neither a path nor `inline:true` returns a clear error telling you which to pass. -- **`inline: true` → the payload comes back in the response** (base64 / hex / text / the image). Use this when you actually want it in context. - -There is **no hidden default location** - nothing ever lands in a temp dir you can't find, so you never lose a ROM to `/tmp`. You (the agent) decide where output goes; pass your project directory. - -Ergonomic exceptions: -- **Small reads stay inline.** `memory({op:'read'})` of ≤4 KB returns hex inline with no path needed (peeking a few RAM/OAM/palette bytes is the common case). Only large reads require a path/inline. -- **`build({output:'run'})` returns its screenshot inline by default** - its whole purpose is "build + run + show me." Pass `screenshotPath` only if your client can't display inline images. - -**On images specifically:** the `inline:true` image is only useful if YOUR client actually delivers inline images to you - some clients silently drop or down-convert image content. If you're not certain you can see them, **work from the structured data instead**: start with **`frame({op:'verify'})`** - one call tells you `{verified:true|false|null}` whether the game is actually rendering (fuses a pixel scan with the render-enable registers), so you don't sit staring at a black frame wondering if it's broken or just blank. Then `sprites({op:'inspect'})` / `palette({source:'live'})` / `background({view:'renderState'})` always return their decoded JSON (sprite lists, palette entries, render flags) regardless of inline/path, and `frame({op:'screenshot', format:'ascii'})` gives a text render. The inline PNG is an opt-in luxury, not the primary signal. - -## Trust hierarchy - where to find ground truth (R58 + R58b) - -Two parallel paths depending on what you need: - -### Path A - Fork a working example game (the dumb-model-friendly path) - -Most agent sessions start here. You want a working ROM, not a -research project. **Never start from a blank file - fork the example -whose CORE LOOP is nearest your game (even for a very different game), -then modify one thing at a time, re-running `build({output:'run'})` -after each change.** Retro bring-up is a long chain of fragile -hardware init with zero partial credit; a working game is a -regression oracle. - -1. **`examples({op:'list', platform?})`** - the mechanics map of the - complete working example games (kind `game` vs minimal `reference`). - Pick the one whose core loop is nearest your game. -2. **`examples({op:'fork', example:"/", name, path})`** - - copies that example into a NEW project dir as YOUR game (sources + - every runtime file + crt0 + linker cfg + vendored library source + - README + .gitignore), renamed throughout. It builds and runs before - you change a line. The response lists only the files you EDIT - (`files`) + a `vendorFileCount`; pass `verbose:true` for the full manifest. - Build the whole dir in one call with `build({output:'project', path, - outputPath})` (toolchain/crt0/linker inferred - no manifest); the bundled - examples ARE the reference implementation. -3. **`examples({op:'show', example, file?, technique?})`** - read a - DONOR example without forking it; `technique` extracts one marked - HARDWARE IDIOM block (with its dependency header) to graft into - your game instead of rewriting it. -4. **`examples({op:'snippets', platform, mode})`** (mode `list`/`get`/`getAll`) - / **`examples({op:'copySnippets', platform, destinationDir})`** - fetch - vetted helper files (reset routine, read_pad, OAM DMA, palette - upload, etc.) as one-off references. - `examples({op:'copySnippets'})` writes the files to disk in one call - without round-tripping bytes through your context - preferred - when you're copying into a project dir. - -Reminder (it's the second rule up top): **read your platform's -`platform({op:'doc', platform, name:'mental_model'})` BEFORE you write code for -it** - that's where the footguns that would otherwise burn your session live. - -For most workflows, path A is all you need. **When a tool call FAILS, read the -error message and `issues[]` first - see "When a call fails" below; the error -usually names the fix.** File a feedback round if the bundled examples are wrong. - -### Path B - Debug when the bundled code disagrees with behavior - -When the example builds clean but doesn't render / sound / behave -right, when an API call doesn't do what you expect, when you need -ground truth on what a library function actually does - dig in this -order: - -1. **Bundled examples** (`examples//templates/*.{c,asm}`) - - verified to compile + (usually) run. Start here for the working pattern. -2. **Your own project's runtime source** (alongside `main.c`) - our - thin wrappers (gb_runtime.c, lynx_sfx.c, sms_vdp_init.c, etc.). - All ~50-200 lines, fully readable. Read these when an API call - isn't doing what you expect. -3. **Your own project's `vendor/` library source** (R58b - auto- - copied into every project at fork time). The FULL source of - every library your ROM links against - `vendor/cc65/libsrc/

/` - for cc65 platforms, `vendor/libtonc/src/` + `vendor/libgba/src/` - for GBA, `vendor/pvsneslib/source/` for SNES, `vendor/sgdk/src/` - for Genesis. **`grep -rn vendor/`** inside your project - finds the actual implementation of any library function. No MCP - call needed. -4. **`platform({op:'doc', platform, name:"upstream_sources"})`** - per- - platform pointers at every bundled source path + upstream GitHub - links for the compilers + emulators we DON'T bundle (cc65, - sdcc, m68k-gcc, snes9x, gambatte, handy, etc.). Use as a - cheat-sheet for "where do I look for X?" -5. **Upstream GitHub** for compilers + emulators when the bug is - below our thin wrappers. Don't bundle (gigabytes for gcc/binutils - source) but the link is one click. -6. **Hit a real bug in romdev itself?** Open an issue at - https://github.com/monteslu/romdev/issues with repro details. File - only with a diagnosis (not bare "it doesn't work") - read the bundled - source first. - -**Important constraint on path B:** the `vendor/` library source is -**read-only in practice**. You can read + grep it freely, but if -you EDIT a file there, the linker still uses our precompiled -`libtonc.a` / `libmd.a` / etc., so your ROM won't pick up the -change. R59 (planned) will fix this with a per-TU object cache + -source-first library build. Until then, treat `vendor/` as a window -into "what the linked code actually does." - -The "vendor/" library source in your project is new in R58b (it was -previously in the install only; you'd have to call -`examples({op:'copySnippets'})` to pull it in). Now it lands automatically -when you `examples({op:'fork'})`. Round 30/31 Lynx wedges took 5 friction -rounds partly because cc65's TGI driver source wasn't visible; -post-R58b you can `grep -rn bar_c vendor/cc65/libsrc/lynx/` from -inside your project directory and read the actual blitter code. - -**Practical rule for path B:** if you find yourself filing a -feedback round without first `grep`ping `vendor/` for the symbol -you're debugging, you're skipping the cheap diagnosis path. The -bundled examples are starting points, NOT ground truth - when they -disagree with behavior, trust the library source over the example. - -### Which path to use - -- **Just need a working game** → Path A. Fork the nearest example with `examples({op:'fork'})`, iterate. -- **Hit a bug or unexpected behavior** → switch to Path B. -- **Don't know which** → start in Path A; if iterations fail to - converge after 2-3 attempts, you're hitting something path A - can't fix and need path B. - -### Where files land in your project tree - -A forked project (`examples({op:'fork'})`) is -**FLAT** for everything you author. `main.c` / `main.asm`, your -helper modules (e.g. `gb_runtime.c`, `nes_runtime.c`, -`atari7800_sfx.c`, `vcs_constants.h`), the platform crt0 + linker -config - all sit at the project root, next to each other. Asm -`include "vcs_constants.h"` / C `#include "gb_runtime.h"` resolves -without `-I` flags because dasm / cc65 / sdcc all default to the -current directory. - -The **only** subdir you'll see at fork time is `vendor/` - -that's the read-only library source tree (cc65 libsrc, libtonc / -libgba src, PVSnesLib source, SGDK src) auto-bundled by R58b so -you can `grep -rn vendor/` when debugging. Don't put your own -source under `vendor/`. - -So when `examples({op:'copySnippets'})` drops e.g. `read_joystick.asm` into -your project dir, it lands at `./read_joystick.asm` (alongside -`main.asm`), NOT under `./include/` or `./lib/`. Every platform -follows the same flat layout. - -Because the layout is flat, **the simplest loop is `build({output:'run', path, platform})` -(build + load + run + screenshot in one call) or `build({output:'project', path, platform})` -(build the dir to a ROM) - no per-iteration file manifest, on EVERY platform.** Point it at -a forked project directory and it does the right per-platform thing automatically: finds the -entry (`main.c` for C / SGDK Genesis / GBA / cc65-C / SDCC-C, or `main.s` / `main.asm` for -asm), routes the platform's crt0 correctly (e.g. GB/GBC `gb_crt0.s` via the cart-header path, -not as a plain source - so no `gsinit` collision), applies the right linker preset -(e.g. NES `chr-ram-runtime`, which supplies the OAM/CHARS segments), skips SDK intermediates -(e.g. Genesis `sega.preprocessed.s`, the SNES SPC700 driver, any `*.upstream.*`), wires the -runtime (GBA libtonc/libgba/maxmod by what the source includes), routes `#include`d C/asm -siblings as includes, treats `.h`/`.inc` as includes, and folds binary assets -(`.bin/.chr/.pcm/.brr/.vgm/.xgc/...`) in as `binaryIncludes`. So iterating an on-disk project -is just `build({output:'run', path:'/my/proj', platform})` every time - you do **not** need to -enumerate `sources`/`includes`/`crt0Path`/`linkerConfig` by hand. (Use `build({output:'rom'})` -with explicit `sources` only when the files aren't on disk, e.g. generated in-context.) - -## Supported platforms - -**14 tier-1 platforms** (build + run + screenshot + inspect + genre example games + sound + music + per-platform MENTAL_MODEL.md + TROUBLESHOOTING.md): - -NES, Game Boy, Game Boy Color, SNES, Genesis, Game Boy Advance, SMS, Game Gear, C64, Atari 7800, Lynx, PC Engine, MSX - all with the full set of forkable genre example games (`examples({op:'fork', example:'/shmup|platformer|puzzle|sports|racing', name, path})`). The Atari 2600 is also tier-1 but ships **4** of those genres (no `puzzle` - the TIA has no tilemap to draw a match-3 board). The `platformer` example side-scrolls (hardware camera + per-platform column streaming) on every tier-1 platform except NES and the Atari 2600, which are single-screen (neither has hardware background scroll). Every tier-1 platform also ships a music demo using the platform's de-facto music engine - `music_demo` for most: FamiTone2 (NES), hUGEDriver (GB/GBC), SPC700 driver (SNES), XGM2 via SGDK (Genesis), maxmod + .xm soundbank (GBA), PSG trackers (SMS/GG), SID sequencer (C64), `lynx_snd_play` (Lynx), 2-voice TIA (Atari 2600/7800); PC Engine and MSX ship theirs as `music_sfx` (HuC6280 PSG; AY-3-8910 PSG). PC Engine and MSX additionally ship a hardware helper library plus `sprite_move` / `catch_game` example projects alongside the genre examples. - -**Bring-up only** (build pipeline works, single `default` example, no genre example games or sound/music wrappers yet): ColecoVision. Uses SDCC z80 same as SMS/GG/MSX - the genre examples are queued. - -**Delisted** (toolchain works but core-side issue blocks the run loop): Atari 5200 (atari800 BIOS-load path), ZX Spectrum (fuse tape-load path). - -Call `platform({op:'list'})` (in the `platforms` category) for the live capability matrix, including per-platform language defaults and quirks. **Defaults are picked to maximize agent effectiveness** - for every platform that has a bundled C compiler, C is the default (LLMs write C cleanly; the compiler handles register allocation + memory mapping). Platforms whose only bundled toolchain is an assembler default to asm. Override with `language: "asm"` or `language: "c"` when you specifically need the non-default. - -For maintainers: the platform / core / patch / region-ID matrix and the recipe for adding a new platform live in the project repo at https://github.com/monteslu/romdev. - -## Deep debug tooling status per platform - -Different platforms have different levels of MCP-exposed debugging - different hardware needs different tools, and we've patched the cores where it's been worth it. The generic shapes - `cpu({op:'read'})`, `breakpoint({on:'write'})`, `disasm({target:'rom'})`/`disasm({target:'references'})`, `memory({op:'search'})`/`memory({op:'readCart'})`/`memory({op:'classify'})`, cheats - work on **all 18 platforms** (disassembly via native binutils `objdump` compiled to WASM, one per CPU family - incl. GBA ARM7/Thumb and the 3D consoles' MIPS/SH-4); byte-exact `disasm({target:'project'})` reassembly is the **15 classic platforms** (incl. GameTank, cc65/6502). The deep per-platform inspectors (`sprites({op:'inspect'})`, `palette({source:'live'})`, `background({view:'renderState'})`, `audioDebug({op:'inspect'})`) are detailed for **12 systems** below; **PC Engine and MSX** currently have the generic shapes + their core's native regions but not yet the full custom-inspector treatment (extend by patching their cores per the snes9x/gpgx pattern). `audioDebug({op:'inspect'})` covers the **13 with a sound chip** (all but Atari 2600/7800; incl. GameTank's ACP coprocessor). A few are honest hardware-shaped exceptions, noted inline below (the Lynx has no fixed OAM so `sprites({op:'inspect'})` returns the SCB list head; GameTank is a blitter framebuffer with no sprite OAM / no tilemap, so `sprites({op:'inspect'})`/`background` are N/A). Coverage detail per platform: - -> **Universal across the 15 classic platforms:** `breakpoint({on:'write'})` (the core-level -> instruction write watchpoint - the exact PC that wrote a RAM byte, all 15 classic CPU -> families), **`breakpoint({on:'pc'})`** (execution breakpoint - freeze the CPU AT an -> instruction and read its registers), **`breakpoint({on:'read'})`** (the exact PC that read -> a byte - read-side mirror of `breakpoint({on:'write'})`), **`frame({op:'stepInstruction'})`** (CPU single-step), -> **`cpu({op:'setReg'})`** (write a CPU register), **`cpu({op:'call'})`/`cpu({op:'decompress'})`** -> (drive the ROM's OWN routine - e.g. its decompressor - and capture the output; -> a per-instruction watchdog on **every CPU core** (m68k, 6502/6507/6510/65c02/65816, -> z80 incl. SMS/GG, sm83, arm7tdmi, huc6280) force-stops a runaway routine and -> returns `{watchdog:true, finalPC, finalRegs}` instead of hanging. It catches BOTH -> a tight infinite loop AND a wrong-entry FREE-RUN (a wrapper PC with a bad source -> that falls back into the game's main loop): the default budget is PER-CPU, sized -> to trip before the frame cap on the slow ~1MHz cores too. Pass `maxInstructions` -> to override the budget, `presetMemory`/`stopAtPC` for codecs that read RAM globals -> or need a mid-routine halt. With `sandbox:false` (the default - you want the dst -> buffer left live to read), a call that does NOT return leaves the sentinel push and -> the callee's own pushes stranded on the game's stack; the CPU register file is -> restored automatically in that case (`cpuContextRestored:true`) so the interrupted -> code can still resume, while the RAM the routine wrote is deliberately left live), -> **`watch({on:'range'})`** (log EVERY read/write hitting an address range - discovery; -> pass **`fromState`**/`fromStatePath` to restore a savestate FIRST so the trace runs from a -> known, repeatable moment - jump to the boss, then see what writes HP), -> **`watch({on:'pc'})`** (coverage trace - EVERY distinct PC executed in a window, exact and uncapped on every core: a one-bit-per-PC bitmap at the CPU's instruction granularity, `method:'bitmap', exact:true` in the result; also takes `fromState`), -> **the RE-INJECT trio** (put an edited asset BACK, all 15 classic platforms): **`romPatch({op:'findPointer'})`** -> (find every pointer to a ROM offset - Genesis 32-bit BE, SNES LoROM/HiROM, GBA -> 0x08000000+offset incl. literal pools, banked 8-bit 16-bit-LE aliases), -> **`romPatch({op:'makeStored'})`** (wrap raw bytes so the game's OWN decompressor expands them -> verbatim - GBA LZ77 / SNES LC_LZ2 / SMS+MSX RLE / NES PackBits / `raw` for the -> uncompressed-graphics systems; Nemesis + C64 crunchers honestly refused), and -> **`romPatch({op:'relocate'})`** (write to free space + repoint), -> `cheats({op:'lookup'})`/`cheats({op:'search'})`/`cheats({op:'apply'})`/`cheats({op:'make'})` (cheat -> lookup/apply/create), `cpu({op:'read'})`, `memory({op:'search'})`/`memory({op:'searchNext'})`/`memory({op:'readCart'})`/`memory({op:'classify'})`, -> `memory({op:'snapshot'})`/`memory({op:'diff'})`/`state({op:'diff'})`, `watch({on:'mem'})`/`breakpoint({on:'write',precision:'sampled'})`. -> `audioDebug({op:'inspect'})` covers the 13 systems with a sound chip (all but Atari 2600/7800; incl. GameTank's ACP coprocessor). -> **`watch({on:'dma', precision:'exact'})`** (which DMA wrote a VRAM tile, and from where) is **Genesis-only** -> (VDP DMA) - elsewhere use `breakpoint({on:'write'})`/`watch({on:'range'})`. All other RE tools above -> work on every platform that has the register-write/watch core hooks (the 15 classic platforms). -> `disasm({target:'rom'})` + `disasm({target:'references'})` cover **all 18** (incl. the 3D consoles' MIPS/SH-4), and `disasm({target:'project'})` byte-exact reassembly the **15 classic platforms** (incl. GameTank) - every -> CPU family disassembles through a native binutils `objdump` (WASM). To REBUILD, -> **`build({output:'reassemble', platform, path})` turns a `disasm({target:'project'})` -> dir back into a byte-identical ROM in ONE call on all 15** - it assembles each -> region `.asm` with the native assembler and splices the results into the original's -> header/gaps/pad. (Edit a region first for an intentional change; a same-length edit -> rebuilds a modified ROM, a length-changing edit is refused.) The per-platform notes -> below cover the platform-SPECIFIC inspectors + chips (PC Engine + MSX: generic shapes only so far). - -The deep per-platform inspectors + the exact memory-region names, core quirks, and any platform-specific traps live in **each platform's `MENTAL_MODEL.md`** (read via `platform({op:'doc', platform, name:'mental_model'})`) - read it for the system you're on. Symptom → doc: -- **NES** - blank/black screen, wrong sprites/colors, or need live PPU regs / CIRAM-attribute / MMC1-banked CHR state. -- **SNES** - garbage/flashing sprites, or live OAM/CGRAM/SPC700/S-DSP state (PPU regs read via the FillRAM shadow - no core patch needed). -- **Genesis** - missing/wrong sprites, palette/scroll, or live SAT/CRAM/VSRAM/VDP/Z80 state (mind the gpgx VRAM byte-swap). -- **GB / GBC** - wrong sprites/palette/tiles/BG or live SM83/APU/LCDC state; gambatte exposes `gb_vram` (NOT `video_ram`) + `gb_oam`/`gb_io`/`gb_hram`. (GB MENTAL_MODEL also holds the SDCC toolchain notes; GBC adds the CGB palette deltas.) -- **SMS / GG** - sprite/tile/palette/BG issues or live Z80 + VRAM/CRAM/VDP regions (SMS holds the shared gpgx detail; GG = 12-bit-vs-6-bit palette + `gg_vram`/`gg_cram` deltas). -- **GBA** - sprite/palette/BG wrong, ARM7 `execPc` (pipeline-adjusted PC), the `gba_*` regions, or ARM-vs-Thumb objdump (Thumb decodes as `.byte`). -- **Atari 2600** - blank screen / missing sprite / TIA-or-palette state, or `audioDebug` "not supported" (no OAM, no standard sound chip). -- **Atari 7800** - display-list garbage, MARIA palette/DPP, `sprites({op:'inspect'})` returns no OAM, or no `audioDebug`. -- **C64** - VIC/sprites/SID/banking misbehaving: live palette/sprites/cpu/renderState inspectors, `c64_*` regions, `.prg` disasm, disk load/save+export (and its keyboard/joyport input - see "Driving input over MCP"). -- **Atari Lynx** - `sprites({op:'inspect'})` returns an SCB list head (no fixed OAM), or you need the Mikey palette/audio, 65C02 regs, or the `lynx_hw_regs` $FC00-$FDFF window. -- **MSX** - VDP/PSG inspection or AY8910 `audioDebug`. (ColecoVision is bring-up-only: standard `system_ram`/`save_ram`/`video_ram`, no custom inspectors - extend by patching its core per the snes9x/gpgx pattern.) -- **PC Engine** - generic shapes + the core's native regions only so far (no custom-inspector treatment yet). -- **GameTank** - Clyde Shaffer's open-hardware W65C02S console (cc65 toolchain, ext `.gtr`). Full classic-style Tier-1: `cpu({op:'read'})` (65c02 regsnap), `audioDebug({op:'inspect', chip:'acp'})` (the ACP audio coprocessor), `breakpoint({on:'write'|'read'|'pc'})` + watchdog + coverage, `disasm` (`bytes`/`rom`/`references`/`project` + the 6502 Rizin/Ghidra cfg/xrefs/functions/decompile path - a 32KB flat cart @ `$8000`, one region, rebuilt byte-identical via `build({output:'reassemble', platform:'gametank', path})`), `cart({op:'extract'|'wrap'})`, and the 6502 re-inject path (`romPatch`) same as NES/C64/Lynx. **No `sprites({op:'inspect'})`/`background`** - it's a blitter framebuffer with no sprite OAM / no tilemap (like the Dreamcast). All five genre examples ship (`gametank/shmup|platformer|puzzle|sports|racing`) - real games on the bundled SDK draw-queue runtime, with pixel-art sprites loaded into GRAM. Fork with `examples({op:'fork', example, path, name})`, then `build({output:'project', path})`. `sports` is a genuine 2P game (the GameTank has two gamepad ports, unlike the handhelds). - -- **sync32** - monteslu's RP2350 console (arm-none-eabi Cortex-M33, ext `.s32`). A cart is `game_main(api)` against a function-pointer ABI drawing into a flat 8-bit canvas: **no PPU, no tilemap, no OAM, no banking**. Build with `build({platform:'sync32', language:'c', sources, title, id, mode:'ram'|'xip'})` - the whole pipeline is WASM (cc1/as/ld/objcopy + a JS packer), no native gcc and no Python. A game with resources passes `data`/`dataPaths` and `api:2`; use **`form:'folder'`** if you want to RUN it here, because the core loads a bare executable plus a sibling `/` data dir and does not unpack the `archive` tar you would ship. Inspectors: `memory({region:'system_ram'})` is the live 520KB SRAM at `0x20000000` (globals, stack, and in ram mode the code) so snapshot/diff/search/watchpoints all work; `cpu({op:'read'})` decodes r0-r15 + APSR + the FPv5-SP registers (**no `execPc`** - this is an interpreter, so r15 is already the next instruction); `palette({source:'live'})` reads the 256-entry RGB565 table; sprite sheets are the `sync32_sheet0` region (`0x1B0+n` for the rest). **No `sprites({op:'inspect'})`/`background`/`decompile`** - there is no OAM and no tilemap to decode, and no commercial ROMs to reverse-engineer. Docs: `platform({op:'doc', platform:'sync32', name:'mental_model'|'troubleshooting'})`. All five genre examples ship (`sync32/shmup|platformer|puzzle|sports|racing`) - fork one with `examples({op:'fork', example, path, name})`, then `build({output:'project', path})` in one call. **The idiom that surprises everyone:** `rect()`/`clear()` take an RGB565 colour but the canvas is 8-bit INDEXED, so the console snaps your colour to the NEAREST palette entry - a colour you did not put in the palette renders as something else. - -Starter snippets per platform live under `src/platforms//lib/`. Discover via `examples({op:'snippets', platform})` (default `mode:'list'`), fetch one via `examples({op:'snippets', platform, mode:'get', snippetName})`. SNES + NES + Genesis + SMS + Game Boy + Atari 2600 + Atari 7800 have substantial snippet libraries; others are minimal. - -## ROMs are finalized for real hardware automatically - -`build({output:'rom'})` / `build({output:'run'})` return ROMs that boot on **real hardware, -flashcarts, and strict emulators (RetroDECK / RetroArch)** - not just our -lenient WASM cores. The build pipeline runs each platform's required -post-link finalize step for you. **You do NOT need to checksum, pad, or -header-patch the output yourself.** What gets fixed: - -- **Genesis** - padded to a 128KB boundary (min 512KB) + `$18E` checksum. -- **GB / GBC** - `rgbfix`: Nintendo logo ($0104), header checksum ($014D), - global checksum, CGB flag ($0143 = $00 for `.gb`, $C0 for `.gbc`). -- **SMS** - `TMR SEGA` header at $7FF0 + checksum ($7FFA) + region/size byte - (export region $4) so the SMS BIOS doesn't reject it. (GG BIOS doesn't - check, but it's written anyway.) -- **SNES** - padded to a power of 2 (min 32KB) + internal checksum ($FFDE) + - complement ($FFDC), LoROM/HiROM auto-detected. -- **NES** - the iNES header is emitted by the linker config; nothing to add. - -Why this matters: our WASM emulator skips the boot-ROM validation that real -hardware runs, so a ROM can look perfect in `frame({op:'screenshot'})`/`playtest` yet fail -to boot on a console or RetroDECK. The finalize step closes that gap. The -build response `romLayout` / `log` states what was applied. - -## First, try build({output:'run'}) - -**`build({output:'run'})` is the primary tool.** It does build + load + run + screenshot -in a single call, returning the image inline. Reach for it before any 4-call -sequence of build({output:'rom'}) → loadMedia → frame({op:'step'}) → frame({op:'screenshot'}). - -```js -build({ - output: "run", - platform: "gbc", - source: /* your C or asm */, - frames: 60, - holdInputs: [{ a: true }], // optional - hold buttons during the run -}) -``` - -Round trip is ~50-500 ms depending on platform. Use it for fast iteration, -prototyping, "does my change still render correctly", "does the d-pad -move the sprite". When you change a line of code, the next call is usually -just another `build({output:'run'})` with the same args. - -**Where it shines:** -- Trying out a new game-loop change -- Verifying a sprite renders at the right position -- Testing input handling - `holdInputs: [{right: true}]` for 60 frames and - see if the player moved right -- Quick "did I break it" sanity checks after a refactor - -You don't need `loadMedia` / `frame({op:'step'})` / `frame({op:'screenshot'})` separately for any -of these. The 4-call workflow only matters when you want to drive multiple -emulator-state changes within one ROM lifetime (e.g. screenshot at frame 30, -save state, screenshot at frame 60, etc.). - -## Going deeper - -When `build({output:'run'})` is too coarse, the long-form workflow: - -1. `build({output:'rom', platform, source})` → get a ROM as base64 bytes -2. `loadMediaBytes({ platform, base64 })` → load without disk I/O -3. `frame({op:'step', frames: N})` or `runUntil({ condition })` → advance time -4. `frame({op:'screenshot'})` for vibes, `tiles({op:'pixels'})`/`tiles({op:'fingerprints'})` for byte-precise work, `memory({op:'read'})` for game state -5. `input({op:'set'})` / `input({op:'press'})` / `input({op:'sequence'})` to drive the game (for DIFFERENTIAL work against a reference, use **`input({op:'timeline'})`** instead - an absolute per-frame schedule `[{frame, buttons, until|holdFrames}]` anchored to the emulator's frame counter, so two runs hold the same buttons on the same ROM frames; `sequence` is relative runs and converting a frame schedule into them by hand is where phase drift comes from) - some platforms have extra control/input modes worth reading in their `MENTAL_MODEL.md` (e.g. C64 needs keyboard keys like F1/RUN-STOP to start many games; `input({op:'pressKey'/'typeText'/'joyport'})`) -6. `state({op:'save'}, "checkpoint")` / `state({op:'load'}, "checkpoint")` for try/undo - -## Diagnosing behavior over time (game-feel, not just "is it alive") - -`frame({op:'verify'})` answers "is it rendering / alive". When the screen looks -plausible but the game is WRONG - choppy movement, a value that's off, a piece -that locks mid-air - STOP eyeballing screenshots and trace the state. These tools -already exist; reach for them by symptom: - -- **"Movement/scrolling feels choppy / camera desyncs / scroll jumps."** - `recordSession({frames:180, holdInputs:[{right:true}], includeScreenshots:false, - memorySamples:[{region, offset, length, label}]})` - holds input over N frames and - returns an analyzable timeline. Sample the player's screen-X + the scroll - registers (Genesis: `genesis_vsram` + the HSCROLL table in `video_ram`; per - platform varies) and look for camera scroll changing while the sprite barely - moves, or non-monotone deltas. `watch({on:'mem', format:'series', ranges:[...]})` - gives the same idea as a compact value-vs-frame CURVE per byte. (Genesis: see - its MENTAL_MODEL "Why does horizontal movement feel choppy?" - the usual cause - is rewriting tilemaps in the frame loop; `watch({on:'dma', perFrame:true})` - shows the per-frame DMA bytes that spike when you do.) -- **"A computed value is wrong but the build is clean."** Don't re-read your C. - Resolve the variable's address and read it: `build({output:'romWithDebug', - resolveSymbols:["grid","score"]})` (or `symbols({op:'resolve', mapPath|dbgPath, - name})`) → `memory({op:'read', region, offset})`. Cheap, zero image tokens, and - it tells you whether the bug is your logic or your data. (sm83/z80: a "wrong - value" is far more often a WRAM layout collision than a miscompile - see the - GB/GBC SDCC_GOTCHAS "codegen traps in plain game logic".) -- **"I can't tell what's on the background."** `background({view:'map'})` decodes - the BG tilemap (grid of tile indices, or a rendered PNG) - don't hand-compute - nametable offsets. Small handheld too tiny to read inline? `frame({op:'screenshot', - scale:4})` up-scales (nearest-neighbor). - -## When a call fails: READ THE ERROR FIRST - -romdev errors are written FOR you - they name what went wrong AND how to recover. Read the message (and `issues[]`) before guessing, screenshotting, or retrying blindly. Two shapes: - -- **Build/compile failures** return `issues: [{file, line, col, severity, message, stage}, ...]` - the structured error list. Use that array, NOT the raw `log`; it almost always names the exact line. Fall back to `log` only if `issues` is empty but `ok: false`. `issues[]` is RANKED most-dangerous first (**critical → error → warning → info**), so read it top-down: an entry flagged `critical: true` (e.g. a `WILL HANG:` `uint8`-loop-bound trap) is a latent crash even on a build that otherwise succeeded - fix those FIRST, never skip them as "just a warning". Link errors carry no `line` but include a `hint` naming the missing symbol + how to resolve it. -- **Tool/runtime errors** (thrown) carry the recovery step in the message itself. Examples: a "No ROM loaded" error after a session reconnect echoes the EXACT `loadMedia({...})` call to restore your state; a rejected `loadMedia` names the likely cause (wrong platform / truncated / unsupported mapper) and points you at `cart({op:'identify'})`; an `input({op:'set'})` with a typo'd button returns `ignoredButtons[]` so you see it pressed nothing. Don't discard these - they're the fix. - -**Crash isolation (R12).** Every WASM toolchain call runs in a child worker process. If a tool aborts (`_abort()`, SIGSEGV, OOM), only the worker dies - the MCP server keeps running, all other agent sessions are unaffected, tool registration + save states + playtest windows survive. The build response surfaces as `{ ok: false, stage: "crash", log: "[crash] worker exited unexpectedly - signal=... code=...", crash: { exitCode, signal } }`. Treat `stage: "crash"` as "the toolchain blew up - log the args + source somewhere durable so it can be triaged; you can keep iterating in this session without reconnecting". - -## ROM hacking workflow - -**The full RE/romhack workflow is the playbook - read it FIRST:** -`platform({op:'doc', platform:'romhacking', name:'playbook'})`. It's the cross-platform -decision tree that wires the primitives below together (with the trap each one exists -to avoid), plus the per-asset round-trips (text, compressed assets, graphics) and a -Quick-reference table. Don't reconstruct the flow from this summary - it's only here so -you know the capability exists and where the detail lives. - -Key primitives (all bundled, all 15 classic tier-1 systems unless noted; full detail in the -playbook): - -- **Find a value's RAM address** - the Cheat-Engine loop `memory({op:'search'})` → - `memory({op:'searchNext', compare})`, NOT a full-RAM diff. (`memory({op:'snapshot'})`+`memory({op:'diff'})` - answers the different question "which bytes did THIS one event touch?".) -- **Free RAM/code map for a known game** - `cheats({op:'lookup', path})` decodes each cheat - into labeled addresses (`kind:ram`=variable, `kind:code`=patch site); `cheats({op:'apply'})` - confirms a label live + non-destructively; `cheats({op:'make'})` mints a verified shareable - code from a byte you found. Probable (name) match - verify before patching. -- **Find the instruction that wrote/read a byte** - `breakpoint({on:'write', address})` returns - the EXACT writer (core-level watchpoint, correct under NMI/IRQ; reports `bank`); - `precision:'sampled'` is the lighter frame-sampled lead. `breakpoint({on:'read'})` is the - read-side mirror. `found:false` ⇒ the region is bulk-copied/DMA'd from a SOURCE struct. -- **Read a register AT an instruction** - `breakpoint({on:'pc', address})` freezes the CPU → - `cpu({op:'read'})` for the live register file (e.g. a decoder's source pointer); - `frame({op:'stepInstruction'})` single-steps (or **`frame({op:'stepInstructions', count})`** to bulk-step N into ONE ordered trace - each step carries `flow` (seq/branch/call/jump/ret) and a true instruction `width` on `flow:'seq'`; pass **`stepFormat:'compact'`** for one string per step (`"$PC flow->$target"`) + a `pcRanges` loop-map with hit counts, ~90% fewer tokens for the "which loop is the CPU in" triage view). The "infer for hours → read it in 3 calls" move. On **banked platforms (SMS/GG)** each step also carries `mapper` (the slot registers), `bank` and `blockId` (`":$"`), read per step so a mid-trace bank switch is visible - a PC alone does not identify an instruction when `$8000` in two banks is different code. A cart that never writes the mapper leaves those registers at power-on RAM values; that is flagged `uninitialised` and no bank is claimed rather than reporting a byte as a bank number. -- **Discover the unknown routine** - `watch({on:'range'|'pc'})` logs every PC touching a - region; `watch({on:'dma'})` (Genesis) traces a graphic back to its ROM source offset. -- **Confirm bytes / classify** - `memory({op:'readCart'})` reads the running program image - (un-banked: file offset = CPU address); `memory({op:'classify'})` tells a real table from - ASCII/code before you trust it. -- **Edit on-screen text** - `text({op:'learn'})` infers the font map (incl. LIVE - `fromScreen` mode - no offset needed) and flags pre-rendered-graphic text (don't patch - the "string"); `text({op:'find'})`/`text({op:'encode'})` do the string round-trip. -- **Compressed assets** - drive the ROM's OWN codec: `cpu({op:'decompress'})`/`cpu({op:'call'})` - to expand, then the re-inject trio `romPatch({op:'makeStored'})` (verbatim-expand block) → - `romPatch({op:'findFree'})` → `romPatch({op:'relocate'})`, with `romPatch({op:'findPointer'})` for the - loader pointer. Don't reimplement the compressor. -- **Author/verify the patch** - `assembleSnippet({cpu, origin, code})` → bytes; - `romPatch({op:'write'})` (always pass `expect`); `romPatch({op:'diff'})` mapper-aware verify; - `disasm({target:'references'})` (static "who touches this?"); `cart({op:'extract'|'wrap'})`. -- **Graphics swaps** - `tiles({op:'png'})`/`importArt({from:'rom'})` → edit → - `romPatch({op:'spliceCHR'})`; `background({view:'rendered'})` for the tile IDs drawn now. - -Category placement: most live in `assets`; `disasm({target:'rom'})` is in `debug`; the -breakpoint trio (`pc`/`read`/`stepInstruction`) is in `advanced`. - -## Disassembler - -`disasm({target:'rom'|'references'})` covers **all 18 platforms** (incl. the 3D consoles' -MIPS R3000/R4300 + SH-4); byte-exact `disasm({target:'project'})` reassembly is the **15 -classic platforms** (incl. GameTank, cc65/6502). Every CPU -family disassembles through a native binutils disassembler compiled to WASM (no -hand-rolled JS decoders): 6502/65816 via cc65's `da65`, Z80 (SMS/GG/MSX) + SM83 -(GB/GBC) via one z80-elf `objdump` (`-m z80` / `-m gbz80`), m68k (Genesis) via -`m68k-elf-objdump`, ARM/Thumb (GBA) via `arm-none-eabi-objdump`. The annotations -(vector labels / hardware-register names / file-offset comments / `untilReturn`) are -post-processing layered on top. - -```js -disasm({target:'rom', path, platform:"nes", startAddress:0xC184, - length:64, untilReturn:true}) -// reset: sei ; C184 78 @0x194 (prg @0x184) -// lda #$00 ; C186 A9 00 @0x196 (prg @0x186) -// sta $2000 ; C188 8D 00 20 @0x198 (prg @0x188) PPUCTRL -``` - -`disasm({target:'project'})` is the **RE-rebuild workhorse**: one call turns a whole ROM -into a byte-exact, re-buildable disassembly (per-region `.asm` + rebuild glue), faithful -where it can be and falling back to `.byte` where it can't - so it *always* reassembles to -the original image. That's the path for any structural hack (new logic / text / graphics). - -The tool's own params document the flags (`untilReturn` / `dataRanges` / `endAddress` / -`bank` / `thumb` / `outputPath`; auto vector labels + register-name + file-offset -annotations, all on by default; NES file offsets report both `.nes` and PRG). The -ROM-hacking playbook (`platform({op:'doc', platform:'romhacking', name:'playbook'})`) has -the end-to-end workflow - read those rather than re-deriving the detail here. - -## CHR/tile tools - file vs emulator source - -`tiles({op:'pixels'})`, `tiles({op:'png'})`, `tiles({op:'png',source:'path'})`, `tiles({op:'fingerprints'})`, -and `tiles({op:'ascii'})` all accept an optional `path` arg: -- **With `path` set**: reads CHR straight from a file (iNES auto-locates - CHR; raw `.chr`/`.bin` files read as-is). Use to survey assets BEFORE - loading. Response reports `source: "file"`. -- **Without `path`**: reads from the running emulator's pattern table / - VRAM. Response reports `source: "emulator"`. - -## Demake / enhance / cross-platform workflow - -The full "take game X on platform A, make it on platform B" pipeline: - -1. Study source: `loadMedia({ platform: A, path })`, `recordSession`, `disasm({target:'rom'})` -2. Rip art: `tiles({op:'png', source:'path', platform: A, path})` returns a PNG sheet -3. Recook art: `encodeArt({stage:'tiles', platform: B, pngBase64})` re-encodes in B's tile format and bit depth -4. Write target game: `build({output:'run', platform: B, source})` for fast iteration -5. Embed converted art: `romPatch({op:'writeMany'})` to inject the new CHR/tile bytes - -The tile codec handles 4 bit-layouts × 4 bit-depths. NES↔GB is byte-exact at 2bpp. Going up in bit depth (NES→SNES) gains palette headroom. Going down (Genesis→GB) requires color quantization that the codec does automatically. - -### Lifting a CHARACTER (not a rectangular tile region) - use meta-sprite capture - -`tiles({op:'png',source:'path'})` / `encodeArt({stage:'crop'})` / `importArt({from:'rom'})` work on **rectangular tile-grid regions**. That is the WRONG model for a real character, which is built from **multiple independent hardware sprites** (OAM/SAT entries), each with its own position, size, tile index, palette, flips, priority, and a non-contiguous tile range. Cropping a screenshot or a tile sheet looks right and then renders as garbage in-game because the hardware multi-cell tile order differs per platform (Genesis is column-major; SNES large OBJ + NES/GB 8×16 are their own orders). The meta-sprite tools handle all of it. Works on **genesis, snes, nes, gb, gbc, sms, gg** (C64 MOBs are 24×21 bitmaps, not tiles - not supported): - -1. `loadMedia` → step / press to a frame where the character is fully on screen (NOT a menu - if no sprites are up, captures come back empty). -2. `sprites({op:'group', platform})` → clusters on-screen OAM/SAT entries into objects, largest-first (usually the player). Pick a group's `slots`. -3. `sprites({op:'capture', platform, slots:[...] /* or rect:{x,y,w,h} */, name:"enemy", emit:"both", outputDir:"..."})` → writes `tiles.bin`, `palette.bin`/`.json`, `layout.json`, `preview.png` (re-rendered from the EXPORTED data, not a screenshot crop), and a platform-idiomatic `.h`. Hardware tile order is preserved per platform. -4. Inspect `preview.png`. Re-verify any time with `sprites({op:'render', tilesPath, layoutPath})` - no rebuild needed. -5. Include `.h` (Genesis → SGDK `_draw()` helper; NES/GB → shadow-OAM cell table; SNES → oamSet pieces; SMS → SAT cells) - or get it later via `sprites({op:'emitC'})`. Build with `build({output:'run'})`. - -This keeps the lifted asset faithful to the source ROM's hardware composition instead of the lossy crop-the-screenshot fallback. - -## Visual vs programmatic inspection - -You have two modes. Pick per task: - -**Image mode** - `frame({op:'screenshot'})`, `tiles({op:'png'})`, `background({view:'map', render: true})`, `palette({source:'live'})`. Returns PNGs. Best for aesthetic judgment ("does this look right?", "did the explosion play?"). - -**Text mode** - `tiles({op:'pixels'})`, `tiles({op:'ascii'})`, `tiles({op:'fingerprints'})`, `memory({op:'read'})`. Returns structured data or ASCII art. Best for precise comparison ("is this tile blank?", "did $00F4 change between frame 60 and 90?", "find all tiles whose hash matches X"). - -Both work fine. Image mode is more flexible but burns more tokens per call. Use text mode for scans and diffs, image mode for "does this look like the hero sprite?" questions. - -## Active Bezels - when a screenshot is NOT the core's picture - -An **Active Bezel** is an executable companion to a specific ROM (a `.ab` -package). It runs once per emulated frame, reads the core's live memory, and -renders the final scene - a map, a HUD, reconstructed world graphics - around or -over the game. Load one with: - -```js -loadMedia({platform:'nes', path:'/roms/Game.nes', useActiveBezel:true}) -``` - -That looks for a same-basename sidecar (`Game.nes` → `Game.ab`) and **fails -loudly** if there isn't one, rather than quietly loading the ROM alone. - -**Why this section matters even if you never load one:** with a bezel running, -`frame({op:'screenshot'})` returns the **composite** by default, not the raw -emulator framebuffer. If you assume otherwise you will misread every capture. So -before interpreting a screenshot in an unfamiliar session, check -`catalog({op:'status'})` - it reports `activeBezel` whenever one is attached. - -**A package can be confidently, completely wrong.** It can load, tick without -trapping, emit perfectly valid draw commands, and still have nothing to do with -the game - an early package for a maze game declared it read the player's room, X and -Y, its readable `main.c` contained room-aware logic, and the compiled -`main.wasm` ignored the room byte entirely and drew fake progress bars. Unit -tests proved it loaded and drew. They proved nothing about meaning. - -Catching that needs three things observed at the same instant, which is exactly -why the bezel runs inside romdev instead of only in a player: - -```js -frame({op:'screenshot', source:'both', path:'/tmp/shot.png'}) -``` - -`source` selects the picture: `'composite'` (default with a bezel) = the final -scene the human sees, `'core'` = the raw framebuffer ignoring the bezel, -`'both'` = the pair for the SAME frame, plus the geometry triple. Compare the -two against the guest's own region reads - don't settle for "it drew -something." - -**Geometries that are easy to conflate,** all reported under `geometry`: - -| Key | What it is | -| --------- | ---------------------------------------------------------------------- | -| `core` | the raw framebuffer the emulator produced - does NOT describe intended shape (Atari 2600 pixels are famously not square) | -| `scene` | the bezel's logical composition, which the host may scale | -| `display` | the runtime's own account: `logicalWidth/Height`, `internalWidth/Height`, `physicalWidth/Height`, `pictureEffect`, and `rendererBackend` (`opengl-es-3` or `cpu`) | - -Conflating them is how a 4:3 game ends up stretched into a tall rectangle. When -a golden frame stops matching, check `display.rendererBackend` first - a GPU/CPU -compositor difference is the usual cause. - -**Lifecycle, so a stale package never composites over the wrong game:** - -- The bezel ticks on `frame({op:'step'})`, not just at capture time - a package - with per-frame state (an animation, a room transition) would otherwise see a - timeline full of holes. -- `host({op:'unload'})` / `host({op:'shutdown'})` **detach** it, and a plain - `loadMedia` without the flag detaches the previous one. The package is bound - to a ROM hash; keeping it across a media swap would draw one game's map over - another game's picture. -- `host({op:'reset'})` and `state({op:'load'})` **keep** the package but notify - it that continuity broke, so it discards caches built from a timeline that no - longer exists. -- A guest fault is recorded in `activeBezel.lastError` and the capture falls - back to the core frame. A broken package never takes down your session. -- **A SCRIPT error is not a guest fault.** The four scripting runtimes catch - script exceptions inside the guest and draw an error panel over the scene - - the tick returns normally, so `error` and `lastError` stay null while the - human is looking at a stack trace. `catalog({op:'status'})` hoists it as - `activeBezel.BEZEL_SCRIPT_ERROR` (from the runtime's `scriptError`); check - that key before declaring a bezel healthy from a null `error`. -- **Suspend/resume without teardown:** `playtest({op:'bezel', show:false})` - (or the human's **B** hotkey - same state) bypasses the bezel: captures and - the window show the raw core frame (`source:'core'`), pre_frame stops - shaping the game, and the guest keeps ALL its state - resuming never - re-runs `init()`. `catalog({op:'status'})` shows `activeBezel.bypassed` - while suspended; check it before interpreting a `source:'core'` capture as - "no bezel exists". - -**pre_frame - a bezel can SHAPE the frame, not just observe it (ABI 2).** -A package may define `pre_frame(frame)`, which the host calls before EVERY -core frame (every driver: `frame({op:'step'})`, `runUntil`, watch/breakpoint -runs, playtest). Inside it the bezel can write live regions (the write lands -before the game's logic consumes it - a `tick`-time write is one frame late by -construction) and call `ab.input_override(port, device, index, id, value)` to -replace what the core is polled with (id 256 = the whole joypad mask). -Overrides clear at the top of every frame and `ab.input` keeps reporting the -PHYSICAL pad, so a left/right swap can't feed back on its own output, and a -bezel can *claim* a button the game uses by reading it and masking it out. -Two things to know when debugging a session with such a bezel attached: - -- `catalog({op:'status'})` reports `activeBezel.preFrame` - - `{defined, calls}`. **Check it before trusting any negative input result or - "value changed with no writer" observation**: pre_frame writes are - host-side pokes into core memory, INVISIBLE to `breakpoint`/`watch` (those - hook CPU access core-side), and an input you "pressed" may never reach the - game. -- `input({op:'set'})` still sets the physical pad; what the core sees that - frame is physical + the bezel's override. `activeBezel.preFrameHookError` - surfaces a hook that threw host-side (the session keeps stepping). - -`input({op:'set'})` also accepts a raw analog channel per port - -`ports:[{right:true, axes:{lx:0.6, rt:1}}]` (sticks −1..1, triggers 0..1). -Axes are additive: the digital mask stays the game-facing contract; axes feed -the libretro ANALOG device (real proportional N64 steering instead of -full-deflection d-pad synthesis) and a bezel's analog `ab.input` reads -(`ab.DEVICE.ANALOG`, index `ab.ANALOG.LEFT/RIGHT` with id `ab.ANALOG.X/Y`, or -index `ab.ANALOG.BUTTON` with id `ab.BTN.L2/R2` for trigger pressure). In the -playtest window the physical pad's triggers land on the L2/R2 mask bits -(baseline + hysteresis, so a mid-scale-idling X360 trigger neither sticks nor -chatters) and both sticks + trigger pressures flow through as axes - on most -retro platforms the game ignores L2/R2/L3/R3 entirely, which makes them free -real estate for bezel controls. - -**Development overrides** (ordinary use should rely on same-basename discovery): -`activeBezelPath` points at a package elsewhere (an unpacked directory works), -`activeBezelConfig` passes per-package settings, `activeBezelForce:true` loads -despite a ROM-hash mismatch (**the composite may be meaningless** - a map keyed -to another revision's RAM layout draws confidently wrong things), and -`activeBezelRenderer:'software'` pins the deterministic CPU compositor, which is -what you want for golden-frame comparisons. - -Not supported on `slot:'b'` - that slot is comparison scratch for -`frame({op:'sideBySide'})` and never drives the presented frame. - -### Writing one: no toolchain required - -The `active-bezel` package ships prebuilt runtimes, so authoring a bezel is -**one command**. No emcc, no build step. - -```sh -npx --package active-bezel abtool scaffold my-bezel lua -``` - -`lua | js | python | ruby` need no toolchain at all; `c` adds the SDK header -and a build.sh for anyone who wants to compile. The scaffold is a complete -package -- runtime wasm, a commented script that is already a working bezel, -and a manifest -- so it loads and renders before you have edited a line. - -| Language | Scaffold | Script | API root | -|---|---|---|---| -| Lua 5.4 | `abtool scaffold my-bezel lua` | `main.lua` | `ab.` | -| Python (MicroPython) | `abtool scaffold my-bezel python` | `main.py` | `ab.` | -| JavaScript (QuickJS) | `abtool scaffold my-bezel js` | `main.js` | `ab.` | -| Ruby (mruby) | `abtool scaffold my-bezel ruby` | `main.rb` | `AB.` | -| C | `abtool scaffold my-bezel c` | `main.c` | `ab_*()` | - -The scaffold's script is a **working bezel** with a commented example of each -capability: 2D shapes, the live game, TrueType and -bitmap text, live memory reads, transforms, a decoded PNG, a per-vertex mesh, -and a GLSL shader effect. All four expose the same API, so a bezel ports -between languages by changing syntax alone. - -```lua -function tick(frame) - ab.clear(ab.rgb(14, 16, 26)) - ab.draw_game(0, 0, 1440, 1080, ab.SAMPLE.NEAREST) - local ram = ab.region('system_ram') - ab.print(font, ('HP %d'):format(ab.read_u8(ram, 0x0E)), 1500, 80, 40, 0xffffffff) -end -``` - -**The iteration loop is why this matters here.** `activeBezelPath` takes an -unpacked directory, so: edit the script, `loadMedia` again, `frame({op: -'screenshot'})`, look. Nothing needs packing until you ship. To keep game state -across a reload, `state({op:'save'})` → `loadMedia` → `state({op:'load'})`. - -The script contract is `init()` / `pre_frame(frame)` / `tick(frame)` / -`event(kind)` - only `tick` is required. `pre_frame` runs BEFORE the core -executes the frame (write RAM, override input - see the pre_frame block -above); `tick` draws the scene the frame produced. `ab.input_override` is only -honored inside `pre_frame` and refuses (logged once) anywhere else. - -A script error does **not** kill the session: the runtime draws the message and -the failing line on an on-screen panel and keeps ticking, so a screenshot tells -you what broke. - -Single-pass RetroArch shaders port into `ab.effect_set()` almost verbatim -(rename `Texture` → `u_texture`, `vTexCoord` → `v_uv`, `FragColor` → -`out_color`, add `#version 300 es`). Gate on `v_uv` to treat only the game rect -and leave your panels alone. - -**Offscreen surfaces and multi-pass presets.** `ab.surface_create(w, h)` gives -a real render target: draw into it, filter it with its own shader, reuse it as -a texture, keep it across frames. `ab.surface_filter(src, dst, glsl)` runs one -shader into a surface; `ab.surface_preset(src, dst, 'crt.glslp')` runs a whole -multi-pass RetroArch preset. Filtering into a surface runs the shader flat at -the source's own scale, so a CRT shader behaves as written and any geometry -(tilt, curvature) happens once, afterwards. `ab.GAME` is the live frame as a -texture handle. No shaders ship with the package -- point at -[libretro/glsl-shaders](https://github.com/libretro/glsl-shaders) or a -RetroArch install. - -**The bezel sees the controller.** `ab.input(port, ab.DEVICE.JOYPAD, 0, -ab.BTN.A)` reads the same libretro state the core does, so an on-screen -controller or input display cannot disagree with the game about what is -held. - -## NES-specific (most common platform) - -Patched fceumm exposes extra memory regions beyond the libretro standard: - -| Region | Contents | -| ----------------- | ---------------------------------------------- | -| `system_ram` | 2KB CPU RAM ($0000-$07FF) | -| `nes_chr` | 8KB CHR (gathered from VPage[0..7]; R59 fixed an off-by-page-offset bug that returned zeros for offsets >= 4096 - if you see CHR uploads "fail" only above 4 KB, you're on a pre-R59 build) | -| `nes_nametables` | 2KB CIRAM (background tile maps) | -| `nes_palette` | 32 bytes ($3F00-$3F1F) | -| `nes_oam` | 256 bytes sprite list (64 sprites × 4 bytes) | - -OAM format: bytes per sprite are `[y, tileIndex, attributes, x]`. - -`background({view:'map', render: true})` composites the active CHR + nametable + palette into a real 256×240 PNG - what the BG layer would look like even if rendering is currently disabled. - -## Save-state semantics - -`state({op:'save'}, name)` / `state({op:'load'}, name)` slots are **in-memory** and discarded on `host({op:'shutdown'})` or new media. To persist a state across sessions: -- `state({op:'save', path})` writes the CURRENT live host to a file directly. -- `state({op:'export', fromSlot, path})` copies an EXISTING in-memory slot (e.g. one the human saved with a playtest emulator-hotkey - it appears in `state({op:'list'})`) to a file **without disturbing the live host** (no pause/resume needed). Reload either with `state({op:'load', path})`. -- **`path` resolution:** a RELATIVE `path` resolves against the **loaded ROM's directory** (so `path:"states/start.state"` lands next to your ROM), an absolute path is used as-is; the result echoes `resolvedPath` when they differ. (It is NOT resolved against the server's CWD.) - -**SRAM (the cartridge BATTERY SAVE FILE - distinct from a savestate).** A savestate is the whole machine; SRAM is just the bytes a real cart keeps on its battery (the in-game save). romdev exposes it three ways, all on existing tools: -- **Live read/write:** `memory({op:'read'/'write', region:'save_ram'})` - poke/inspect the running game's save RAM. -- **Persist the `.sav`:** `state({op:'exportSram', path})` writes the save file; `state({op:'importSram', path})` loads one back (edit a save offline, or inject one a player made elsewhere). Same relative-path-resolves-to-ROM-dir rule. -- **Presence:** `cart({op:'identify'})` returns `saveRam:{hasBattery, bytes}` so you know whether a save even exists before reaching for it. -- **No battery save?** Many carts use passwords or no save (and Atari 2600/7800 + Lynx never had cartridge saves). `save_ram` is empty there and the tools say so plainly - use a full-machine savestate (`state({op:'save'/'load'})`) instead. **C64 is different:** its save medium is the floppy disk, not battery SRAM - use the disk ops (`state({op:'exportDisk'/'importDisk'/'putDiskFile'})`, see the C64 platform notes), not save_ram. - -`state({op:'load'})` removes any active cheats (a save-state blob doesn't carry frontend cheat state) and reports `cheatsCleared`. `host({op:'reset'})` resets the frame counter + core state (and clears cheats) but keeps the loaded ROM. Both KEEP an attached Active Bezel and notify it that the timeline jumped, so the first composite afterwards is drawn from the restored memory rather than from the abandoned timeline's caches. - -## Starting a project: fork an example game - -**Never start from a blank file - fork the example whose CORE LOOP is nearest your game (even for a very different game), then modify one thing at a time, re-running `build({output:'run'})` after each.** Read OTHER examples with `examples({op:'show'})` for techniques to graft. Rationale: retro bring-up is a long chain of fragile hardware init with zero partial credit; a working game is a regression oracle. - -- **`examples({op:'list', platform?})`** - the mechanics map of the example library: every example with its kind (`game` = complete working game, `reference` = minimal demo like `default` / `hello_sprite` / `tile_engine`), mechanics inventory, hardware techniques demonstrated, players, SRAM. Pick the example whose core loop is nearest your game. - -- **`examples({op:'fork', example:"/", name, path, title?, overwrite?})`** - copies that example into a NEW project dir as YOUR game: `main.{c,asm,s}` + every runtime file it depends on (headers, crt0, linker .cfg) + README + `.gitignore`, renamed throughout. Self-contained: take it elsewhere and rebuild with stock cc65/sdcc, no romdev install needed. (You can also pass `platform` + `template` instead of `example`.) **Then build it in ONE call: `build({output:'run', path:, platform})`** - the dir build applies the platform's recipe (crt0/linker-preset/runtime/intermediate-skip) automatically, so you never hand-wire `crt0Path`/`codeLoc`/`linkerConfig`. This fork→build path is verified to build + render on every platform/example. - -- The **genre example games** (`shmup` / `platformer` / `puzzle` / `sports` / `racing`) are the usual fork targets - complete working ROMs with state machine + sprite allocation + sound wired. Available on **all 14 tier-1 platforms** (NES, GB, GBC, SNES, Genesis, SMS, GG, C64, GBA, Lynx, Atari 7800, PC Engine, MSX - full 5 each; Atari 2600 - 4, no `puzzle` since the TIA has no tilemap for a match-3 board). Availability is derived from the registered examples (not a hardcoded list), so the error message for an unsupported (platform, name) pair always names the current set; e.g. `atari2600/puzzle` is rejected and the error lists the examples it *does* have. ColecoVision (bring-up only) has no genre examples. No example matches your genre exactly? Fork the NEAREST core loop and reshape it - `examples({op:'list'})` returns the genre→nearest-fork guidance. **Want a side-scroller? Fork `/platformer`** - on every platform EXCEPT NES and the Atari 2600 it already side-scrolls: a hardware camera follows the player (SCX/$D016/R8/BXR/BG?HOFS/REG_BG?HOFS/bgSetScroll depending on platform), with software tile-column streaming where the world is wider than one nametable/plane. NES and the Atari 2600 are single-screen (no hardware background scroll - platforms drawn as sprites/playfield); to make NES scroll, draw platforms into the background nametables + `ppu_scroll(camX,0)` (it flips the PPUCTRL nametable-select bit past 256 px) + stream columns past 512 px. Each platformer's `describe` text gives the per-platform specifics; the scroll-register details live in the platform's MENTAL_MODEL.md "Horizontal scrolling" section. +### Project layout and the directory build -- **`examples({op:'show', example, file?, technique?})`** - read a donor example WITHOUT forking it: a whole file, or one marked HARDWARE IDIOM block (`technique`) with the dependency header that says what the block needs to survive a transplant. Fork for the core loop; show OTHER examples for techniques to graft. +A forked project is flat: `main.c`/`main.asm`, your helper modules, crt0 and linker config sit at the root, so includes resolve without `-I`. The only subdirectory is `vendor/`, the full source of every library the ROM links (`vendor/cc65/libsrc//`, `vendor/libtonc/src/`, `vendor/libgba/src/`, `vendor/pvsneslib/source/`, `vendor/sgdk/src/`). It is read-only in practice: the linker uses the precompiled libraries, so edits there do not reach the ROM. `grep -rn vendor/` finds any library function's implementation. -Then iterate with `build({output:'run'})` against the source you read from `path/main.*`. +The directory build finds the entry (`main.c`, `main.s`, `main.asm`), routes the crt0 (GB/GBC `gb_crt0.s` through the cart-header path), applies the linker preset (NES `chr-ram-runtime`), skips SDK intermediates, wires runtimes (GBA libtonc/libgba/maxmod by include), treats `.h`/`.inc` as includes and folds binary assets (`.bin`, `.chr`, `.pcm`, `.brr`, `.vgm`, `.xgc`, ...) in as `binaryIncludes`. Use `build({output:'rom'})` with explicit `sources` only for files not on disk. -## Symbol-aware debugging - assert state headlessly instead of screenshotting ⭐ +`build({output:'run'})` takes `frames` and `holdInputs` (for example `[{right:true}]`) to test input in the same call; round trips are 50-500 ms. Use the separate `loadMedia` / `frame` / `state` calls only when you need several state changes in one ROM lifetime. -**The single biggest win for headless verification:** every "did the score go up / HP -drop / level change?" check is one byte of RAM. Build with debug, resolve the C global, -read it - no screenshot, no visual interpretation. Works on **every platform with a C -toolchain** (all 12 buildable ones): +### ROMs are finalized for real hardware -```js -const b = build({ output: "romWithDebug", platform, source, inline: true }) -const sym = symbols({ op: "resolve", /* dbg or map: */ name: "score" }) -memory({ op: "read", region, offset }) // the live value - 0 image tokens -``` +`build` output boots on real hardware, flashcarts and strict emulators; the post-link finalize step runs for you (do not checksum or pad by hand): Genesis padding and `$18E` checksum; GB/GBC `rgbfix` (logo, header and global checksums, CGB flag); SMS `TMR SEGA` header, checksum and region byte; SNES power-of-two padding and internal checksum with LoROM/HiROM detection; NES iNES header from the linker config. The response's `romLayout` / `log` say what was applied. -`build({output:'romWithDebug'})` returns the right debug artifact for your platform; pass -whichever it gives you to `symbols`: +### Where ground truth is when the example disagrees with behaviour -| Platform | debug artifact | pass to `symbols` | -|----------|---------------|-------------------| -| NES, C64, Atari7800, Lynx, PCE (cc65) | `.dbg` | `{ dbg }` | -| GB, GBC, SMS, GG, MSX (SDCC) | sdld `.map` (`mapText`) | `{ map }` | -| Genesis (m68k-elf) | GNU ld `.map` (`mapText`) | `{ map }` | -| GBA (arm-none-eabi) | GNU ld `.map` (`mapText`) | `{ map }` | +1. The bundled examples (verified to build and run). +2. Your project's runtime source (`gb_runtime.c`, `lynx_sfx.c`, ...; 50-200 readable lines each). +3. Your project's `vendor/` library source. +4. `platform({op:'doc', platform, name:'upstream_sources'})` for bundled source paths and upstream links. +5. Upstream repositories for compilers and emulators. +6. A real romdev bug: open an issue at https://github.com/monteslu/romdev/issues with a diagnosis and repro. -All five ops - `resolve` (name→addr), `lookup` (addr→sym), `list`, `map` (layout by -region), `addr` (live PC→enclosing C function) - work for **all** of these now (`map` -auto-detects sdld vs GNU ld). cc65 prepends `_` to C identifiers (`score`→`_score`); -`resolve` tries both spellings, and SDCC/GNU names come back without the underscore. +If two or three iterations on the example do not converge, switch from editing to reading the library source. When the example and the library disagree, trust the library. -**Genesis (and GBA) specifics:** -- Genesis C globals live in the `$E0FF0000` work-RAM mirror. `resolve` hands you a - `ramOffset` (the low 16 bits) **and** a ready `readHint` - read with - `memory({op:'read', region:'system_ram', offset: ramOffset})`. (gpgx word-swaps WRAM, - so a 16-bit value's two bytes are swapped at the offset - read bytes, or account for it.) -- `static` file-local globals resolve too (per-symbol sections). A non-`static` global - that's never read can be DCE'd at -O2 - mark state vars you inspect `volatile`. -- PC→function: `symbols({op:'addr', pc, symbolsText: b.mapText})` names the routine a live - `cpu({op:'read'}).pc` sits in. +### Toolchain traps that apply everywhere -When you don't know the symbol yet, `memory({op:'snapshot'})` → trigger the event → -`memory({op:'diff'})` shows exactly which bytes changed. +- C builds run a pre-flight lint. Read `issues[]`; `stage:"lint"` entries name the right file:line (raw compiler line numbers are often off by one) and carry a `ref:` into the platform's gotchas. `lint:"strict"` fails the build on any lint hit. +- All SDCC platforms (GB, GBC, SMS, GG, MSX) are C89: declarations at the top of each block, no `for (int i...)`, no compound literals or designated initializers. The GB/GBC SDCC notes (in the package at `src/platforms/gb/lib/c/SDCC_GOTCHAS.md`) also cover WRAM-layout traps that look like miscompiles. +- cc65 zero page starts at $02 ($00-$01 are reserved). +- Platform-specific traps (asar silent failures and CHR/tilemap overlap on SNES, SNES audio as a separate SPC700 build, NES 256-unique-tile cap, GB `shadow_oam` alignment and `memcpy_vram`, SMS/GG 8-sprites-per-line and `$D0` terminator) are in each platform's mental model and troubleshooting docs. -## Playtest mode (optional) +## Running, looking and asserting -`playtest({ scale: 3 })` opens a real SDL window for a human to play the loaded ROM with a keyboard or USB controller. It **returns immediately** - the render loop runs in the background and you keep using every other tool against the same live host (so `build({output:'run'})`/`loadMedia` rebuilds update the window in place; it does not relaunch or crash on rebuild). Close it with `playtest({op:'stop'})` (or the human pressing ESC / Select+Start). Needs a desktop display *and* the optional `@kmamal/sdl` dep; without them the open FAILS with a `reason`-tagged tool error and the rest of the server keeps working headless. Use this when the human wants to feel the game, not when you want to test it (for your own checks, use `frame({op:'screenshot'})` - it reads the same live host the window shows). `playtest({op:'status'})` reports liveness + the window's media/frame + `perf` (rolling fps/tickHz and per-stage ms - the "is it slow, and where" readout); the title bar always shows live fps, and `playtest({op:'fps', show?})` toggles an on-screen counter for the human (F3 does the same from the keyboard). `playtest({op:'framebuffer'})` captures exactly what the human sees. +- `frame({op:'verify'})` answers "is the game actually rendering?" without vision: `{verified:true|false|null, issues[], pixels, render}`. +- Assert state by reading memory, not by reading screenshots: `build({output:'romWithDebug'})`, `symbols({op:'resolve', name})`, `memory({op:'read'})`. The debugging guide has the per-toolchain table. +- `frame({op:'screenshot'})` takes `crop:{x,y,w,h}` (a native-resolution HUD strip for a fraction of the tokens), `scale` (below 1 for cheap change checks, not for reading text; integer above 1 to enlarge), `format:'ascii'`, and `source` when an Active Bezel is attached. +- Input: `input({op:'set', ports})` is positional (`ports[N]` is port N) with one boolean per button; the spatial names `north/east/south/west` resolve to the right physical button on every platform (the raw libretro `a`/`b` are inverted on Genesis, SMS and Game Gear). `input({op:'layout', platform})` gives the real buttons and bit order; read it before writing a `read_pad` routine. `input({op:'timeline'})` is an absolute per-frame schedule for differential runs; `navigate` advances menus on screen change. +- `memory({op:'regions'})` lists the regions for the loaded platform; start there rather than guessing. -**Window hotkeys (for the human):** ESC / Select+Start close, F3 toggles the fps counter, **B** suspends/resumes an attached bezel, **H** soft-resets (the console RESET button - same path as `host({op:'reset'})`, including the bezel continuity notification). **The gamepad works even when the window is NOT focused** (the human can watch a terminal while playing; SDL's background-events hint is set by the runner) - the keyboard fallback still requires focus, since keys route to the focused window. +### Large output: a path, or ask for it inline -**Windows are PER SESSION.** The server is multi-session (several agents, or a user with 2-3 games open at once); each session gets its OWN window - opening one never disturbs another agent's, `playtest({op:'stop'})` closes only yours, and a session disconnecting tears down just its own window. **Aspect:** the window defaults to `aspect:"tv"` (the 4:3 / native-LCD shape the game was authored for) with nearest-neighbor scaling, so it looks like real hardware and stays crisp + correct aspect when the human resizes it; pass `aspect:"fb"` for raw square-pixel dev geometry. +Tools that can return large payloads (ROM bytes, disassembly, memory dumps, build logs, tile blobs, screenshots) default to `inline:false` and need an output path (`outputPath`, `outputDir` or `path`); you get back `{path, bytes}`. Pass `inline:true` to get the payload in the response. There is no hidden default location. Exceptions: `memory({op:'read'})` of 4 KB or less is inline, and `build({output:'run'})` returns its screenshot inline (`screenshotPath` to write it instead). If you are not sure your client shows inline images, work from `frame({op:'verify'})` and the decoded JSON of `sprites`, `palette` and `background`. -## Common gotchas +Prefer paths over base64 for inputs too: the server shares your filesystem. -- **CHR-RAM vs CHR-ROM**: Most NES homebrew uses CHR-RAM. CHR tools (`tiles({op:'pixels'})`, `tiles({op:'png'})`, `tiles({op:'fingerprints'})`, `tiles({op:'ascii'})`, `tiles({op:'png',source:'path'})`) all accept an optional `path` arg - pass it to read CHR from the iNES file (CHR-ROM carts), omit to read live CHR-RAM from the running emulator. Response always reports `source: "file" | "emulator"`. NES homebrew built with `linkerConfig:"chr-ram"` has no CHR in the file - must read from the emulator after upload. -- **Mapper-aware addressing**: NES NROM 16KB carts mirror PRG at $8000 and $C000 (`disasm({target:'rom'})` reports the canonical $C000+ addresses since that's where the reset vector points). Banked mappers (MMC1/MMC3/UxROM) have the top 16KB fixed at $C000 with bank 0 at $8000 by default - pass a startAddress in the right range to disassemble a different bank. -- **C64 isn't a console**: media is `.prg` / `.d64` / `.t64`, not "ROM". `loadMedia` takes a `mediaKind` arg; auto-defaults are usually right. -- **Atari 5200 build works but doesn't run**: cc65 produces .a52 files, but our atari800 core needs Asyncify which isn't yet wired into the host. Use Atari 7800 or Lynx if you want a 6502 platform that actually runs. -- **Genesis BG init**: a freshly-booted Genesis ROM shows a black screen for many frames because VDP init is slow. Step 60+ frames before screenshotting. -- **`framesRun` is monotonic**: `state({op:'load'})` restores the core but doesn't roll back our frame counter. Use it for state, not for "what frame am I on" precision. +### When a call fails, read the error first -## Before writing input or memory-layout code +Errors name the fix. Build failures return `issues: [{file, line, col, severity, message, stage}]` ranked critical first; fix `critical:true` entries (such as `WILL HANG:` loop-bound traps) even on a successful build; fall back to `log` only when `issues` is empty. Tool errors carry the recovery step (an eviction's "No ROM loaded" names the exact `loadMedia({...})`; a rejected load points at `cart({op:'identify'})`; a mistyped button returns `ignoredButtons[]`). A crashed WASM toolchain returns `stage:"crash"` without affecting the session. -Two tools that save real time and frustration: +## Reverse engineering and romhacking -- `input({op:'layout', platform})` - returns the platform's controller protocol, bit order, libretro id mapping, AND which buttons physically exist. Read this before writing an asm `read_pad` routine OR before designing controls (so you don't bind to a button the platform doesn't have). -- `symbols({op:'map', dbg, platform})` - after `build({output:'romWithDebug'})`, returns where every variable in your source actually landed in memory, grouped by region (zeropage / system RAM / code / data). cc65 reserves the first 2 zeropage bytes for its runtime; your first `.res 1` lands at `$02`, not `$00`. Don't guess. +Read the playbook first: `platform({op:'doc', platform:'romhacking', name:'playbook'})`. It wires the tools below into a decision tree and covers text, compressed assets and graphics round trips. -## Cross-platform inputs +A good default order: -`input({op:'set'})` accepts an Xbox-shaped controller: D-pad, 4 face buttons (use `north/east/south/west` for portable code - they translate per platform), shoulders (`l/r`), triggers (`l2/r2`), sticks (`l3/r3`), plus `start`/`select`. Older platforms are subsets - `input({op:'layout'})` tells you which buttons are real. Pressing a non-existent button is a silent no-op. +1. `cart({op:'identify', path})`: platform, title, mapper, save RAM (handles zip-wrapped ROMs). +2. `cheats({op:'lookup', path})`: the bundled cheat database is a labeled RAM and code map for thousands of known ROMs (`kind:ram` = a variable, `kind:code` = a patch site). Cheap; check early. Labels are probable name matches; verify before patching. +3. Disassemble and trace for anything about code or data the cheats do not cover: `disasm({target:'project'})` for a byte-exact rebuildable project (edit a region `.asm`, then `build({output:'reassemble', platform, path})`; pass `background:true` for ROMs of 512 KB or more and poll with `job`); `disasm({target:'references'|'accessScan'})` for who touches an address; `breakpoint({on:'write'|'read'|'pc'})` for the exact instruction; `watch({on:'range'|'pc'|'copy'|'dma'})` to discover routines; `symbols({op:'analyze'})`, `disasm({target:'functions'|'cfg'|'xrefs'|'reachable'})` for structure; `disasm({target:'decompile'})` for Ghidra pseudocode; `breakpoint({on:'jumptable'})` for computed dispatchers no static walk can follow. +4. Verify live before patching: `memory({op:'write'})` the address and watch the effect. +5. Patch: `romPatch({op:'write'|'writeMany'})` with `expect:` bytes (refuses a wrong revision), or prototype with `cheats({op:'apply'})`. -⚠ **The raw libretro names `a`/`b`/`x`/`y` are NOT the platform's printed button labels - and on the three genesis_plus_gx platforms (Genesis, SMS, Game Gear) they're INVERTED.** Verified live across all 14 classic platforms: -- **Genesis**: gpgx maps Genesis A/B/C onto libretro **y/b/a** - so `input({op:'set', a:true})` presses Genesis **C**, and Genesis A (SGDK `BUTTON_A`) is `{y:true}` / `{west:true}`. -- **SMS / Game Gear**: button 1 (TL, main fire) is libretro **b**, button 2 (TR) is libretro **a** - so `{a:true}` presses button 2, not 1. -- **Every other core maps straight through** (`{a}`→A, `{b}`→B): NES, GB/GBC, SNES (incl. x/y/l/r), GBA, PC Engine (a=I, b=II), MSX (a=trig 1), Lynx (a=A). C64 + Atari 2600 are single-fire - fire is `{b}`/`{south}`, `{a}` is a no-op. Atari 7800 boots in 1-button mode (both fires read INPT4) until you enable 2-button mode. +Find a value's address with the search loop (`memory({op:'search'})` then `searchNext`), not a full-RAM diff. Drive the ROM's own codecs with `cpu({op:'call'|'decompress'})` and put assets back with `romPatch({op:'makeStored'|'findFree'|'relocate'|'findPointer'})`. Edit on-screen text with `text({op:'learn'|'find'|'encode'})`. Assemble patches with `assembleSnippet`. These work on the 15 classic platforms; disassembly and the Rizin/Ghidra analysis cover 18 platforms including the 3D consoles' MIPS and SH-4. -**The safe habit: use the spatial names (`north/east/south/west`) or `input({op:'press', button:'a'|'b'|'c'|'1'|'2'})` - both resolve to the correct physical button per platform.** Reach for raw `a`/`b` only when you mean the literal libretro id. `input({op:'layout', platform}).faceButtons` is the authoritative per-platform map; each platform's MENTAL_MODEL has a "Driving input over MCP" note. +## Static recompilation -## Starter snippets +`disasm({target:'recompile', emit:'wasmcart', platform, path, outputPath})` recompiles a whole ROM into a playable wasmcart for nes (fceumm), snes (snes9x, with SA-1, SuperFX, DSP-n, ST010/011/018, S-DD1, SPC7110, CX4, OBC1, S-RTC, MSU-1, BS-X, Sufami Turbo), gb/gbc (gambatte), gba (mGBA), sms/gg and genesis (genesis_plus_gx, including SVP carts). Every ROM byte offset is a compiled entry point and RAM code runs in a matching interpreter, so no discovery run is needed. Per-game settings go in `options` (ST011/ST018 and DSP-1 carts need firmware you supply; romdev does not ship chip firmware). `emit:'sync32'|'c'` builds a native sync32 cart from a Genesis ROM; `emit:'ir'|'blockMap'` exports decoded instructions for your own tools; the default `asm` output translates one routine to SNES or Genesis assembly. -`examples({op:'snippets', platform})` (default `mode:'list'`) and `examples({op:'snippets', platform, mode:'get', snippetName})` give you vetted boilerplate - reset routine, `read_pad`, OAM DMA, palette upload, nametable clear. Each snippet's comments encode foot-guns prior agent sessions already hit. Always check what's available for your platform before writing platform-specific boilerplate from scratch. NES, SNES, SMS, GG, GB/GBC, Genesis, GBA, C64, Atari 7800 all have substantial snippet libraries. (Prefer forking + grafting from the real example games; snippets remain for one-off references.) +Verify with the `frame` ops: `verifyRecompile` (pixels, memory regions, audio and must-fail controls against the reference core in one call; `auto:true` picks the schedule itself), `findDiverge` with `cart` (first differing frame and byte; `level:'instruction'` finds the first divergent instruction), `fuzzRecompile` (seeded play hunting traps), `traceInstructions` (the real executed instruction stream), `cycles` (sync32 frame cost and profile). -**Three ways to actually use them:** +Every recompiled cart carries a `licence` entry naming the emulator code it contains (GPL, MPL or non-commercial terms, depending on the platform); the texts are in the package's `LICENSES/` directory. Read `platform({op:'doc', platform:'guide', name:'recompile'})` before using any of this. -- `examples({op:'snippets', platform, mode:'get', snippetName})` - one snippet's contents, returned as a string. -- `examples({op:'snippets', platform, mode:'getAll', language?})` - every snippet joined into one string. Useful for **reading**; the giant blob lands in your context (or pass `outputPath` to write it to disk instead). -- **`examples({op:'copySnippets', platform, destinationDir, language?, include?})`** - writes every snippet (or a filtered subset) straight to disk. **Bytes never pass through your context.** Use this when you're copying into a project dir. Flattens `lib//foo.c` → `/foo.c`. Optional `include: ["vdp_init", "joypad_read"]` whitelist for cherry-picking. Default `overwrite: true` (vetted boilerplate is meant to be regenerated). +## Matching decompilation -## Don't burn your own context with binary data +`decomp({op})` drives a splat-based decomp project (N64 and PlayStation) through the original compiler as WASM. The loop: `setup` (fresh checkout), `import`, `plan`, `resolve`, `generate` (m2c candidate via romdev-m2c), `compare` (compile inside its translation unit; per-instruction and relocation equality), `search` (bounded permuter job via romdev-permuter; `job`, `jobs`, `candidates`), `integrate` (patch, full-ROM byte verify, auto-revert), `progress`. Runtime ops (`smoke`, `overlays`, `symbolize`, `state`, `trace`, `coverage`) check a live session. Campaign ops (`workbench`, `dispatch`, `experiment`, `gate`, `diagnose`, `variants`, `rank`, `ledger`, `research`, `knownSource`, `assets`, `skill`, `handoff` and others) run the bundled decomp workbench in process. `exactFunctionMatch` and `romLinked.status:'exact'` are the acceptance signals; `distance` only ranks. Read `platform({op:'doc', platform:'n64', name:'decomp'})` first; `decomp({op:'skill'})` returns the bundled campaign skill. -The biggest mistake agents make on this server is reading binary files into their own context just to forward them to a tool. Don't. Every tool that consumes large binary inputs accepts paths: +## wasmcart, WebGPU and jsgame -- `loadMedia({ platform, path })` instead of inlining `base64` -- `build({ output:'rom', sourcePath, binaryIncludePaths, includePaths, outputPath })` - paths in AND a path back out (`binaryPath`). Inline base64 only on opt-in `inline: true`. (Or `build({output:'project', path})` to build a whole dir without a manifest.) -- `encodeArt({ stage:'tilemap', platform, pngPath, outputDir })` - full-screen PNG → deduped tiles + tilemap + palette, input from disk, output to disk. **This is the tool for splash/title screens** (see the splash-screen section below). Supported: nes, snes, genesis, sms, gg, gb, gbc, c64. -- `frame({ op:'screenshot', path })` - writes PNG to disk, skips inline payload. For a quick "did it change?" sanity check, add `scale: 0.5` (nearest-neighbor, pixel-art-safe) - ~75% fewer image tokens; reserve full resolution for when you actually need pixel detail. **Cheaper still: `symbols({op:'resolve'})` → `memory({op:'read'})` reads the one byte of state with zero image tokens (see Symbol-aware debugging).** -- `tiles({ op:'png', source:'path', outputPath })` - render a ROM file's tiles to a PNG sheet -- `encodeArt({ stage:'tiles', platform, pngPath, outputDir })` - PNG → native tile bytes, input from disk. Pass `tileOrder:'sprite'` for COLUMN-major (Genesis/Lynx multi-cell hardware-sprite order) instead of the default row-major. -- `encodeAudio({ target:'brr', pcmPath, outputPath })` - SNES BRR (the SPC700's only sample format) -- `encodeAudio({ target:'xgm2pcm', wavPath, name, outputCPath })` - GENESIS sample SFX: WAV → XGM2 PCM (8-bit signed mono, 13.3 kHz / 6.65 half-rate, 256-padded) + a 256-aligned C array you `#include` and play with `XGM2_playPCM`. Bakes in the format rules so you don't botch sign/rate/alignment/padding. -- `encodeAudio({ target:'xgm2', vgmPath, name, outputCPath })` - **GENESIS MUSIC: a `.vgm`/`.vgz` → a COMPILED XGM2 blob** + a 256-aligned C array you `#include` and `XGM2_play()`. `XGM2_play()` needs a *compiled* blob (split FM/PSG streams + sample table), NOT raw VGM - this does that compile (a pure-JS port of SGDK's `xgm2tool`; no Java/jar). PSG-only tracks coexist with `xgm2pcm` SFX. `system:'ntsc'|'pal'` forces the timing flag. +`loadMedia({platform:'wasmcart', path})` runs a WebAssembly cart. Carts must target wasmcart ABI v4 or later (older ones are refused). Buttons map by position (`a` is east). GL carts get their own GL context; WebGPU carts load the same way (`gpuPower`, `wgpu:false`, `deterministicStepMs` are load options). Load GL carts with `presentWindow:true` before opening a playtest window. `wasm({op})` inspects a cart (conformance, named debug state, events, a `command` request/reply channel). `pack({target:'wasc'|'jsgame'})` builds the archive. Details: `platform({op:'doc', platform:'guide', name:'wasmcart'})`. -When a tool has `path` and `base64` variants, prefer `path`. The server runs on the same machine; both sides share the filesystem. There's no reason to round-trip 50KB of base64 through your prompt. - -## Art-first workflow (user does the pixel art, agent wires the ROM) - -For users who'd rather paint sprites in LibreSprite than write tile bytes by hand, four asset-loader tools parse FOSS editor outputs directly into platform-native tile data - no `encodeArt({stage:'tiles'})` + ImageMagick chain, no installs beyond the editor itself. - -- **`importArt({from:'aseprite', path, platform, outputDir})`** - parse `.ase` (LibreSprite, GPLv2 fork of Aseprite). Returns deduped `tile_bytes` + named `tiles[sliceName] = { tile_indices, width_tiles, height_tiles }` + `tags[name] = { from, to, delays_ms[] }` for animations. Indexed-mode .ase preserves the artist's palette; RGBA mode falls back to platform-master nearest-neighbour. The artist names their slices ("player_idle", "chalice") → game code references the same names. **The killer DX feature** for art-led projects. - -- **`importArt({from:'tiled', path, platform, outputDir})`** - parse Tiled `.tmj` (BSD, the de facto FOSS level editor; export as JSON, not XML `.tmx`). Returns per-layer `data` blob + `empty_mask` bitfield (so "no tile" stays distinguishable from "tile 0") + `object_layers[name]` with named placements (player_start, doors, chests) and arbitrary key/value properties. **Multi-layer + object support** means the artist owns level design end-to-end, including spawn data. - -- **`importArt({from:'gif', path, platform, outputDir, frame_indices?})`** - extract frames + delays from any GIF. Every editor exports GIF; this is the universal animation pipeline. omggif under the hood - no native deps. Caveat: doesn't apply GIF disposal, so export with `Disposal: Replace` for full-frame anims. - -- **`importArt({from:'texturepacker', pngPath, manifestPath, platform, outputDir})`** - TexturePacker-style PNG+JSON. LibreSprite's `Export Sprite Sheet → JSON-Hash` writes this directly. Supports `meta.frameTags` for animation grouping. - -**Palette interop:** - -- `palette({source:'platformMaster', platform, format: "png" | "lospec" | "hex", outputPath?})` - `"png"` is the swatch sheet for `-remap` dithering (existing behavior). `"lospec"` returns `{name, author, colors:[hex_no_hash]}` for direct LibreSprite/lospec.com import. `"hex"` returns one `#RRGGBB` per line - universal interchange. - -- `encodeArt({stage:'tiles'})` now validates the input PNG against the platform's master palette (PLTE for indexed PNGs, distinct-RGB scan for truecolor) with ±8/channel tolerance and surfaces colors-outside-gamut as `warnings[]`. Doesn't throw - silent color shift was the most common newbie failure; now it's loud. - -**Workflow walkthrough** + canonical glue code: [`examples/art-first-workflow/README.md`](examples/art-first-workflow/README.md). Six-step path from picking a Lospec palette through `importArt({from:'aseprite'})` + `importArt({from:'tiled'})` to a working ROM. - -For repeated builds in an iteration loop, this compounds: a 256KB SNES ROM in 20 build cycles = 7 MB of base64 text accumulated in your context. Paths cost ~60 bytes per call. - -## Splash / title / full-screen background images - USE `encodeArt({stage:'tilemap'})`, do NOT hand-roll +## If a human is watching, open playtest early -If you want a full-screen picture (a splash screen, title card, cutscene still, status panel), there is exactly ONE correct path. **Do not write your own PNG→tile loop** - packing 4bpp/2bpp bitplanes, deduping tiles, assigning palette lines, and building the name-table entry words by hand is fiddly and the failure mode is ugly: the image comes out with the right *shapes* but wrong colors (everything one color) and vertical striping/choppiness. That means your tile bytes were raw RGB-ish values instead of palette indices, or the bit packing/row stride was off. +If a human is with you, open the playtest window as soon as the first build succeeds: `playtest()` opens a native SDL window that runs the ROM live with USB gamepads and returns immediately. Every other tool keeps working on the same live host, and rebuilds update the window in place. The human should be playing while you iterate. -The correct workflow (all platforms with a tilemap - nes, snes, **genesis**, sms, gg, gb, gbc, c64): +- No gamepad: relay the `keyboardControls` / `tellUser` note from the response. +- `playtest({op:'status'})` reports `perf` (fps and per-stage costs); `playtest({op:'fps', show:true})` draws a counter for the human. +- While the human presses buttons, their input wins and responses carry `humanCoDriveWarning`; `catalog({op:'status'})` shows `humanInputActive`. Use `host({op:'pause'})` or a second session for deterministic stepping. +- Skip it for CI, batch RE, or when told "headless". A failed open is a tool error with a `reason` (`sdl-binary-missing`, `no-display`, `sdl-error`) and every other tool stays headless. -1. **Size the source** to the platform's screen: Genesis **320×224**, NES/SNES/SMS 256×224/256×192, GB 160×144, C64 320×200. -2. **Quantize to the platform palette** so colors land on hardware-displayable values: - ``` - palette({ source:'platformMaster', platform:"genesis", format:"png", outputPath:"/tmp/pal.png" }) - magick splash.png -dither FloydSteinberg -remap /tmp/pal.png splash_q.png - ``` -3. **Convert in one call:** - ``` - encodeArt({ stage:'tilemap', platform:"genesis", pngPath:"splash_q.png", outputDir:"out/" }) - ``` - You get `out/chr.bin` (deduped tiles), `out/nametable.bin` (tilemap entries), `out/palette.bin`, and `out/preview.png`. **Look at `preview.png`** - it's the tool re-rendering its own output, so if the preview is correct your in-game result will be too. If the preview is wrong, the input PNG is the problem, not the encode. -4. **Wire it in:** DMA `chr.bin` to VRAM, load `palette.bin` into CRAM/CGRAM, write `nametable.bin` to your BG plane base. The response `note` tells you the exact sizes + where each blob goes per platform. +To show a game moving on the `/livestream`, call `host({op:'play', seconds})` once; never loop `frame({op:'step'})` calls to keep the stream alive. -Genesis specifics: 4bpp tiles (32 B each), **40×28 cells**, up to **4 palette lines of 16 colors** - `encodeArt({stage:'tilemap'})` bin-packs your image's colors across the lines and picks the right line per 8×8 cell automatically. Name-table entries are 16-bit big-endian. Set your Plane A width to 64 cells. The response's `genesis.warnings[]` flags any 8×8 cell that needs >16 colors (the VDP's hard limit) - if you see those, the source art has too many colors crammed into one cell; re-author or accept the approximation. +The sessions guide covers the window ops, hotkeys, aspect, pointer carts and the livestream in full. -If a platform genuinely lacks a tilemap (Atari 2600 races the beam; 7800 uses display lists) `encodeArt({stage:'tilemap'})` throws with an explanation - those need hand-authored per-scanline data, there is no automated path. +## Active Bezels -## Known toolchain landmines +An Active Bezel (`.ab`) runs beside a ROM every frame and draws a composite scene. With one attached, `frame({op:'screenshot'})` returns the composite by default, not the core's picture; `catalog({op:'status'})` reports `activeBezel` whenever one is attached, so check it before interpreting captures in an unfamiliar session. `source:'core'|'both'` selects the picture. Bezels with `pre_frame` can poke memory and override input invisibly to breakpoints (`activeBezel.preFrame` in status). Load with `loadMedia({..., useActiveBezel:true})`; authoring needs no toolchain (`npx --package active-bezel abtool scaffold my-bezel lua`). Details: `platform({op:'doc', platform:'guide', name:'bezels'})`. -Two cross-cutting notes apply broadly; the rest is platform-specific and lives in -each platform's docs (read them for the system you're on - see below). +## Sessions -- **C compilers run a pre-flight lint before the real compile.** When a build - fails (or even when it succeeds with warnings), read the structured `issues[]` - - entries with `stage:"lint"` name the exact file:line and carry a `ref:` into - the relevant GOTCHAS section. Pass `lint:"strict"` to FAIL the build on any - lint hit (default is advisory). Don't trust the raw compiler `log` line numbers - - they're often off-by-one; the lint line is the right one. -- **All SDCC platforms (GB, GBC, SMS, GG, MSX, ColecoVision) are C89.** No inline - `for (int i = ...)`, no mid-block declarations, no compound literals/designated - initializers - hoist every declaration to the top of its block. The lint catches - these; the canonical reference (plus the WRAM-layout traps that masquerade as - "miscompiles") is [`src/platforms/gb/lib/c/SDCC_GOTCHAS.md`](src/platforms/gb/lib/c/SDCC_GOTCHAS.md). +Your emulator lives in your session for the server's lifetime; sessions do not expire. Use one session for the whole job and keep sending the same identity. +On MCP, call initialize once and reuse the session id; re-initialize only after a server restart (HTTP 404) or an explicit missing-session error. +Clients on the 2026-07-28 protocol revision should pass one stable `session` argument (a descriptive slug) on every tool call. -**Platform-specific toolchain traps live in each platform's -`MENTAL_MODEL.md` / `TROUBLESHOOTING.md` (read via -`platform({op:'doc', platform, name:'mental_model'|'troubleshooting'})`) - read -them for YOUR platform before you build.** By symptom: +- A host idle for about 10 minutes may be evicted; the next call fails with "No ROM loaded" and names the exact `loadMedia({...})` to re-run. Open playtest windows are never evicted. +- `state({op:'autoSnapshot', enabled:true})` and `state({op:'recoverSnapshot'})` survive a server restart. +- Running several sessions: declare yourself with the `x-romdev-agent` header (or `dev.romdev/agentHandle` in `_meta`) and end sessions with `host({op:'shutdown'})`. +- A different `session` value is a fully isolated second emulator. +- `feedback({op:'record', title, body, severity})` logs a defect locally for the human. -- **SNES asm `ok:false` with empty/cryptic `issues[]`** → asar silent-fail idioms - (`$ - label` size expr, `STA SYMBOL+N` on a `=`-constant, bank-border crossed) + - **CHR/tilemap VRAM overlap** (garbage BG tiles) → snes `TROUBLESHOOTING`. -- **SNES has no sound** → audio is a SEPARATE SPC700 build (`platform:"spc700"` → - `.incbin` → $2140-$2143 handshake; `encodeAudio({target:'brr'})` for samples) → - snes `MENTAL_MODEL` "Sound" + `TROUBLESHOOTING`. -- **Hand-asm clobbers the C runtime / a ZP var isn't where you put it** → cc65 - zero-page starts at **$02** ($00-$01 reserved); first `.res 1` = $02. All cc65 - platforms (NES, C64, Atari, Lynx) → nes/c64 `MENTAL_MODEL`. -- **Busy BG art renders garbage / `encodeArt({stage:'tilemap'})` warns** → NES - 256-unique-tiles-per-pattern-table cap → nes `MENTAL_MODEL`. -- **GB/GBC: white screen, sprites garbage, VRAM stays empty, or "works until a - button is held then corrupts"** → header/CGB-flag auto-fix, `shadow_oam` - page-alignment, `memcpy_vram` (raw VRAM stores get elided), OAM-DMA-from-HRAM, - crt0 BSS-zeroing, and `gb_vram` (NOT `video_ram`) → gb `MENTAL_MODEL` footguns + - `SDCC_GOTCHAS`. -- **SMS/GG: sprites past slot N vanish / text cut off / sprites invisible** → - 8-sprites-per-scanline limit, SAT `$D0` terminator, R6 sprite-tile-base - ($2000 vs $0000), GG OAM hardware-vs-visible coords → sms/gg `MENTAL_MODEL`. - -Turnkey NES/GB/GBC projects (`examples({op:'fork'})`) copy every runtime file -the example needs (`*_runtime.{h,c}`, `gb_hardware.h`, crt0, linker cfg) into the -project dir and auto-fix the cart header at build - iterate the whole dir with -`build({output:'run', path, platform})`. Details in those platforms' MENTAL_MODELs. - -## Session continuity - REUSE YOUR SESSION - -**MCP sessions on romdev do NOT expire.** They are persistent for -the lifetime of the server process - which is hours/days, not minutes. -If you call `initialize` ONCE at conversation start, that same session -key works for every subsequent tool call all session long. - -**DO NOT** call `initialize` again "just to be safe," "because the -session might have timed out," or "because it's been a few minutes." -None of those things happen here. Every tool is already registered at -session init (no loading step), but creating a fresh session breaks the -per-session emulator state (loaded ROM, save states, scroll position, -etc. live PER session) - you'd have to re-`loadMedia` and lose your place. - -You ONLY need to re-initialize in TWO cases: - -1. **Server restart.** You'll see HTTP 404 with "unknown session id" - on your next tool call. Send `initialize` once - every tool re-registers automatically (no category reload). You can confirm a restart by checking - the server's process lifetime - but really, just react to the 404 - when it happens; don't preemptively reconnect. - -2. **`Mcp-Session-Id` header missing from your tool call.** If - somehow your client lost the session ID, you'll get an explicit - error pointing you at re-initialize. The header is sticky in - normal MCP client usage; you won't lose it without something going - wrong on the client side. - -**Known historical friction (acknowledged 2026-05-25, since fixed):** -real-world agents previously reported losing connections ~30% of long -sessions. Server-side persistence is stable now. If you DO observe a -session drop without a server restart, open an issue at -https://github.com/monteslu/romdev/issues with the timing - it's a -regression we want to catch. - -**Anti-pattern to AVOID:** opening a new session before every "block" -of work. This is almost always wrong, loses your per-session emulator state, and bloats the server's session table. One session per -conversation, end of story. +Details: `platform({op:'doc', platform:'guide', name:'sessions'})`. ## When in doubt -`platform({op:'list'})` for capabilities. `catalog({op:'status'})` for what's currently loaded. `platform({op:'toolchains'})` for build tools. `state({op:'list'})` for save slots. Tools are introspectable; you don't have to remember the matrix. +`platform({op:'list'})` for capabilities, `platform({op:'capabilities', platform})` for which ops a platform supports, `catalog({op:'status'})` for what is loaded, `platform({op:'toolchains'})` for build tools, `state({op:'list'})` for save slots, `memory({op:'regions'})` for memory. Tools describe themselves; you do not have to remember the matrix. diff --git a/packages/romdevtools/CHANGELOG.md b/packages/romdevtools/CHANGELOG.md index 694c25dc..8a5f428f 100644 --- a/packages/romdevtools/CHANGELOG.md +++ b/packages/romdevtools/CHANGELOG.md @@ -6,25 +6,366 @@ the `romdev-mcp` bin is kept as an alias.) ## Unreleased -### Browser-capable glue for the 2D cores and the CLI toolchains - -`romdev-core-host` documents a bytes-only browser path (`loadCore({ factory, -wasmBinary })`), but the glue it would load could not run there: every 2D -libretro core and every tool linked with `EM_CLI_FLAGS` was built with -`-s ENVIRONMENT=node`, which makes emcc hard-code `ENVIRONMENT_IS_NODE=true`. -The glue's first statement is then `await import("module")`, so a browser or -Web Worker fails before the wasm is even instantiated, although neither the -cores nor the tools use anything but MEMFS. - -These recipes now link with `-s ENVIRONMENT=node,web,worker`: the 13 2D cores -(fceumm, fake08, bluemsx, geargrafx, gametank, gambatte, genesis_plus_gx, -handy, mgba, prosystem, snes9x, stella2014, vice) and `EM_CLI_FLAGS` (sdcc + -sdas*/sdld, mcpp, rgbds, cc65, asar, dasm, sjasm, tcc816, wla-dx, vasm). -Runtime detection picks node under Node, so server behaviour is unchanged, -and the `.wasm` binaries are unaffected (the flag only changes the JS glue). -`verify-wasm.mjs` now refuses to publish those glue files if they regress to -node-only. NODERAWFS builds, the GPU cores and the gcc-family wraps are left -as they were. +- **The 2D cores and the CLI toolchains load in a browser or Web Worker.** + They were linked with `-s ENVIRONMENT=node`, so their glue began with + `await import("module")` and failed outside Node before the wasm loaded, + although they use nothing but MEMFS. The 14 2D core recipes (fceumm, fake08, + bluemsx, bsnes, geargrafx, gametank, gambatte, genesis_plus_gx, handy, mgba, + prosystem, snes9x, stella2014, vice) and `EM_CLI_FLAGS` (sdcc + sdas*/sdld, + mcpp, rgbds, cc65, asar, dasm, sjasm, tcc816, wla-dx) now link with + `node,web,worker`. Under Node nothing changes, and the `.wasm` files are the + same; only the JS glue differs. `verify-wasm.mjs` refuses to publish those + glue files if they come out node-only again. + +## 0.151.1 - 2026-10-20 + +- **wasmcart ^0.36.1**, which ships wasmcart's test cart + (`node_modules/wasmcart/testcart/testcart.wasc`): every pad with all 21 + button bits, sticks and triggers, every pointer slot, the wheel and keyboard, + a note per face button with L/R channel panning, and a save checked byte for + byte at every start. Load it to see what `input` or a real controller + delivers; the wasmcart guide says how. +- **The playtest window sends Guide and the back paddles to a wasmcart cart as + their own buttons.** Guide arrived as Select, so on a wasmcart cart the + Guide button pressed Select, and the paddles never arrived. A libretro core + still gets Guide as Select. + +## 0.151.0 - 2026-10-20 + +- **wasmcart ^0.35.1.** Carts can prefetch assets: `wc_asset_prefetch` + fetches an asset in the background, so the read that follows does not stall + a frame (wasmcart SPEC.md, "Asset prefetch"; a cart that never calls it is + unaffected). +- **Runtime code generation takes bigger modules.** A cart can link one + generated module of up to 256 MiB (it was 4 MiB), so a static recompiler's + guest code is no longer refused. + +## 0.150.2 - 2026-10-16 + +- **A closed WebGPU cart frees its memory.** wasmcart ^0.34.4 (native-dawn + ^0.1.6): every WebGPU cart the server loaded stayed in memory after it was + closed, about 240 MB a load, with its GPU device and Dawn threads, so a long + session that loaded WebGPU carts over and over ran the machine out of memory. + GL carts were not affected. +- **WebGPU carts read GPU results on time when stepped.** Between stepped + frames the host now waits for the GPU work a frame submitted before the next + one runs, as a browser does between animation frames. Buffer reads a cart + maps (GPU particle counts, readbacks) arrived a varying number of frames late. + +## 0.150.1 - 2026-10-15 + +- **Four controllers.** `input({op:'set'})` takes up to four ports (it stopped + at two), so a wasmcart cart reads all four pads. +- **wasmcart ^0.34.3**: pads keep their slots when controllers are unplugged + and plugged back in a different order. + +## 0.150.0 - 2026-10-11 + +### Breaking changes + +- **wasmcart ^0.34 (ABI v4).** The `wasmcart` dependency moves from ^0.24 to + ^0.34.2. Carts built against an ABI older than v4 are refused at load: rebuild + them against wasmcart 0.32 or later. A cart must also export `wc_alloc` and + `wc_free` for any host-to-cart write (GL strings such as `glGetString`, + WebGPU messages, text payloads); carts built with the 0.32 or later SDK do. +- **wasmcart buttons map by position.** `input({a:true})` on a wasmcart now + presses the east face button (`WC_BTN_B`), as `a` does on every libretro + core, and `b` presses south (`WC_BTN_A`). Update wasmcart input scripts, or + use the `south`/`east`/`west`/`north` names, which mean the same thing on + every platform. +- **wasmcart triggers are 0..32767** (ABI v4), not a byte. Carts that read + triggers need the v4 range. +- **Zero `inputPtr`/`timePtr`.** The host no longer writes pads or the clock + through a zero or misaligned pointer, and `wasm({op:'conformance'})` fails + such a cart. A cart that relied on offset 0 must point them at real memory. +- **`sms_cram` is 64 bytes**: one little-endian u16 per colour, all 32 colours. + It was 32 bytes holding the first 16 colours as word pairs. Readers of the + region need the new layout. `palette({source:'live'})` on SMS is now + correct. +- **`disasm` emit:'ir' output records.** Undecodable offsets now produce + `decodeStatus:'data'` records, bytes at the end of the ROM are reported as + `truncated-at-rom-end`, pc-relative operands of secondary records are + rebased (they were wrong), and GB records carry CPU addresses. IR consumers + should expect these records. +- **Instruction stepping.** `frame({op:'stepInstructions'})` refuses a `count` + over the cap instead of clamping it, and a step that ran no instruction + returns `stepped:false` with an `error` instead of an empty success. +- **decomp never runs the host toolchain.** Compile, compare, integrate and + verify run IDO, binutils, asm-processor and cpp as WASM/JS from a recipe + romdev reads out of the project's Makefile. A build step with no WASM/JS + equivalent is reported and its existing output kept, never run on the host; + host compilers and build drivers are refused. `buildCommand` is recorded for + reference only. The workbench no longer looks for an external checkout and + no Python environment is used. +- **sync32 `video`.** An unknown `build({platform:'sync32', video})` value now + fails the build naming the valid values (`'240'`, `'180'`, `'128'`). It used + to pack silently as mode 1. +- **SNES chip data is user-supplied.** snes9x, bsnes and recompiled SNES + carts no longer carry any chip data ROM. A DSP-1, DSP-3 or ST010 cart needs + the chip's data ROM in the system directory (`dsp1b.data.rom` or + `dsp1b.rom`, `dsp3.data.rom` or `dsp3.rom`, `st010.data.rom` or + `st010.rom`; `loadMedia({firmware})` copies one there), and `options.firmware` + when recompiling. Without it the cart is refused with the file and its size + named. On bsnes the Super Game Boy needs `sgb_boot.bin` / `sgb2_boot.bin`, + and a Cx4 cart uses bsnes's high-level emulation unless `cx4.data.rom` is + there. +- **GL carts get a private GL context.** Every GL wasmcart session has its own + context, which fixes server crashes with parallel GL sessions. Set + `ROMDEV_SHARED_GL=1` to restore the shared context. +- **Genesis assembly is assembled by GNU as.** `build({platform:'genesis'})` + for assembly sources, `assembleSnippet({cpu:'68k'})` and the recompiler's + m68k target now run the m68k-elf GNU as from `romdev-toolchain-m68k-gcc` + through a Motorola-syntax front end (`src/toolchains/m68k-asm/`) instead of + vasm. The source syntax is unchanged (org, dc/dcb/ds, equ/set/=, rs and + offset, rept, macros with \1..\9 \0 \@ \# NARG and mexit, conditional + assembly, include/incdir/incbin, .local and 1$ labels, equr/reg, + cnop/align/even), and the encoding choices are kept (moveq/addq/lea forms, + shortest branches, short absolute addresses for labels below $8000), so + existing sources build to the same bytes. What changes: + - The build result's `toolchain` is `"m68k-elf-as"` (was `"vasm68k"`), and + diagnostics read `main.s:12: error: message` with `issues[].stage` + `"m68k-as"` (was vasm's `error N in line L of "file"` with stage + `"vasm"`). + - An underscore between digits is a digit separator (`$7000_0083` is + $70000083; vasm read $7000). This fixes the precomputed VDP command in the + shipped `sprite_table.s` snippet. `0x` hex is accepted (vasm read 0). + - A space after a comma inside instruction operands is accepted. + - `suba.w #$8000,An` is no longer rewritten into a `lea` that subtracted in + the wrong direction. + - `rorg`, `comm`, `dr.*` and extended/packed floating point data are + reported as unsupported; section directives have no effect (one flat + image laid out by `org`). + - Assembler options: `-D NAME=VALUE`/`--define`, `-I` and `-m68000`..`-m68060` + are honored, other vasm flags are ignored with a note. + - The build result now carries `symbols` (each label and its address). + +### Prebuilt binary fixes + +- `z80-elf-objdump` in `romdev-toolchain-sdcc` 0.2.2 printed every 8-bit H + register operand as `/` (`ld d,/`), and that reached `disasm` and emit:'ir' + output for Z80 platforms. The Z80, MIPS and SH toolchains are rebuilt from + source and the register names are correct again. +- The MIPS, SH and ARM `cc1` builds wrote a damaged `.ident` string into + every object (`GCC: (GNU) //////`). MIPS and SH are rebuilt; ARM and m68k + are restored from clean builds. + +### Static recompiler (new) + +- `disasm({target:'recompile', emit:'wasmcart'|'wasm'|'wat', platform, rom})` + recompiles a whole ROM into a playable wasmcart (or the bare module, or its + WAT text). Each backend is ported from its reference emulator and is checked + against it frame by frame: + - NES (fceumm): mappers 0, 1, 2, 3 and 4, undocumented opcodes, code run + from RAM, APU audio sample-exact. + - SNES (snes9x): LoROM, HiROM and ExHiROM, SPC700 and S-DSP audio, hires, + interlace and PAL, battery saves, and the coprocessors SA-1, SuperFX, + DSP-1 to DSP-4, ST010, ST011, ST018, OBC1, S-RTC, MSU-1, S-DD1, SPC7110, + CX4, BS-X and Sufami Turbo. DSP-1, DSP-3, ST010, ST011 and ST018 carts + need `options.firmware` (chip program and data ROMs are not shipped). + - GB and GBC (gambatte): the PPU dot for dot, timers, HDMA, OAM DMA, + MBC1/2/3/5 and HuC1, the MBC3 clock, APU audio sample-exact. + - GBA (mGBA): ARM and Thumb, audio, mosaic, the OBJ budget, GPIO with + RTC and sensors. + - SMS and GG (genesis_plus_gx): cycle-exact, PAUSE NMI, IM2, TMS9918 modes, + the Korean mapper, GG carts in SMS mode, a cart database, audio + sample-exact. + - Genesis (genesis_plus_gx): 6-button and second pads, J-Cart, PAL, backup + RAM, EEPROM and mappers, address errors, interlace mode 2, Mode 4, + YM2612 and PSG audio sample-exact, and SVP carts (the SSP1601 DSP and its + DRAM). +- Code a game writes into RAM, or code in a bank its compiled code did not + cover, runs exactly with default options: SMS/GG and Genesis carry an + interpreter built from the backend's own lowering (`options.ramInterpreter`), + and the other backends already ran RAM code generically. +- Must-fail controls build a deliberately wrong cart so a verification run can + prove it detects a fault: `options.breakArm`, `breakThumb`, `breakChip`, + `svpBreak`, `ramInterpreter:false`, and `muteChannels` for audio. +- Recompiled carts declare wasmcart ABI v4. +- A recompiled cart contains code ported from its reference emulator, so it is + under that emulator's licence (fceumm and gambatte GPL-2.0, mGBA MPL-2.0, + Genesis Plus GX, Musashi, z80.c and snes9x non-commercial). Every cart's + `romdev.recompile` section carries a `licence` entry (SPDX id, terms, + upstream name, URL and pinned commit, the licence texts and the notices that + must travel with every copy). NOTICE has a "Recompiled carts" section and the + licence texts ship in the new `LICENSES/` directory. +- `emit:'sync32'` (and `emit:'c'`) on `platform:'genesis'` builds a native + sync32 cart for an open RP2350-based console, with `options.extraCflags`, + `audioRate:'reference'`, `audioQuality:'half'` and exact or fast timing + profiles. +- `pack` writes .wasc files deterministically (fixed timestamps, sorted + entries), so the same inputs give the same bytes. + +### disasm emit:'ir' and blockMap + +- `emit:'ir'` now covers genesis (68000), gb/gbc (LR35902), nes (6502), + snes (65816) and gba (ARM and Thumb) as well as Z80, with `fileOffset` and + `length` ranges and `cpuState:'arm'|'thumb'`. +- New `emit:'blockMap'` (with `primaryOnly`). + +### frame: recompile verification and profiling + +- `frame({op:'verifyRecompile', cart, reference})` runs a recompiled cart + beside its source ROM on the reference core and scores pixels, machine state + and audio at chosen frames, with wrong-input controls and frame-offset + search. `requireStateMatch` defaults to true; `referenceCore`, `firmware`, + `cartButtonMap` and `p1.`-`p4.` input prefixes are accepted. +- Auto mode (`auto:true`, or `atFrames` omitted) picks the input schedule and + the scored frames itself from the reference core, reports every candidate + and a `reproduce` call, and returns INCONCLUSIVE with the reason when no + reference frame has enough content. +- `findDiverge` gains a recompile mode (cart against reference), + `level:'instruction'` and `audio:true`, and accepts frame 0. +- New `frame({op:'traceInstructions'})` and `frame({op:'fuzzRecompile'})`. +- New `frame({op:'cycles'})` for sync32 carts: profile, per-frame cycles, + annotated source, series and groups. +- `frame({op:'step'})` accepts `count` as an alias for `frames`; + `stepInstructions` accepts `format:'compact'`. + +### Cores and memory regions + +- fceumm, gambatte, snes9x, genesis_plus_gx and mGBA keep a free-running + instruction trace with register columns. +- New regions: `gba_iwram`, `gba_timing`, `snes_timing`, `gb_lcdlog`, + `gb_apu_raw`, `gba_audio_raw`, `gpgx_blip_deltas`, `genesis_svp_dram`, + `genesis_svp_iram`, `genesis_svp_ssp`, `snes_chipstate`, `snes_bsx_psram`, + `sync32_timing` and `sync32_profile`. `gb_cpu_regs` bytes 14-17 carry the + cycle counter. +- `cpu({op:'read'})` reports the core's clocks under `coreInternal`, and + sync32 frame cycles. +- The `genesis_cram` description is corrected (little-endian packed 9-bit). +- Fixes: gambatte single-step and breakpoints no longer hang in HALT; + gambatte's F register reads correctly; a Z80 interrupt entry on + genesis_plus_gx is visible to breakpoints and the trace; mGBA's Thumb ADD + sets the V flag correctly on overflow. +- New alternate SNES core: `loadMedia({platform:'snes', core:'bsnes', + firmware})`, in the new package `romdev-core-bsnes`. +- snes9x includes ares's firmware-chip code, used only when `st011.rom` or + `st018.rom` is in the system directory. + +### wasmcart host + +- WebGPU carts load, step, screenshot and run in the playtest window. The load + result and `catalog({op:'status'})` report `gpu:'webgpu'|'gl'|null`, and + capabilities carry `hasWgpuRendering`. `loadMedia({gpuPower:'low-power'| + 'high-performance'})` picks the GPU on a two-GPU machine and the result's + `gpuAdapter` names it; `loadMedia({wgpu:false})` runs a dual GL/WebGPU cart + on GL. wasi-sdk carts (threads included) built with wasmcart's WebGPU + support run the same way. +- `loadMedia({deterministicStepMs})` sets the clock step of a deterministic + replay. +- `wasm({op:'command'})` is a text request/reply debug channel through named + debug fields. +- Bytes debug fields read as `{length, hex, text}`, and `wasm({op:'write', + name, hex})` writes one by name. +- Stick axes set with `input` reach the cart. +- `loadMedia` and `catalog({op:'status'})` report `abiWarnings` when a cart's + pointers are unusable; `wasm({op:'conformance'})` reports + `input-span-overlap` when a cart's pad block overlaps its clock or audio + cursor. + +### Server and tools + +- `host({op:'play', seconds})` runs a session in real time on the server from + one call (default 60 s, max 600), so the livestream shows a moving game + without a step loop; `host({op:'stop'})` ends it and reports `framesRun`. + Any other call on the session also ends it. Refused while a playtest window + is open. +- A session that averages more than 20 requests a second gets an extra + advisory naming the bulk form of the tool it is calling (`floodWarning` over + HTTP). +- `state` ops `importSram`, `exportSram`, `importDisk`, `exportDisk` and + `putDiskFile` accept `path` (they were refused before). +- `build({platform:'sync32', video:'128'})` builds a 128x128 mode-2 cart that + the console shows at 3x; `frame` screenshots of it are 128x128. sync32 + builds return symbols from the map file. + +### Decomp + +- The compile path runs in process as WASM/JS: IDO 5.3 and 7.1, the + mips-linux-gnu binutils, a JS port of asm-processor and the C preprocessor, + with the flags the project's own Makefile chooses per file (romdev reads the + Makefile itself). Objects come out byte-identical to the project's own + build. +- IDO is SGI's proprietary compiler and does not ship with romdev. Build it to + WASM from a romdev source checkout with `scripts/build-ido.sh`, or set + `ROMDEV_IDO_DIR` to a directory holding its `5.3/` and `7.1/` folders. + Without it the compile path says how to build it. +- New `decomp({op:'setup', root, targets, makeVariables})` runs a fresh + checkout's setup and extract steps in process (splat runs as romdev-splat); + `import` accepts `buildPath` and `makeVariables`. +- Workbench commands run in process. +- m2c candidates come from romdev-m2c, and permuter searches from + romdev-permuter (worker threads, the WASM toolchain, `--algorithm + levenshtein`, and distributed searches with `-J`). +- New WASM toolchains: KMC gcc 2.7.2 with binutils 2.6, EGCS 1.1.2 with + binutils 2.9.5, PS1 gcc 2.6.3 with maspsx (as JS), mips-linux-gnu gcc 14.2, + armips, slinky, pigment64 and crunch64. +- PS1 decomp projects set up through WASM/JS ports of their tools. +- Search reports gate outputs against the base function; a jump-table compare + bug is fixed. + +### New packages + +- `romdev-m2c` (GPL-3.0-only) +- `romdev-permuter` (MIT) +- `romdev-pycparser` (BSD-3-Clause) +- `romdev-rabbitizer` (MIT) +- `romdev-spimdisasm` (MIT) +- `romdev-splat` (MIT) +- `romdev-toolchain-decomp-gcc` (GPL-2.0-or-later, GPL-3.0-or-later, + LGPL-2.1-or-later, AGPL-3.0-only, MIT and Zlib, per tool) +- `romdev-core-bsnes` (GPL-3.0-only) + +`romdev-toolchain-ido` is private and is never published (see Decomp). + +### No Python, no git at runtime + +- romdev never launches Python, and its builds no longer need it (rizin + builds without meson, fake08 pins are read with node, the Genesis code + generators are JS, bsnes builds with a Python-free emcc). +- romdev reads git repositories in pure JS and never launches the git + program. + +### Licensing and packaging + +- The SNES SPC700 boot ROM is replaced by romdev's own clean-room + reimplementation (MIT, `scripts/spc700-ipl/`), in snes9x, bsnes and + recompiled carts. It samples and answers the ports on the same SPC700 cycles + as the console's (matched by measuring the ports from outside), so games + upload their sound on the same schedule and recorded frames are unchanged. + The chip data ROMs and boot ROMs upstream snes9x and bsnes + embed (DSP-1, DSP-3, ST010, Cx4, Super Game Boy) are removed at build time + and become user-supplied, like the ST011 and ST018 program ROMs. +- `romdev-platform-gba` ships the libgba and libtonc licence files. +- vasm is no longer bundled and `romdev-toolchain-vasm` is retired (its + licence allows non-commercial use only and redistribution of the unmodified + archive only). Genesis assembly uses the GPL-3.0 GNU binutils already in + `romdev-toolchain-m68k-gcc`; as with every bundled toolchain, its licence + does not encumber the ROMs you build. +- Shipped toolchain and core binaries no longer contain build-machine paths: + the GBA, m68k, MIPS, SH and decomp toolchains, cc65's libraries and + flycast are rebuilt with mapped paths. Built ROMs are unchanged. +- armips ships in `romdev-toolchain-mips-gcc`, beside the mips-linux-gnu + binutils. +- `romdev-toolchain-decomp-gcc`'s PS1 asset and string tools get neutral + names (`psx-str`, `psx-disk`, `psx-assets`), and `romdev-permuter`'s commands are renamed under the + `romdev-permuter-` prefix (`romdev-permuter-remote`, `romdev-permuter-remote-controller`). +- `psx-assets`, `psx-disk` and `psx-str` no longer carry any of the game's + names. The upstream tools compiled in the game's stage, boss and character + names, its short title (module, package and crate names, file paths, env + vars, messages) and the disc's volume identifiers. romdev builds them from a + rewritten copy of the pinned source: objdiff progress labels are the overlay + codes, the console-port file lists come from the project's config, the + short title in paths and env vars is read from the project the tool runs + in, and `psx-disk make` copies the volume identifiers from the original + disc image. `extract-assets`, `build-assets`, `psx-disk make` and + `psx-str process` output is unchanged, and `objdiff-gen` writes the same + units and categories with code labels. +- The `romdevtools` package licence field becomes `SEE LICENSE IN NOTICE`: + the package is MIT, and the recompiler backends it ships carry their + reference emulators' licences, as NOTICE and `LICENSES/` describe. +- Every published package whose contents changed gets a new version, and + romdevtools pins them. ## 0.149.1 - 2026-09-16 @@ -2533,8 +2874,9 @@ Affects 0.116.0 only. 30,531 of 30,532 published 8-letter codes in the bundled DB, and after the fix 20,090 of 20,118 unique DB codes re-encode byte-identical; the rest are known mis-published outliers). Every emitted 8-letter code used - to differ from its published spelling by exactly this bit (`SLZPLOVS` - for Contra's `SLXPLOVS`). Codes spelled either way still APPLY - fceumm + to differ from its published spelling by exactly this bit (for example, a published + Game Genie code with X as its third letter came out with Z there). Codes + spelled either way still APPLY - fceumm and romdev's decoder branch on length and mask the bit - but emitted text is published text, and real hardware sets the marker. - Why the round-trip test never caught it: the decoder masks the bit, so @@ -3045,7 +3387,7 @@ The earlier stall was an input mistake on my side, not an emulator limit: these DC dialogs confirm on **B**, and only `a` had been tried. Nothing in the core changed. -Still honestly scoped: *sustained* play (a full level, long-run stability, +Still out of scope: *sustained* play (a full level, long-run stability, framerate in the heaviest scenes) remains uncharacterised, so the platform is still flagged EXPERIMENTAL. @@ -3137,7 +3479,7 @@ regression goldens all see the actual draws. - `status.gl`: `"rendered"` | `"stubbed"` for GL carts, `null` for 2D carts; `getCapabilities().hasGlRendering` alongside. -- Degrades honestly: wasmcart < 0.6.0 or missing webgl-node → the old +- Degrades cleanly: wasmcart < 0.6.0 or missing webgl-node → the old stubbed-GL behavior (2D framebuffer only), reported as `"stubbed"`, never a load failure. Version-gated by reading wasmcart's package version (its exports map hides package.json - resolved next to the entry). @@ -3263,7 +3605,7 @@ only because that is where a wasmcart cart first met the playtest window. **wasmcart harness, the rest of the plan - deterministic replay, debug events, positioning, and the dogfood proof** (WS3 Parts B+C, WS5, WS6 of -internal-romdev/WASMCART_UMBRELLA_PLAN.md). Consumes wasmcart 0.5.0 (spec-side: +the wasmcart harness plan). Consumes wasmcart 0.5.0 (spec-side: `WC_FLAG_DETERMINISTIC` + `wc_set_seed` + `WC_DETERMINISTIC_RNG`; `wc_debug_mark` + captured `wc_log`; both opt-in, default structurally absent). Feature-detected - inert on wasmcart 0.4.0. **Depends on `wasmcart` ^0.5.0** @@ -3304,7 +3646,7 @@ Feature-detected - inert on wasmcart 0.4.0. **Depends on `wasmcart` ^0.5.0** loads, seed divergence, caps/status surfacing, events drain, conformance, airtight golden, seed-mismatch refusal, WAV rate) - skip-guarded so a clean clone on wasmcart 0.4.0 stays green. -- **WS6 dogfood shipped** - `rom-games/wasmcart/starfall/`: a real game +- **WS6 dogfood shipped** - a test game (deterministic spawns, named state, marks, audio, input) developed and verified END-TO-END through the live MCP server: seeded load → conformance → screenshot → input-driven `player_x` by name → non-silent audio record → @@ -3321,8 +3663,8 @@ live for a fresh install rather than feature-detected-inert. ## 0.104.0 - 2026-07-23 -**wasmcart harness, Slice 1 - the sense loop + conformance** (internal-romdev/ -WASMCART_UMBRELLA_PLAN.md WS1+WS2). romdev is the run/debug/validate harness +**wasmcart harness, Slice 1 - the sense loop + conformance** (the wasmcart harness +plan, WS1+WS2). romdev is the run/debug/validate harness for wasmcart carts, NOT an SDK - it starts at the `.wasc` the developer's own toolchain produced. This slice makes the WASM-runtime introspection WasmcartHost already had reachable, and gives the agent EARS to go with its eyes: @@ -3521,7 +3863,7 @@ repinned here as `romdev-core-host@0.2.0` + `romdev-core-runner@0.1.1`): ## 0.99.0 - 2026-07-18 -**The host + runner extraction** (internal-romdev/ROMDEV_CORE_RUNNER_PLAN.md +**The host + runner extraction** (core runner plan Phase 1; MODULARITY.md item 4's trigger fired - six SDK run bridges + the web IDEs are the consumers): @@ -3570,7 +3912,7 @@ that go across systems get done for all systems"): touched - nothing that could alias ROM/regs (a Genesis read-watch on a cart table at $000218 stays literal). Verified live on gpgx: arming the $E2-mirror form catches the canonical $FF-form writer. - ⚠ Residual, stated honestly: snes9x is the only core whose hooks + Residual limitation: snes9x is the only core whose hooks canonicalize LIVE accesses, so on the other platforms a WRITER that itself uses a mirror form still evades the watch. Fixing that direction needs per-core hook patches + core rebuilds - deferred until it bites someone. @@ -3850,7 +4192,7 @@ A batch of RE-workflow fixes from two SNES annotation sessions (carving routines byte-exact, since the reassemble rebuild splices each chunk into `original.rom` by offset. Measured on a real 512 KB cart: **~5 min → ~33 s**, and the one-call `build({output:'reassemble'})` rebuild is **byte-identical** (verified). `planRebuild`'s Genesis header/pad math spans all chunks. -- For the fully-robust path on any multi-MB ROM, `background:true` + poll (0.89.0) now genuinely +- For the most reliable path on any multi-MB ROM, `background:true` + poll (0.89.0) now genuinely helps here - 15 chunks parallelize where one region couldn't. ## 0.91.2 - 2026-07-15 @@ -3984,7 +4326,7 @@ Two fixes from a real-world `disasm({target:'project'})` + `build({output:'reass - **`readablePercent` no longer lies about padding.** A uniform-fill bank (all `$FF` or `$00`) disassembles into junk instructions (`sbc $FFFFFF,x` ...) and used to report a bogus ~100% readable - so the *emptiest* bank looked the "most readable," inverting the "low % = data bank" heuristic. Fill - regions are now detected (≥99.5% one byte, ≥256 bytes) and reported honestly: `readablePercent: null` + regions are now detected (≥99.5% one byte, ≥256 bytes) and reported as such: `readablePercent: null` + `fill: true` + `fillByte`, excluded from the code-only `readablePercentAvg`, and labeled in the region `.asm` header. The payload reports `fillRegions` count. @@ -4271,7 +4613,7 @@ test makes any drift a hard failure. ## 0.71.1 - 2026-06-29 -Feedback from the first run against the `pret/pokeruby` GBA decompilation. +Feedback from the first run against a GBA decompilation project. - **Project-mode `entry` now resolves a NESTED path** (e.g. `entry:'src/main.c'`). The recursive asset staging already walked subdirs, but entry resolution stayed top-level @@ -4286,7 +4628,7 @@ Feedback from the first run against the `pret/pokeruby` GBA decompilation. - **`platform({op:'resolve'})` surfaces the toolchain(s)** + a note that the build toolchain is WASM/harness-only (was core-paths-only, forcing `node_modules` spelunking). - **GBA `mental_model` "What's NOT bundled"** now calls out **agbcc's absence** (the real - blocker for byte-exact Gen-III decomps like pokeruby/pokeemerald) and adds a "romdev's + blocker for byte-exact GBA decomps) and adds a "romdev's build model" section: `build` is single-shot compile→ROM, the toolchain can't back an external Makefile, with the confirmed host agbcc recipe for matching builds. @@ -4424,7 +4766,7 @@ The build + host fixes that made it work (every one was a real wall): ### Dreamcast examples + sh-c -O level fix -Four DC example programs (rom-games/dreamcast/): dchello (test card), bounce (animation), +Four DC example programs: dchello (test card), bounce (animation), starfield (shmup background), grid (puzzle/board) - all build via the WASM toolchain and render distinct content through Flycast, exercising the dc.h helper (no-KOS PowerVR2 framebuffer + 2D primitives). @@ -4734,7 +5076,7 @@ buildable through the normal createProject/build tool flow. **PS1** (4 × 3D + 1 × 2D, on a software 3D engine + the GPU): shmup STARFALL, racing POLE BENDER (a real receding 3D road), platformer BLOCK HOP, sports -SLAM COURT (3D pong/air-hockey), puzzle DROP GRID (2D - the right idiom for a grid). +SLAM COURT (3D paddle/air-hockey), puzzle DROP GRID (2D - the right idiom for a grid). **N64** (all 5 × 3D - the N64 was a 3D-first machine, so even the puzzle is a 3D well of cubes): STARFALL 64 / POLE BENDER 64 / BLOCK HOP 64 / SLAM COURT 64 / @@ -4801,7 +5143,7 @@ pcsx_rearmed (R3000) are rebuilt with romdev's CPU instrumentation, so: - Reproducible via the updated build-pcsx-rearmed.sh / build-parallel-n64.sh (patch the source + hooks + exports). -**Remaining honest gap:** `audioDebug` (PS1 SPU / N64 audio chip decoders) is still +**Remaining gap:** `audioDebug` (PS1 SPU / N64 audio chip decoders) is still TODO. The tile/sprite/nametable inspectors stay N/A by hardware (framebuffer/3D renderers have no such tables). Everything else is at parity. Suite 1050/1050. @@ -4890,7 +5232,7 @@ shim's `instanceof WebGLRenderingContext` check (needs WebGL1 to be a distinct class), the signed-vs-unsigned `RETRO_HW_FRAME_BUFFER_VALID` compare, and the all-transparent FBO alpha (forced opaque in a new RGBA decode path). -**Still pending** for full parity (honestly off in the manifest): `build` (needs a +**Still pending** for full parity (off in the manifest): `build` (needs a MIPS toolchain - PSn00bSDK/libdragon), `decompile` (needs a MIPS SLEIGH spec in the decompiler - slaspec sources exist, a decompiler-package rebuild), `getCPUState` + `cheats` (need a core rebuild exposing those exports). The framebuffer/3D renderers @@ -5373,7 +5715,7 @@ three guarantees now hold across the whole platform matrix: scripts/patches/ carry all of it - the whole stack reproduces from a clean clone). `cpu({op:'call', pure:true})` remains gpgx-only (the other systems' CPU/video loops are not separable without deeper core surgery); their calls - carry the ⚠ frame-logic caveat instead. + carry the frame-logic caveat instead. - `test/regsnap-all-cores.test.js`: live single-step snapshot + freeze proof on 10 platforms (plus the existing gpgx suite for Genesis/SMS/GG). @@ -5397,7 +5739,7 @@ The first core rebuild in this release (gpgx only; pins unchanged, patch extende raised - so the game's own VBlank logic can NOT run "concurrently" and stomp the driven routine's output buffer (a real session diffed a correct codec reimplementation against that poisoned output for ~1.5h). Non-pure - calls that spanned frames now carry a loud ⚠ caveat naming the risk and + calls that spanned frames now carry a warning caveat naming the risk and the fix. - **Genesis `system_ram` normalized to CPU byte order** - gpgx stores 68k work RAM host-LE word-swapped (`work_ram[A^1]`); the raw layout leaked @@ -5463,7 +5805,7 @@ treatment: byte-identical `build()` rebuilds** - their asm toolchain is cc65/ca65, the same match that made NES one-call. NES-style glue: HEADER segment carrying the original header bytes, per-bank segment wrappers, generated multi-bank - `.cfg` via `linkerConfigPath`. **PCE was previously the one honestly-LOSSY + `.cfg` via `linkerConfigPath`. **PCE was previously the one LOSSY case** (planRegions trimmed real $FF padding and didn't strip copier headers) - both fixed, `verifiable:true` now. - **SMS/GG, MSX, and 2600 banked carts get per-bank native rebuild recipes** @@ -5612,7 +5954,7 @@ resolution it may not change what the model sees (and can slightly degrade it vi bicubic downscale of stretched pixels). Reworded the param + tool description to lead with **native (`scale:1`, the default) = perfect pixels = the accurate representation**, keep the genuinely-useful DOWNscale (`<1`, fewer tokens for -"did it change?" checks), and frame upscale honestly as a last resort for clients +"did it change?" checks), and frame upscale as a last resort for clients that can't zoom a small image. (No behavior change - `scale` was already opt-in and defaulted to native; this is the docs telling the truth about it.) (Committed during the 0.27.0 cycle but AFTER 0.27.0 published - ships in 0.28.0.) @@ -6435,7 +6777,7 @@ discoverable rename table). ### Fixed - Genesis music docs named the wrong tool/API. Corrected to `XGM2_play` (there is - no `XGM2_startPlay` in R58), the compiled-blob requirement, and that the legacy + no `XGM2_startPlay`), the compiled-blob requirement, and that the legacy `xgmtool`/`.xgc`/`XGM_*` is a DIFFERENT format. - **`romPatch({op:'findPointer'})` no longer doubles its hit list with shadows.** On the multi-width systems (Genesis: 32+24-bit BE; SNES: 16+24-bit LE) a wider diff --git a/packages/romdevtools/LICENSES/GPL-2.0.txt b/packages/romdevtools/LICENSES/GPL-2.0.txt new file mode 100644 index 00000000..d511905c --- /dev/null +++ b/packages/romdevtools/LICENSES/GPL-2.0.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/packages/romdevtools/LICENSES/ISC-ares.txt b/packages/romdevtools/LICENSES/ISC-ares.txt new file mode 100644 index 00000000..d5161cf5 --- /dev/null +++ b/packages/romdevtools/LICENSES/ISC-ares.txt @@ -0,0 +1,16 @@ +---------------------------------------------------------------------- +ares + +Copyright (c) 2004-2025 ares team, Near et al + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/packages/romdevtools/LICENSES/ISC-spc7110.txt b/packages/romdevtools/LICENSES/ISC-spc7110.txt new file mode 100644 index 00000000..26b749a4 --- /dev/null +++ b/packages/romdevtools/LICENSES/ISC-spc7110.txt @@ -0,0 +1,16 @@ +/***** + * SPC7110 emulator - version 0.03 (2008-08-10) + * Copyright (c) 2008, byuu and neviksti + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * The software is provided "as is" and the author disclaims all warranties + * with regard to this software including all implied warranties of + * merchantibility and fitness, in no event shall the author be liable for + * any special, direct, indirect, or consequential damages or any damages + * whatsoever resulting from loss of use, data or profits, whether in an + * action of contract, negligence or other tortious action, arising out of + * or in connection with the use or performance of this software. + *****/ diff --git a/packages/romdevtools/LICENSES/LGPL-2.1.txt b/packages/romdevtools/LICENSES/LGPL-2.1.txt new file mode 100644 index 00000000..2d2d780e --- /dev/null +++ b/packages/romdevtools/LICENSES/LGPL-2.1.txt @@ -0,0 +1,510 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations +below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it +becomes a de-facto standard. To achieve this, non-free programs must +be allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control +compilation and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least + three years, to give the same user the materials specified in + Subsection 6a, above, for a charge no more than the cost of + performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply, and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License +may add an explicit geographical distribution limitation excluding those +countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms +of the ordinary General Public License). + + To apply these terms, attach the following notices to the library. +It is safest to attach them to the start of each source file to most +effectively convey the exclusion of warranty; and each file should +have at least the "copyright" line and a pointer to where the full +notice is found. + + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or +your school, if any, to sign a "copyright disclaimer" for the library, +if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James + Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/packages/romdevtools/LICENSES/LicenseRef-GenesisPlusGX.txt b/packages/romdevtools/LICENSES/LicenseRef-GenesisPlusGX.txt new file mode 100644 index 00000000..79296dca --- /dev/null +++ b/packages/romdevtools/LICENSES/LicenseRef-GenesisPlusGX.txt @@ -0,0 +1,1028 @@ + +Unless otherwise explicitly stated, all code in Genesis Plus GX is released +under the following license: + +Copyright (c) 1998-2003 Charles MacDonald +Copyright (c) 2007-2025 Eke-Eke +Some portions copyright Nicola Salmoria and the MAME team +All rights reserved. + +Redistribution and use of this code or any derivative works are permitted +provided that the following conditions are met: + +* Redistributions may not be sold, nor may they be used in a commercial +product or activity. + +* Redistributions that are modified from the original source must include the +complete source code, including the source code for all components used by a +binary built from the modified sources. However, as a special exception, the +source code distributed need not include anything that is normally distributed +(in either source or binary form) with the major components (compiler, kernel, +and so on) of the operating system on which the executable runs, unless that +component itself accompanies the executable. + +* Redistributions must reproduce the above copyright notice, this list of +conditions and the following disclaimer in the documentation and/or other +materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +---------------------------------------------------------------------------------------- + +Nuked OPN2 core is distributed under the following license: + +/* + * Copyright (C) 2017-2022 Alexey Khokholov (Nuke.YKT) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +---------------------------------------------------------------------------------------- + +TREMOR library is distributed under the following license: + +Copyright (c) 2002, Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +---------------------------------------------------------------------------------------- + +MINIMP3 library is distributed under the following license: + +CC0 1.0 Universal + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see + + + +---------------------------------------------------------------------------------------- + +LIBCHDR is distributed with code under following licenses: + + +MAME CHD interface +------------------ +Copyright Aaron Giles +Copyright Romain Tisserand +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + Neither the name of the nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +DR_FLAC DECODING LIBRARY +------------------------ +Copyright 2023 David Reid + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +ZLIB COMPRESSION LIBRARY +------------------------ +(C) 1995-2022 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + +ZSTD COMPRESSION LIBRARY +------------------------ +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +LZMA COMPRESSION LIBRARY +------------------------ +LZMA SDK is written and placed in the public domain by Igor Pavlov. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute the +original LZMA SDK code, either in source code form or as a compiled binary, for +any purpose, commercial or non-commercial, and by any means. + +---------------------------------------------------------------------------------------- + + +NTSC FILTER LIBRARY +------------------- + +Copyright (C) 2006-2007 Shay Green. This module is free software; you +can redistribute it and/or modify it under the terms of the GNU Lesser +General Public License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. This +module is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +details. You should have received a copy of the GNU Lesser General Public +License along with this module; if not, write to the Free Software Foundation, +Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ + + +BLIP BUFFER LIBRARY +------------------- + +Copyright (C) 2003-2009 Shay Green. This library is free software; +you can redistribute it and/or modify it under the terms of the GNU Lesser +General Public License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. This +library is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +details. You should have received a copy of the GNU Lesser General Public +License along with this module; if not, write to the Free Software Foundation, +Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ + + + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + +---------------------------------------------------------------------------------------- + +Gamecube & Wii ports are linked with LIBOGC library which is distributed under +the following license: + + Copyright (C) 2004 - 2009 + Michael Wiedenbauer (shagkur) + Dave Murphy (WinterMute) + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any + damages arising from the use of this software. + + Permission is granted to anyone to use this software for any + purpose, including commercial applications, and to alter it and + redistribute it freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you use + this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. + 3. This notice may not be removed or altered from any source + distribution. + +---------------------------------------------------------------------------------------- + +Gamecube & Wii ports are linked with LIBFAT library which is distributed under +the following license: + + Copyright (c) 2006 - 2012 + Michael "Chishm" Chisholm + Dave "WinterMute" Murphy + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +---------------------------------------------------------------------------------------- + +Gamecube & Wii ports are linked with LIBPNG library which is distributed under +the following license: + + Copyright (c) 1998-2010 Glenn Randers-Pehrson + (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + + The PNG Reference Library is supplied "AS IS". The Contributing Authors + and Group 42, Inc. disclaim all warranties, expressed or implied, + including, without limitation, the warranties of merchantability and of + fitness for any purpose. The Contributing Authors and Group 42, Inc. + assume no liability for direct, indirect, incidental, special, exemplary, + or consequential damages, which may result from the use of the PNG + Reference Library, even if advised of the possibility of such damage. + + There is no warranty against interference with your enjoyment of the + + library or against infringement. There is no warranty that our + + efforts or the library will fulfill any of your particular purposes + + or needs. This library is provided with all faults, and the entire + + risk of satisfactory quality, performance, accuracy, and effort is with + + the user. + + Permission is hereby granted to use, copy, modify, and distribute this + source code, or portions hereof, for any purpose, without fee, subject + to the following restrictions: + + 1. The origin of this source code must not be misrepresented. + + 2. Altered versions must be plainly marked as such and + must not be misrepresented as being the original source. + + 3. This Copyright notice may not be removed or altered from + any source or altered source distribution. + + The Contributing Authors and Group 42, Inc. specifically permit, without + fee, and encourage the use of this source code as a component to + supporting the PNG file format in commercial products. If you use this + source code in a product, acknowledgment is not required but would be + appreciated. + +---------------------------------------------------------------------------------------- + +Gamecube & Wii ports are linked with LIBASND library which is distributed under +the following license: + +Copyright (c) 2008 Hermes +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are +permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. +- Redistributions in binary form must reproduce the above copyright notice, this list + of conditions and the following disclaimer in the documentation and/or other + materials provided with the distribution. +- The names of the contributors may not be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +---------------------------------------------------------------------------------------- + +Wii port is linked with WiiDRC library which is distributed under +the following license: + +Copyright (c) 2017 FIX94 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/romdevtools/LICENSES/LicenseRef-MAME-Z80.txt b/packages/romdevtools/LICENSES/LicenseRef-MAME-Z80.txt new file mode 100644 index 00000000..e4e5a6d4 --- /dev/null +++ b/packages/romdevtools/LICENSES/LicenseRef-MAME-Z80.txt @@ -0,0 +1,19 @@ +/***************************************************************************** + * + * z80.c + * Portable Z80 emulator V3.9 + * + * Copyright Juergen Buchmueller, all rights reserved. + * + * - This source code is released as freeware for non-commercial purposes. + * - You are free to use and redistribute this code in modified or + * unmodified form, provided you list me in the credits. + * - If you modify this source code, you must add a notice to each modified + * source file that it has been changed. If you're a nice person, you + * will clearly mark each change too. :) + * - If you wish to use this for commercial purposes, please contact me at + * pullmoll@t-online.de + * - The author of this copywritten work reserves the right to change the + * terms of its usage and license at any time, including retroactively + * - This entire notice must remain in the source code. + * diff --git a/packages/romdevtools/LICENSES/LicenseRef-Musashi.txt b/packages/romdevtools/LICENSES/LicenseRef-Musashi.txt new file mode 100644 index 00000000..48ed82a6 --- /dev/null +++ b/packages/romdevtools/LICENSES/LicenseRef-Musashi.txt @@ -0,0 +1,17 @@ +/* + * MUSASHI + * Version 3.32 + * + * A portable Motorola M680x0 processor emulation engine. + * Copyright Karl Stenerud. All rights reserved. + * + * This code may be freely used for non-commercial purposes as long as this + * copyright notice remains unaltered in the source code and any binary files + * containing this code in compiled form. + * + * All other licensing terms must be negotiated with the author + * (Karl Stenerud). + * + * The latest version of this code can be obtained at: + * http://kstenerud.cjb.net + */ diff --git a/packages/romdevtools/LICENSES/LicenseRef-SVP-notaz.txt b/packages/romdevtools/LICENSES/LicenseRef-SVP-notaz.txt new file mode 100644 index 00000000..724db398 --- /dev/null +++ b/packages/romdevtools/LICENSES/LicenseRef-SVP-notaz.txt @@ -0,0 +1,9 @@ +/* + basic, incomplete SSP160x (SSP1601?) interpreter + with SVP memory controller emu + + (c) Copyright 2008, Grazvydas "notaz" Ignotas + Free for non-commercial use. + + For commercial use, separate licencing terms must be obtained. + diff --git a/packages/romdevtools/LICENSES/LicenseRef-snes9x.txt b/packages/romdevtools/LICENSES/LicenseRef-snes9x.txt new file mode 100644 index 00000000..ca6de271 --- /dev/null +++ b/packages/romdevtools/LICENSES/LicenseRef-snes9x.txt @@ -0,0 +1,200 @@ + Snes9x - Portable Super Nintendo Entertainment System (TM) emulator. + + (c) Copyright 1996 - 2002 Gary Henderson (gary.henderson@ntlworld.com), + Jerremy Koot (jkoot@snes9x.com) + + (c) Copyright 2002 - 2004 Matthew Kendora + + (c) Copyright 2002 - 2005 Peter Bortas (peter@bortas.org) + + (c) Copyright 2004 - 2005 Joel Yliluoma (http://iki.fi/bisqwit/) + + (c) Copyright 2001 - 2006 John Weidman (jweidman@slip.net) + + (c) Copyright 2002 - 2006 funkyass (funkyass@spam.shaw.ca), + Kris Bleakley (codeviolation@hotmail.com) + + (c) Copyright 2002 - 2010 Brad Jorsch (anomie@users.sourceforge.net), + Nach (n-a-c-h@users.sourceforge.net), + + (c) Copyright 2002 - 2011 zones (kasumitokoduck@yahoo.com) + + (c) Copyright 2006 - 2007 nitsuja + + (c) Copyright 2009 - 2023 BearOso, + OV2 + + (c) Copyright 2017 qwertymodo + + (c) Copyright 2011 - 2017 Hans-Kristian Arntzen, + Daniel De Matteis + (Under no circumstances will commercial rights be given) + + + BS-X C emulator code + (c) Copyright 2005 - 2006 Dreamer Nom, + zones + + C4 x86 assembler and some C emulation code + (c) Copyright 2000 - 2003 _Demo_ (_demo_@zsnes.com), + Nach, + zsKnight (zsknight@zsnes.com) + + C4 C++ code + (c) Copyright 2003 - 2006 Brad Jorsch, + Nach + + DSP-1 emulator code + (c) Copyright 1998 - 2006 _Demo_, + Andreas Naive (andreasnaive@gmail.com), + Gary Henderson, + Ivar (ivar@snes9x.com), + John Weidman, + Kris Bleakley, + Matthew Kendora, + Nach, + neviksti (neviksti@hotmail.com) + + DSP-2 emulator code + (c) Copyright 2003 John Weidman, + Kris Bleakley, + Lord Nightmare (lord_nightmare@users.sourceforge.net), + Matthew Kendora, + neviksti + + DSP-3 emulator code + (c) Copyright 2003 - 2006 John Weidman, + Kris Bleakley, + Lancer, + z80 gaiden + + DSP-4 emulator code + (c) Copyright 2004 - 2006 Dreamer Nom, + John Weidman, + Kris Bleakley, + Nach, + z80 gaiden + + OBC1 emulator code + (c) Copyright 2001 - 2004 zsKnight, + pagefault (pagefault@zsnes.com), + Kris Bleakley + Ported from x86 assembler to C by sanmaiwashi + + SPC7110 and RTC C++ emulator code used in 1.39-1.51 + (c) Copyright 2002 Matthew Kendora with research by + zsKnight, + John Weidman, + Dark Force + + SPC7110 and RTC C++ emulator code used in 1.52+ + (c) Copyright 2009 byuu, + neviksti + + S-DD1 C emulator code + (c) Copyright 2003 Brad Jorsch with research by + Andreas Naive, + John Weidman + + S-RTC C emulator code + (c) Copyright 2001 - 2006 byuu, + John Weidman + + ST010 C++ emulator code + (c) Copyright 2003 Feather, + John Weidman, + Kris Bleakley, + Matthew Kendora + + Super FX x86 assembler emulator code + (c) Copyright 1998 - 2003 _Demo_, + pagefault, + zsKnight + + Super FX C emulator code + (c) Copyright 1997 - 1999 Ivar, + Gary Henderson, + John Weidman + + Sound emulator code used in 1.5-1.51 + (c) Copyright 1998 - 2003 Brad Martin + (c) Copyright 1998 - 2006 Charles Bilyue' + + Sound emulator code used in 1.52+ + (c) Copyright 2004 - 2007 Shay Green (gblargg@gmail.com) + + S-SMP emulator code used in 1.54+ + (c) Copyright 2016 byuu + + SH assembler code partly based on x86 assembler code + (c) Copyright 2002 - 2004 Marcus Comstedt (marcus@mc.pp.se) + + 2xSaI filter + (c) Copyright 1999 - 2001 Derek Liauw Kie Fa + + HQ2x, HQ3x, HQ4x filters + (c) Copyright 2003 Maxim Stepin (maxim@hiend3d.com) + + NTSC filter + (c) Copyright 2006 - 2007 Shay Green + + GTK+ GUI code + (c) Copyright 2004 - 2023 BearOso + + Win32 GUI code + (c) Copyright 2003 - 2006 blip, + funkyass, + Matthew Kendora, + Nach, + nitsuja + (c) Copyright 2009 - 2023 OV2 + + Original Mac OS GUI code + (c) Copyright 1998 - 2001 John Stiles + (c) Copyright 2001 - 2011 zones + New MacOS GUI code + (c) Copyright 2022 - 2023 Michael Donald Buckley + + Libretro port + (c) Copyright 2011 - 2017 Hans-Kristian Arntzen, + Daniel De Matteis + (Under no circumstances will commercial rights be given) + + + Specific ports contains the works of other authors. See headers in + individual files. + + + Snes9x homepage: http://www.snes9x.com/ + Snes9x source code: https://github.com/snes9xgit/snes9x/ + + Permission to use, copy, modify and/or distribute Snes9x in both binary + and source form, for non-commercial purposes, is hereby granted without + fee, providing that this license information and copyright notice appear + with all copies and any derived work. + + This software is provided 'as-is', without any express or implied + warranty. In no event shall the authors be held liable for any damages + arising from the use of this software or it's derivatives. + + Snes9x is freeware for PERSONAL USE only. Commercial users should + seek permission of the copyright holders first. Commercial use includes, + but is not limited to, charging money for Snes9x or software derived from + Snes9x, including Snes9x or derivatives in commercial game bundles, and/or + using Snes9x as a promotion for your commercial product. + + The copyright holders request that bug fixes and improvements to the code + should be forwarded to them so everyone can benefit from the modifications + in future versions. + + Super NES and Super Nintendo Entertainment System are trademarks of + Nintendo Co., Limited and its subsidiary companies. + +------------------------------------------------------------------------------- + +Some parts included in Snes9x are usually available under a different license, +their authors have granted exception for their use in Snes9x (and/or they are +licensed as LGPL): + - JMA: GPL/LGPL, see jma/license.txt + - snes_ntsc: LGPL, see filter/snes_ntsc-license.txt + - xBRZ: GPLv3, see filter/xbrz-license.txt diff --git a/packages/romdevtools/LICENSES/MIT-blipper.txt b/packages/romdevtools/LICENSES/MIT-blipper.txt new file mode 100644 index 00000000..78b3e943 --- /dev/null +++ b/packages/romdevtools/LICENSES/MIT-blipper.txt @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2013 - Hans-Kristian Arntzen + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and + * associated documentation files (the "Software"), + * to deal in the Software without restriction, + * including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ diff --git a/packages/romdevtools/LICENSES/MIT-musl.txt b/packages/romdevtools/LICENSES/MIT-musl.txt new file mode 100644 index 00000000..c1628e9a --- /dev/null +++ b/packages/romdevtools/LICENSES/MIT-musl.txt @@ -0,0 +1,193 @@ +musl as a whole is licensed under the following standard MIT license: + +---------------------------------------------------------------------- +Copyright © 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +---------------------------------------------------------------------- + +Authors/contributors include: + +A. Wilcox +Ada Worcester +Alex Dowad +Alex Suykov +Alexander Monakov +Andre McCurdy +Andrew Kelley +Anthony G. Basile +Aric Belsito +Arvid Picciani +Bartosz Brachaczek +Benjamin Peterson +Bobby Bingham +Boris Brezillon +Brent Cook +Chris Spiegel +Clément Vasseur +Daniel Micay +Daniel Sabogal +Daurnimator +David Carlier +David Edelsohn +Denys Vlasenko +Dmitry Ivanov +Dmitry V. Levin +Drew DeVault +Emil Renner Berthing +Fangrui Song +Felix Fietkau +Felix Janda +Gianluca Anzolin +Hauke Mehrtens +He X +Hiltjo Posthuma +Isaac Dunham +Jaydeep Patil +Jens Gustedt +Jeremy Huntwork +Jo-Philipp Wich +Joakim Sindholt +John Spencer +Julien Ramseier +Justin Cormack +Kaarle Ritvanen +Khem Raj +Kylie McClain +Leah Neukirchen +Luca Barbato +Luka Perkov +M Farkas-Dyck (Strake) +Mahesh Bodapati +Markus Wichmann +Masanori Ogino +Michael Clark +Michael Forney +Mikhail Kremnyov +Natanael Copa +Nicholas J. Kain +orc +Pascal Cuoq +Patrick Oppenlander +Petr Hosek +Petr Skocik +Pierre Carrier +Reini Urban +Rich Felker +Richard Pennington +Ryan Fairfax +Samuel Holland +Segev Finer +Shiz +sin +Solar Designer +Stefan Kristiansson +Stefan O'Rear +Szabolcs Nagy +Timo Teräs +Trutz Behn +Valentin Ochs +Will Dietz +William Haddon +William Pitcock + +Portions of this software are derived from third-party works licensed +under terms compatible with the above MIT license: + +The TRE regular expression implementation (src/regex/reg* and +src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed +under a 2-clause BSD license (license text in the source files). The +included version has been heavily modified by Rich Felker in 2012, in +the interests of size, simplicity, and namespace cleanliness. + +Much of the math library code (src/math/* and src/complex/*) is +Copyright © 1993,2004 Sun Microsystems or +Copyright © 2003-2011 David Schultz or +Copyright © 2003-2009 Steven G. Kargl or +Copyright © 2003-2009 Bruce D. Evans or +Copyright © 2008 Stephen L. Moshier or +Copyright © 2017-2018 Arm Limited +and labelled as such in comments in the individual source files. All +have been licensed under extremely permissive terms. + +The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008 +The Android Open Source Project and is licensed under a two-clause BSD +license. It was taken from Bionic libc, used on Android. + +The AArch64 memcpy and memset code (src/string/aarch64/*) are +Copyright © 1999-2019, Arm Limited. + +The implementation of DES for crypt (src/crypt/crypt_des.c) is +Copyright © 1994 David Burren. It is licensed under a BSD license. + +The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was +originally written by Solar Designer and placed into the public +domain. The code also comes with a fallback permissive license for use +in jurisdictions that may not recognize the public domain. + +The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011 +Valentin Ochs and is licensed under an MIT-style license. + +The x86_64 port was written by Nicholas J. Kain and is licensed under +the standard MIT terms. + +The mips and microblaze ports were originally written by Richard +Pennington for use in the ellcc project. The original code was adapted +by Rich Felker for build system and code conventions during upstream +integration. It is licensed under the standard MIT terms. + +The mips64 port was contributed by Imagination Technologies and is +licensed under the standard MIT terms. + +The powerpc port was also originally written by Richard Pennington, +and later supplemented and integrated by John Spencer. It is licensed +under the standard MIT terms. + +All other files which have no copyright comments are original works +produced specifically for use as part of this library, written either +by Rich Felker, the main author of the library, or by one or more +contibutors listed above. Details on authorship of individual files +can be found in the git version control history of the project. The +omission of copyright and license comments in each file is in the +interest of source tree size. + +In addition, permission is hereby granted for all public header files +(include/* and arch/*/bits/*) and crt files intended to be linked into +applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit +the copyright notice and permission notice otherwise required by the +license, and to use these files without any requirement of +attribution. These files include substantial contributions from: + +Bobby Bingham +John Spencer +Nicholas J. Kain +Rich Felker +Richard Pennington +Stefan Kristiansson +Szabolcs Nagy + +all of whom have explicitly granted such permission. + +This file previously contained text expressing a belief that most of +the files covered by the above exception were sufficiently trivial not +to be subject to copyright, resulting in confusion over whether it +negated the permissions granted in the license. In the spirit of +permissive licensing, and of not having licensing issues being an +obstacle to adoption, that text has been removed. diff --git a/packages/romdevtools/LICENSES/MPL-2.0.txt b/packages/romdevtools/LICENSES/MPL-2.0.txt new file mode 100644 index 00000000..14e2f777 --- /dev/null +++ b/packages/romdevtools/LICENSES/MPL-2.0.txt @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/packages/romdevtools/LICENSES/README.txt b/packages/romdevtools/LICENSES/README.txt new file mode 100644 index 00000000..108417b2 --- /dev/null +++ b/packages/romdevtools/LICENSES/README.txt @@ -0,0 +1,18 @@ +Licence texts of the emulator code romdevtools' static recompiler carries +into recompiled carts (see NOTICE, "Recompiled carts"). Each file is copied +verbatim from the upstream source at the commit pinned in +scripts/versions.json (only line endings normalised). + + GPL-2.0.txt gambatte COPYING (also fceumm's licence) + LGPL-2.1.txt GNU LGPL 2.1 text (blip_buf, snes_spc) + MPL-2.0.txt mGBA LICENSE + LicenseRef-GenesisPlusGX.txt Genesis Plus GX LICENSE.txt + LicenseRef-Musashi.txt Musashi notice, gpgx core/m68k/m68k.h + LicenseRef-MAME-Z80.txt z80.c notice, gpgx core/z80/z80.c + LicenseRef-SVP-notaz.txt SVP notice, gpgx core/cart_hw/svp/svp.c + LicenseRef-snes9x.txt snes9x LICENSE + ISC-spc7110.txt snes9x spc7110emu.cpp notice + ISC-ares.txt ares LICENSE (its own ISC block) + MIT-blipper.txt gambatte-libretro libretro/blipper.c notice + MIT-musl.txt musl COPYRIGHT (Emscripten 4.0.18's copy) + msun-Sun.txt FreeBSD msun notice, musl src/math/__sin.c diff --git a/packages/romdevtools/LICENSES/msun-Sun.txt b/packages/romdevtools/LICENSES/msun-Sun.txt new file mode 100644 index 00000000..087d7700 --- /dev/null +++ b/packages/romdevtools/LICENSES/msun-Sun.txt @@ -0,0 +1,10 @@ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ diff --git a/packages/romdevtools/NOTICE b/packages/romdevtools/NOTICE index 2daf41ef..24a17428 100644 --- a/packages/romdevtools/NOTICE +++ b/packages/romdevtools/NOTICE @@ -1,102 +1,598 @@ -romdev - third-party component inventory -======================================== - -TL;DR - Games you build with romdev are YOURS, including to sell commercially. -A built ROM contains only your code + permissive runtime libraries, compiled by -toolchains with runtime exceptions. The non-commercial caveat below applies ONLY -to redistributing the romdev tool bundle (which contains two non-commercial -emulator cores) - never to the games you make with it. - -romdev's own code is MIT (see LICENSE). It bundles and redistributes -third-party emulator cores, compiler toolchains, and game runtime libraries, -each under its own license. This file inventories them. - -Two kinds of bundled component, governed differently: - - • COMPILERS / TOOLCHAINS produce the user's ROM. Several are GPL/LGPL, but - compilers carry a RUNTIME EXCEPTION: the license of the compiler does NOT - extend to its output. A game compiled with GPL gcc/cc65/sdcc is the - author's own work, freely licensable. The GPL obligation falls on US (we - redistribute the compiler binary) - satisfied by shipping the build recipe - + pinned upstream source so anyone can reproduce the binary (see - packages/romdev/scripts/ and BUILDING.md). - - • EMULATOR CORES never touch the user's ROM - they are a dev instrument - (run + observe). Their license governs only OUR redistribution of the core - binary. Most are GPL (OSI open source, source available upstream). Two are - NON-COMMERCIAL (see below), which is why romdev as a whole is distributed - as SOURCE-AVAILABLE / FREE FOR NON-COMMERCIAL USE rather than OSI open - source. romdev's own code is MIT and the game runtime libraries are - permissive, so games you BUILD with romdev are unencumbered (see below); - the non-commercial terms apply only to redistributing the bundled core - binaries themselves. - - -NON-COMMERCIAL COMPONENTS (why romdev is "free for non-commercial use") ------------------------------------------------------------------------ -These two cores are under custom NON-COMMERCIAL licenses. They forbid -commercial redistribution of the core, so a distribution of romdev that -bundles them is free for non-commercial use and is not labeled OSI open -source. (Your code is MIT; your built games are unencumbered - this affects -only redistribution of these emulator binaries.) - - snes9x SNES core non-commercial (snes9x license) - genesis_plus_gx Genesis/SMS/GG core non-commercial (Genesis Plus GX license) +romdevtools - licence statement and third-party inventory +========================================================== + +This file is the licence of the romdevtools npm package (package.json: +"SEE LICENSE IN NOTICE"). It has three parts: + + 1. romdev's own code is MIT. The full text is in LICENSE. + + 2. Third-party components. romdevtools contains some third-party code + itself (listed under "Third-party code inside romdevtools"), and it + depends on separate npm packages (romdev-core-*, romdev-platform-*, + romdev-toolchain-*, romdev-analysis*, and the decompilation ports) that + redistribute emulator cores, compiler toolchains and tools, each under + its own licence. This file lists all of them. Each component's own + licence governs that component. + + 3. Recompiled carts. The static recompiler (disasm({target:'recompile'}), + emit 'wasmcart' or 'sync32') builds code ported from a reference + emulator into every cart it makes. A recompiled cart carries that + emulator's licence: GPL-2.0 for NES and GB/GBC, MPL-2.0 for GBA, and + non-commercial for SMS/GG, Genesis and SNES. It also contains the code + of the game it was recompiled from. See "Recompiled carts" below. + +In short: + + - Games you COMPILE with romdev from your own source are yours, including + to sell commercially. A compiled ROM contains only your code plus + permissive runtime libraries, built by toolchains whose licences do not + extend to their output. + - RECOMPILED carts are not unencumbered (part 3). + - The non-commercial terms of two emulator cores apply to redistributing + the romdev tool bundle that contains them (and to recompiled carts built + from their code), never to games you compile. + +This section describes what each licence says; it is not legal advice. + + +How the kinds of component are governed +--------------------------------------- + + COMPILERS / TOOLCHAINS produce the user's ROM. Several are GPL or LGPL, but + their licences do not reach the compiled output: gcc's runtime library + carries the GCC Runtime Library Exception, SDCC's runtime libraries carry a + linking exception, and the other assemblers and linkers place no + conditions on what they produce. A game compiled with GPL gcc, cc65 or + sdcc is the author's own work, freely licensable. The GPL obligation falls + on romdev as the redistributor of the compiler binaries. It is met by + publishing the build recipes, romdev's patches and the pinned upstream + sources in the source repository (https://github.com/monteslu/romdev): + see packages/romdevtools/scripts/BUILD_MAP.md (which recipe builds which + package) and packages/romdevtools/scripts/versions.json (every upstream + URL and pinned commit). The recipes and patches are not in the npm + tarballs. + + EMULATOR CORES are a development instrument: running a game on a core puts + none of the core's code into the game. A core's licence governs the + redistribution of the core binary. Most are GPL. Two are non-commercial + (below), which is why a romdev distribution that bundles them is free for + non-commercial use rather than OSI open source. + + THE STATIC RECOMPILER is the exception: it copies code ported from the + reference cores into its output. Every recompiled cart carries the licence + of the core it was ported from (see "Recompiled carts"). + + +Non-commercial components +------------------------- +These two cores are under custom non-commercial licences that forbid +commercial redistribution of the core. Your own code and the games you +compile are unencumbered; a cart the recompiler builds for SMS/GG, +Genesis or SNES contains code from these cores and is non-commercial. + + snes9x SNES snes9x licence (non-commercial) + genesis_plus_gx Genesis / SMS / GG Genesis Plus GX licence + (non-commercial) + +romdevtools itself ships source derived from both (the recompiler backends +under src/analysis/recompile/), under their terms. Their licence texts are in +LICENSES/ in this package. + + +Third-party code inside romdevtools +----------------------------------- +Everything in this package not listed here is romdev's own code (MIT). + + src/analysis/recompile/ recompiler backends: code ported or generated + from fceumm, gambatte, mGBA, Genesis Plus GX, + snes9x, ares and musl. Each backend directory's + NOTICE.txt lists the ported files; licences in + "Recompiled carts" and LICENSES/. + src/decomp/asm-processor.js + JS port of asm-processor + (https://github.com/simonlindholm/asm-processor), + public domain (Unlicense). + src/decomp/maspsx.js JS port of maspsx (https://github.com/mkst/maspsx), + MIT, Copyright (c) 2023 Mark Street. + src/decomp/workbench/ JS port of n64-decomp-workbench 0.8.0 + (https://github.com/akratch/n64-decomp-workbench) + and its bundled data (field guide, compiler-law + notes, skills, fingerprints), CC0-1.0. + src/git/wildmatch.js port of git's wildmatch.c (Rich Salz, Wayne + Davison), public domain. + src/platforms/*/lib/ game runtime libraries, shipped as source (see + "Game runtime / SDK libraries"). Emulator cores -------------- - fceumm NES GPL-2.0 - gambatte GB / GBC GPL-2.0 - genesis_plus_gx Genesis / SMS / GG non-commercial ⚠ (see above) - snes9x SNES non-commercial ⚠ (see above) - mgba GBA MPL-2.0 - vice (x64) C64 GPL-2.0 - stella2014 Atari 2600 GPL-2.0 - prosystem Atari 7800 GPL-2.0 - handy Atari Lynx zlib - -Compiler toolchains (runtime exception - does not encumber compiled ROMs) --------------------------------------------------------------------------- - cc65 NES/C64/2600/7800/Lynx zlib - sdcc GB/GBC/SMS/GG GPL-2.0 (runtime libs: GPL + linking exception) - arm-none-eabi-gcc GBA GPL-3.0 (GCC Runtime Library Exception) - m68k-elf-gcc Genesis (C) GPL-3.0 (GCC Runtime Library Exception) - binutils (gcc toolchains) GPL-3.0 - newlib (gcc toolchains) BSD-style (mixed permissive) - asar SNES (asm) LGPL-3.0 - dasm Atari 2600 (asm) GPL-2.0 - vasm (m68k) Genesis (asm) free for any use (vasm license) - rgbds GB/GBC (asm) MIT - tcc816 SNES (C) LGPL-2.1 - wla-dx SNES (asm) GPL-2.0 - -Game runtime / SDK libraries (linked into the user's game; shipped as source) ------------------------------------------------------------------------------- - SGDK Genesis C engine MIT - PVSnesLib SNES C library MIT - libtonc / libgba GBA C libraries public domain / zlib-style - maxmod / mmutil GBA music ISC - hUGEDriver GB/GBC music MIT-style (see LICENSE-HUGEDRIVER) - FamiTone2 NES music permissive (see LICENSE-FAMITONE) - -Full license texts for the bundled SDK libraries live alongside their source -under packages/romdev/src/platforms/*/lib/. Emulator-core and compiler license -texts travel with their upstream source, which is fetched at build time from -the pinned commits recorded in packages/romdev/scripts/versions.json. - - -Bundled data (cheat database - used by gameCheats / applyCheat / makeCheat) ----------------------------------------------------------------------------- - romdev bundles a cheat database under packages/romdev/src/cheats/index/ - a - pre-parsed, per-platform index built from the community-aggregated RetroArch / - libretro-database cheat collection (the same data RetroArch, RetroDECK, and - Batocera ship). These cheat codes are an aggregation assembled over years from - Game Genie / Pro Action Replay code books and community cheat dumps; the - collection has no single uniform license and individual codes carry no stated - provenance. romdev redistributes a pre-parsed form (game name → decoded - address/value entries) rather than the raw .cht files, and uses it only as a - read/inspect aid + non-destructive cheat application. It is not linked into any - built game and does not affect the license of games you make. Source: - https://github.com/libretro/libretro-database (cht/). Rebuild the index from a - local .cht tree with packages/romdev/scripts/build-cheat-index.mjs. +Each core is built to WebAssembly from its upstream source (at the commit +pinned in versions.json in the source repository, where one is pinned), +with romdev's patch, and shipped in the package named. 18 cores in 18 packages. + + Core Platform Licence Package + ---------------- ------------------- ----------------- ------------------------ + fceumm NES GPL-2.0 romdev-core-fceumm + https://github.com/libretro/libretro-fceumm + gambatte GB / GBC GPL-2.0 romdev-core-gambatte + https://github.com/libretro/gambatte-libretro + genesis_plus_gx Genesis / SMS / GG non-commercial romdev-core-gpgx + https://github.com/libretro/genesis-plus-gx + snes9x SNES non-commercial romdev-platform-snes + https://github.com/libretro/snes9x + (with ares's chip cores, ISC; see below) + bsnes SNES (accuracy GPL-3.0 (libco, romdev-core-bsnes + reference for the nall: ISC) + firmware chips) + https://github.com/libretro/bsnes + A separate core, linked into nothing else. + mGBA GBA MPL-2.0 romdev-platform-gba + https://github.com/libretro/mgba + stella2014 Atari 2600 GPL-2.0 romdev-platform-atari2600 + https://github.com/libretro/stella2014-libretro + ProSystem Atari 7800 GPL-2.0 romdev-core-prosystem + https://github.com/libretro/prosystem-libretro + Handy Atari Lynx zlib romdev-core-handy + https://github.com/libretro/libretro-handy + VICE (x64) C64 GPL-2.0 romdev-core-vice + https://github.com/libretro/vice-libretro + (see "Firmware and BIOS" for the C64 ROMs) + Geargrafx PC Engine / TG-16 GPL-3.0 romdev-core-geargrafx + https://github.com/drhelius/Geargrafx + blueMSX MSX / MSX2 blueMSX licence romdev-core-bluemsx + https://github.com/libretro/blueMSX-libretro + (zlib-style; some sound-chip files from openMSX and fMSX-SDL + are GPL, per upstream license.txt) + (with C-BIOS, BSD-style; see "Firmware and BIOS") + GameTank GameTank MIT romdev-core-gametank + https://github.com/monteslu/gametank-libretro (libretro core), built on + GameTankEmulator (https://github.com/clydeshaffer/GameTankEmulator, + MIT, Copyright 2020 Clyde Shaffer) and its mos6502 core (MIT, + Copyright 2017 Gianluca Ghettini) + FAKE-08 PICO-8 carts MIT romdev-core-fake08 + https://github.com/jtothebell/fake-08 (with z8lua, MIT) + A clean-room PICO-8 player; not Lexaloffle's PICO-8. + ParaLLEl-N64 N64 GPL-2.0 romdev-core-parallel-n64 + https://github.com/libretro/parallel-n64 + Built with the glide64 GPU renderer (GL). + Beetle PSX HW PlayStation GPL-2.0 romdev-core-beetle-psx-hw + https://github.com/libretro/beetle-psx-libretro (a Mednafen PSX fork), + GLES3 hardware renderer, with OpenBIOS embedded (see "Firmware and + BIOS") + Flycast Dreamcast GPL-2.0 romdev-core-flycast + https://github.com/flyinghead/flycast, with its reios HLE BIOS + s32core sync32 MIT romdev-core-s32core + First-party interpreter for sync32, an open RP2350-based console. + +The SNES coprocessor code from ares +----------------------------------- + The firmware-running SNES coprocessors (the ST010/ST011 NEC uPD96050 and the + ST018 ARM) are compiled from ares (https://github.com/ares-emulator/ares, at + the commit pinned in versions.json, cores.ares): its processor cores + ares/component/processor/upd96050 and arm7tdmi, the Super Famicom driver + files ares/sfc/coprocessor/necdsp/memory.cpp and armdsp/memory.cpp and + io.cpp, and the nall headers they use, with romdev's glue (MIT) restating + the rest of those drivers and ares's thread clock. That code is compiled + into: + - recompiled SNES carts built with options.firmware (ST011 / ST018): the + units in src/analysis/recompile/wat/snes/ares-chips.json in this + package; + - romdev's snes9x core (romdev-platform-snes), used when st011.rom / + st018.rom is in the system directory. + ares is under the ISC license, a permissive license whose only condition is + keeping its notice, so it can sit with snes9x's non-commercial license and + with romdev's MIT code. A recompiled cart (in its licence entry's notices) + or a snes9x core build that contains it carries this notice: + + ares + + Copyright (c) 2004-2025 ares team, Near et al + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + A recompiled SNES cart's machine follows snes9x and carries snes9x's own + chip units, so those parts of a cart stay under snes9x's non-commercial + license; the ares code adds no condition of its own. No bsnes (GPL-3.0) + code is compiled into snes9x or into a cart: bsnes ships only as its own + core, romdev-core-bsnes. + + +Firmware and BIOS +----------------- +romdev ships no console manufacturer's BIOS or firmware. Where a system +needs one, romdev uses a free replacement or its own code, or the user +supplies the image. + + C64 MEGA65 Open ROMs (https://github.com/MEGA65/open-roms), + GPL-3.0 / LGPL-3.0, a clean-room KERNAL, BASIC and CHARGEN, + in romdev-core-vice roms/ with their licence files. Upstream + vice-libretro compiles Commodore's ROMs into the core; romdev + builds VICE with that disabled and redistributes none of them. + Set ROMDEV_C64_ROM_DIR to use original ROMs you own instead. + MSX C-BIOS (https://cbios.sourceforge.net), BSD-style licence, in + romdev-core-bluemsx bios/ (licence in each cbios.txt). + PlayStation OpenBIOS from PCSX-Redux (https://github.com/grumpycoders/ + pcsx-redux), MIT, embedded in romdev-core-beetle-psx-hw. + Dreamcast Flycast's reios HLE BIOS (part of Flycast, GPL-2.0). + GBA mGBA's own HLE BIOS (part of mGBA, MPL-2.0). + N64 build({platform:'n64'}) adds romdev's own minimal IPL3 boot + stub (MIT) to the ROM it produces. + SNES The SPC700 boot program in recompiled SNES carts and in + romdev's SNES path is romdev's own code (MIT), written from + the documented behaviour of the console's boot ROM. + Coprocessor firmware is supplied by the user and never ships + with romdev: the ST010/ST011 and ST018 programs (for + recompiled carts through options.firmware; for the snes9x and + bsnes cores as st011.rom / st018.rom in the system directory), + and likewise the DSP-1 data ROM, which a DSP-1 cart needs + supplied as firmware. + PICO-8 FAKE-08 needs no BIOS. + + +Analysis engines +---------------- + Rizin (CFG, xrefs, functions) LGPL-3.0 romdev-analysis + https://github.com/rizinorg/rizin + Ghidra decompiler and SLEIGH Apache-2.0 romdev-analysis-decompiler + https://github.com/NationalSecurityAgency/ghidra, built via rz-ghidra + (https://github.com/rizinorg/rz-ghidra, LGPL-3.0), plus the SLEIGH + specs GhidraBoy (SM83, Apache-2.0), ghidra-snes (65816, MIT) and + Ghidra_HuC6280 (HuC6280, Apache-2.0). Each package's NOTICE has the + full attribution. + + +Compiler toolchains (their licences do not encumber compiled ROMs) +------------------------------------------------------------------- + Toolchain Used for Licence Package + ------------------------ ---------------------- ---------------- --------------------------- + cc65 NES, 2600, 7800, C64, zlib romdev-toolchain-cc65 + Lynx, PC Engine, + GameTank + SDCC 4.4.0 GB/GBC, SMS/GG, MSX GPL-2.0 (runtime romdev-toolchain-sdcc + libs: GPL with a + linking exception) + binutils 2.42, z80-elf Z80/SM83 disassembly GPL-3.0 romdev-toolchain-sdcc + and reassembly + RGBDS GB/GBC (asm) MIT romdev-toolchain-rgbds + m68k-elf gcc 14.2.0, Genesis (C and asm) GPL-3.0 with the romdev-toolchain-m68k-gcc + binutils 2.42, newlib GCC Runtime + 4.4.0 Library Exception; + newlib BSD-style + sjasm (from SGDK) Genesis Z80 driver asm zlib romdev-toolchain-m68k-gcc + bintos (from SGDK) Z80 blob embedding MIT romdev-toolchain-m68k-gcc + asar SNES (asm) LGPL-3.0 romdev-platform-snes + tcc816 (alekmaul/tcc) SNES (C) LGPL-2.1 romdev-platform-snes + wla-dx (wla-65816, SNES (asm, link) GPL-2.0 romdev-platform-snes + wlalink) + dasm Atari 2600 (asm) GPL-2.0 romdev-platform-atari2600 + arm-none-eabi gcc 14.2.0, GBA, sync32 (C) GPL-3.0 with the romdev-platform-gba + binutils 2.42, newlib GCC Runtime + 4.4.0 Library Exception; + newlib BSD-style + mips-elf gcc 14.2.0, N64, PS1 (C) GPL-3.0 with the romdev-toolchain-mips-gcc + binutils 2.42, newlib GCC Runtime + 4.4.0 Library Exception; + newlib BSD-style + mips-linux-gnu binutils N64 decomp builds GPL-3.0 romdev-toolchain-mips-gcc + 2.46 + armips N64 decomp RSP MIT romdev-toolchain-mips-gcc + microcode + sh-elf gcc 14.2.0, Dreamcast (C) GPL-3.0 with the romdev-toolchain-sh-gcc + binutils 2.42, newlib GCC Runtime + 4.4.0 Library Exception; + newlib BSD-style + mips-linux-gnu gcc 14.2.0 N64 decomp data TUs, GPL-3.0; glibc's romdev-toolchain-decomp-gcc + .s and linker-script stdc-predef.h + preprocessing LGPL-2.1 + KMC gcc 2.7.2 + N64 decomp (N64 SDK GPL-2.0 romdev-toolchain-decomp-gcc + binutils 2.6 as compiler) + EGCS 1.1.2 (gcc 2.91.66) N64 decomp (iQue GPL-2.0 romdev-toolchain-decomp-gcc + + binutils 2.9.5 as builds) + gcc 2.6.3 (PS1 recipe of PS1 decomp GPL-2.0 romdev-toolchain-decomp-gcc + decompals/old-gcc) + slinky-cli 0.5.0, decomp builds (linker MIT romdev-toolchain-decomp-gcc + pigment64 0.6.3, scripts, textures, + crunch64 compression) + raw-deflate (zlib 1.3.1) decomp builds zlib romdev-toolchain-decomp-gcc + A PS1 decomp project's PS1 decomp setup AGPL-3.0 romdev-toolchain-decomp-gcc + own setup tools (string (Go runtime: + encoder, disc extractor, BSD-3-Clause) + asset tool) + + Upstream sources: gcc, binutils and newlib from https://gnu.org and + https://sourceware.org/newlib; cc65 https://github.com/cc65/cc65; SDCC + https://sdcc.sourceforge.net; RGBDS https://github.com/gbdev/rgbds; SGDK + https://github.com/Stephane-D/SGDK; asar https://github.com/RPGHacker/asar; + tcc816 https://github.com/alekmaul/tcc; wla-dx https://github.com/vhelin/wla-dx; + dasm https://github.com/dasm-assembler/dasm; armips + https://github.com/Kingcom/armips; the decomp compilers and tools from + https://github.com/decompals (mips-gcc-2.7.2, mips-binutils-2.6, + mips-gcc-egcs-2.91.66, mips-binutils-egcs-2.9.5, old-gcc, slinky, + pigment64, crunch64). The exact versions and commits are in versions.json + in the source repository. + + The PS1 decomp projects' assembly post-processor, maspsx, is ported to JS + inside romdevtools (see "Third-party code inside romdevtools"). + +IDO (not shipped) +----------------- + SGI's IDO 5.3 and 7.1 C compilers, which many N64 decompilation projects + build with, are proprietary. romdev does not ship them, and no romdev npm + package contains them. romdev-toolchain-ido is a private package in the + source repository that npm will not publish. To use IDO, build it yourself + from a checkout with packages/romdevtools/scripts/build-ido.sh (it + statically recompiles the IRIX programs with the pinned ido-static-recomp, + https://github.com/decompals/ido-static-recomp, MIT, and compiles the + result to WebAssembly), or set ROMDEV_IDO_DIR to a directory holding your + own build (its 5.3/ and 7.1/ folders). The IRIX programs remain the + property of their owners. + + +Game runtime / SDK libraries (linked into the user's game) +----------------------------------------------------------- + SGDK Genesis C engine MIT romdev-toolchain-m68k-gcc + PVSnesLib SNES C library MIT romdevtools + libgba 0.5.4 GBA C library LGPL with static- romdev-platform-gba + linking exceptions + libtonc 1.4.5 GBA C library MIT romdev-platform-gba + devkitPro crt0 GBA start-up code MPL-2.0 romdev-platform-gba + maxmod GBA music ISC romdev-platform-gba + hUGEDriver GB/GBC music public domain romdevtools + FamiTone2 NES music public domain romdevtools + cc65 runtime 6502 targets zlib romdev-toolchain-cc65, + romdevtools (cc65-src/) + SDCC runtime Z80 / SM83 targets GPL with a romdev-toolchain-sdcc + linking exception + libgcc gcc targets (incl. GPL-3.0 with the the gcc toolchain + sync32's ARMv8-M GCC Runtime packages, + build) Library Exception romdev-platform-sync32 + newlib gcc targets BSD-style (mixed) the gcc toolchain packages + + Notes for games that link these: + - libgba's licence says static linking does not make your game a + derivative work, but asks that a program identify its use of libgba + (for example: "based in part on the work of the devkitpro project"). + - The devkitPro crt0 is MPL-2.0: you may ship a game that contains it + under any licence; the MPL applies only to that file's source. + - libtonc is MIT: a game that links it should carry its copyright and + permission notice (libtonc/LICENSE) in its credits or documentation. + - Licence texts ship beside the libraries (LICENSE-HUGEDRIVER, + LICENSE-FAMITONE, pvsneslib/LICENSE, sgdk/LICENSE and COPYING.RUNTIME, + maxmod/LICENSE-MAXMOD, libgba/LICENSE, libtonc/LICENSE). + + Upstreams: SGDK https://github.com/Stephane-D/SGDK; PVSnesLib + https://github.com/alekmaul/pvsneslib; libgba + https://github.com/devkitPro/libgba; libtonc + https://github.com/devkitPro/libtonc; maxmod + https://github.com/devkitPro/maxmod; hUGEDriver + https://github.com/SuperDisk/hUGEDriver. + + +Decompilation tools (development instruments; they never touch a built ROM) +----------------------------------------------------------------------------- +JS ports, each in its own package with its own LICENSE and NOTICE. +romdevtools only calls them; their output is the user's work. + + Package Port of (upstream) Licence + ----------------- ---------------------------------------- --------------- + romdev-splat splat 0.37.1 (and 0.34.1 behaviour) MIT + https://github.com/ethteck/splat, + with n64img 0.3.3, pypng's writer, zlib + romdev-spimdisasm spimdisasm 1.42.4, 1.39.3, 1.35.0 MIT, plus + https://github.com/Decompollaborate/ PSF-2.0 for + spimdisasm tables and + algorithms + derived from + CPython + romdev-rabbitizer rabbitizer 1.16.2, 1.14.3, 1.13.0 (C MIT + library built to WASM, JS binding) + https://github.com/Decompollaborate/rabbitizer + romdev-m2c m2c at 1d1c4454 GPL-3.0 + https://github.com/matt-kempster/m2c (kept in its own + package) + romdev-permuter decomp-permuter at 41bd0bfc MIT + https://github.com/simonlindholm/decomp-permuter + romdev-pycparser pycparser 2.23 as vendored by m2c and BSD-3-Clause + decomp-permuter, with PLY 3.10 + https://github.com/eliben/pycparser + + Graphviz (WASM) used only by romdev-m2c for --visualize SVG output, via + the @viz-js/viz npm package (MIT wrapper); Graphviz is + EPL-1.0 and runs as a separate program. + + Also inside romdevtools: the asm-processor, maspsx and + n64-decomp-workbench ports (see "Third-party code inside romdevtools"). + + +Audio tool ports +---------------- + romdev-famitone FamiTone2's text2data (Shiru) public domain + (the port is MIT) + romdev-maxmod devkitPro mmutil (Mukunda Johnson) ISC (the port + is MIT) + romdev-xgm2 SGDK's xgm2tool MIT + + +Recompiled carts (WAT and native backends) +------------------------------------------ + disasm({target:'recompile', emit:'wasmcart'}) turns a ROM into a wasmcart + (backends: src/analysis/recompile/wat// in this package), and + emit:'sync32' turns a Genesis ROM into a sync32 .s32 + (src/analysis/recompile/native/genesis/). A recompiled cart does not run on + an emulator: so that it matches its reference core frame for frame, the + backend builds the core's machine model INTO the cart, from code ported by + hand from the core's source or generated mechanically from it. Every cart + a backend builds contains that code, so the cart is under that code's + licence. + + romdev's own parts of those directories (the CPU instruction lowerers, the + dispatch and layout code, the WAT assembler, the packer) are MIT, and each + backend directory's NOTICE.txt lists which files are ported. In a built + cart the two are combined, so the cart as a whole follows this table. + Commits are short here; the full ones are in every cart's licence entry + (and in versions.json in the source repository). + + NES (wat/nes) + from fceumm: PPU, APU, CPU timing, mappers, frame loop + https://github.com/libretro/libretro-fceumm @ 3a84a6fd + licence GPL-2.0-or-later + means sharing the cart requires offering its complete corresponding + source under the GPL. + + Game Boy / Game Boy Color (wat/gb) + from gambatte: PPU, APU, MBCs, timers, CPU timing; blipper resampler + https://github.com/libretro/gambatte-libretro @ 3262c2aa + licence GPL-2.0-only AND MIT (blipper) + means sharing the cart requires offering its complete corresponding + source under the GPL; the MIT notice travels in the cart. + + GBA (wat/gba) + from mGBA 0.11: ARM7TDMI, bus, scheduler, DMA, timers, video, audio, + GPIO/RTC, its HLE BIOS; musl's sin/cos (Emscripten 4.0.18, + with the FreeBSD msun notice of the files they come from) + https://github.com/libretro/mgba @ 6dce57ee + licence MPL-2.0 AND MIT (musl) + means file-level copyleft: sharing the cart requires making the source + of the MPL-covered files available; the MIT and msun notices + travel in the cart. + + Master System / Game Gear (wat/sms) + from Genesis Plus GX: VDP, I/O, frame order, SN76489 PSG, blip_buf + https://github.com/libretro/genesis-plus-gx @ 162c3439 + licence Genesis Plus GX licence (non-commercial) AND LGPL-2.1-or-later + (blip_buf, Shay Green) + means no commercial distribution: the cart may not be sold or used in + a commercial product or activity; the blip_buf part's source + must be offered. + + Genesis / Mega Drive (wat/genesis, and native/genesis for sync32) + from Genesis Plus GX: VDP, memory map, Z80 bus, YM2612 (from MAME's + fm.c), PSG, blip_buf, frame loop; its Musashi 68000 core 3.32 + and MAME z80.c 3.9 opcode handlers, evaluated into the cart; + SVP carts also get svp.c / ssp16.c (notaz). The sync32 backend + vendors the upstream C files (runtime/gpgx/, see UPSTREAM.txt). + https://github.com/libretro/genesis-plus-gx @ 162c3439 + licence Genesis Plus GX licence AND Musashi licence AND z80.c licence + (all non-commercial) AND LGPL-2.1-or-later (blip_buf); SVP carts + add the SVP code's licence (free for non-commercial use only) + means no commercial distribution; Musashi's notice must stay in every + binary (the cart carries it); the blip_buf part's source must be + offered. + + SNES (wat/snes) + from snes9x: memory map and ROM loading, CPU timing, DMA/HDMA, PPU, + SPC700 (its 64-byte boot ROM is romdev's own, MIT, see "SNES boot + ROM and chip data"), the coprocessors (SA-1, SuperFX from + fxinst.cpp, S-DD1, CX4, SPC7110, DSP-1..4, ST010/011/018 HLE, + OBC1, S-RTC, BS-X, MSU-1; no chip data ROM: a DSP-1, DSP-3 or + ST010 cart is built with the user's, options.firmware), and the + S-DSP from snes_spc (Shay Green) + https://github.com/libretro/snes9x @ 185488cd + SPC7110 carts: spc7110emu/dec (byuu and neviksti, ISC-style) + CX4 carts: musl's sin/cos/atan (MIT) + ST011 / ST018 carts built with options.firmware: ares (ISC, + https://github.com/ares-emulator/ares @ 4cb8d92b, see above) + The SPC700 boot program is romdev's own (see "Firmware and + BIOS"). Coprocessor firmware, including the DSP-1 data ROM, is + supplied by the user and is not part of romdev. + licence snes9x licence (non-commercial) AND LGPL-2.1-or-later (S-DSP), + plus ISC / MIT for those chips + means no commercial distribution; snes9x's licence text must go with + every copy (the cart carries it); the S-DSP part's source must + be offered. + + The cart says this itself. Its romdev.recompile custom section (for a + sync32 .s32, the metadata in rd_meta.c) has a `licence` entry: + spdx the SPDX expression above, e.g. "GPL-2.0-or-later" + terms one plain line per licence + upstream [{name, url, commit, spdx}] of each transplanted component + source the romdevtools version and directory holding the ported + code: that package, at that version, is where the + corresponding source of the emulator code is + licenceTexts where the full licence texts are (romdevtools LICENSES/) + romCode the reminder about the game's own code (below) + notices verbatim, the notices that must travel with every copy + (the non-commercial licences, Musashi, snes9x, and the + MIT / ISC notices); the standard GPL, LGPL and MPL texts + are named by SPDX id and found in LICENSES/ + The entry depends only on the platform, the cart's chips and the romdev + version, so the same inputs still build a byte-identical cart. + + The game inside. A cart recompiled from someone else's game also contains + that game's code (and any BIOS, firmware, MSU-1 data or add-on images built + into it). It can only be shared with the game owner's permission, whatever + the emulator licences allow. + + blip_buf and snes_spc are LGPL-2.1 libraries inside non-commercial cores; + the carts combine them the same way the upstream cores do. If you plan to + distribute recompiled carts, read the licences in LICENSES/. + + +Bundled data (cheat database, used by cheats({op:'lookup'|'apply'|'make'})) +----------------------------------------------------------------------------- + The cheat database ships in the romdev_game_codes package (index/), a + pre-parsed, per-platform index built from the community-aggregated + RetroArch / libretro-database cheat collection (the same data RetroArch, + RetroDECK and Batocera ship). These codes are an aggregation assembled over + years from Game Genie / Pro Action Replay code books and community cheat + dumps; the collection has no single uniform license and individual codes + carry no stated provenance. romdev redistributes a pre-parsed form (game + name to decoded address/value entries) rather than the raw .cht files, and + uses it only as a read/inspect aid and for non-destructive cheat + application. It is not linked into any built game and does not affect the + license of games you make. Source: + https://github.com/libretro/libretro-database (cht/). The index is rebuilt + from a local .cht tree with packages/romdevtools/scripts/build-cheat-index.mjs + in the source repository. + +SNES boot ROM and chip data - romdev's own, or the user's +-------------------------------------------------------- + The SPC700 sound CPU starts from a 64-byte boot ROM (the IPL) that runs the + upload protocol over ports $2140-$2143. Upstream snes9x and bsnes embed + Nintendo's. romdev uses its own instead: a clean-room reimplementation + written from the public description of the protocol and of the state it + hands over (romdevtools scripts/spc700-ipl/ipl.asm, MIT), assembled with + asar. Its port timing was matched by measuring the ports from outside + only, so a program uploads on the same SPC700 cycles as on the console. + The snes9x core, the bsnes core and every recompiled SNES cart run it; the + builds replace the upstream array (scripts/spc700-ipl/install-ipl.mjs). + + romdev ships no chip firmware, chip data ROM or boot ROM. snes9x embeds the + DSP-1 data ROM (and a sine table taken from it), the DSP-3 data ROM and the + ST010's data ROM tables; bsnes embeds the DSP-1 data ROM, the ST010 tables, + the Cx4 data ROM and the Super Game Boy boot ROMs. romdev builds both with + those tables emptied (scripts/recompile-gen/snes9x-chips/hle-data.mjs, + scripts/patches/bsnes/strip-firmware.mjs) and takes the user's files + instead: snes9x reads dsp1b.data.rom, dsp3.data.rom or st010.data.rom from + its system directory, a recompiled cart is built with the same file + (options.firmware), and bsnes reads each chip's firmware (and sgb_boot.bin / + sgb2_boot.bin) from its system directory. Without the file such a cart is + refused with the file and its size named; bsnes runs a Cx4 cart with its + high-level emulation when cx4.data.rom is absent. + + +Where the licence texts and sources are +--------------------------------------- + - romdev's own licence: LICENSE in this package. + - Licences of the emulator code the recompiler carries into carts: + LICENSES/ in this package (copied verbatim from the pinned upstream + sources; LICENSES/README.txt maps each file to its origin). + - SDK library licences: beside each library (see "Game runtime / SDK + libraries"). + - The decompilation ports: LICENSE and NOTICE in each package. + - Emulator-core and compiler licence texts travel with their upstream + source, fetched at build time from the pinned commits. The recipes, + patches and pins are in the source repository, + https://github.com/monteslu/romdev, under packages/romdevtools/scripts/ + (BUILD_MAP.md maps each recipe to the package it builds; versions.json + holds every upstream URL, commit and licence). diff --git a/packages/romdevtools/README.md b/packages/romdevtools/README.md index f173bfa2..4ff024c3 100644 --- a/packages/romdevtools/README.md +++ b/packages/romdevtools/README.md @@ -1,116 +1,66 @@ -# romdev +# romdevtools -The entry point for **romdev** - vibe-code real retro games. Build, run, inspect, and reverse-engineer actual homebrew ROMs (NES, SNES, Game Boy, Genesis, Atari, C64, GBA, PC Engine, MSX, GameTank, sync32 - and the 3D consoles N64, PlayStation, and Dreamcast), plus the **PICO-8** fantasy console (via FAKE-08), with one command - drive it yourself or let a coding assistant do it. +romdevtools is the romdev tool server. It lets a coding agent (or you) build, run, debug, reverse-engineer and recompile retro console games: NES, SNES, Game Boy and Game Boy Color, GBA, Genesis, Master System, Game Gear, Atari 2600, 7800 and Lynx, C64, PC Engine, MSX, GameTank, sync32, and the 3D consoles N64, PlayStation and Dreamcast, plus PICO-8 and the wasmcart and jsgame runtimes. Every compiler, emulator core and analysis engine is bundled as WebAssembly. ```bash npx romdevtools ``` -**What you get:** +The server listens on `http://127.0.0.1:7331` (`PORT` and `HOST` override it). Node 24 or newer. -- **Build** - bundled per-platform toolchains (cc65, SDCC, RGBDS, asar, vasm, SGDK, PVSnesLib, libtonc, ...) as WASM. Write source, compile, get a real ROM. -- **Run + see + drive** - load the ROM into an emulated console (libretro cores as WASM), step frames, screenshot, script controller input. The 2D consoles render in software; the 3D consoles (N64 via glide64, PlayStation via Beetle PSX HW, Dreamcast via Flycast) render on the **real GPU** through [`native-gles`](https://github.com/monteslu/native-gles) - headless OpenGL/EGL, no browser. PlayStation ships [OpenBIOS](https://github.com/grumpycoders/pcsx-redux) (MIT) embedded, so there's no proprietary firmware to supply. **Dreamcast is EXPERIMENTAL, but no longer just a curiosity** - the SH-4 runs on a WASM recompiler, so commercial discs boot, render, respond to input, and drive through their menus into gameplay. Across the five discs used for testing: all five boot and take controller input, and two reach live in-game scenes (3D world rendering with a working HUD); the rest land on title menus or save-file prompts. Throughput is ~70-140fps headless, against ~16fps when the SH-4 was interpreted through core 0.2.0. AICA sound is still interpreted and measures under ~12% of frame time. What hasn't been characterised is *sustained* play - a full level, long-run stability, framerate under the heaviest scenes - so treat it as young rather than finished. -- **Inspect + romhack** - read CPU/video/save RAM, watch memory, write-breakpoints, the Cheat-Engine value-search loop, a bundled cheat database, mapper-aware disassembly, and a byte-exact rebuildable-project disassembler (`disasm({target:'project'})` splits a ROM into byte-exact region `.asm`; **`build({output:'reassemble'})` rebuilds it into a byte-identical ROM in one call on all 15 classic platforms** - edit a region and rebuild, the "cmp before commit" gate for any structural hack). -- **Reverse-engineering analysis engine (all 18 platforms - incl. the 3D consoles' MIPS R3000/R4300 + SH-4)** - control-flow graphs, deep cross-references, auto-detected functions (ranked real-code-first), a one-shot structural map, and a Ghidra **decompiler** (C-like pseudocode, with hardware registers named and 6502 SLEIGH clutter folded to readable C; N64/PS1/Dreamcast images are analyzed at their true load address, and an N64 splat project gives segment-exact mapping with provenance): `disasm({target:'cfg'|'xrefs'|'functions'|'decompile'})` and `symbols({op:'analyze'})`. And the piece no static tool has: **live computed-jumptable recovery** - `breakpoint({on:'jumptable'})` runs the emulator to resolve the `JMP (table,X)` / RTS-trick dispatchers (state machines, script/battle VMs) that static analysis collapses to "could not recover." Understand *how* a routine works before you touch it - no $3,000 IDA license, no install. -- **Convert assets** - PNG → platform tiles/tilemaps, quantize-to-palette, audio importers (BRR for SNES, XGM2 PCM for Genesis). -- **Active Bezels** - an executable companion to a specific ROM (a `.ab` package) that runs once per emulated frame, reads the core's live memory, and renders the complete final scene: a map, a HUD, reconstructed world graphics, around or over the game. `loadMedia({useActiveBezel:true})` picks up the same-basename sidecar (`Game.nes` → `Game.ab`) and makes the **composite** the presented and captured picture. romdev is where these get *verified*, not just played: a package can load, tick without trapping, emit valid draw commands, and still be completely wrong about the game, so `frame({op:'screenshot', source:'both'})` returns the composite and the raw core framebuffer for the SAME frame - plus the three geometries (core framebuffer / intended display aspect / bezel scene) that are easy to conflate. Compare them against the guest's own memory reads to check the package's *interpretation*, not just that it drew something. -- **Matching decompilation (`decomp`, N64 proven)** - the function-level generate → compile → compare → refine loop against a registered splat project's OWN compiler and build (IDO via ido-static-recomp or MIPS GCC; the per-file compile command is captured from the project's `make`). `compare` compiles a candidate inside its real translation unit and returns ONE aggregate verdict - strict instruction + relocation equality vs the extracted asm, ROM-linked words vs the base ROM, the function's own jump tables/literals, and every other function in the TU unchanged; a check that could not run is `unknown`/`error`, never `exact`, and the verifier version is part of the result cache key. Around it: `import`/`resolve` (the splat segment map is the only VA→ROM resolver; overlay VAs are ambiguous until named), `plan`/`batch` (call graph from the built objects' relocations), `generate` (m2c with the TU's preprocessed context; `types propose:true` turns asm access widths into struct proposals fed back as `extraContext`/`declarations`), `search`/`job` (bounded decomp-permuter jobs with reports), `integrate`/`verify` (patch → full build → ROM sha1, auto-revert), `progress` (code bytes per object; asm, C, library, handwritten asm and retained inline asm kept apart), and runtime ops on a live session - `trace` (a real PC break at the function: a0-a3/f12/f14/stack at entry, v0/v1/f0 at return), `coverage` (instruction-exact from the core's PC bitmap, attributed to functions and basic blocks), `overlays`/`symbolize`, `state`, `smoke`. State lives in `~/.romdev/decomp//`; nothing touches the checkout except `integrate apply:true`. Backends pinned under `~/.romdev/tools/` (m2c, decomp-permuter). Doc: `platform({op:'doc', platform:'n64', name:'decomp'})`. -- **Native game runtimes (beyond emulation)** - the same run/see/drive loop also hosts two *native* game formats: **wasmcart** (`.wasc` - WASM games from any language; 2026) and **jsgame** (`.jsgame` - JavaScript canvas/WebGL games; 2024). `loadMedia({platform:'wasmcart'|'jsgame'})` → `frame({op:'step'|'screenshot'})` → `input`, over the same tools - plus **`wasm({op:'conformance'})`** (the 'won't load, why?' verdict - required exports / manifest-vs-instance / declared caps / debug + determinism consistency), `wasm({op:'info'|'exports'|'read'|'write'})` (live WCInfo + heap + module exports), **named debug state** (`wasm({op:'debugState'})` and read/write BY NAME - the cart's opt-in `wc_debug_state` table: `player_x` instead of a raw offset), **frame-stamped events** (`wasm({op:'events'})` drains `wc_debug_mark` annotations + captured `wc_log` - a run navigable by the moments the cart marked), **deterministic replay** (`loadMedia({deterministicSeed})` seeds `wc_set_seed` + fixes the virtual clock, so `regression({op:'capture'/'check'})` frame-hash goldens are airtight on carts that declare `WC_FLAG_DETERMINISTIC`; named-state checkpoints cover the carts that can't), **`audioDebug({op:'record'})`** (capture the cart's audio to WAV - ears to go with the eyes), **headless GL** (a cart whose wasm imports from the `gl` module renders on an offscreen WebGL2 context - screenshots, `frame({op:'verify'})`, and regression goldens see the real GPU draws, no window; `status.gl` reports rendered vs stubbed), and `pack({target:'wasc'|'jsgame'})` to zip a source dir into the distributable archive (the "build" step; romdev doesn't compile the WASM - bring your own). A capability descriptor marks the emulator-only tools (memory regions / cpuState / disasm) *not-applicable* for these kinds. Depends on the [`wasmcart`](https://www.npmjs.com/package/wasmcart) + [`rungame`](https://www.npmjs.com/package/rungame) packages (jsgame runs in a `vm` realm - the server self-re-execs with `--experimental-vm-modules`). -- **PICO-8 (fantasy console)** - the [FAKE-08](https://github.com/jtothebell/fake-08) player (MIT, no BIOS) runs PICO-8 `.p8` (Lua source) and `.p8.png` (cart-in-a-label-PNG) carts at 128×128 with sound. `loadMedia({platform:'pico8'})` → `frame`/`input` work like any core; `build({platform:'pico8', source: lua})` PACKAGES a runnable `.p8` from Lua (+ optional gfx/sfx/map sections) - it's a cart assembler, not a CPU compiler (the Lua IS the code). PICO-8 is a Lua VM, so instead of machine-code disasm/decompile you read the cart's Lua directly with `disasm({target:'source'})`; `memory({region:'system_ram'})` exposes the full 64KB PICO-8 address space (sprite sheet, map, sfx, general RAM, screen buffer). Its capability descriptor is a `fantasy` tier - cpuState/decompile/tile-inspectors report *not-applicable* (there's no CPU or tile hardware to inspect). Ships the [`romdev-core-fake08`](https://www.npmjs.com/package/romdev-core-fake08) core package. +## What you get -Point any coding agent at it three ways: +38 tools, each a verb with an operation axis (`memory({op:'search'})`, `disasm({target:'cfg'})`, `build({output:'run'})`): -- **Plain HTTP** - `POST http://127.0.0.1:7331/tool/{name}`; browse/try every tool at `/documentation`. -- **Agent Skill** - `GET /skills/romdev/SKILL.md` (the [Agent Skills](https://agentskills.io) standard; save it to your skills dir as `skills/romdev/SKILL.md`; ~100 tokens until invoked). -- **MCP** - it's also a [Model Context Protocol](https://modelcontextprotocol.io/) server at `/mcp` for clients that want it. **Both protocol eras are served on that one endpoint**: legacy clients (the `initialize` handshake + `Mcp-Session-Id`) work unchanged, and clients speaking the stateless **2026-07-28** revision - no handshake, no session id, per-request `_meta` - are served natively, with `server/discover` advertising what the server supports. Since that revision has no protocol session to hold your identity, the server takes it from (in order) a `_meta["dev.romdev/sessionHandle"]` handle, the optional **`session` argument every tool accepts**, or - when a call names nothing - your keep-alive connection, in which case each result ends with a `session: ` line you can pass back to pin it. Over plain HTTP the same job is done by `x-romdev-session`. +- **Build.** cc65, SDCC, RGBDS, asar, dasm, gcc and binutils for m68k, ARM, MIPS and SH, with SGDK, PVSnesLib, libtonc/libgba and other SDKs. Fork an example game with `examples({op:'fork'})`; `build({output:'run'})` builds, loads, runs and screenshots in one call. ROMs come out with the headers and checksums real hardware checks. +- **Run, see, drive.** libretro cores as WebAssembly: step frames, screenshots, controller input, save states. The 3D consoles render on the GPU through [native-gles](https://github.com/monteslu/native-gles) (headless OpenGL ES): N64 through parallel-n64's glide64, PlayStation through Beetle PSX HW with OpenBIOS embedded, Dreamcast through Flycast with its reios HLE BIOS and an SH-4 recompiler. Dreamcast support is experimental. +- **Inspect and romhack.** CPU, video and save RAM; value search; write, read and execution breakpoints; single-step; coverage; a bundled cheat database used as a labeled RAM map; mapper-aware disassembly; `disasm({target:'project'})` plus `build({output:'reassemble'})` for a byte-identical rebuild on the 15 classic platforms; ROM patching with re-injection of compressed assets; custom-font text tools. +- **Analysis.** Rizin and Ghidra compiled to WebAssembly on 18 platforms (all but sync32), including the 3D consoles' MIPS and SH-4: functions, control-flow graphs, cross-references, reachable blocks, a structural map and C pseudocode (`disasm({target:'functions'|'cfg'|'xrefs'|'reachable'|'decompile'})`, `symbols({op:'analyze'})`). `breakpoint({on:'jumptable'})` resolves computed-jump dispatchers by running the game. +- **Static recompilation.** `disasm({target:'recompile', emit:'wasmcart'})` recompiles a whole NES, SNES (with its coprocessors), Game Boy, Game Boy Color, GBA, Master System, Game Gear or Genesis ROM into a playable wasmcart. `frame({op:'verifyRecompile'})` checks it against the reference core (pixels, memory, audio, must-fail controls; `auto:true` picks the input itself), and `findDiverge` (down to `level:'instruction'`), `fuzzRecompile`, `traceInstructions` and `cycles` find and measure differences. A Genesis ROM can also be built as a native sync32 cart (`emit:'sync32'`). `emit:'ir'` exports decoded instructions for your own tools. +- **Matching decompilation.** `decomp({op})` runs the generate, compile, compare, search and integrate loop on a splat-based N64 or PlayStation project, using the project's own compiler as WebAssembly with the flags its Makefile chooses: IDO 5.3/7.1, KMC gcc 2.7.2, EGCS 1.1.2, PS1 gcc 2.6.3 with maspsx, mips-linux-gnu gcc 14, with armips and the mips-linux-gnu binutils. `setup` runs a fresh checkout's extraction in process. m2c, decomp-permuter, splat and spimdisasm run as JavaScript ports. No Python, make or host compiler is used. Project state lives in `~/.romdev/decomp//`. IDO is SGI's proprietary compiler and is not distributed: build it from a romdev source checkout with `scripts/build-ido.sh`, or set `ROMDEV_IDO_DIR` to your build. Start with `platform({op:'doc', platform:'n64', name:'decomp'})`. +- **Assets.** PNG to tiles, tilemaps and palettes (`encodeArt`), Aseprite/LibreSprite, Tiled, GIF and TexturePacker import (`importArt`), multi-sprite character capture (`sprites({op:'capture'})`), and audio for each platform (`encodeAudio`: SNES BRR and SPC driver data, Genesis XGM2 music and PCM, GBA maxmod soundbanks, NES FamiTone2, note tables for the other sound chips, sync32 synth and PCM). +- **Native runtimes.** wasmcart (`.wasc`, WebAssembly games from any language, with GL and WebGPU rendering; ABI v4 required) and jsgame (JavaScript canvas and WebGL games) on the same load, step, screenshot and input loop. `wasm({op})` validates a cart (`conformance`), reads its named debug state, drains its event log and talks to it over a `command` channel. `loadMedia({deterministicSeed, deterministicStepMs})` gives replayable runs for `regression({op:'capture'|'check'})` goldens. `pack({target:'wasc'|'jsgame'})` builds the archive; you bring your own compiler. +- **PICO-8.** The FAKE-08 player runs `.p8` and `.p8.png` carts. `build({platform:'pico8', source})` packages Lua into a `.p8`; `disasm({target:'source'})` returns a cart's Lua. +- **Active Bezels.** `.ab` companion packages that read the game's memory every frame and draw a composite scene. `frame({op:'screenshot', source:'both'})` returns the composite and the raw core frame for the same frame so a bezel's reading of the game can be checked. +- **A human in the loop.** `playtest()` opens an SDL window on the running game, with gamepads, while the agent keeps working. `host({op:'play', seconds})` shows a session moving on the `/livestream` page. -This package contains all the JavaScript - the tool surface, the WASM emulator host, the per-platform example games, runtime/library source, and debug helpers - but **no emulator or compiler WASM itself.** Those ship in the `romdev-*` binary packages it depends on; each platform's core/toolchain WASM is resolved (`import.meta.resolve`) and instantiated only the first time you build or run that platform, so memory stays proportional to what you actually use. +Detailed guides are served in session: `platform({op:'doc', platform, name:'mental_model'|'troubleshooting'})` per platform, `platform({op:'doc', platform:'romhacking', name:'playbook'})`, and `platform({op:'doc', platform:'guide', name})` for recompile, debugging, assets, music, wasmcart, bezels and sessions. -> For the full project - what romdev is, the supported-platform matrix, how the pieces fit together, and how to develop on it - see the [repository README](https://github.com/monteslu/romdev#readme). +## Connecting an agent -## What's in this package +- **MCP:** a streamable-HTTP MCP server at `http://127.0.0.1:7331/mcp`. For Claude Code: `claude mcp add --transport http romdev http://127.0.0.1:7331/mcp`. Other clients are listed in the [repository README](https://github.com/monteslu/romdev#connect). The session-based protocol and the stateless 2026-07-28 revision are both served; on the stateless revision pass one stable `session` argument on every call. The server sends [`AGENTS.md`](./AGENTS.md) as its connection instructions. +- **Plain HTTP:** `POST /tool/{name}` with the arguments as a JSON body. Send an `x-romdev-session` header on every call (required; without it you get a 401). Pick one unique, descriptive id per task; it keeps your emulator between calls and labels your work on `/livestream`. When running many sessions, also send a stable `x-romdev-agent` header so eviction at the caps takes your own idle sessions, and end each with `host({op:'shutdown'})`. `GET /openapi.json` is the spec and `GET /documentation` a local Swagger UI. Errors come back as non-2xx responses with the reason. +- **Agent Skill:** `GET /skills/romdev/SKILL.md` is an [Agent Skills](https://agentskills.io) file generated from the running server. Save it in your agent's skills directory; it costs little context until used. -- **`bin`** - - `romdevtools` → the tool server (`src/mcp/server.js`). Serves the HTTP tool routes, `/documentation`, `/skills/romdev/SKILL.md`, and an MCP endpoint on `http://127.0.0.1:7331` by default (`PORT` / `HOST` to override). `romdev-mcp` is kept as an alias of the same command. - - `romdevtools-cli` → a smoke/utility CLI, incl. `romdevtools-cli play ` (SDL window, hot-plug controllers, live fps in the title bar). -- **`src/`** - the server, MCP tools, WASM host, core/toolchain resolvers, per-platform memory interpretation, and bundled library/runtime source (cc65 libs, PVSnesLib, SGDK, libtonc/libgba, hUGEDriver, ...) that forked projects link against. -- **`examples/`** - per-platform example games (complete, working, forkable) and minimal references. +romdev runs on the same machine as your agent. Path arguments (`path`, `outputPath`, ...) are local filesystem paths, not uploads. -## Dependencies +## What is in this package -`romdevtools` depends on the binary/data packages it needs (exact-pinned), so a single install gets a matched, tested set: +- **bin:** `romdevtools` (the server; `romdev-mcp` is an alias) and `romdevtools-cli` (`romdevtools-cli play ` opens an SDL window with hot-plugged controllers and live fps). +- **src/:** the server, tools, WebAssembly host, recompiler, decomp engine, platform docs and the library and runtime source that forked projects link against. +- **examples/:** forkable example games and minimal references per platform. +- **AGENTS.md**, **NOTICE**, **LICENSES/** (licence texts for the emulator code carried into recompiled carts), **CHANGELOG.md**. -- 2D cores: `romdev-core-{fceumm,gambatte,gpgx,vice,handy,prosystem,geargrafx,bluemsx,gametank,s32core,fake08}` -- 3D / GPU cores (rendered through `native-gles`): `romdev-core-{parallel-n64,beetle-psx-hw,flycast}` -- Platforms (core + dedicated toolchain bundled): `romdev-platform-{snes,gba,atari2600}` -- Toolchains: `romdev-toolchain-{cc65,sdcc,m68k-gcc,vasm,rgbds,mips-gcc,sh-gcc}` (mips-gcc = N64/PS1 C; sh-gcc = Dreamcast C) -- GPU deps (OPTIONAL - only the 3D cores need them; the 2D cores never touch GL): `native-gles` + `webgl-node`. A headless user without a GPU stack can still run all the 2D platforms. -- Analysis: `romdev-analysis` (Rizin → WASM: control-flow graphs, cross-references, function detection) and `romdev-analysis-decompiler` (Ghidra's C++ decompiler → WASM + SLEIGH processor specs for all 18 CPUs, incl. MIPS R3000/R4300 + SH-4). Power `disasm({target:'cfg'|'xrefs'|'functions'|'decompile'})` and `symbols({op:'analyze'})`. Lazy-loaded on first use. -- Data: `romdev_game_codes` - the bundled game-code / cheat database (a free labeled RAM/code map for thousands of known ROMs), split out so it can grow independently. Lazy-loaded one platform at a time. -- Native runtimes: [`wasmcart`](https://www.npmjs.com/package/wasmcart) (runs `.wasc` WASM game carts) and [`rungame`](https://www.npmjs.com/package/rungame) (runs `.jsgame` JavaScript games headlessly). Also `romdev-audio-resampler` (WASM+SIMD S16-stereo resampler, used by the live-window audio sink). -- Active Bezels: `active-bezel` - the `.ab` package format, its reference runtime, and the compositor, shared with retroemu so the composite an agent inspects is the one a player sees. Imported lazily, only when a package is actually attached. +This package contains no emulator or compiler WebAssembly. Those ship in the `romdev-*` packages below, and each platform's binaries load the first time you use that platform. -`@kmamal/sdl` is used only by `playtest()` / `romdevtools-cli play` (the live window). It ships its native binary via its own install script, which npm skips when romdev is a transitive dep (e.g. under `npx`) - so romdev's `postinstall` fetches it, and `playtest()` also self-heals at runtime if the binary is still missing (downloading the prebuilt before the first window open). Either way, if the binary can't be fetched (offline/locked-down network), the headless server is unaffected - only the live window degrades, and the error tells you the one command to fix it. +## Dependencies -## Connect +Exact-pinned, so one install is a matched set: -```bash -npx romdevtools -# then, e.g. for Claude Code (MCP): -claude mcp add --transport http romdev http://127.0.0.1:7331/mcp -``` - -It's a standard **streamable-HTTP** MCP server at `http://127.0.0.1:7331/mcp`. For opencode, Codex CLI, and other clients, see **[Connect](https://github.com/monteslu/romdev#connect)** in the repository README. An optional human observer (live tool-call view) is at `/livestream`. - -Agents: the server delivers [`AGENTS.md`](./AGENTS.md) as connection-time instructions - the workflow guide for the full tool surface. Or just connect your agent and call `catalog({op:'categories'})` to explore the tools live, and `catalog({op:'status'})` for the running version + session snapshot. - -## Prefer not to use MCP? Use HTTP or a Skill - -Most agents support MCP, but you don't have to use it. Run the server -(`npx romdevtools`) and **skip wiring it into your agent's MCP -config** - no `claude mcp add`, no `mcp.json` entry, no MCP client at all. The -same 32 tools are reachable over plain HTTP / as an Agent Skill against the -running server: - -- **Plain HTTP:** `POST http://127.0.0.1:7331/tool/{name}` with the args as a JSON - body; the response is JSON. Browse/try every tool at **`/documentation`** - (Swagger UI, served locally - no CDN), or get the machine spec at - **`/openapi.json`**. **The agent picks its own session id** and sends it as the - `x-romdev-session` header on every call - it's **required** (no header → `401`; - the server won't silently run you in a throwaway session). Make it unique and - task-descriptive (e.g. `nes-platformer-build`), since it's also the label shown - in the `/livestream` observer. The emulator host is per-session, so the same id - keeps your ROM across calls, and several agents can share one server by each - using a different id. **Running many sessions at once?** Also send a stable - `x-romdev-agent` header - one value for *you*, across all your sessions. It is - optional and cooperative, and it buys two things: at the session/host caps - eviction targets the **largest holder's** oldest session, so your parallel - burst evicts its own idle sessions instead of another agent's, and the first - response of each new session you open carries `agentSessionReminder` - your - other live sessions, what each holds, how idle they are - which is exactly the - list you need to sweep up afterwards. When you finish with a session, - **`host({op:'shutdown'})`** releases all of it (emulator, session record, - livestream entry) immediately rather than waiting out the idle timer. A call - that fails returns a non-2xx (4xx) with the reason in the body - never a 200 - that hides an error. romdev runs **locally** and tool path args (`path`, - `outputPath`, ...) are **local filesystem paths**, not uploads - pass absolute - paths on the same machine. -- **Agent Skill:** **`GET /skills/romdev/SKILL.md`** is a portable [Agent - Skills](https://agentskills.io) `SKILL.md` (works in Claude Code, opencode, - OpenClaw, Hermes, ...). Drop it in your agent's skills dir; it costs ~100 tokens - until invoked (vs always-on MCP tool defs), then teaches the workflows + the - `POST /tool/{name}` calls. - -Both are generated from the same tool registry as the MCP surface, so they never -drift. **You still run the server** - `npx romdevtools` (it hosts the -emulators/toolchains in-process and serves these routes on :7331). What the -HTTP/skill path removes is the *MCP client/protocol and its always-on context -cost* - not the server. There's no separate install beyond romdev itself, and -never a host `gcc` or emulator. +- Emulator cores: `romdev-core-{fceumm,gambatte,gpgx,vice,handy,prosystem,geargrafx,bluemsx,gametank,bsnes,fake08,s32core}` and the GPU cores `romdev-core-{parallel-n64,beetle-psx-hw,flycast}`. `romdev-core-bsnes` is an alternate SNES core (`loadMedia({platform:'snes', core:'bsnes'})`), the accuracy reference for the ST010/ST011/ST018 coprocessors. +- Core runtime: `romdev-core-host`, `romdev-core-runner`. +- Platform bundles: `romdev-platform-{snes,gba,atari2600,sync32}`. +- Toolchains: `romdev-toolchain-{cc65,sdcc,rgbds,m68k-gcc,mips-gcc,sh-gcc,decomp-gcc}`. +- Analysis: `romdev-analysis` (Rizin) and `romdev-analysis-decompiler` (Ghidra decompiler and SLEIGH specs). +- Decomp: `romdev-m2c`, `romdev-permuter` and `romdev-splat`, which bring in `romdev-spimdisasm`, `romdev-rabbitizer` and `romdev-pycparser`. +- Audio: `romdev-famitone`, `romdev-maxmod`, `romdev-xgm2`, `romdev-audio-resampler`. +- Data: `romdev_game_codes`, the cheat database, loaded one platform at a time. +- GPU: `native-gles` and `webgl-node`, required (the 3D cores and GL wasmcarts render through them). +- Runtimes: [`wasmcart`](https://www.npmjs.com/package/wasmcart) and [`rungame`](https://www.npmjs.com/package/rungame); `active-bezel` for Active Bezels (loaded only when one is attached). +- `@kmamal/sdl` for the playtest window. npm skips its binary download when romdevtools is installed through `npx`, so romdevtools' `postinstall` fetches it and `playtest()` retries at run time. If the binary cannot be fetched, only the window is affected and the error names the command that fixes it. ## License -romdev's code is **MIT**, and **the games you build are yours - including to -sell.** Full details + third-party component inventory: -[LICENSE](https://github.com/monteslu/romdev/blob/main/LICENSE) and -[NOTICE](https://github.com/monteslu/romdev/blob/main/NOTICE). +`"license": "SEE LICENSE IN NOTICE"`. romdev's own code is MIT ([LICENSE](./LICENSE)). The third-party components bundled or depended on keep their own licences, listed in [NOTICE](./NOTICE). + +Games you build with romdev are yours, including to sell. Carts made by the static recompiler are different: they contain code ported from the reference emulator (GPL, MPL or non-commercial terms, by platform) as well as the original game's code. Each recompiled cart carries a `licence` entry naming those components; the texts are in [LICENSES/](./LICENSES) and the terms are explained in NOTICE. diff --git a/packages/romdevtools/binary-manifest.json b/packages/romdevtools/binary-manifest.json new file mode 100644 index 00000000..b4bac32a --- /dev/null +++ b/packages/romdevtools/binary-manifest.json @@ -0,0 +1,174 @@ +{ + "note": "sha256 of every shipped prebuilt binary. Regenerate ONLY when a build script legitimately rebuilds one: node scripts/binary-manifest.mjs --write", + "generated": "2026-10-11", + "binaries": { + "romdev-analysis-decompiler/wasm/decompile.wasm": "2dd4ef4da24713f95052ab80658082356ca8806060890b074dcd218364b6c76f", + "romdev-analysis/wasm/rizin.wasm": "d3f3b2a1ab5e5a34899a37fb53d58ea3eb41b58920758eea98c225facd1a0610", + "romdev-audio-resampler/resampler.wasm": "5ed6708b1716e2f7b9c65b50bde97c15d00d0b306534c0afa41d4f9c64d2e327", + "romdev-core-beetle-psx-hw/wasm/beetle_psx_hw_libretro.wasm": "162e6b933d562061289c743fca95d9919060018a24f2760bf9e347ef13c80646", + "romdev-core-bluemsx/wasm/bluemsx_libretro.wasm": "133878c8e09153581044275a53945410797fdf55f55e4a15674cbd9aa5f73dea", + "romdev-core-bsnes/wasm/bsnes_libretro.wasm": "ca1d11610f1c0c51fa9b49c6a956f000e3b316ea664f595c28c08e8973ba9f51", + "romdev-core-fake08/wasm/fake08_libretro.wasm": "62cfca239bfca5b887feca7379b1f8cf5570a05e5c962ced1e03b75ec1758e7e", + "romdev-core-fceumm/wasm/fceumm_libretro.wasm": "a3da4a98b14f2b9adc8a6b384dccfe0ba5205e6c80adc3e4d1689627012a93ce", + "romdev-core-flycast/wasm/flycast_libretro.wasm": "72f7f6e3052b7bac923d4fdfed2507530ab9a66aafc90479b99029ea67fab0c8", + "romdev-core-gambatte/wasm/gambatte_libretro.wasm": "79c71986f4dea8b51c24aad6c165986acca603db2b56a8d2537c70cae8d02431", + "romdev-core-gametank/wasm/gametank_libretro.wasm": "3693a411f01c8e93fc9dea8a399c370f7845d280a81041d102c83689ae412677", + "romdev-core-geargrafx/wasm/geargrafx_libretro.wasm": "0e4c4dbf40ea001c24b6077743f279be3107c4b88fe783dfa895db1c856e0e16", + "romdev-core-gpgx/wasm/genesis_plus_gx_libretro.wasm": "51ca41461f94031d8404a8bdbabeed22e4e06ca3c4d386591e0920df5e938dbc", + "romdev-core-handy/wasm/handy_libretro.wasm": "ae70f8fa006fd82851055b9c2cc00bef50f7333605dee456e7fd10324fd247d8", + "romdev-core-parallel-n64/wasm/parallel_n64_libretro.wasm": "b4a6af011cbc58e80eb81985977d38fce4270d3fa826193aeff69ebb5d5939e7", + "romdev-core-prosystem/wasm/prosystem_libretro.wasm": "74f50628925047cce2443407f94695ae1f4290b81c0a64451a8f35a03a8aef4a", + "romdev-core-s32core/wasm/s32core_libretro.wasm": "9f42673ba67f1f2b845f6c0d87de8bb1d2a38cc8aa57295efbe5ec1cda12a921", + "romdev-core-vice/wasm/vice_x64_libretro.wasm": "2094843c3363c6120f9228c826d7b0f721f57b2a17e3e1d57e22fa3e539b10de", + "romdev-platform-atari2600/wasm/dasm.wasm": "93d85efcef7cacee33f2a1fdd6cc437e3c9bf3afa676469e982c7c1b4cb890f7", + "romdev-platform-atari2600/wasm/stella2014_libretro.wasm": "1b068833f64a9f29ededa3ed6afe1cd864a9e683485fc8227435f2e774a76494", + "romdev-platform-gba/share/gba/lib/arm-archives/libc.a": "64b7d7a1d5a673900b090b405cc3f628b8450cecea7fcf1745119731f0cca962", + "romdev-platform-gba/share/gba/lib/arm-archives/libgcc.a": "a3ec4e062caeb3180e1e56174b93bfa2c33bef8fa90ec6a0a182a5b7dd2b6bec", + "romdev-platform-gba/share/gba/lib/arm-archives/libnosys.a": "3791e42f80a4896269aeda22ea72bf9a344ed9f8391257d8228bc9b0c0c01a32", + "romdev-platform-gba/share/gba/lib/libgba/libgba.seed.a": "58322b718922ace03ef399b513edb5d06199e2ac858568a521f84f3b5649b15d", + "romdev-platform-gba/share/gba/lib/libtonc/libtonc.seed.a": "b7959eecaed29f09fcbd34978a81bedcc6947a5474e586fe9d4e67c7fbad9cac", + "romdev-platform-gba/share/gba/lib/maxmod/maxmod.seed.a": "25ab6364f182f8fe29ad5c14209fa3eb5dc6010bb1de317394f72995836856e7", + "romdev-platform-gba/wasm/arm-none-eabi-as.wasm": "abd3a4f53137323e2b81a764f2c6549868656b48c4596ebc60faf9f9e32af7c3", + "romdev-platform-gba/wasm/arm-none-eabi-ld.wasm": "0db97cb386d7cfedd1493a9bb1e9185d213335831055502559a8408af888d93e", + "romdev-platform-gba/wasm/arm-none-eabi-objcopy.wasm": "2a10379139ddbb052430d57db6328a90abb791536fd056d23db0b710da71bc44", + "romdev-platform-gba/wasm/arm-none-eabi-objdump.wasm": "a5df33f7e3d2583432fb7c225f8d992920857506fc5eb41ac584ee80cbec4496", + "romdev-platform-gba/wasm/cc1-arm.wasm": "62e794225ed7f898ae05b081e91defccf329a70f4880c3cd0ee2916d71d2720c", + "romdev-platform-gba/wasm/mgba_libretro.wasm": "fd42a23859f81a6d129fd1cfeedc57b1ffb9c9c685c708d715cfcf58b22e99f5", + "romdev-platform-snes/wasm/asar.wasm": "071a19e371c5195d73deeef772acbe7841a0ef2f50e565b4626c8a667e8a1359", + "romdev-platform-snes/wasm/snes9x_libretro.wasm": "f8be1c18840890af766b42b465432fd5b829c4f2905ff5c74a0f60d9ec047b45", + "romdev-platform-snes/wasm/tcc816.wasm": "9ec365d5865a8959e614dc7483f30dd7902ec883f8b848dfdc4b24663add7bad", + "romdev-platform-snes/wasm/wla-65816.wasm": "4c41b364580b5b14ac753874e8535248f4c48eca15935f6d61c04989dd7cbd7c", + "romdev-platform-snes/wasm/wlalink.wasm": "8aa019f8fde6ff918d70d221a3110c68685a85df83f455f11e1fb9b9a630e1cc", + "romdev-platform-sync32/share/sync32/lib/libgcc.a": "f0fff2ddd2db71c680e7dc5dcca7e804a33e89627ce7c4c9b668babd4716ec77", + "romdev-rabbitizer/wasm/rabbitizer-1.13.0.wasm": "cadeba8dcf91a003883541df92027221ab205a2216c144ab1381716209cde855", + "romdev-rabbitizer/wasm/rabbitizer-1.14.3.wasm": "dc3ee1284dcee954a4710be6784d088aba3da6b6d3dc05b0f5af695895a4194e", + "romdev-rabbitizer/wasm/rabbitizer-1.16.2.wasm": "277f3eddb0fcc63aa864d063d663bbaae9e405437fc12c0440d19021bedea97f", + "romdev-splat/src/wasm/zlib-stream.wasm": "aac137ee7253048db8ed60ed6a19df888df8191780cfeacbbaa01c4f1cad03da", + "romdev-toolchain-cc65/wasm/ca65.wasm": "d00459e3fe4d92ab8c475f102aa0303d3a628a69abd8c638992b17cdc1fafb2d", + "romdev-toolchain-cc65/wasm/cc65.wasm": "e1e43726296befc2f8ec17c130206f73319239311b6a2d2c4ddef5f32b777ec9", + "romdev-toolchain-cc65/wasm/da65.wasm": "14fe31f1c85a9d76be635b3cc7d48de993d820beb5df7bbdcf14d6755b66490e", + "romdev-toolchain-cc65/wasm/ld65.wasm": "c7a06578a56abfe84631a9b303c21cbab08e81601a05dec83928dccdd90c6631", + "romdev-toolchain-decomp-gcc/wasm/egcs-1.1.2/as.wasm": "241d206d31fd364986e367a4af411f1351e40c2382554de8c4d7cde7092c308f", + "romdev-toolchain-decomp-gcc/wasm/egcs-1.1.2/cc1.wasm": "825ce9a8107d8bce15be748ad50b588be3651198a21913a376b598ac989b7fc3", + "romdev-toolchain-decomp-gcc/wasm/egcs-1.1.2/cpp.wasm": "0803f7cb4893ce772a3576c45f6a5e0d3ef51e3881906a396bfd8af7e52419f8", + "romdev-toolchain-decomp-gcc/wasm/egcs-1.1.2/gcc.wasm": "303229ec2f64c385fc93844979262a16c60656feba43c53e4f929e6975a79e8e", + "romdev-toolchain-decomp-gcc/wasm/kmc-2.7.2/as.wasm": "e5eb34e2070528bb4f5d61bcb80b2f3dd5473cf772c03c0601d139b159abc4ae", + "romdev-toolchain-decomp-gcc/wasm/kmc-2.7.2/cc1.wasm": "e1cc6e758f09a919c546324d6556ac9ba5287b3a0747a6247e8fdce2e9fee42f", + "romdev-toolchain-decomp-gcc/wasm/kmc-2.7.2/cpp.wasm": "a1eb6483fd3b2f9be2f8f91f66cdbdce14d9a01abf28cd3afb11ebb77fee542f", + "romdev-toolchain-decomp-gcc/wasm/kmc-2.7.2/gcc.wasm": "0582fe8fcf30a25008219571a1c85660df4912c7218c25d70b22fa8646843fac", + "romdev-toolchain-decomp-gcc/wasm/mips-linux-gnu-14.2/cc1.wasm": "64c86f5b3f94e1adb7e8ee187746073c875f966536f281f12ee72ebc0cb538dd", + "romdev-toolchain-decomp-gcc/wasm/mips-linux-gnu-14.2/cpp.wasm": "5a812a5e1de127994965ea339a0fcbfb807b13ed063e3532945bfe7dbfbea7c3", + "romdev-toolchain-decomp-gcc/wasm/mips-linux-gnu-14.2/gcc.wasm": "3424270687aa3e1584c1a2ec75eb0241a4c97aa9bf25aba32eb82ab3b0c5f216", + "romdev-toolchain-decomp-gcc/wasm/psx-gcc-2.6.3/cc1.wasm": "005cff988ac85095ab1a28809099e217ddc6ebb43514151c7b2c9186144bda5b", + "romdev-toolchain-decomp-gcc/wasm/psx-gcc-2.6.3/cpp.wasm": "9253f6ba6f8cd8c4ca6667b6114a3951687b2b4558867c12501370c7018f91fc", + "romdev-toolchain-decomp-gcc/wasm/psx-gcc-2.6.3/gcc.wasm": "757721d179476ec9700fe4b02b3052f05247f278b606cd8211f9eccff85bd87d", + "romdev-toolchain-decomp-gcc/wasm/tools/crunch64.wasm": "a827db9eb112473111d4ac3eca239ed16d4418c00d29f0b4c8bc1457079fa458", + "romdev-toolchain-decomp-gcc/wasm/tools/pigment64.wasm": "2a51ab26b12dde9eae642e63b31daa6a83eb187e6900d12e8c044ddb0a3590f4", + "romdev-toolchain-decomp-gcc/wasm/tools/psx-assets.wasm": "1801f27a5e7ea3617f63cd9921b55b44a959d887b09a8373aa1875b312408478", + "romdev-toolchain-decomp-gcc/wasm/tools/psx-disk.wasm": "2c792f92a07d98027079bb7fee4783b5b066a78937d431c599e9197dcecc75b6", + "romdev-toolchain-decomp-gcc/wasm/tools/psx-str.wasm": "a9534a37207085e1e189f5839c119b3e4044fa419e3d7d759e5cc3023c4ffbaf", + "romdev-toolchain-decomp-gcc/wasm/tools/raw-deflate.wasm": "85f780fba5a4e59d36fb8aa92795e9e08331e0b7345a424219fe945418c76509", + "romdev-toolchain-decomp-gcc/wasm/tools/slinky-cli.wasm": "679f37871bd25ffefe1689d21995057b3f058a3fb9f06cc36cecc0694d12db61", + "romdev-toolchain-ido/wasm/5.3/acpp.wasm": "a70202b6daf28838b4602643471bbf0ed3b976846bf9bfad6ff7b62ca550cbc7", + "romdev-toolchain-ido/wasm/5.3/as0.wasm": "e643590a1d6d9940da0ff6d783477e2ba93e652395d4c54488a0c31a863962c8", + "romdev-toolchain-ido/wasm/5.3/as1.wasm": "a90f14812ad18b852a14c0e7373d8449d27c3faaad3976b41e56652903c720c4", + "romdev-toolchain-ido/wasm/5.3/cc.wasm": "fe899f8673a0f038d15e1e5ed044ed5425fffc32fc10c51c43e3cede9d91d7b8", + "romdev-toolchain-ido/wasm/5.3/cfe.wasm": "cc65197b4665154b91bd05fcde91937231507c12a94b61de2cb18aea9b241971", + "romdev-toolchain-ido/wasm/5.3/ugen.wasm": "9f3220f6b538a1c3d9fe827b286dafaf6e61441f9343cde5ad3a9c270bbffbe4", + "romdev-toolchain-ido/wasm/5.3/ujoin.wasm": "c383a380ba13511e7242e6f4661120754939df3c0adb652b9458076779a84655", + "romdev-toolchain-ido/wasm/5.3/uld.wasm": "5406b139815e042aa2fddabcca8845fa0d1cedd27ff65a0c01eccec01443b88a", + "romdev-toolchain-ido/wasm/5.3/umerge.wasm": "ab2b8b762277d8e5384760c43d2bebec4d0162c41111d1b0a63f250df50515d7", + "romdev-toolchain-ido/wasm/5.3/uopt-globalcolor.wasm": "dfbf527b4ebfcbc78a722afab126d684a036ae5e4e9a95245d13eabcbc8c1cf3", + "romdev-toolchain-ido/wasm/5.3/uopt.wasm": "aabc087af64596ead879b3b8cd2e18470ba74b06ea38ed91299f7dc8d13e6d01", + "romdev-toolchain-ido/wasm/5.3/usplit.wasm": "cb3744de9c521ae22f542fedc687a8312f4dcf45b4ec2c57f546fc549105efcf", + "romdev-toolchain-ido/wasm/7.1/acpp.wasm": "522f5c635931c21ae4945e219a01f6b4aa1367d85e37e7021ba9acd761d7f34f", + "romdev-toolchain-ido/wasm/7.1/as0.wasm": "c8b89b14ad4ec7ff5acf17da4c4a87b06efe49226c5ccf1fe8a598bfd3471651", + "romdev-toolchain-ido/wasm/7.1/as1.wasm": "5d2fe8e9ebfaaa15aae2d9d4c0f0153a1f42ea46f6f76d5de704a5460542d1f3", + "romdev-toolchain-ido/wasm/7.1/cc.wasm": "9ddd0ce9dee8e0a5042939f3395c5968567f0b7d975a16bc3ed86e1c8cf1620d", + "romdev-toolchain-ido/wasm/7.1/cfe.wasm": "506dc980caf00fba193819f2e57db9493b4a69ff3b3d6650f0ac0fd8c357fc2b", + "romdev-toolchain-ido/wasm/7.1/ugen.wasm": "77b8937c3a2a98be8c0b3d92cc0b783e9d253ab8036a6ddf2e4b0242ae6529b7", + "romdev-toolchain-ido/wasm/7.1/ujoin.wasm": "b638e004aec2d6f072092148d7fd9322727bfd589bca6f0bf277c4ff60a9049e", + "romdev-toolchain-ido/wasm/7.1/uld.wasm": "7167cb766f787c22fa7d5b45156fdc1d52b64374385c41ed895990b7bf8b014f", + "romdev-toolchain-ido/wasm/7.1/umerge.wasm": "be78fc6778ee9f388db1232c9431fc06bca48a5f96a4895fba52157ccd9fe021", + "romdev-toolchain-ido/wasm/7.1/uopt.wasm": "b6e6e30ef4cc384c9ad62268a2d916ff2e75b112cbcbddeac0b69a8559063af4", + "romdev-toolchain-ido/wasm/7.1/usplit.wasm": "dac6e693b30cb39317a218bc3a8cabc9f65f7cb0598841d52d6a0eafc32d7081", + "romdev-toolchain-m68k-gcc/share/genesis/lib/c/libc.a": "2094e2a11994329a0d0282215585129ef3e473375fffe500c31310f47fc80a5d", + "romdev-toolchain-m68k-gcc/share/genesis/lib/c/libgcc.a": "398d51fe92719d1b87aa446b10e5915070529800a076028d642ff0ccfe726fde", + "romdev-toolchain-m68k-gcc/share/genesis/lib/c/libm.a": "7fb7b71e836eeaee3d6e52e3267caf7fe4208e7969254c43b70f33ae9377785f", + "romdev-toolchain-m68k-gcc/share/genesis/lib/sgdk/libmd.seed.a": "eb14b8ab0e3c094785169e9546a8dd628bcda7402d5d001076908ff09a08fcf1", + "romdev-toolchain-m68k-gcc/wasm/bintos.wasm": "e32002dece8d22300e3aabc08f94d6ca790fa42637c6952e7d6f54290ffeb2a2", + "romdev-toolchain-m68k-gcc/wasm/cc1-m68k.wasm": "a03c8bd24557aa275d40623e97b77bcf247eafd9a32658202ab498e656e443f0", + "romdev-toolchain-m68k-gcc/wasm/m68k-elf-as.wasm": "f557c70be8df1625a13adabb5fda8a0ff4e9fb3941477247e8eb16e804653ccc", + "romdev-toolchain-m68k-gcc/wasm/m68k-elf-ld.wasm": "cb0dd72e2ead1c3122eb8fa672a738a4cc1731aeb250e72505625d0d08074cd2", + "romdev-toolchain-m68k-gcc/wasm/m68k-elf-objcopy.wasm": "715c814325287d20037836177cf3a21babadd85741abbe5645ad7f425014d540", + "romdev-toolchain-m68k-gcc/wasm/m68k-elf-objdump.wasm": "15269ddfe0d00bf345c866efecd888d22e6a58af6d5e7b1da0a4fde5020f7fe4", + "romdev-toolchain-m68k-gcc/wasm/sjasm.wasm": "294e12b0c52b73b9fd750e32ea4538d7bc37d1d780ad0f05df00b4f1e5eaceaa", + "romdev-toolchain-mips-gcc/wasm/armips.wasm": "fa8f8bd436b38dad9888cb1137e5aca857a5d379ea5df77d9046ca37987aaa99", + "romdev-toolchain-mips-gcc/wasm/cc1.wasm": "89611b9c3f18e0def7e1d5985184dbf2726156d8764d00585ee45bf62decccb3", + "romdev-toolchain-mips-gcc/wasm/mips-elf-as.wasm": "f9d7b5b9db674388975499433d15fd894af47786532b85346081b0412a254903", + "romdev-toolchain-mips-gcc/wasm/mips-elf-ld.wasm": "72fc4d905fb326608f22da26535d2eafd2866e6842aaffa4f3e5a9b374ad789b", + "romdev-toolchain-mips-gcc/wasm/mips-elf-objcopy.wasm": "e80c4fb7cd9365f0be4dfb54cc62f3f4fcb46babf076e550140ce0ea61e2b597", + "romdev-toolchain-mips-gcc/wasm/mips-elf-objdump.wasm": "cf0c40668e83bc0073e04b3ba9d1604facf80d1c3857e4d56fe2b84d468a203f", + "romdev-toolchain-mips-gcc/wasm/mips-linux-gnu-as.wasm": "fcd368482f0ecd8aa9e275d5f8bcde83c20a0dcb980628284a1592034565a3dd", + "romdev-toolchain-mips-gcc/wasm/mips-linux-gnu-ld.wasm": "6e13a33c10329fa8406e03cbb32b1427a0ce711ed651998f2a2900f75d792b6d", + "romdev-toolchain-mips-gcc/wasm/mips-linux-gnu-objcopy.wasm": "18f77fbec19387272f661eae11f3a99e3eed80da5bf2cc28014923d5eda99e19", + "romdev-toolchain-mips-gcc/wasm/mips-linux-gnu-objdump.wasm": "68c314942968b8cc24ecf5605c370deb3d2d11adc7759feb14d97f720d665d63", + "romdev-toolchain-rgbds/wasm/rgbasm.wasm": "bc42f1d88d424d74555ee8c9c17724230becf588bc1216b9c30e4cee53d9455e", + "romdev-toolchain-rgbds/wasm/rgbfix.wasm": "3721c33818aac429e9debd7105f4a0052683b6c1a736307c9787586d6d32e449", + "romdev-toolchain-rgbds/wasm/rgblink.wasm": "0c8f93d416f33323639f18e38396d2547bc58dd10df54002cabca93f6b671273", + "romdev-toolchain-sdcc/wasm/mcpp.wasm": "8e14622b4466121607ebe2b07387ad3d755e2ab0d7f4748ab0ab46f24db57cb0", + "romdev-toolchain-sdcc/wasm/sdasgb.wasm": "642d402730ce88ae3029ad4dc8fefa6e10465a174ce63438c239416ce8acb436", + "romdev-toolchain-sdcc/wasm/sdasz80.wasm": "cbd8b612f846f9d6253c940088e25d9fb8c1f448f8da73ba6d1ff64f8a3eed38", + "romdev-toolchain-sdcc/wasm/sdcc.wasm": "ff3ba6e6eddeecceaefb3e1de336f7082e1325d3b056d89dabfd1fad9df3c43f", + "romdev-toolchain-sdcc/wasm/sdld.wasm": "9c76886065a71fdaacf5adc4c071630a715bea50316cf5e5d301c53c786556cc", + "romdev-toolchain-sdcc/wasm/z80-elf-as.wasm": "3dd3b67e4f4028c061f5c5ff32ca46bfe6aaa1f82acc122c23e38b9f2ead9903", + "romdev-toolchain-sdcc/wasm/z80-elf-ld.wasm": "503b646b972d3ff0d128d6c6e168b90a8a0b27262387ad75f63c3545d43e5779", + "romdev-toolchain-sdcc/wasm/z80-elf-objcopy.wasm": "c4450d87fbf5fd21eb61650a9272e2b3f60cd0ff8d5cd1f32c707799c0103ca4", + "romdev-toolchain-sdcc/wasm/z80-elf-objdump.wasm": "7b5feee4d05ca4bf6a5584c6e01fdd84b31f394271624d10e55813758d32e6e0", + "romdev-toolchain-sh-gcc/wasm/cc1.wasm": "77679284aac1177908e52b8e0d616db359456c2161a4a1eaff251f0386ccfff6", + "romdev-toolchain-sh-gcc/wasm/sh-elf-as.wasm": "40ed3b40ad77c02af489271b1c35758df930b3b0926d4faf0697eda5fc0d777a", + "romdev-toolchain-sh-gcc/wasm/sh-elf-ld.wasm": "81e35ed71f183a2f903f84f7e340eeebbddec90e75ebbbe38b3d2eba12662136", + "romdev-toolchain-sh-gcc/wasm/sh-elf-objcopy.wasm": "f07228f0a2c90eb6812493e75b35f5a40cec40404475bb9ffdf740320093208d", + "romdev-toolchain-sh-gcc/wasm/sh-elf-objdump.wasm": "5a3908ab34c1aa24b5455fce0c123096a5451416849d774346c41bc2a308bacd", + "romdevtools/.romdev-build/mgba/src/mgba_libretro_emscripten.a": "a8b16f08b49af50c1f73048ac85c63bb77e43d0d9f03e5e31f7c466ce2a4cf5d", + "romdevtools/src/analysis/decompiler/wasm/decompile.wasm": "2dd4ef4da24713f95052ab80658082356ca8806060890b074dcd218364b6c76f", + "romdevtools/src/analysis/wasm/rizin.wasm": "d3f3b2a1ab5e5a34899a37fb53d58ea3eb41b58920758eea98c225facd1a0610", + "romdevtools/src/cores/wasm/beetle_psx_hw_libretro.wasm": "162e6b933d562061289c743fca95d9919060018a24f2760bf9e347ef13c80646", + "romdevtools/src/cores/wasm/bsnes_libretro.wasm": "ca1d11610f1c0c51fa9b49c6a956f000e3b316ea664f595c28c08e8973ba9f51", + "romdevtools/src/cores/wasm/fake08_libretro.wasm": "62cfca239bfca5b887feca7379b1f8cf5570a05e5c962ced1e03b75ec1758e7e", + "romdevtools/src/cores/wasm/fceumm_libretro.wasm": "a3da4a98b14f2b9adc8a6b384dccfe0ba5205e6c80adc3e4d1689627012a93ce", + "romdevtools/src/cores/wasm/flycast_libretro.wasm": "72f7f6e3052b7bac923d4fdfed2507530ab9a66aafc90479b99029ea67fab0c8", + "romdevtools/src/cores/wasm/gambatte_libretro.wasm": "79c71986f4dea8b51c24aad6c165986acca603db2b56a8d2537c70cae8d02431", + "romdevtools/src/cores/wasm/gametank_libretro.wasm": "3693a411f01c8e93fc9dea8a399c370f7845d280a81041d102c83689ae412677", + "romdevtools/src/cores/wasm/geargrafx_libretro.wasm": "0e4c4dbf40ea001c24b6077743f279be3107c4b88fe783dfa895db1c856e0e16", + "romdevtools/src/cores/wasm/genesis_plus_gx_libretro.wasm": "677fd02f7beb897712c8283e29c40bfaf66f99df301864e301e56a1071ede1b7", + "romdevtools/src/cores/wasm/handy_libretro.wasm": "ae70f8fa006fd82851055b9c2cc00bef50f7333605dee456e7fd10324fd247d8", + "romdevtools/src/cores/wasm/mgba_libretro.wasm": "fd42a23859f81a6d129fd1cfeedc57b1ffb9c9c685c708d715cfcf58b22e99f5", + "romdevtools/src/cores/wasm/mupen64plus_next_libretro.wasm": "271b6c1cc4382d5ecc46ece8436c535302eadcb6f25e6127ba0cbe2d6324a78a", + "romdevtools/src/cores/wasm/parallel_n64_libretro.wasm": "b4a6af011cbc58e80eb81985977d38fce4270d3fa826193aeff69ebb5d5939e7", + "romdevtools/src/cores/wasm/prosystem_libretro.wasm": "74f50628925047cce2443407f94695ae1f4290b81c0a64451a8f35a03a8aef4a", + "romdevtools/src/cores/wasm/s32core_libretro.wasm": "9f42673ba67f1f2b845f6c0d87de8bb1d2a38cc8aa57295efbe5ec1cda12a921", + "romdevtools/src/cores/wasm/snes9x_libretro.wasm": "f8be1c18840890af766b42b465432fd5b829c4f2905ff5c74a0f60d9ec047b45", + "romdevtools/src/cores/wasm/stella2014_libretro.wasm": "1b068833f64a9f29ededa3ed6afe1cd864a9e683485fc8227435f2e774a76494", + "romdevtools/src/cores/wasm/vice_x64_libretro.wasm": "2094843c3363c6120f9228c826d7b0f721f57b2a17e3e1d57e22fa3e539b10de", + "romdevtools/src/toolchains/mips-c/lib/be/libc.a": "d4ac2beae8d89cbc1be94cefc1e85b49be65c8ce053680227e82bafac4dc4382", + "romdevtools/src/toolchains/mips-c/lib/be/libgcc.a": "857039067f2ded9b62bc4aa5688fd2b68cdae3e82fb35f29bea81f7c9a934589", + "romdevtools/src/toolchains/mips-c/lib/be/libm.a": "66545020aab909dc0f945fe62cab22847f31693c1f84e9596423300d3b1f9ffb", + "romdevtools/src/toolchains/mips-c/lib/el/libc.a": "3e0d6f723b22a26a3ab9d97d8f291702c7376c6aa80666fa185a5780d8025d89", + "romdevtools/src/toolchains/mips-c/lib/el/libm.a": "2b9496a832ef3a86b493d52ed6a096af543b02285b7e43e1bbf88b8a7d5e45c4", + "romdevtools/src/toolchains/mips-elf-gcc/wasm/cc1.wasm": "89611b9c3f18e0def7e1d5985184dbf2726156d8764d00585ee45bf62decccb3", + "romdevtools/src/toolchains/mips-elf-gcc/wasm/mips-elf-as.wasm": "f9d7b5b9db674388975499433d15fd894af47786532b85346081b0412a254903", + "romdevtools/src/toolchains/mips-elf-gcc/wasm/mips-elf-ld.wasm": "72fc4d905fb326608f22da26535d2eafd2866e6842aaffa4f3e5a9b374ad789b", + "romdevtools/src/toolchains/mips-elf-gcc/wasm/mips-elf-objcopy.wasm": "e80c4fb7cd9365f0be4dfb54cc62f3f4fcb46babf076e550140ce0ea61e2b597", + "romdevtools/src/toolchains/mips-elf-gcc/wasm/mips-elf-objdump.wasm": "cf0c40668e83bc0073e04b3ba9d1604facf80d1c3857e4d56fe2b84d468a203f", + "romdevtools/src/toolchains/sh-c/lib/libc.a": "1bf74fe5063ddce833053e0e59ad26b8c4e737317ffcb97cf2f7f2a0651eac40", + "romdevtools/src/toolchains/sh-c/lib/libgcc.a": "9f89ef3c7e29495a56ad0cc47461da802e837e2092d0187bd5f8151c9335642e", + "romdevtools/src/toolchains/sh-c/lib/libm.a": "a3c0c0b0adbef4d4e453b7025e2175a78a2407b0547ff1269fb71d7338d13950", + "romdevtools/src/toolchains/sh-elf-gcc/wasm/cc1.wasm": "77679284aac1177908e52b8e0d616db359456c2161a4a1eaff251f0386ccfff6", + "romdevtools/src/toolchains/sh-elf-gcc/wasm/sh-elf-as.wasm": "40ed3b40ad77c02af489271b1c35758df930b3b0926d4faf0697eda5fc0d777a", + "romdevtools/src/toolchains/sh-elf-gcc/wasm/sh-elf-ld.wasm": "81e35ed71f183a2f903f84f7e340eeebbddec90e75ebbbe38b3d2eba12662136", + "romdevtools/src/toolchains/sh-elf-gcc/wasm/sh-elf-objcopy.wasm": "f07228f0a2c90eb6812493e75b35f5a40cec40404475bb9ffdf740320093208d", + "romdevtools/src/toolchains/sh-elf-gcc/wasm/sh-elf-objdump.wasm": "5a3908ab34c1aa24b5455fce0c123096a5451416849d774346c41bc2a308bacd", + "romdevtools/test/fixtures/bezel/main.wasm": "d677c2f2954bd3388eeecafd5b18d6aba6b60e65debde33584679774d968340f" + } +} diff --git a/packages/romdevtools/docs/decomp-throughput.md b/packages/romdevtools/docs/decomp-throughput.md index c2456758..e79797cd 100644 --- a/packages/romdevtools/docs/decomp-throughput.md +++ b/packages/romdevtools/docs/decomp-throughput.md @@ -1,26 +1,28 @@ -# Measured decompilation and bulk SMS analysis +# Measured decompilation, bounded search and Z80 IR export -These additions extend existing tools. They do not add a top-level tool, -decomp operation, independent decoder or replacement decompilation backend. They are development changes until the -server running your requests has been restarted from this checkout. +How to work a matching-decompilation residual with measured evidence, how to +keep permuter searches bounded, and how to export decoded SMS/GG instructions +for bulk analysis. Everything here goes through existing tools: `decomp`, +`disasm`, `frame` and `catalog`. ## Matching workflow 1. Compile a baseline with `decomp({op:'compare', project, symbol, candidatePath, detail:true})`. Require `measurementValidity.state:'valid'`. - Missing evidence is unknown, not zero. Exactness and source quality remain + Missing evidence is unknown, not zero. Exactness and source quality are independent, and function exactness is not full-ROM verification. -2. Pass its `artifacts.diff` as `artifactId` to `diagnose`. Symbol-only diagnosis - requires current evidence rather than silently selecting a historical score. -3. Test a bounded `variants` batch with a specific hypothesis. Put the diagnosis - experiment ID in each variant's `lever`, such as `declaration-order`. The - existing experiment store records the measured inputs/outcomes automatically. - A declaration permutation that did not improve is evidence about that exact - input, not proof that every declaration arrangement is exhausted. +2. Pass its `artifacts.diff` as `artifactId` to `diagnose`. A symbol-only + diagnosis requires current evidence instead of silently picking a + historical score. +3. Test a bounded `variants` batch with one specific hypothesis. Put the + diagnosis experiment id in each variant's `lever`, such as + `declaration-order`. The experiment store records the measured inputs and + outcomes. A declaration permutation that did not improve is evidence about + that exact input, not proof that every declaration order is exhausted. 4. Check `snapshotStable`, per-row input identities, failures and truncation. `instructionIdenticalTo` covers function instruction bytes and relocations; - it does **not** establish identical rodata, whole objects or semantics. -5. For persistent residues, reuse the existing workbench from the artifact: + it does not establish identical rodata, whole objects or semantics. +5. For a persistent residue, run the workbench on the stored artifact: ```js decomp({op:'workbench', project, symbol, artifactId, @@ -29,17 +31,17 @@ decomp({op:'workbench', project, symbol, artifactId, wbGroup:'trace', wbCommand:'scheduler'}) ``` -The second call captures native IDO `-Wa,-R` using the retained compiled TU. -Optimization flags and compiler are not silently substituted. Invocation, -trace hash, ordered instruction/relocation identity and whole-object equality -must agree before attribution is used. A non-equivalent trace is unavailable -evidence, not an explanation of the original build. Loose external logs need -their verified `.manifest.json` bundle. Scheduler evidence does not explain -allocator decisions. Older artifacts without retained objects require a fresh -`compare` with `noCache:true`. +The second call captures native IDO `-Wa,-R` output from the retained +compiled translation unit. The compiler and optimization flags are never +substituted. Invocation, trace hash, ordered instruction and relocation +identity and whole-object equality must all agree before the trace is used for +attribution; a trace that fails that check is reported as unavailable. Loose +external logs need their verified `.manifest.json` bundle. Scheduler evidence +does not explain allocator decisions. An artifact from before objects were +retained needs a fresh `compare` with `noCache:true`. -For allocator decisions, explicitly opt into the existing workbench's pinned -IDO 5.3 instrumentation profile: +For allocator decisions, opt into the workbench's pinned IDO 5.3 +instrumentation profile: ```js decomp({op:'workbench', project, artifactId, @@ -47,68 +49,55 @@ decomp({op:'workbench', project, artifactId, wbArgs:['--proc','19','--web','40']}) // ordinals must come from THIS build ``` -This builds a diagnostic compiler copy in the workspace using the project's -generated uopt source/runtime and installed host gcc; it never installs or -replaces the game compiler. The profile rejects unknown source hashes. Both -tracing-disabled and tracing-enabled objects must equal the original whole -object. Forced coloring is not enabled. `-K` intermediate files are confined to -the diagnostic working directory and bound by the manifest. Procedure ordinals -are run-local: retained Ucode provides names, but do not guess the ordinal from -another TU or mistake UGEN and UOPT namespaces for a universal mapping. - -Large workbench reports are written to disk automatically with bounded inline -projections. Existing `outputPath` chooses the report destination; existing -`detail:true` explicitly requests full inline output. Artifact-bound `wbArgs` -accepts paired report filters, not replacement input/identity arguments. - -`variants` reuses `threads`: default 1, optional 2, larger pools refused. The -baseline runs first; results and duplicate attribution retain request order. -Two workers reduced fixed-workload batch wall time by 29.7% in one four-round, -six-target evaluation with equal per-input results. That is not an improvement -in recovery rate; no new integrations were demonstrated. Use one worker when -sharing a busy machine. Compile artifacts are immutable per run; only their -cache index is atomically replaced. Experiment read/modify/write updates are -serialized across processes; a crashed writer's lock produces a bounded -`EXPERIMENT_LOCKED` error, not a silent lost update. Inspect its recorded PID -before manually recovering a stale lock. - -`plan` temporarily penalizes repeated independent no-progress batches on the -same measured baseline/tree. `ignoreCooldown:true` permits deliberate hard-target -work; `proposedLever` permits a genuinely new lever. `cooldownBatches` and -`cooldownMinutes` configure the threshold and expiry. Reasons stay visible and -targets are not excluded. Changed dependencies prompt reconsideration/refresh, -not a claim that old failed experiments suddenly became promising. - -## Bounded search - -### Field corrections (September 16) - -ROM-linked comparison now resolves expression aliases and defined `PROVIDE` -symbols from GNU ld's evaluated address column. It does not evaluate linker -expressions itself. Unresolved relocation words remain unknown even when their -unlinked placeholders happen to equal ROM bytes. For partial comparisons, -`romLinked.mismatches` and projected `linkedMismatches` are `null`; -`romLinked.knownMismatches` is only a lower bound. A known differing word still -establishes a mismatch, but unknown words never establish exactness. - -Verifier policy is now version 3: older artifacts remain available for explicit -historical diagnosis, but require a fresh comparison for current selection or -search preflight. Resolved aliases do **not** relax raw symbolic-relocation -equality. An alias may therefore have exact ROM-linked bytes while the strict -and aggregate local verdict remain nonexact; full-link verification is separate. +This uses a diagnostic WASM IDO 5.3 in which only the uopt pass is replaced by +the trace profile. Build that module once with `scripts/build-ido-globalcolor.sh` +from a romdev source checkout; it never replaces the project's compiler. The +profile rejects unknown source hashes. Both the tracing-disabled and the +tracing-enabled objects must equal the original whole object. Forced colouring +is not enabled. Procedure ordinals are local to one run: retained Ucode gives +names, but do not reuse an ordinal from another translation unit or treat the +UGEN and UOPT namespaces as one mapping. + +Large workbench reports are written to disk with a bounded inline projection. +`outputPath` chooses the destination and `detail:true` requests full inline +output. With `artifactId`, `wbArgs` accepts only paired report filters, not +replacement inputs. + +`variants` takes `threads`: 1 by default, 2 at most. The baseline runs first +and results keep request order. Two workers cut batch wall time by about 30% +in one fixed-workload evaluation with identical per-input results; that is +throughput, not a better recovery rate. Use one worker on a busy machine. +Experiment updates are serialized across processes; a crashed writer's lock +produces an `EXPERIMENT_LOCKED` error naming the lock file. Confirm its owner +is no longer running before clearing the lock by hand. + +`plan` temporarily lowers the rank of a target after repeated independent +no-progress batches on the same measured baseline. `ignoreCooldown:true` +allows deliberate work on a hard target, `proposedLever` allows a new lever, +and `cooldownBatches` / `cooldownMinutes` set the threshold and expiry. The +reasons stay visible and no target is excluded. + +## Comparison rules + +ROM-linked comparison resolves expression aliases and defined `PROVIDE` +symbols from GNU ld's evaluated address column; it does not evaluate linker +expressions itself. A relocation word that cannot be resolved stays unknown, +even when its unlinked placeholder happens to equal the ROM bytes. For a +partial comparison, `romLinked.mismatches` and `linkedMismatches` are `null` +and `romLinked.knownMismatches` is a lower bound. A known differing word +establishes a mismatch; unknown words never establish exactness. + +Results from an older verifier version stay readable for diagnosis but need a +fresh comparison before they can drive selection or search preflight. A +resolved alias does not relax raw symbolic-relocation equality, so an alias can +have exact ROM-linked bytes while the strict local verdict stays nonexact. Diagnosis checks small instruction permutations before register mappings. It -requires equal stream lengths and identical instructions/relocations, and does -not cross branch/jump boundaries. This establishes reordered instructions, not -proof of a particular source-level cause or compiler scheduling tie. - -Recorded no-improvement stops retain `complete-no-progress` when shutdown emits -only a Python `KeyboardInterrupt` traceback. Other errors and unexpected exits -remain failures. New stop markers record a log byte boundary, so an earlier -interrupt is not discounted as shutdown noise. Historical markers lack that -boundary and provide weaker attribution. Raw logs and artifacts are preserved. +requires equal stream lengths and identical instructions and relocations, and +does not cross branch or jump boundaries. A hit shows reordered instructions; +it does not prove a particular source-level cause. -### Usage +## Bounded search ```js decomp({op:'search', project, symbol, candidatePath, @@ -117,102 +106,73 @@ decomp({op:'search', project, symbol, candidatePath, seed:'73', threads:1, timeLimitS:30, noImprovementS:5}) ``` -Pass names are validated against the installed decomp-permuter. Selecting passes -sets other randomization weights to zero; a family label alone is not a backend -constraint. The baseline must compile with valid identity. Legacy -`preflight:false` is refused. Identical no-progress search scopes require -`repeatSearch:true` to repeat deliberately. - -Backend score zero is never an integration verdict. A zero-scoring baseline that -is nonexact under romdev is reported as a scorer blind spot. The no-improvement -watchdog is process-local; after server restart the external total-time budget -still applies. Cancellation retains artifacts and never integrates code. - -`decomp({op:'job', project, jobId, action:'report', maxFunctions:12})` rechecks a -bounded number of saved outputs through the real comparison pipeline. It reports -unique **verified saved** outputs and useful residual improvements separately -from backend score improvements. Outputs not checked are counted. The backend -does not publish every discarded compilation, so all-backend unique-output and -effective-compilation totals remain unknown, not inferred from iterations. - -## SMS/GG decoded IR without a second decoder +- `purpose` is required: name the residual or hypothesis that justifies the + budget. +- `mutationPasses` are validated against the installed decomp-permuter. + Selecting passes sets every other randomization weight to zero; a `family` + label alone does not constrain the backend. +- The baseline must compile with a valid identity. `preflight:false` is + refused. Repeating an identical scope that already ended without progress + needs `repeatSearch:true`. +- `noImprovementS` stops a run that has not improved for that many seconds. + The watchdog is per process; after a server restart the total time budget + still applies. +- A backend score of zero is never an integration verdict. A zero-scoring + baseline that romdev's comparison calls nonexact is reported as a scorer + blind spot. Cancelling keeps the artifacts and never integrates code. + +`decomp({op:'job', project, jobId, action:'report', maxFunctions:12})` +rechecks a bounded number of saved outputs through the real comparison +pipeline. It reports verified saved outputs and residual improvements apart +from backend score improvements, and counts the outputs it did not check. The +backend does not publish every discarded compilation, so totals across all +backend compilations are reported as unknown. + +## SMS/GG decoded IR ```js -disasm({target:'recompile', platform:'sms', path:'/path/game.sms', - emit:'ir', allOffsets:true, outputPath:'/tmp/game.jsonl'}) +disasm({target:'recompile', platform:'sms', path:'/abs/path/game.sms', + emit:'ir', allOffsets:true, outputPath:'/abs/path/game.jsonl'}) ``` -The response is a small manifest. JSONL records contain physical `off`, CPU -`addr`, bank/slot, bytes, mnemonic/operands/length, cycles, flags, control-flow -edges and existing lifted IR. Cycles derive from the bundled Genesis Plus GX -tables. Their order is taken-or-repeat, not-taken-or-final. Unknown/data opcodes -are explicit. Linear decoding does not establish reachability. - -Maintainers can check mechanical cycle provenance with -`node scripts/generate-z80-cycle-tables.mjs`; after reviewing a bundled-core -update, append `--write` to regenerate. This is a data-generation script, not a -new API tool or decoder. It requires exactly six 256-entry `cc_*` tables with -the core's documented ×15 master-clock scale and refuses changed formats. +The response is a small manifest. Each JSONL record holds the physical `off`, +the CPU `addr`, bank and slot, bytes, mnemonic, operands, length, cycles, +flags, control-flow edges and the lifted IR. Cycle counts come from the +bundled Genesis Plus GX tables, ordered taken-or-repeat then +not-taken-or-final. Unknown and data opcodes are marked explicitly. Linear +decoding does not establish reachability. `fileOffset` selects physical ROM bytes; `startAddress` is a CPU address. -`allOffsets` traverses the entire cartridge in 16KB banks. Default presentation -slots are bank0 at $0000, bank1 at $4000, later banks at $8000; `slot` overrides -presentation. Absolute branch/call operands are never rebased as file offsets. -Instruction decoding does not invent a crossing instruction without its actual -adjacent mapped bank context. MSX/raw Z80 mapper semantics are not inferred. - -For static SMS/GG CPU windows, `mapper` supports `sega`, `codemasters`, `korean` -(A000 16KB paging), and `korean-16k-v2` (4000/8000 paging). `mapperState.pages` -gives three 16KB physical page indices; `control` models the Sega control byte -and `ramEnabled` models Codemasters cartridge RAM. ROM requests against mapped -cartridge RAM fail explicitly. Other Korean boards are not implied. - -These options configure **static analysis**, not runtime core mapper selection. -The emulator already detects supported Codemasters/Korean cartridges using its -database. Synthetic runtime tests exercise those existing paging paths. There -is no new forced-mapper runtime option in this change. - -## WASM comparison and error traffic - -Load SMS in slot A and wasmcart in slot B with the existing `loadMedia` tool. -For `frame({op:'findDiverge', ...})`, set `regionB:'linear_memory'`, `offsetA`, -`offsetB` and `compareLength` explicitly. WASM carts do not have complete state -snapshots: `restore:false` is required and advances both hosts. Equal idle -memory is inconclusive, not a pass. Matching a bounded window for a bounded -number of frames is not whole-game equivalence or proof of identical timing. - -`findDiverge` compares from wherever the two slots currently stand. A cart that -stays byte-exact for the first N frames and breaks on the next one must be -warmed on BOTH sides first, or the comparison starts from a point where the two -already agree trivially: `frame({op:'step', frames:60})` for slot A and -`frame({op:'step', slot:'b', frames:60})` for slot B, then `findDiverge`. - -If the slots already differ at frame 0 the search returns before stepping -anything. That result carries `activity.framesStepped: 0` and an -`activity.activityNote`: the `changedFramesA/B` counts are `0` by construction -there and say nothing about whether either slot executes. To test that -directly, step a slot on its own and watch `frameCount`. - -`catalog({op:'status'})` includes `serverHealth.requestTelemetry`: bounded -per-session completed-call counts, error rates, recent errors and error-storm -warnings. HTTP schema failures count. Statistics reset with the process; -MCP SDK errors rejected before handler dispatch are outside observer coverage. - -## Verification commands - -```sh -node --test test/decomp-measurement.test.js test/experiment-variant-history.test.js test/residual-diagnosis.test.js -node --test test/decomp-field-regressions.test.js -ROMDEV_DECOMP_INTEGRATION=1 node --test test/decomp-inflight-integration.test.js test/decomp-search-policy.test.js -ROMDEV_AUDIT_URL=http://127.0.0.1:7332 node --test test/decomp-measurement-live.test.js test/sms-throughput-live.test.js -ROMDEV_AUDIT_URL=http://127.0.0.1:7332 node --test test/decomp-field-live.test.js -node --test test/z80-ir-export.test.js test/sms-static-mappers.test.js test/sms-mapper-runtime.test.js test/frame-wasmcart-diverge.test.js test/request-stats.test.js -``` - -Opt-in integration tests use the registered N64 toolchain/read-only game -inputs and disposable workspaces. They do not edit the game checkout. Keep the -shared server separate from the development endpoint. Passing these checks does -not establish a decompilation speed multiplier or a new verified recovery. -The field HTTP tests additionally require the checkpoint-312 research source, -original diff artifact, and stopped job in the registered decomp workspace. -They create comparison artifacts and refresh that stopped job's report. +`allOffsets` walks the whole cartridge in 16KB banks: bank 0 at $0000, bank 1 +at $4000 and later banks at $8000 unless `slot` overrides it. Absolute branch +and call operands are never rebased as file offsets, and no instruction is +decoded across a bank boundary without the adjacent mapped bank. + +For static SMS/GG CPU windows, `mapper` accepts `sega`, `codemasters`, +`korean` (A000 16KB paging) and `korean-16k-v2` (4000/8000 paging). +`mapperState.pages` gives three 16KB physical page indices; `control` models +the Sega control byte and `ramEnabled` models Codemasters cartridge RAM. A ROM +request against mapped cartridge RAM fails. These options configure static +analysis only; the emulator detects supported mappers from its own database. + +## Comparing an emulator run with a recompiled cart + +Load the SMS ROM in slot A and the wasmcart in slot B with `loadMedia`. For +`frame({op:'findDiverge', ...})`, set `regionB:'linear_memory'`, `offsetA`, +`offsetB` and `compareLength` explicitly. WASM carts have no complete state +snapshot, so `restore:false` is required and both hosts advance. Equal idle +memory is inconclusive, and a bounded window matching for a bounded number of +frames is not whole-game equivalence or proof of identical timing. + +`findDiverge` compares from wherever the two slots currently stand. Warm both +sides first, `frame({op:'step', frames:60})` for slot A and +`frame({op:'step', slot:'b', frames:60})` for slot B, so the search does not +start from a point where both trivially agree. If the slots already differ at +frame 0 the search returns without stepping, with `activity.framesStepped: 0` +and an `activity.activityNote`; the `changedFramesA/B` counts are then 0 by +construction. To check that a slot executes, step it alone and watch +`frameCount`. + +`catalog({op:'status'})` reports `serverHealth.requestTelemetry`: per-session +completed-call counts, error rates, recent errors and error-storm warnings. +The counts reset when the server restarts. diff --git a/packages/romdevtools/examples/README.md b/packages/romdevtools/examples/README.md index 2c50328a..e7b52398 100644 --- a/packages/romdevtools/examples/README.md +++ b/packages/romdevtools/examples/README.md @@ -12,21 +12,25 @@ Each example fits the convention: | ------------ | -------------------- | --------- | ------------------------------------ | | nes | `nes/main.c` | cc65 | `linkerConfig: "chr-ram"` (writes tiles at runtime via PPUADDR/PPUDATA; preset defines OAM segment + drops CHR-ROM region) | | nes (full game) | `nes/space-shooter/` | cc65 | Canonical complete-game reference - a generic fixed-shooter showing "NES-shaped C": bit-packed alien state, 5-col formation for the 8-sprite/scanline limit, correct OAM-staging order, shields/HUD as BG tiles, CHR-RAM upload, APU SFX. Build with `linkerConfig: "chr-ram-runtime"` + `nes_runtime.c`. See its README. | -| c64 | `c64/main.c` | cc65 | Direct VIC-II + screen-RAM demo: paints background, writes screen codes for "HELLO ROM-DEV-MCP" into screen RAM with white-on-blue color, cycles the border color. C89 (cc65) - no mixed decl/code. | +| c64 | `c64/main.c` | cc65 | Direct VIC-II + screen-RAM demo: paints background, writes a greeting as screen codes into screen RAM with white-on-blue color, cycles the border color. C89 (cc65) - no mixed decl/code. | | atari2600 | `atari2600/main.asm` | dasm | Standard NTSC kernel (3 vsync + 37 vblank + 192 visible + 30 overscan) with a single GRP0 sprite, joystick-driven movement, and the vector table at $FFFA. | -| atari2600 (gallery shooter) | `atari2600/templates/mini_invaders.asm` | dasm | Fixed-shooter 2600 game using the RIGHT TIA objects (not playfield "barcode" bars): P0 double-width cannon, P1 + NUSIZ1=%011 = a row of 3 hardware-replicated invaders, M0 = shot. Aliens march + drop at edges; button fires. The honest 2600-idiomatic genre layout. `examples({op:'fork', example:"atari2600/mini_invaders", name, path})`. | +| atari2600 (gallery shooter) | `atari2600/templates/mini_invaders.asm` | dasm | Fixed-shooter 2600 game using the RIGHT TIA objects (not playfield "barcode" bars): P0 double-width cannon, P1 + NUSIZ1=%011 = a row of 3 hardware-replicated enemies, M0 = shot. The enemy row marches + drops at the edges; button fires. The 2600-idiomatic genre layout. `examples({op:'fork', example:"atari2600/mini_invaders", name, path})`. | | atari7800 | `atari7800/main.c` | cc65 | Minimal MARIA bring-up: DLL pointing at a single-zone DL, palette load, CHARBASE = 0. cc65 can't constant-fold pointer→int for static initializers, so the DL/DLL addresses are patched in at runtime in `main()`. | | lynx | `lynx/main.c` | cc65 | | | snes | `snes/main.asm` | asar | | -| genesis | `genesis/main.s` | vasm68k | | -| gb | `gb/main.c` (default) or `gb/main.asm` (`language:"asm"`) | sdcc sm83 port (C, default) / rgbds (asm) | C example cycles the BG palette every 32 frames. Asm example shows yellow 'H' on light BG, scrollable with A. SDCC GB hardware-register headers under `src/platforms/gb/lib/c/gb_hardware.h`. | +| genesis | `genesis/main.s` | m68k-elf-as | | +| gb | `gb/main.c` (default) or `gb/main.asm` (`language:"asm"`) | sdcc sm83 port (C, default) / rgbds (asm) | C example cycles the BG palette every 32 frames. Asm example shows yellow 'H' on light BG, scrollable with A. SDCC GB hardware-register header: `gb_hardware.h` (copied in by `examples({op:'fork'})`). | | gbc | `gbc/main.asm` | rgbds (asm) / sdcc sm83 (C) | The bundled example is an asm CGB-color demo (yellow 'H' on a true-blue BG, only possible on GBC). C is also supported via SDCC sm83 - same as GB. | -| sms | `sms/main.c` (or `sms/templates/*.c`) | sdcc | Pair with `src/platforms/sms/lib/c/sms_crt0.s` (passed via `crt0` arg) - boots into a real cartridge with vector table + SP=$DFF0 + IM 1. Yellow 'H' on blue, scrollable with P1-B1. The 10 examples under `sms/templates/` (default, hello_sprite, tile_engine, shmup, shmup_2p, platformer, puzzle, sports, racing, music_demo) all use this crt0 - `examples({op:'fork'})` copies it in automatically. | -| gg | `gg/templates/default.c` (or any other example) | sdcc | R53: GG now ships `src/platforms/gg/lib/c/gg_crt0.s` (byte-identical to SMS's). Real visible-and-runnable default: VDP Mode 4 init + palette + yellow 'H' centered in the 160×144 visible viewport + B1 scroll loop. The 9 examples (default, hello_sprite, tile_engine, shmup, platformer, puzzle, sports, racing, music_demo) all link the GG runtime + crt0 via `examples({op:'fork', example:"gg/", name, path})`. | +| sms | `sms/main.c` (or `sms/templates/*.c`) | sdcc | Pair with the bundled `sms_crt0.s` (passed via `crt0` arg) - boots into a real cartridge with vector table + SP=$DFF0 + IM 1. Yellow 'H' on blue, scrollable with P1-B1. The 10 examples under `sms/templates/` (default, hello_sprite, tile_engine, shmup, shmup_2p, platformer, puzzle, sports, racing, music_demo) all use this crt0 - `examples({op:'fork'})` copies it in automatically. | +| gg | `gg/templates/default.c` (or any other example) | sdcc | GG ships its own `gg_crt0.s` (byte-identical to SMS's). Real visible-and-runnable default: VDP Mode 4 init + palette + yellow 'H' centered in the 160×144 visible viewport + B1 scroll loop. The 9 examples (default, hello_sprite, tile_engine, shmup, platformer, puzzle, sports, racing, music_demo) all link the GG runtime + crt0 via `examples({op:'fork', example:"gg/", name, path})`. | | gba | `gba/templates/*.c` | arm-none-eabi-gcc | Default runtime = **libtonc** (`#include `). 9 examples incl. `tonc_hello`, `tonc_hello_sprite`, the 5 genre games, and `maxmod_demo` (music). Pass `runtime:"libgba"` for the devkitPro API, `runtime:"none"` for bare newlib. **Always call `irq_init(NULL); irq_add(II_VBLANK, NULL);` before `VBlankIntrWait()`** - otherwise the BIOS halts forever. | | pce | `pce/