Skip to content

Prevent JP2/J2K assertions after failed stream length probes - #232

Merged
danoli3 merged 1 commit into
masterfrom
fix/jp2-callback-length
Oct 28, 2026
Merged

danoli3 merged 1 commit into
masterfrom
fix/jp2-callback-length

Conversation

@danoli3

@danoli3 danoli3 commented Oct 28, 2026

Copy link
Copy Markdown
Owner

When a JP2/J2K read callback rejects SEEK_END, the stream adapter ignores the error and can declare a zero-byte stream to OpenJPEG. Reading the signature then violates OpenJPEG's stream-length invariant and aborts Debug builds with the assertion reported in #198.

Validate both tell results, the seek to EOF, restoration of the original position, and a positive readable length before creating the decoder stream. Invalid probes now make FreeImage_LoadFromHandle() return NULL. Output streams no longer run an unnecessary length probe. Successful lengths also avoid the old intermediate unsigned truncation.

Add a self-contained callback regression test for JP2 and raw J2K, covering seven callback faults, signature detection, full/header-only loading, exact lossless pixels, and saving without SEEK_END. Run it in the existing JP2/JXR workflow on Linux, macOS, and MSVC static/shared builds, with Windows DLL deployment.

Validation on macOS, Debug + ASan, against pre-fix master c210b8b:

  • The new synthetic regression and all four supplied JP2/J2K files reproduce the exact assertion before the fix when SEEK_END is rejected; fixed builds return NULL without an ASan report. Normal callbacks still load all four files.
  • With JXR disabled and OpenEXR disabled: all 12 fixed-build CTests pass; all 11 existing baseline CTests pass. This demonstrates the missing callback-failure coverage.
  • With JXR enabled and OpenEXR disabled: the new callback test and all other tests except MainTestSuite pass. MainTestSuite exposes the same pre-existing EXIF/JXR stack over-read at Exif.cpp:1228 in both baseline and fixed builds; it is not fixed by this PR.
  • With JXR enabled: all six supplied JP2/JXR samples pass file/memory pixel matching and PNG preview export under ASan.

Refs #198. This prevents a reproduced cause of the assertion; the reporter's actual callback implementation is still needed to confirm their exact trigger. Historical analysis and the reason existing tests missed it are in the investigation comment.

@danoli3

danoli3 commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

Investigation of the assertion reported in #198, including when the bug appeared and why the tests missed it.

When did this regress?

The available history does not establish a recent regression. The unchecked callback error handling is already present in the repository's earliest commit, 279da23, FreeImage 3.16.0, 4 September 2014:

The 19 August 2026 OpenJPEG 2.0.0 → 2.5.4 update, 229de19, did not introduce this assertion: it exists in the parent revision too. git blame attributing today's line 587 to that vendor refresh is not evidence that the check originated there. The later explicit (unsigned) cast in a2e787f retained an existing conversion and did not introduce the ignored callback failures.

The 25 October 2026 display tests, 30ed59f / PR #207, added successful decode, format selection, native pixel-type and preview coverage. They did not add this fault case. The assertion was reported in the issue on 27 October, followed by the linked follow-up on 28 October.

Therefore the supported conclusion is: a longstanding callback-handling bug, present since at least the 2014 import, now reproduced on pre-fix master c210b8b. This is source-history evidence plus a current baseline reproduction, not a runtime bisect of every historical release. The upstream introduction date before this repository's history, and any separate recent change in the reporting application's callbacks/build, remain unknown.

Reproduction and cause

I reproduced the exact assertion in a macOS Debug + ASan build; it is not restricted to Windows:

  1. Supply normal read, tell and SEEK_SET/SEEK_CUR callbacks, but reject SEEK_END with a nonzero return value.
  2. Call FreeImage_GetFileTypeFromHandle(), then FreeImage_LoadFromHandle() on the same handle, as in the report.
  3. Signature detection succeeds and preserves position zero. The loader then calls _LengthProc().
  4. _LengthProc() ignores the failed end seek. The next tell still returns zero, so FreeImage registers a zero-length input with OpenJPEG.
  5. Reads nevertheless return real image bytes. OpenJPEG's byte offset becomes positive while the declared length remains zero, triggering m_user_data_length >= (OPJ_UINT64)m_byte_offset.

The generated 32×32 regression fixture and all four supplied JPEG 2000 files reproduce this failure on the unmodified baseline:

Input Baseline, normal callbacks Baseline, rejected SEEK_END Fixed, rejected SEEK_END
Generated JP2 fixture Loads Exact assertion / SIGABRT Returns NULL
4px.jp2 Loads Exact assertion / SIGABRT Returns NULL
balloon.jp2 Loads Exact assertion / SIGABRT Returns NULL
sample1.jp2 Loads Exact assertion / SIGABRT Returns NULL
sample-photo.jp2 (raw J2K) Loads as J2K Exact assertion / SIGABRT Returns NULL

Normal callbacks still load every input after the fix. This demonstrates a sufficient cause for the reported assertion; the reporter's actual callback implementation has not been supplied, so its exact trigger is not yet confirmed. Incorrect length reporting or other inconsistent stream callbacks can produce similar symptoms.

Why did the existing unit tests miss it?

  • The existing file/memory tests and CodecDisplayTest use working file or memory seek/tell implementations. The real-sample diagnostic also uses ordinary file and memory APIs.
  • The earlier signed-32-bit callback check allowed SEEK_END and rejected only out-of-range seeks. These samples never approached 2 GiB, so that check never injected the relevant failure.
  • Successful format detection does not validate end-seek support. It reads/restores signatures; the stream-length probe happens later during loading.
  • This is a missing fault-injection case, not a disabled assertion or a broken test runner. Existing CI includes Debug builds, where the assertion is active.

As a direct check, all 11 existing CTests pass on the pre-fix Debug + ASan baseline with JXR/OpenEXR disabled. Linking the new regression test against that same baseline library immediately reproduces the assertion. The fixed build passes all 12 CTests in that configuration.

Fix and prevention

The adapter now validates the initial tell, seek to EOF, end tell, restoration seek, and positive remaining input length. On failure it rejects stream creation, so JP2/J2K loading returns NULL before decoder reads. The OpenJPEG assertion stays intact. Output streams skip the unnecessary length probe, and a successful input length no longer passes through an intermediate 32-bit unsigned value. The public seek/tell ABI is unchanged.

J2KCallbacksTest exercises both JP2 and raw J2K, with full and header-only loading, across:

  • normal callbacks;
  • negative and positive nonzero SEEK_END failure returns;
  • a callback claiming end-seek success without moving;
  • failed initial/end tells;
  • failed position restoration;
  • a falsely reported zero length.

It also checks content detection/position preservation, byte-exact lossless pixels, saving without SEEK_END, and that a failed length probe performs no decoder reads. Checks remain active in Release. The JP2/JXR workflow now builds/runs this target on Linux, macOS and Windows MSVC static/shared configurations.

Callers should implement the FreeImageIO seek contract consistently: 0 means success; nonzero means failure, and tell returns -1 on error. SEEK_SET, SEEK_CUR and SEEK_END must behave correctly for this loader. For example, a callback wrapping FreeImage_SeekMemory() must convert its BOOL result:

return FreeImage_SeekMemory(memory, offset, origin) ? 0 : -1;

Do not remove the OpenJPEG assertion or advertise a fabricated length to suppress it. Returning NULL prevents the process abort; successful decoding still requires suitable callbacks.

Separate ASan finding during verification

With JXR enabled, the full suite exposes a pre-existing stack buffer over-read while saving EXIF metadata. It reproduces identically on baseline and fixed builds. Exif.cpp:1228 requests ifd_size bytes from &empty_byte, which points to a one-byte stack object. This is the MainTestSuite / tiff_write_ifd / WriteMetadata crash seen during the test run, a different failure from OpenJPEG's assertion.

The JP2 callback test and the other 10 tests pass in that JXR-enabled fixed build; MainTestSuite remains affected by the baseline EXIF bug. Separately, all six supplied JP2/JXR samples pass file/memory pixel matching and PNG preview export under ASan with JXR enabled. The EXIF over-read is not fixed or hidden by this PR.

@danoli3

danoli3 commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

okay @haobinnan I got my local ai models to really smash the analysis on this one. Qwen and Glimmer and I think it's fixed. Goes back a long way

@danoli3
danoli3 merged commit 80ac96c into master Oct 28, 2026
77 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