Skip to content

fix(runtime): prevent corrupt B3D hangs, bone crashes, unsupported audio exits, and empty Replace loops (7/10) - #16

Merged
shlifedev merged 1 commit into
mainfrom
fix/runtime-crash-safety
Oct 31, 2026
Merged

shlifedev merged 1 commit into
mainfrom
fix/runtime-crash-safety

Conversation

@shlifedev

@shlifedev shlifedev commented Oct 30, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes shared Blitz runtime paths where mod/map data alone can hang or terminate the game.

  1. Reading a truncated or damaged .b3d model can leave the loader running forever, freezing the game during loading.
  2. Reading a .b3d with a BONE node outside a MESH node can crash through a null-pointer dereference.
  3. 24/32-bit PCM WAV and WAV/OGG with three or more channels can load successfully through LoadSound but terminate the game with RuntimeError("unsupport format") as soon as playback starts.
  4. Passing an empty search string to Replace from a script causes an infinite loop, with unbounded memory growth if the replacement string is nonempty.

Severity and impact

# Severity Trigger Result
1 High Incompletely downloaded/copied .b3d, or a .b3d with corrupted chunk lengths or texture-coordinate set counts LoadMesh/LoadAnimMesh never returns (100% CPU), requiring forced termination
2 High A .b3d whose root is a pivot and whose bone node is outside the mesh node (a sibling/ancestor) Process crash through a null dereference in MeshLoader::numVertices()
3 Medium Mod-provided audio such as a 24-bit PCM WAV Runtime-error termination on first playback, losing unsaved progress
4 Medium Empty search string in map/mod script replace or msg_replace Game hangs

These shared runtime changes (src/blitz3d/src/modules/bb/) apply to both Stranded II and Extended and to Windows/macOS/web builds. Loading/playback results for valid files and original numeric/save semantics are unchanged.

Reproduction and evidence

1-a. Infinite loop on truncated B3D — loader_b3d.cpp:33-53

  • If reading a chunk header fails, readChunk() pushes the current position and returns 0. The caller's loop then uses exitChunk() to fseek back to that position.
  • fseek clears the EOF flag, so chunkSize()'s feof() check passes again. With the parent chunk end beyond the file end, failed readChunk() → fseek to the same position repeats forever.
  • Truncating a valid 227-byte skinned-mesh .b3d to every length from 8–226 bytes and reading through actual fopen produced 116 non-returning cases out of 219.

1-b. Texture-coordinate set counts / brush texture counts — loader_b3d.cpp:140, 179-183

  • VRTS loops over the file's raw tc_sets value for each vertex. A corrupted value of 0x7fffffff causes about 2.1 billion iterations for one vertex (fuzzer-discovered input; did not return for more than 10 seconds before the fix).
  • (n_texs-n_read)*4 and (tc_size-tc_read)*4 are int multiplications. Large values can become negative, seek backward, and create a loop reading the same bytes again.

2. Bone-node null dereference — loader_b3d.cpp:225 → meshloader.cpp:37-39

  • readBone() unconditionally calls MeshLoader::numVertices() before its loop to check weight bounds. Outside a MESH node, ml_mesh is nullptr.
  • In the upstream blitz3d-ng base (d8d5d1b), readBone() accesses MeshLoader only when weights exist, so weightless bone nodes originally loaded successfully. Adding the bounds check introduced this regression.
  • ASan: member access within null pointer of type 'MLMesh', SEGV on unknown address 0x000000000020 in MeshLoader::numVertices().

3. Unsupported audio formats — audio.openal.cpp:91-94, wav_stream.cpp:36-55, ogg_stream.cpp:55

  • WAV header parsing checks only format tag 1 (PCM) and accepts bit depth/channel count unchanged. Later, OpenALChannel::setStream() throws RTEX("unsupport format") for anything other than 8/16-bit mono/stereo. The exception reaches bbruntime_run and terminates the game.
  • A harness using the actual WAVAudioStream confirmed that stereo24.wav, mono32.wav, and surround16.wav all follow the successful LoadSound → playback RTEX path.
  • The engine already skips sounds when LoadSound returns 0 (sfx_play/sfx_music in sfx.bb, and the resource loader in ressources.bb).

4. Empty search string in Replace — string.cpp:27-34

  • An empty string matches at every position. n advances only by the replacement length while the string grows by the same amount, so the loop never ends. If to is also empty, it repeats at the same position.
  • Script commands replace (parser_commands.bb:5456) and msg_replace (parser_commands.bb:2294) pass script values unchanged. The original 1.118 implementation uses the same loop, so this hang predates the port.

Changes

  • loader_b3d.cpp:
    • Records short reads with a truncated flag so chunkSize() returns 0. Loading finishes using only data already read. The flag resets in clear() for each file.
    • Replaces skip() with skipValues(), calculating byte counts in 64 bits and doing no seek for counts ≤0.
    • Reads only the two texture-coordinate sets actually used and skips the remaining sets in one operation. Valid files retain the same read positions and results.
  • meshloader.cpp: numVertices() returns 0 if no mesh is open. Weights on bone nodes outside a mesh are ignored by the existing bounds check.
  • wav_stream.cpp, ogg_stream.cpp: reject streams other than 8/16-bit mono/stereo at header parsing, making LoadSound return 0.
  • audio.openal.cpp: returns false instead of throwing when format mapping fails. Existing callers reclaim the channel and return channel 0.
  • string.cpp: returns the original string unchanged for an empty search string.

Validation

Completed (macOS arm64, Homebrew clang 23):

  • ASan/UBSan harness compiling the modified loader_b3d.cpp/meshloader.cpp directly with scene-class stubs:
    • Truncation scan: 116 non-returning cases out of 219 before → 0 after, with zero crashes.
    • Two bone-node-outside-mesh cases: null dereference before → successful loading after.
    • Six valid .b3d variants with 1–4 texture-coordinate sets and 0–5 components, plus a skinned mesh: vertex/UV/triangle dumps identical before and after.
    • tc_sets=0x7fffffff file: did not return for more than 10 seconds before → loads immediately after.
    • All non-returning B3D inputs found by pre-fix fuzzing terminate normally after the fix.
    • Post-fix B3D-specific libFuzzer (ASan+UBSan, excluding float→int conversion checks): five minutes, 4.05 million executions, no crashes/timeouts.
  • WAV harness using actual wav_stream.cpp/stream.cpp: 16-bit mono and 8-bit stereo retain the playback path; 24/32-bit and six-channel inputs return LoadSound 0.
  • Extracted the bbReplace function body for before/after comparison: ordinary replacement results match; empty search times out before → returns the original string after.
  • git diff --check.

Not completed:

  • Blitz builds, dev.py check, or actual game execution (no dependencies/cmake in this environment). Windows CI build/check must verify these.
  • Playback on an actual OpenAL device or measurements with multichannel OGG; only the code path was checked.
  • macOS/web builds.

Score rationale

Harnesses confirmed hangs/crashes reproducible from mod/map data, and the fixes are narrowly scoped. Valid-data results are unchanged, keeping risk low. However, these are not issues encountered in ordinary play with only the base resources, and actual game-runtime validation remains with CI, so the score is 7.

Follow-up work

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-30T20:41:01.964852Z 88efba9 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@shlifedev shlifedev changed the title (7/10) fix(runtime): 손상된 B3D 무한 루프·본 노드 크래시·미지원 오디오 종료·빈 Replace 멈춤 수정 fix(runtime): prevent corrupt B3D hangs, bone crashes, unsupported audio exits, and empty Replace loops (7/10) Oct 31, 2026
@shlifedev
shlifedev merged commit 29bf286 into main Oct 31, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant