Skip to content

Fix signed integer overflow in TFLite Div op (INT32_MIN / -1) (#124409) - #124567

Merged
copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
genius-0963:fix/security-crash-bugs-124409-87912-123114
Aug 25, 2026
Merged

copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
genius-0963:fix/security-crash-bugs-124409-87912-123114

Conversation

@genius-0963

@genius-0963 genius-0963 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Fixes #124409

Guards against signed integer overflow (INT_MIN / -1) in TFLite Div and BroadcastDivSlow reference and optimized kernels by saturating to std::numeric_limits<T>::max().

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Aug 3, 2026
@google-cla

google-cla Bot commented Aug 3, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds protobuf dependencies across several BUILD files, updates debug ops to log warnings instead of failing on tensor publication errors, and adds a negative index check in TensorListSetItem. It also introduces guards against signed integer overflow (INT_MIN / -1) in reference division kernels. The review feedback correctly identifies a bug in these overflow guards where they would incorrectly trigger for unsigned integer types, and suggests adding a signedness check to ensure correct behavior.

@keerthanakadiri
keerthanakadiri requested a review from a team August 3, 2026 09:06
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Aug 3, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Aug 3, 2026
@keerthanakadiri

Copy link
Copy Markdown
Contributor

Hi @genius-0963 , Can you kindly sign the CLA? Thank you!

@genius-0963
genius-0963 force-pushed the fix/security-crash-bugs-124409-87912-123114 branch 2 times, most recently from c9b65bd to 856ae3f Compare August 3, 2026 19:55
@hunterkritik-byte

Copy link
Copy Markdown
Contributor

@genius-0963
genius-0963 force-pushed the fix/security-crash-bugs-124409-87912-123114 branch from 856ae3f to ff8a15c Compare August 4, 2026 13:07
@genius-0963

Copy link
Copy Markdown
Contributor Author

Finally, the CLA flow is working! 🎉

@tejprasadbhattarai638-collab

Copy link
Copy Markdown

Still no merge :(

@dmiltr3
dmiltr3 self-requested a review August 5, 2026 17:25

@dmiltr3 dmiltr3 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Scope of Changes

  • In Scope: The changes in tensorflow/lite/kernels/internal/reference/div.h are in scope because the Div operator is reachable via the WebNN delegate.

Feedback on div.h (In Scope)

The overflow guard in tensorflow/lite/kernels/internal/reference/div.h contains a bug for unsigned integer types.

The condition std::is_integral<T>::value && val2 == static_cast<T>(-1) && val1 == std::numeric_limits<T>::min() will trigger for unsigned types when val1 == 0 and val2 == UINT_MAX (or equivalent max value), returning UINT_MAX instead of 0 (since 0 / UINT_MAX is 0).

The condition should verify that T is signed, for example by adding std::is_signed<T>::value.

Please also include unit tests in div_test to verify the overflow guards work as expected and cover the bug mentioned above.

Discrepancy

The PR description mentions fixing TensorListSetItem in tensorflow/core/kernels/list_kernels.cc. This file is not included in the files changed in this PR, and such changes would be considered out of security hardening scope for TFLite in any case.

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Aug 5, 2026
@genius-0963
genius-0963 force-pushed the fix/security-crash-bugs-124409-87912-123114 branch from a6701f4 to 1ba7d1d Compare August 5, 2026 18:01
@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Aug 6, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CI Build Checks Failure

The latest CI workflow runs failed on the following jobs due to compilation errors:


Root Causes & Code Solutions

1. Compilation Error in tensorflow/lite/kernels/internal/reference/div.h

In BroadcastDivSlow, the lambda was defined as div_func while op was passed to BroadcastBinaryOpSimple, resulting in:
error: use of undeclared identifier 'op'

Solution:
Keep op concise and add the signed integer overflow check directly:

template <typename T, int N = 5>
void BroadcastDivSlow(const ArithmeticParams& params,
                      const RuntimeShape& unextended_input1_shape,
                      const T* input1_data,
                      const RuntimeShape& unextended_input2_shape,
                      const T* input2_data,
                      const RuntimeShape& unextended_output_shape,
                      T* output_data) {
  T output_activation_min;
  T output_activation_max;
  GetActivationParams(params, &output_activation_min, &output_activation_max);

  auto op = [output_activation_min, output_activation_max](T a, T b) {
    T div_result;
    if (std::is_integral<T>::value && std::is_signed<T>::value &&
        b == static_cast<T>(-1) &&
        a == std::numeric_limits<T>::min()) {
      div_result = std::numeric_limits<T>::max();
    } else {
      div_result = a / b;
    }
    return ActivationFunctionWithMinMax(div_result, output_activation_min,
                                        output_activation_max);
  };

  BroadcastBinaryOpSimple(unextended_input1_shape, input1_data,
                          unextended_input2_shape, input2_data,
                          unextended_output_shape, output_data, op);
}

2. Overflow Protection in tensorflow/lite/kernels/internal/optimized/optimized_ops.h

BroadcastDivSlow in optimized_ops.h is duplicated from reference/div.h for generic optimized execution on CPU targets. To prevent hardware SIGFPE traps during broadcast evaluation of INT32_MIN / -1, apply the same guard:

template <typename T, int N = 5>
void BroadcastDivSlow(const ArithmeticParams& params,
                      const RuntimeShape& unextended_input1_shape,
                      const T* input1_data,
                      const RuntimeShape& unextended_input2_shape,
                      const T* input2_data,
                      const RuntimeShape& unextended_output_shape,
                      T* output_data) {
  ruy::profiler::ScopeLabel label("BroadcastDivSlow");
  T output_activation_min;
  T output_activation_max;
  GetActivationParams(params, &output_activation_min, &output_activation_max);

  auto op = [output_activation_min, output_activation_max](T a, T b) {
    T div_result;
    if (std::is_integral<T>::value && std::is_signed<T>::value &&
        b == static_cast<T>(-1) &&
        a == std::numeric_limits<T>::min()) {
      div_result = std::numeric_limits<T>::max();
    } else {
      div_result = a / b;
    }
    return ActivationFunctionWithMinMax(div_result, output_activation_min,
                                        output_activation_max);
  };
  reference_ops::BroadcastBinaryOpSimple(
      unextended_input1_shape, input1_data, unextended_input2_shape,
      input2_data, unextended_output_shape, output_data, op);
}

3. Syntax Error in tensorflow/lite/kernels/div_test.cc

TEST(IntegerDivOpTest, NormalNegOneDivision) is missing its closing brace } before TEST(QuantizedDivOpTest, AsymmetricQuantizedDivisorZeroCheck).

Solution:
Ensure all tests are properly closed:

TEST(IntegerDivOpTest, Int32MinDivNegOne_Saturates) {
  IntegerDivOpModel m({TensorType_INT32, {1, 1, 4, 1}},
                      {TensorType_INT32, {1, 1, 4, 1}}, {TensorType_INT32, {}},
                      ActivationFunctionType_NONE);
  const int32_t int32_min = std::numeric_limits<int32_t>::min();
  const int32_t int32_max = std::numeric_limits<int32_t>::max();
  m.PopulateTensor<int32_t>(m.input1(), {int32_min, int32_min, -10, 10});
  m.PopulateTensor<int32_t>(m.input2(), {-1, 1, -1, -1});
  ASSERT_EQ(m.Invoke(), kTfLiteOk);
  EXPECT_THAT(m.GetOutput(),
              ElementsAreArray({int32_max, int32_min, 10, -10}));
}

TEST(IntegerDivOpTest, Int32MinDivNegOne_Broadcast) {
  IntegerDivOpModel m({TensorType_INT32, {1, 1, 4, 1}},
                      {TensorType_INT32, {}},
                      {TensorType_INT32, {}}, ActivationFunctionType_NONE);
  const int32_t int32_min = std::numeric_limits<int32_t>::min();
  const int32_t int32_max = std::numeric_limits<int32_t>::max();
  m.PopulateTensor<int32_t>(m.input1(), {int32_min, -100, 0, 100});
  m.PopulateTensor<int32_t>(m.input2(), {-1});
  ASSERT_EQ(m.Invoke(), kTfLiteOk);
  EXPECT_THAT(m.GetOutput(), ElementsAreArray({int32_max, 100, 0, -100}));
}

TEST(IntegerDivOpTest, NormalNegOneDivision) {
  IntegerDivOpModel m({TensorType_INT32, {1, 2, 2, 1}},
                      {TensorType_INT32, {1, 2, 2, 1}}, {TensorType_INT32, {}},
                      ActivationFunctionType_NONE);
  m.PopulateTensor<int32_t>(m.input1(), {-100, 50, 0, 2147483647});
  m.PopulateTensor<int32_t>(m.input2(), {-1, -1, -1, -1});
  ASSERT_EQ(m.Invoke(), kTfLiteOk);
  EXPECT_THAT(m.GetOutput(), ElementsAreArray({100, -50, 0, -2147483647}));
}

Local Verification

All tests in //tensorflow/lite/kernels:div_test passed successfully when tested with these solutions.

@genius-0963
genius-0963 force-pushed the fix/security-crash-bugs-124409-87912-123114 branch 2 times, most recently from 7b70954 to d1a1302 Compare August 8, 2026 20:06
@tejprasadbhattarai638-collab

Copy link
Copy Markdown

@dmiltr3
Any update

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Aug 10, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 August 11, 2026 16:52
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Aug 11, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Compilation Error in tensorflow/lite/kernels/div_test.cc

There is a missing closing brace } at the end of the NormalNegOneDivision unit test in tensorflow/lite/kernels/div_test.cc (right before TEST(QuantizedDivOpTest, AsymmetricQuantizedDivisorZeroCheck)), which causes compilation errors when building div_test:

error: static data member 'test_info_' not allowed in local class 'QuantizedDivOpTest_AsymmetricQuantizedDivisorZeroCheck_Test'
error: function definition is not allowed here

Required Fix

Add the missing } to close TEST(IntegerDivOpTest, NormalNegOneDivision):

diff --git a/tensorflow/lite/kernels/div_test.cc b/tensorflow/lite/kernels/div_test.cc
index 9a048b9..a0453de 100644
--- a/tensorflow/lite/kernels/div_test.cc
+++ b/tensorflow/lite/kernels/div_test.cc
@@ -452,6 +452,8 @@ TEST(IntegerDivOpTest, NormalNegOneDivision) {
   m.PopulateTensor<int32_t>(m.input2(), {-1, -1, -1, -1});
   ASSERT_EQ(m.Invoke(), kTfLiteOk);
   EXPECT_THAT(m.GetOutput(), ElementsAreArray({100, -50, 0, -2147483647}));
+}
+
 TEST(QuantizedDivOpTest, AsymmetricQuantizedDivisorZeroCheck) {
   // Case 1: Divisor is real 0.0 (quantized to -128). This should FAIL.
   {

Fixes tensorflow#124409

The TFLite reference Div kernel performs raw C++ division without
guarding against signed integer overflow. When INT32_MIN is divided
by -1, the result cannot be represented in int32_t, triggering
undefined behavior per C++20 [expr.mul]/4.

Fix: Add an overflow guard in the flat Div function, and in
BroadcastDivSlow in both reference/div.h and optimized/optimized_ops.h.
When the overflow case (T::min() / -1) is detected for signed integral
types, the result is saturated to std::numeric_limits<T>::max().

The guard uses std::is_signed<T>::value to avoid false triggering
on unsigned types (where static_cast<T>(-1) == T::max() and
T::min() == 0, which would incorrectly match 0 / UINT_MAX).

BroadcastDivSlow is refactored to use the op lambda pattern with
BroadcastBinaryOpSimple to match the upstream API.

Also adds unit tests covering:
- INT32_MIN / -1 saturation (flat path)
- INT32_MIN / -1 saturation (broadcast path)
- Normal -1 division still works correctly
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Aug 25, 2026
copybara-service Bot pushed a commit to google-ai-edge/LiteRT that referenced this pull request Aug 25, 2026
… -1) (#124409)

Imported from GitHub PR tensorflow/tensorflow#124567

 Summary:
> Fixes tensorflow/tensorflow#124409
>
> Guards against signed integer overflow (`INT_MIN / -1`) in TFLite `Div` and `BroadcastDivSlow` reference and optimized kernels by saturating to `std::numeric_limits<T>::max()`.

Copybara import of the project:

--
f149119dbc9a59cacce0f16299b4062cb261c29b by Saurabh Sungh <[email protected]>:

Fix signed integer overflow in TFLite Div op (INT32_MIN / -1)

Fixes tensorflow/tensorflow#124409

The TFLite reference Div kernel performs raw C++ division without
guarding against signed integer overflow. When INT32_MIN is divided
by -1, the result cannot be represented in int32_t, triggering
undefined behavior per C++20 [expr.mul]/4.

Fix: Add an overflow guard in the flat Div function, and in
BroadcastDivSlow in both reference/div.h and optimized/optimized_ops.h.
When the overflow case (T::min() / -1) is detected for signed integral
types, the result is saturated to std::numeric_limits<T>::max().

The guard uses std::is_signed<T>::value to avoid false triggering
on unsigned types (where static_cast<T>(-1) == T::max() and
T::min() == 0, which would incorrectly match 0 / UINT_MAX).

BroadcastDivSlow is refactored to use the op lambda pattern with
BroadcastBinaryOpSimple to match the upstream API.

Also adds unit tests covering:
- INT32_MIN / -1 saturation (flat path)
- INT32_MIN / -1 saturation (broadcast path)
- Normal -1 division still works correctly

Merging this change closes #124567

PiperOrigin-RevId: 970687124
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
…ation.

This ensures that the constants created by ZeroSizedHloElimination are folded into their users immediately.

Also remove unnecessary call to `ZeroSizedHloElimination` and only keep the one from `RunPreSPMDPartitionerPasses`.

FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 970440469
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 970006560
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 970371488
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 970106151
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
…arameter

In preparation for adding msan support.

FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 958346385
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
Fix crash when CreateFromProto encounters proto types not linked into
the binary (e.g. from libtpu.so). Unknown entries are now stored as
opaque google.protobuf.Any values and re-emitted by ToProto(), enabling
lossless round-tripping without requiring the proto definitions.

FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 969554949
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 951208867
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
- Fix bit-size calculation for quantized and complex types in const_tensor_utils to account for element count.
- Add QI4 support to TFL_QConstOp results in tfl_ops.td.
- Allow folding TransposeOp and ReshapeOp on resource constants in ShouldFoldOperation.
- Add GetPhysicalBufferHash using xxHash for DenseResourceElementsAttr in FlatBuffer exporters.
- Support direct DenseResourceElementsAttr reading and low-bit packing (INT4/UINT4/INT2) during FlatBuffer serialization.
- Ensure unique name assignment in Translator::InitializeNamesFromAttribute and BuildSignatureDefData.

FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 970156012
copybara-service Bot pushed a commit that referenced this pull request Aug 25, 2026
This allows reading the mlir body and weights separately. Doing this, we can store weights in DenseResourceElementsAttr and avoid increased peak ram.

FUTURE_COPYBARA_INTEGRATE_REVIEW=#124567 from genius-0963:fix/security-crash-bugs-124409-87912-123114 08b198b
PiperOrigin-RevId: 952871637
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kokoro:force-run Tests on submitted change ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

Security: Integer Overflow in WebNN Div Op via INT32_MIN/-1

8 participants