Skip to content

Fix integer overflow in BytesRequiredForTensor and TfLiteEvalTensorByteLength - #3637

Open
TristanInSec wants to merge 1 commit into
tensorflow:mainfrom
TristanInSec:fix/tensor-size-integer-overflow
Open

Fix integer overflow in BytesRequiredForTensor and TfLiteEvalTensorByteLength#3637
TristanInSec wants to merge 1 commit into
tensorflow:mainfrom
TristanInSec:fix/tensor-size-integer-overflow

Conversation

@TristanInSec

Copy link
Copy Markdown

Summary

BytesRequiredForTensor() and TfLiteEvalTensorByteLength() compute tensor byte size using int element_count, which overflows when model-supplied dimensions are large (e.g., 65536 x 65536 wraps int32 to 0). The undersized allocation leads to heap buffer overflow when kernels later write tensor data using the actual dimensions.

Fix

  • Change element_count from int to size_t
  • Add overflow detection via division check after each multiplication
  • Return kTfLiteError on overflow or non-positive dimensions
  • Both functions run during Setup (model loading), consistent with the Error Handling Guide's recommendation to validate model-provided parameters early

This replaces the previous PR #3533 which was closed for not following the Error Handling Guide.

Alignment with Error Handling Guide

Per Section 2 (Phase 1: Setup & Initialization):

"Model-provided parameters: Check the number of inputs/outputs, tensor types, and tensor shapes."

These functions are called during InitializeTfLiteTensorFromFlatbuffer (Setup phase). The fix uses kTfLiteError return which callers propagate via TF_LITE_ENSURE_STATUS, keeping ROM cost low (no additional string literals).

Testing

Verified with ASan-enabled build: crafted model with shape [65536, 65536] now returns kTfLiteError instead of allocating 0 bytes and overflowing.

Fixes GHSA-7rx3-jmhh-gq5m

…teLength

Both functions compute tensor byte size using int32 element_count,
which overflows when model-supplied dimensions are large (e.g.,
65536 x 65536 wraps to 0). The undersized allocation leads to heap
buffer overflow when kernels write tensor data using actual dimensions.

Fix: use size_t for element_count and add overflow detection via
division check after each multiplication. Return kTfLiteError on
overflow or non-positive dimensions. This runs during Setup
(model loading), consistent with the Error Handling Guide's
recommendation to validate model-provided parameters early.

The fix also rejects dimensions <= 0, which are semantically invalid
for tensor shapes and would produce incorrect byte calculations.
@TristanInSec
TristanInSec requested a review from a team as a code owner July 26, 2026 13:52
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