Skip to content

Commit

Permalink
Explicitly set buffer_handle to kTfLiteNullBufferHandle when crea…
Browse files Browse the repository at this point in the history
…ting tensors through `BuildTfLiteTensor`.

The runtime will interpreter buffer_handle == 0 as having a valid delegate, and will dereference nullptr if a delegate is not set. Creating tensors and just zeroing the memory will not properly set buffer_handle to `kTfLiteNullBufferHandle` (which is enum for -1).

Also check for nullptr in `TfLiteDelegateHasValidOpaqueDelegateBuilder` before dereferencing.

PiperOrigin-RevId: 544932843
  • Loading branch information
LukeBoyer authored and tensorflower-gardener committed Jul 1, 2023
1 parent af84c77 commit eded6e3
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 2 deletions.
2 changes: 1 addition & 1 deletion tensorflow/lite/c/common_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ inline bool TfLiteDelegateHasValidOpaqueDelegateBuilder(
//
// TODO(b/245730811): Consider signalling to clients if the delegate is not
// initialized cleanly.
return delegate->Prepare == nullptr &&
return delegate != nullptr && delegate->Prepare == nullptr &&
delegate->opaque_delegate_builder != nullptr;
}

Expand Down
4 changes: 3 additions & 1 deletion tensorflow/lite/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,9 @@ TfLiteStatus BytesRequired(TfLiteType type, const int* dims, size_t dims_size,
}

TensorUniquePtr BuildTfLiteTensor() {
return TensorUniquePtr((TfLiteTensor*)calloc(1, sizeof(TfLiteTensor)));
auto tensor = TensorUniquePtr((TfLiteTensor*)calloc(1, sizeof(TfLiteTensor)));
tensor->buffer_handle = kTfLiteNullBufferHandle;
return tensor;
}

TensorUniquePtr BuildTfLiteTensor(TfLiteType type, const std::vector<int>& dims,
Expand Down
1 change: 1 addition & 0 deletions tensorflow/lite/util_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ TEST(FourBitTest, BytesRequiredOdd) {
TEST(TestMakeUniqueTensor, Valid) {
TensorUniquePtr t = BuildTfLiteTensor(kTfLiteInt32, {2, 3}, kTfLiteDynamic);
ASSERT_NE(t.get(), nullptr);
ASSERT_EQ(t->buffer_handle, kTfLiteNullBufferHandle);

EXPECT_THAT(t.get(), DimsAre({2, 3}));
EXPECT_EQ(t->bytes, 24);
Expand Down

0 comments on commit eded6e3

Please sign in to comment.