feat: add WebAssembly module

This commit is contained in:
Kirill Zhumarin 2026-08-29 08:29:09 +00:00
parent b502ae07fe
commit a6aa89e5c5
14 changed files with 1728 additions and 19 deletions

View file

@ -6,6 +6,7 @@ on:
permissions:
contents: write
id-token: write
jobs:
build:
@ -26,6 +27,23 @@ jobs:
tools/build_win.sh
tools/build_tar.sh
- uses: mymindstorm/setup-emsdk@v14
- uses: actions/setup-node@v4
with:
node-version: '24.x'
registry-url: 'https://registry.npmjs.org'
- run: npm install --global corepack@latest npm@latest
- run: corepack enable pnpm
- run: pnpm install --frozen-lockfile
- run: emcmake cmake -B build-wasm -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTS:BOOL=TRUE
- run: cmake --build build-wasm
- run: pnpm run build
- run: pnpm test
- if: github.event_name == 'release'
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- uses: softprops/action-gh-release@v1
with:
token: "${{ secrets.GITHUB_TOKEN }}"

3
.gitignore vendored
View file

@ -1,7 +1,10 @@
.idea
build
build-win
build-wasm
.cache
dist
node_modules
*.vkp
*.ini
*.exe

View file

@ -14,28 +14,73 @@ add_subdirectory(third_party/spdlog EXCLUDE_FROM_ALL)
set(LIB_SRC lib/src/Arch.cpp lib/src/Pattern.cpp lib/src/Tokenizer.cpp lib/src/Parser.cpp lib/src/utils.cpp)
add_executable(ptr89 src/main.cpp ${LIB_SRC})
target_link_libraries(ptr89 PRIVATE spdlog::spdlog)
target_precompile_headers(ptr89 PRIVATE <argparse/argparse.hpp> <nlohmann/json.hpp> <string> <vector> <memory> <regex> <map> <tuple> <stdexcept>)
install(TARGETS ptr89)
add_library(ptr89-lib STATIC ${LIB_SRC})
set_target_properties(ptr89-lib PROPERTIES OUTPUT_NAME ptr89)
target_link_libraries(ptr89-lib PUBLIC spdlog::spdlog)
if (MSVC)
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
if (CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
add_executable(ptr89_wasm wasm/main.cpp wasm/Ptr89Wasm.cpp)
set_target_properties(ptr89_wasm PROPERTIES
INTERPROCEDURAL_OPTIMIZATION TRUE
SUFFIX ".js"
)
target_link_libraries(ptr89_wasm PRIVATE ptr89-lib)
target_compile_options(ptr89-lib PRIVATE -Oz -fwasm-exceptions)
target_compile_options(ptr89_wasm PRIVATE -Oz -fwasm-exceptions)
target_compile_options(spdlog PRIVATE -Oz -fwasm-exceptions)
target_link_options(ptr89_wasm PRIVATE
-sWASM=1
-sSTRICT=1
-sEXPORT_ES6=1
-sMODULARIZE
-sINVOKE_RUN=0
-sSINGLE_FILE=0
-sASSERTIONS=0
-sEXIT_RUNTIME=1
-sFILESYSTEM=0
-sDYNAMIC_EXECUTION=0
-sSTACK_OVERFLOW_CHECK=0
-sALLOW_MEMORY_GROWTH
-sENVIRONMENT=node,web,worker
-sEXPORTED_FUNCTIONS=['_malloc','_free']
-sEXPORTED_RUNTIME_METHODS=['HEAPU8','getExceptionMessage','decrementExceptionRefcount']
-sMALLOC=emmalloc
-fwasm-exceptions
--bind
--emit-tsd "$<TARGET_FILE_DIR:ptr89_wasm>/ptr89_wasm.d.ts"
)
if (BUILD_TESTS)
enable_testing()
find_program(PNPM_EXECUTABLE pnpm REQUIRED)
add_test(NAME wasm-test COMMAND ${PNPM_EXECUTABLE} test)
set_tests_properties(wasm-test PROPERTIES WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
endif()
else()
if (BUILD_STATIC)
target_link_options(ptr89 PUBLIC -static -static-libgcc -static-libstdc++)
add_executable(ptr89 src/main.cpp)
target_link_libraries(ptr89 PRIVATE ptr89-lib)
target_precompile_headers(ptr89 PRIVATE <argparse/argparse.hpp> <nlohmann/json.hpp> <string> <vector> <memory> <regex> <map> <tuple> <stdexcept>)
install(TARGETS ptr89)
if (MSVC)
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
else()
if (BUILD_STATIC)
target_link_options(ptr89 PUBLIC -static -static-libgcc -static-libstdc++)
endif()
if (CMAKE_BUILD_TYPE MATCHES "Release")
target_link_options(ptr89 PUBLIC -s)
endif()
target_compile_options(ptr89 PRIVATE -Wall -Wextra -Werror -O3)
target_compile_options(ptr89-lib PRIVATE -Wall -Wextra -Werror -O3)
endif()
if (CMAKE_BUILD_TYPE MATCHES "Release")
target_link_options(ptr89 PUBLIC -s)
if (BUILD_TESTS)
enable_testing()
add_executable(ptr89-tests src/tests.cpp)
target_link_libraries(ptr89-tests PRIVATE ptr89-lib)
add_test(NAME test COMMAND ptr89-tests)
endif()
target_compile_options(ptr89 PUBLIC -Wall -Wextra -Werror -O3)
endif()
if (BUILD_TESTS)
enable_testing()
add_executable(ptr89-tests src/tests.cpp ${LIB_SRC})
target_link_libraries(ptr89-tests PRIVATE spdlog::spdlog)
add_test(NAME test COMMAND ptr89-tests)
endif()

127
README.md
View file

@ -129,6 +129,133 @@ Search done in 143 ms
ptr89 -f EL71v45.bin --from-ini ELKA.ini > swilib.vkp
```
# JAVASCRIPT MODULE
[![NPM Version](https://img.shields.io/npm/v/%40sie-js%2Fptr89)](https://www.npmjs.com/package/@sie-js/ptr89)
Install the package with pnpm:
```bash
pnpm add @sie-js/ptr89
```
## Example
```ts
import { Ptr89 } from "@sie-js/ptr89";
const ptr89 = new Ptr89();
await ptr89.open(fullflash, { arch: "c166" });
const matches = ptr89.find("LDR{ DB00 }", 100);
const xrefs = ptr89.findXRefs(0x9A9332, 100);
ptr89.close();
```
## API
### `new Ptr89()`
Creates a pattern finder. Call `open()` before searching.
### `open(data, options?)`
```ts
open(data: Uint8Array, options?: {
arch?: "arm" | "c166",
base?: number,
align?: number,
}): Promise<void>;
```
Copies a fullflash into WebAssembly memory. The input buffer is no longer
needed after the promise resolves. Calling `open()` again replaces the current
fullflash. Node.js `Buffer` values can be passed directly because `Buffer`
extends `Uint8Array`.
- `arch` selects the instruction decoder. Default: `"arm"`.
- `base` sets the load address. The ARM default is `0xA0000000`. For C166 it is
calculated as `0x1000000 - data.byteLength`.
- `align` sets the search alignment in bytes. Default: `1`.
### `find(pattern, limit?)`
```ts
find(pattern: string, limit?: number): PatternSearchResult[];
```
Finds one pattern in the opened fullflash. The default limit is `100`; a limit
of `0` disables it. The return value has the same fields and type names as CLI
JSON output:
```ts
type PatternSearchResult = {
type: "offset" | "pointer" | "reference" | "branch" | "static_value";
address: number;
offset: number;
value: number;
};
```
### `findXRefs(address, limit?)`
```ts
findXRefs(address: number, limit?: number): XRefSearchResult[];
```
Finds branches, decoded references and stored pointers to a 32-bit address.
The default limit is `100`; a limit of `0` disables it.
```ts
type XRefSearchResult = {
type: "pointer" | "reference" | "branch";
address: number;
offset: number;
};
```
### `setDebug(enabled)`
```ts
setDebug(enabled: boolean): void;
```
Enables or disables decoder and pattern-matching logs from the WebAssembly
module.
### `close()`
```ts
close(): void;
```
Releases the copied fullflash and the underlying Embind object. Calling it
more than once is safe.
### `prettify(pattern)`
```ts
prettify(pattern: string): Promise<string>;
```
Parses a pattern and returns its normalized representation. Invalid patterns
reject the promise with a syntax error.
All addresses and offsets are unsigned 32-bit numbers represented as JavaScript
`number` values.
## Building from sources
Build the WebAssembly module from sources:
```bash
pnpm run build:wasm
```
The build produces `ptr89_wasm.js`, `ptr89_wasm.wasm` and `ptr89_wasm.d.ts`
in `build-wasm/`.
# Pattern syntax
Syntax is fully compatible with WinHex, Smelter and Ghidra SRE patterns.

35
package.json Normal file
View file

@ -0,0 +1,35 @@
{
"name": "@sie-js/ptr89",
"version": "1.0.4",
"description": "ARM/THUMB/C166 binary pattern finder",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"build:wasm": "tools/build_wasm.sh",
"test": "vitest run",
"test:watch": "vitest"
},
"files": [
"dist/*",
"build-wasm/*.js",
"build-wasm/*.wasm",
"build-wasm/*.d.ts"
],
"imports": {
"#build/*": "./build-wasm/*"
},
"repository": {
"type": "git",
"url": "git+https://github.com/siemens-mobile-hacks/ptr89.git"
},
"author": "Siemens Mobile Hackers",
"license": "MIT",
"packageManager": "pnpm@11.3.0",
"devDependencies": {
"@types/node": "^24.10.0",
"typescript": "^5.9.3",
"vitest": "^3.2.6"
}
}

1035
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load diff

2
pnpm-workspace.yaml Normal file
View file

@ -0,0 +1,2 @@
allowBuilds:
esbuild: true

175
src/index.ts Normal file
View file

@ -0,0 +1,175 @@
import createModule from "#build/ptr89_wasm.js";
type WasmModule = Awaited<ReturnType<typeof createModule>>;
type WasmPtr89 = InstanceType<WasmModule["Ptr89"]>;
export type Architecture = "arm" | "c166";
export type PatternSearchResultType = "offset" | "pointer" | "reference" | "branch" | "static_value";
export type XRefSearchResultType = "pointer" | "reference" | "branch";
export interface OpenOptions {
arch?: Architecture;
base?: number;
align?: number;
}
export interface PatternSearchResult {
type: PatternSearchResultType;
address: number;
offset: number;
value: number;
}
export interface XRefSearchResult {
type: XRefSearchResultType;
address: number;
offset: number;
}
const C166_ADDRESS_SPACE_SIZE = 0x1000000;
let modulePromise: ReturnType<typeof createModule> | undefined;
function loadModule(): ReturnType<typeof createModule> {
modulePromise ??= createModule();
return modulePromise;
}
function getError(module: WasmModule, error: unknown): Error {
if (error instanceof Error)
return error;
try {
const details = module.getExceptionMessage(error);
const message = Array.isArray(details) ? details[1] ?? details[0] : details;
try {
module.decrementExceptionRefcount(error);
} catch {
// The exception may not be owned by the C++ runtime.
}
return new Error(String(message));
} catch {
return new Error(String(error));
}
}
function validateLimit(limit: number): void {
if (!Number.isSafeInteger(limit) || limit < 0)
throw new RangeError("Result limit must be a non-negative integer.");
}
export class Ptr89 {
private module?: WasmModule;
private handle?: WasmPtr89;
async open(data: Uint8Array, options: OpenOptions = {}): Promise<void> {
const arch = options.arch ?? "arm";
const align = options.align ?? 1;
if (!Number.isSafeInteger(align) || align <= 0)
throw new RangeError("Memory alignment must be a positive integer.");
let base = options.base;
if (base === undefined) {
if (arch === "c166") {
if (data.byteLength > C166_ADDRESS_SPACE_SIZE)
throw new RangeError("C166 fullflash is larger than the 16 MiB address space; specify base explicitly.");
base = C166_ADDRESS_SPACE_SIZE - data.byteLength;
} else {
base = 0xA0000000;
}
}
if (!Number.isSafeInteger(base) || base < 0 || base > 0xFFFFFFFF)
throw new RangeError("Memory base must be a 32-bit unsigned integer.");
const module = await loadModule();
const handle = this.handle ?? new module.Ptr89();
const ptr = module._malloc(data.byteLength);
module.HEAPU8.set(data, ptr);
try {
handle.open(ptr, data.byteLength, base, align, arch);
this.module = module;
this.handle = handle;
} catch (error) {
if (!this.handle)
handle.delete();
throw getError(module, error);
} finally {
module._free(ptr);
}
}
close(): void {
if (!this.handle)
return;
this.handle.close();
this.handle.delete();
this.handle = undefined;
this.module = undefined;
}
setDebug(enabled: boolean): void {
this.getHandle().setDebug(enabled);
}
find(pattern: string, limit = 100): PatternSearchResult[] {
validateLimit(limit);
const [module, handle] = this.getState();
try {
const matches = handle.find(pattern, limit);
try {
return Array.from({ length: matches.size() }, (_, i) => {
const match = matches.get(i);
if (!match)
throw new Error(`Missing search result at index ${i}.`);
return match as PatternSearchResult;
});
} finally {
matches.delete();
}
} catch (error) {
throw getError(module, error);
}
}
findXRefs(address: number, limit = 100): XRefSearchResult[] {
validateLimit(limit);
if (!Number.isSafeInteger(address) || address < 0 || address > 0xFFFFFFFF)
throw new RangeError("Address must be a 32-bit unsigned integer.");
const [module, handle] = this.getState();
try {
const matches = handle.findXRefs(address, limit);
try {
return Array.from({ length: matches.size() }, (_, i) => {
const match = matches.get(i);
if (!match)
throw new Error(`Missing x-ref result at index ${i}.`);
return match as XRefSearchResult;
});
} finally {
matches.delete();
}
} catch (error) {
throw getError(module, error);
}
}
private getHandle(): WasmPtr89 {
if (!this.handle)
throw new Error("Ptr89 is not opened.");
return this.handle;
}
private getState(): [WasmModule, WasmPtr89] {
if (!this.module || !this.handle)
throw new Error("Ptr89 is not opened.");
return [this.module, this.handle];
}
}
export async function prettify(pattern: string): Promise<string> {
const module = await loadModule();
try {
return module.prettify(pattern);
} catch (error) {
throw getError(module, error);
}
}

55
test/index.test.ts Normal file
View file

@ -0,0 +1,55 @@
import { Buffer } from "node:buffer";
import { describe, expect, it } from "vitest";
import { Ptr89, prettify } from "../src/index.js";
describe("Ptr89 WASM", () => {
it("finds ARM patterns and x-refs", async () => {
const memory = Buffer.from([
0x00, 0x48, // LDR R0, [PC, #0]
0x00, 0xBF, // NOP
0x08, 0x00, 0x00, 0xA0, // Pointer to 0xA0000008
0x00, 0xBF, // NOP at 0xA0000008
]);
const ptr89 = new Ptr89();
await ptr89.open(memory, { arch: "arm" });
expect(ptr89.find("LDR[ 00BF ]", 1)).toEqual([{
type: "offset",
address: 0xA0000000,
offset: 0,
value: 0xA0000000,
}]);
expect(ptr89.findXRefs(0xA0000008, 10)).toContainEqual({
type: "reference",
address: 0xA0000000,
offset: 0,
});
ptr89.close();
});
it("accepts the C166 architecture as a string", async () => {
const memory = Uint8Array.from([
0x0D, 0x01, // JMPR cc_UC, 0xFFFFFE
0xCC, 0x00, // NOP
0xDB, 0x00, // RETS
]);
const ptr89 = new Ptr89();
await ptr89.open(memory, { arch: "c166" });
expect(ptr89.find("[ DB00 ]", 1)).toEqual([{
type: "offset",
address: 0xFFFFFA,
offset: 0,
value: 0xFFFFFA,
}]);
ptr89.close();
});
it("prettifies patterns", async () => {
await expect(prettify("00bf")).resolves.toBe("00 BF");
await expect(prettify("GG")).rejects.toThrow("Syntax error");
});
});

10
tools/build_wasm.sh Executable file
View file

@ -0,0 +1,10 @@
#!/bin/bash
set -e
set -x
cd "$(dirname "$0")/../"
pnpm install --frozen-lockfile
emcmake cmake -B build-wasm -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTS:BOOL=TRUE
cmake --build build-wasm -- -j"$(nproc)"
pnpm run build
ctest --test-dir build-wasm --output-on-failure

17
tsconfig.json Normal file
View file

@ -0,0 +1,17 @@
{
"compilerOptions": {
"declaration": true,
"rootDir": "src",
"outDir": "dist",
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"lib": ["ESNext", "DOM"]
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist", "build-wasm"]
}

108
wasm/Ptr89Wasm.cpp Normal file
View file

@ -0,0 +1,108 @@
#include "Ptr89Wasm.h"
#include <stdexcept>
#include <spdlog/spdlog.h>
namespace Ptr89 {
static const char *getPatternTypeName(PatternType type) {
switch (type) {
case PATTERN_TYPE_OFFSET:
return "offset";
case PATTERN_TYPE_POINTER:
return "pointer";
case PATTERN_TYPE_REFERENCE:
return "reference";
case PATTERN_TYPE_BRANCH_REFERENCE:
return "branch";
case PATTERN_TYPE_STATIC_VALUE:
return "static_value";
}
throw std::invalid_argument("Invalid pattern type.");
}
static const char *getXRefTypeName(XRefType type) {
switch (type) {
case XREF_TYPE_REFERENCE:
return "reference";
case XREF_TYPE_BRANCH_CALL:
return "branch";
case XREF_TYPE_POINTER:
return "pointer";
}
throw std::invalid_argument("Invalid x-ref type.");
}
Ptr89Wasm::Ptr89Wasm() {
spdlog::set_pattern("%v");
spdlog::set_level(spdlog::level::warn);
}
void Ptr89Wasm::open(uintptr_t ptr, size_t size, uint32_t base, int align, const std::string &archName) {
if (ptr == 0 && size != 0)
throw std::invalid_argument("Memory pointer is null.");
if (align <= 0)
throw std::invalid_argument("Memory alignment must be greater than zero.");
Architecture arch;
if (archName == "arm") {
arch = ARCH_ARM;
} else if (archName == "c166") {
arch = ARCH_C166;
} else {
throw std::invalid_argument("Invalid architecture '" + archName + "'. Expected arm or c166.");
}
const auto *data = reinterpret_cast<const uint8_t *>(ptr);
m_data.clear();
if (size != 0)
m_data.assign(data, data + size);
m_base = base;
m_align = align;
m_arch = arch;
m_open = true;
}
void Ptr89Wasm::close() {
m_data.clear();
m_data.shrink_to_fit();
m_open = false;
}
void Ptr89Wasm::setDebug(bool enabled) {
spdlog::set_level(enabled ? spdlog::level::debug : spdlog::level::warn);
}
std::vector<WasmPatternSearchResult> Ptr89Wasm::find(const std::string &patternText, size_t limit) const {
auto memory = getMemory();
auto pattern = Pattern::parse(patternText);
auto matches = Pattern::find(pattern, memory, limit);
std::vector<WasmPatternSearchResult> results;
results.reserve(matches.size());
for (const auto &match: matches)
results.push_back({ getPatternTypeName(pattern->type), match.address, match.offset, match.value });
return results;
}
std::vector<WasmXRefSearchResult> Ptr89Wasm::findXRefs(uint32_t address, size_t limit) const {
auto matches = Pattern::finXRefs(address, getMemory(), limit);
std::vector<WasmXRefSearchResult> results;
results.reserve(matches.size());
for (const auto &match: matches)
results.push_back({ getXRefTypeName(match.type), match.address, match.offset });
return results;
}
Pattern::Memory Ptr89Wasm::getMemory() const {
if (!m_open)
throw std::runtime_error("Ptr89 is not opened.");
return { m_base, m_data.data(), m_data.size(), m_align, m_arch };
}
std::string prettify(const std::string &pattern) {
return Pattern::stringify(Pattern::parse(pattern));
}
}; // namespace Ptr89

47
wasm/Ptr89Wasm.h Normal file
View file

@ -0,0 +1,47 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
#include <ptr89.h>
namespace Ptr89 {
struct WasmPatternSearchResult {
std::string type;
uint32_t address;
uint32_t offset;
uint32_t value;
};
struct WasmXRefSearchResult {
std::string type;
uint32_t address;
uint32_t offset;
};
class Ptr89Wasm {
private:
std::vector<uint8_t> m_data;
uint32_t m_base = 0;
int m_align = 1;
Architecture m_arch = ARCH_ARM;
bool m_open = false;
Pattern::Memory getMemory() const;
public:
Ptr89Wasm();
void open(uintptr_t ptr, size_t size, uint32_t base, int align, const std::string &archName);
void close();
void setDebug(bool enabled);
std::vector<WasmPatternSearchResult> find(const std::string &patternText, size_t limit) const;
std::vector<WasmXRefSearchResult> findXRefs(uint32_t address, size_t limit) const;
};
std::string prettify(const std::string &pattern);
}; // namespace Ptr89

32
wasm/main.cpp Normal file
View file

@ -0,0 +1,32 @@
#include <emscripten/bind.h>
#include "Ptr89Wasm.h"
using namespace emscripten;
using namespace Ptr89;
EMSCRIPTEN_BINDINGS(ptr89) {
value_object<WasmPatternSearchResult>("PatternSearchResult")
.field("type", &WasmPatternSearchResult::type)
.field("address", &WasmPatternSearchResult::address)
.field("offset", &WasmPatternSearchResult::offset)
.field("value", &WasmPatternSearchResult::value);
value_object<WasmXRefSearchResult>("XRefSearchResult")
.field("type", &WasmXRefSearchResult::type)
.field("address", &WasmXRefSearchResult::address)
.field("offset", &WasmXRefSearchResult::offset);
register_vector<WasmPatternSearchResult>("PatternSearchResults");
register_vector<WasmXRefSearchResult>("XRefSearchResults");
class_<Ptr89Wasm>("Ptr89")
.constructor<>()
.function("open", &Ptr89Wasm::open)
.function("close", &Ptr89Wasm::close)
.function("setDebug", &Ptr89Wasm::setDebug)
.function("find", &Ptr89Wasm::find)
.function("findXRefs", &Ptr89Wasm::findXRefs);
function("prettify", &prettify);
}