Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[TF FE] fix out-of-bounds read in RestoreV2 output index parsing (#35587)

Evgeny Kotov3ae48ee7db55
diff --git a/src/frontends/tensorflow/src/parse_output_index.hpp b/src/frontends/tensorflow/src/parse_output_index.hpp
new file mode 100644
index 00000000000..528c3017c19
--- /dev/null
+++ b/src/frontends/tensorflow/src/parse_output_index.hpp
@@ -0,0 +1,48 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cctype>
+#include <cerrno>
+#include <cstdint>
+#include <cstdlib>
+#include <limits>
+#include <optional>
+#include <string>
+
+namespace ov {
+namespace frontend {
+namespace tensorflow {
+
+// Strict integer parser for the output-index suffix of a TF node reference
+// like "RestoreV2:3". Returns nullopt for empty / non-numeric / trailing
+// garbage / overflow / out-of-int-range tokens; the caller decides how to
+// react (e.g. throw a frontend exception). Uses strtoll + std::int64_t so
+// the int-range check is meaningful on platforms where long aliases int.
+inline std::optional<int> parse_output_index(const std::string& token) {
+ if (token.empty()) {
+ return std::nullopt;
+ }
+ // strtoll otherwise silently skips leading whitespace; well-formed TF node
+ // references never contain it, so reject it as malformed up front.
+ if (std::isspace(static_cast<unsigned char>(token.front()))) {
+ return std::nullopt;
+ }
+ char* end = nullptr;
+ errno = 0;
+ constexpr auto base = 10;
+ const std::int64_t v = std::strtoll(token.c_str(), &end, base);
+ if (end == token.c_str() || *end != '\0' || errno == ERANGE) {
+ return std::nullopt;
+ }
+ if (v < std::numeric_limits<int>::min() || v > std::numeric_limits<int>::max()) {
+ return std::nullopt;
+ }
+ return static_cast<int>(v);
+}
+
+} // namespace tensorflow
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/tensorflow/src/variables_index.cpp b/src/frontends/tensorflow/src/variables_index.cpp
index 87d5bf87b3d..f287038fb8b 100644
--- a/src/frontends/tensorflow/src/variables_index.cpp
+++ b/src/frontends/tensorflow/src/variables_index.cpp
@@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
//
-#include <stdlib.h>
-
#include <fstream>
#include <string>
@@ -14,6 +12,7 @@
#include "openvino/util/mmap_object.hpp"
#include "ov_tensorflow/tensor_bundle.pb.h"
#include "ov_tensorflow/trackable_object_graph.pb.h"
+#include "parse_output_index.hpp"
#include "tf_utils.hpp"
#ifdef ENABLE_SNAPPY_COMPRESSION
@@ -24,6 +23,13 @@ namespace ov {
namespace frontend {
namespace tensorflow {
+namespace {
+// RestoreV2 data inputs (per the TF Op definition): prefix(0), tensor_names(1),
+// shape_and_slices(2). Control inputs ('^'-prefixed) live in the same input list
+// and are filtered out by the data-port check below.
+constexpr int tensor_names_index = 1;
+} // namespace
+
void VariablesIndex::read_variables_index_block(std::ifstream& fs,
const VIBlock& index,
std::vector<char>& data,
@@ -378,6 +384,62 @@ void VariablesIndex::map_assignvariable(const std::shared_ptr<::tensorflow::Grap
}
}
+ const auto get_variable_name = [](const PtrNode::SharedPtrNode& rv2_node, int idx) -> std::string {
+ std::string tensor_name;
+ if (rv2_node->node->input().size() > tensor_names_index) {
+ const std::string& in = rv2_node->node->input(tensor_names_index);
+ if (!in.empty() && in[0] != '^') {
+ tensor_name = in;
+ }
+ }
+ FRONT_END_GENERAL_CHECK(!tensor_name.empty(), "RestoreV2 node is missing tensor_names input");
+ std::vector<std::string> parsed;
+ PtrNode::parse_node_name(tensor_name, parsed);
+ // Match by local node name on the rv2_node's already-linked inputs. Pointer-based:
+ // works in both top-level and StatefulPartitionedCall scopes (the global node dictionary
+ // uses prefixed keys for SPC-flattened nodes, but each PtrNode's NodeDef carries its
+ // local name in both cases). Also catches the case where associate_node compacted the
+ // inputs vector and inputs[1] silently refers to a non-tensor_names Const.
+ PtrNode::SharedPtrNode tn_ptr = nullptr;
+ for (const auto& input : rv2_node->inputs) {
+ if (input->node->name() == parsed[0]) {
+ tn_ptr = input;
+ break;
+ }
+ }
+ FRONT_END_GENERAL_CHECK(tn_ptr != nullptr,
+ "RestoreV2 tensor_names input not found among RestoreV2 inputs: ",
+ parsed[0]);
+ const auto* tn_node = tn_ptr->node;
+ const auto value_attr_it = tn_node->attr().find("value");
+ FRONT_END_GENERAL_CHECK(tn_node->op() == "Const" && value_attr_it != tn_node->attr().end(),
+ "RestoreV2 tensor_names input is not a Const with 'value' attribute");
+ const auto& tensor = value_attr_it->second.tensor();
+ FRONT_END_GENERAL_CHECK(idx >= 0 && idx < tensor.string_val_size(),
+ "RestoreV2 output index out of range: ",
+ idx,
+ " (size=",
+ tensor.string_val_size(),
+ ")");
+ return tensor.string_val(idx);
+ };
+
+ // Parse the integer suffix of a "RestoreV2:N" reference. The colon-less form
+ // (size < 2) implicitly refers to output 0 — preserved here as an explicit
+ // call-site default. Anything past the colon must be a strictly valid in-range
+ // integer; non-numeric, trailing garbage and overflow all throw via
+ // FRONT_END_GENERAL_CHECK below.
+ const auto resolve_output_index = [](const std::vector<std::string>& restore_output) -> int {
+ if (restore_output.size() < 2) {
+ return 0;
+ }
+ const auto parsed = parse_output_index(restore_output.back());
+ FRONT_END_GENERAL_CHECK(parsed.has_value(),
+ "RestoreV2 output index is not a valid integer: ",
+ restore_output.back());
+ return *parsed;
+ };
+
for (const auto& node : nodes) {
if (node.second->op() == "AssignVariableOp") {
// TODO: assets reading
@@ -405,13 +467,10 @@ void VariablesIndex::map_assignvariable(const std::shared_ptr<::tensorflow::Grap
FRONT_END_THROW("Unexpected topology near AssignVariableOp");
}
- int output_index = std::atoi(restore_output[restore_output.size() - 1].c_str());
+ const int output_index = resolve_output_index(restore_output);
// Expected path is: Const(tensor_names) -(0)-(1)-> RestoreV2
- const auto& variable_name =
- restorev2_nodes[0]->inputs[1]->node->attr().at("value").tensor().string_val(output_index);
-
- variables_map[varhandle_nodes[0]->node->name()] = variable_name;
+ variables_map[varhandle_nodes[0]->node->name()] = get_variable_name(restorev2_nodes[0], output_index);
}
} else if (node.second->op() == "Assign") {
std::vector<PtrNode::SharedPtrNode> restorev2_nodes;
@@ -433,13 +492,10 @@ void VariablesIndex::map_assignvariable(const std::shared_ptr<::tensorflow::Grap
// Expected path is: RestoreV2 -(output_index)-(1)-> Assign
PtrNode::parse_node_name(node.second->node->input(1), restore_output);
- int output_index = std::atoi(restore_output[restore_output.size() - 1].c_str());
+ const int output_index = resolve_output_index(restore_output);
// Expected path is: Const(tensor_names) -(0)-(1)-> RestoreV2
- const auto& variable_name =
- restorev2_nodes[0]->inputs[1]->node->attr().at("value").tensor().string_val(output_index);
-
- variables_map[variablev2_nodes[0]->node->name()] = variable_name;
+ variables_map[variablev2_nodes[0]->node->name()] = get_variable_name(restorev2_nodes[0], output_index);
}
} else if (node.second->op() == "LookupTableImportV2") {
std::vector<PtrNode::SharedPtrNode> hash_tablev2_nodes;
diff --git a/src/frontends/tensorflow/tests/convert_saved_model.cpp b/src/frontends/tensorflow/tests/convert_saved_model.cpp
index efa5b2891ef..af0e6e12a6a 100644
--- a/src/frontends/tensorflow/tests/convert_saved_model.cpp
+++ b/src/frontends/tensorflow/tests/convert_saved_model.cpp
@@ -217,6 +217,122 @@ TEST(FrontEndConvertModelTest, SavedModelMaliciousOverflowOffset) {
}
}
+// Crafted SavedModel where AssignVariableOp input references "save/RestoreV2:999"
+// but the Const(tensor_names) has only 1 string_val entry → OOB positive index.
+TEST(FrontEndConvertModelTest, SavedModelOobPositiveIndex) {
+ try {
+ convert_model("saved_model_oob_pos_index");
+ FAIL() << "Expected exception for OOB positive RestoreV2 output index";
+ } catch (const ov::Exception& e) {
+ EXPECT_TRUE(string(e.what()).find("out of range") != string::npos) << "Unexpected error message: " << e.what();
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected std::exception: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception";
+ }
+}
+
+// Crafted SavedModel where AssignVariableOp input references "save/RestoreV2:-1" → negative OOB.
+TEST(FrontEndConvertModelTest, SavedModelOobNegativeIndex) {
+ try {
+ convert_model("saved_model_oob_neg_index");
+ FAIL() << "Expected exception for negative RestoreV2 output index";
+ } catch (const ov::Exception& e) {
+ EXPECT_TRUE(string(e.what()).find("out of range") != string::npos) << "Unexpected error message: " << e.what();
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected std::exception: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception";
+ }
+}
+
+// Crafted SavedModel where AssignVariableOp input references "save/RestoreV2:0" but
+// Const(tensor_names) has zero string_val entries → upper-bound guard fires at index 0.
+// This exercises the security check on the implicit-0 code path.
+TEST(FrontEndConvertModelTest, SavedModelOobEmptyTensorNames) {
+ try {
+ convert_model("saved_model_oob_empty_names");
+ FAIL() << "Expected exception for OOB index into empty tensor_names";
+ } catch (const ov::Exception& e) {
+ EXPECT_TRUE(string(e.what()).find("out of range") != string::npos) << "Unexpected error message: " << e.what();
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected std::exception: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception";
+ }
+}
+
+// Crafted TF1-style SavedModel where Assign.input(1) = "save/RestoreV2:999" but
+// Const(tensor_names) has only 1 string_val entry → exercises the Assign code path
+// in map_assignvariable() (distinct from the AssignVariableOp path in other OOB tests).
+TEST(FrontEndConvertModelTest, SavedModelOobAssignPath) {
+ try {
+ convert_model("saved_model_oob_assign_path");
+ FAIL() << "Expected exception for OOB RestoreV2 output index in Assign path";
+ } catch (const ov::Exception& e) {
+ EXPECT_TRUE(string(e.what()).find("out of range") != string::npos) << "Unexpected error message: " << e.what();
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected std::exception: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception";
+ }
+}
+
+TEST(FrontEndConvertModelTest, SavedModelOobRestoreV2ShortInputs) {
+ try {
+ convert_model("saved_model_oob_restorev2_short_inputs");
+ FAIL() << "Expected exception when RestoreV2 tensor_names input is missing";
+ } catch (const ov::Exception& e) {
+ EXPECT_TRUE(string(e.what()).find("missing tensor_names input") != string::npos)
+ << "Unexpected error message: " << e.what();
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected std::exception: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception";
+ }
+}
+
+// Crafted SavedModel where RestoreV2.input(1) names "tensor_names" but no such
+// node exists in the GraphDef. shape_and_slices is a Const that occupies the
+// inputs[1] slot in the compacted PtrNode::inputs vector — a buggy
+// implementation that resolves tensor_names via inputs[1] would silently use
+// shape_and_slices. Resolving by matching node->name() across rv2_node->inputs
+// makes the missing input explicit.
+TEST(FrontEndConvertModelTest, SavedModelOobRestoreV2WrongInputAtPort1) {
+ try {
+ convert_model("saved_model_oob_wrong_input_at_port1");
+ FAIL() << "Expected exception when RestoreV2 tensor_names input node is absent";
+ } catch (const ov::Exception& e) {
+ EXPECT_TRUE(string(e.what()).find("not found among RestoreV2 inputs") != string::npos)
+ << "Unexpected error message: " << e.what();
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected std::exception: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception";
+ }
+}
+
+// Crafted SavedModel where RestoreV2.input(1) is a control dep (`^bogus`) and
+// `bogus` is a Const with non-empty `string_val`. parse_node_name strips the
+// `^`, and associate_node has already linked `bogus` into rv2_node->inputs, so
+// a buggy implementation that pulls the candidate from node->input(1) without
+// checking for the `^` prefix would silently bind the variable to bogus's
+// first string_val. The fix iterates node->input() and skips control inputs,
+// finds only one data input ('prefix'), and throws.
+TEST(FrontEndConvertModelTest, SavedModelOobRestoreV2ControlDepAtPort1) {
+ try {
+ convert_model("saved_model_oob_control_dep_at_port1");
+ FAIL() << "Expected exception when RestoreV2.input(1) is a control dep";
+ } catch (const ov::Exception& e) {
+ EXPECT_TRUE(string(e.what()).find("missing tensor_names input") != string::npos)
+ << "Unexpected error message: " << e.what();
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected std::exception: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception";
+ }
+}
+
// Same test with mmap disabled to verify the stream code path is also protected
TEST(FrontEndConvertModelTest, SavedModelMaliciousOverflowOffsetNoMmap) {
shared_ptr<Model> model = nullptr;
diff --git a/src/frontends/tensorflow/tests/parse_output_index_tests.cpp b/src/frontends/tensorflow/tests/parse_output_index_tests.cpp
new file mode 100644
index 00000000000..640deddd654
--- /dev/null
+++ b/src/frontends/tensorflow/tests/parse_output_index_tests.cpp
@@ -0,0 +1,43 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include <limits>
+#include <optional>
+#include <string>
+
+#include "../src/parse_output_index.hpp"
+
+using ov::frontend::tensorflow::parse_output_index;
+
+struct ParseOutputIndexCase {
+ std::string input;
+ std::optional<int> expected;
+};
+
+class ParseOutputIndexTest : public ::testing::TestWithParam<ParseOutputIndexCase> {};
+
+TEST_P(ParseOutputIndexTest, ParsesValidAndRejectsInvalid) {
+ const auto& c = GetParam();
+ EXPECT_EQ(parse_output_index(c.input), c.expected) << "input=\"" << c.input << "\"";
+}
+
+INSTANTIATE_TEST_SUITE_P(Valid,
+ ParseOutputIndexTest,
+ ::testing::Values(ParseOutputIndexCase{"0", 0},
+ ParseOutputIndexCase{"42", 42},
+ ParseOutputIndexCase{"-7", -7},
+ ParseOutputIndexCase{"2147483647", std::numeric_limits<int>::max()},
+ ParseOutputIndexCase{"-2147483648", std::numeric_limits<int>::min()}));
+
+INSTANTIATE_TEST_SUITE_P(Invalid,
+ ParseOutputIndexTest,
+ ::testing::Values(ParseOutputIndexCase{"", std::nullopt},
+ ParseOutputIndexCase{"abc", std::nullopt},
+ ParseOutputIndexCase{"1junk", std::nullopt},
+ ParseOutputIndexCase{" 42", std::nullopt},
+ ParseOutputIndexCase{"99999999999999999999", std::nullopt},
+ ParseOutputIndexCase{"2147483648", std::nullopt},
+ ParseOutputIndexCase{"-2147483649", std::nullopt}));
diff --git a/src/frontends/tensorflow/tests/test_models/gen_scripts/generate_saved_model_oob_index.py b/src/frontends/tensorflow/tests/test_models/gen_scripts/generate_saved_model_oob_index.py
new file mode 100644
index 00000000000..f1e4dc34175
--- /dev/null
+++ b/src/frontends/tensorflow/tests/test_models/gen_scripts/generate_saved_model_oob_index.py
@@ -0,0 +1,775 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+# What: Generates 7 malicious TF SavedModel directories that trigger security guards in
+# VariablesIndex::map_assignvariable() (variables_index.cpp).
+# No TF runtime needed — all protobuf and SSTable structures are built by hand.
+#
+# How: Each SavedModel has:
+# saved_model.pb — GraphDef with nodes described per variant below.
+# variables/variables.index — Minimal SSTable (bundle header only, num_shards=1).
+# variables/variables.data-* — 64 zero bytes (needed to pass open-file checks).
+#
+# Seven variants:
+# saved_model_oob_pos_index/ — TF2 (AssignVariableOp path):
+# Identity.input = "save/RestoreV2:999",
+# tensor_names has 1 entry → positive OOB index
+# saved_model_oob_neg_index/ — TF2 (AssignVariableOp path):
+# Identity.input = "save/RestoreV2:-1",
+# tensor_names has 1 entry → negative OOB index
+# saved_model_oob_empty_names/ — TF2 (AssignVariableOp path):
+# Identity.input = "save/RestoreV2:0",
+# tensor_names has 0 entries → OOB via implicit-0
+# path when string_val_size()==0
+# saved_model_oob_assign_path/ — TF1 (Assign path):
+# Assign.input(1) = "save/RestoreV2:999",
+# tensor_names has 1 entry → positive OOB index
+# saved_model_oob_restorev2_short_inputs/ — TF2 (AssignVariableOp path):
+# RestoreV2 declared with only 1 input in
+# GraphDef → node->input_size()==1 →
+# "missing tensor_names input" guard
+# saved_model_oob_wrong_input_at_port1/ — TF2 (AssignVariableOp path):
+# RestoreV2.input(1) names "tensor_names" but
+# no such node exists; shape_and_slices is a
+# Const present in the dict and would shift to
+# inputs[1] in a buggy implementation
+# saved_model_oob_control_dep_at_port1/ — TF2 (AssignVariableOp path):
+# RestoreV2.input(1) is a control dep (^bogus),
+# bogus is a Const with non-empty string_val
+# already in the node dict; data-port scan must
+# skip control inputs and refuse the silent
+# variable mis-binding
+#
+# Why: SSTable builder is copied verbatim from generate_saved_model_malicious_overflow.py.
+# Generator is run by the CMake build system.
+#
+# Usage: python3 generate_saved_model_oob_index.py <output_dir>
+# Output dirs are created under <output_dir>/.
+
+import os
+import struct
+import sys
+
+
+# ---------------------------------------------------------------------------
+# Protobuf varint / field encoding (copied from generate_saved_model_malicious_overflow.py)
+# ---------------------------------------------------------------------------
+
+def encode_varint(value):
+ result = bytearray()
+ while value > 0x7F:
+ result.append((value & 0x7F) | 0x80)
+ value >>= 7
+ result.append(value & 0x7F)
+ return bytes(result)
+
+
+def encode_signed_varint(value):
+ if value < 0:
+ value = (1 << 64) + value
+ return encode_varint(value)
+
+
+def encode_field(field_number, wire_type, data):
+ tag = (field_number << 3) | wire_type
+ return encode_varint(tag) + data
+
+
+def encode_varint_field(field_number, value):
+ return encode_field(field_number, 0, encode_varint(value))
+
+
+def encode_signed_varint_field(field_number, value):
+ return encode_field(field_number, 0, encode_signed_varint(value))
+
+
+def encode_bytes_field(field_number, data):
+ return encode_field(field_number, 2, encode_varint(len(data)) + data)
+
+
+def encode_string_field(field_number, s):
+ return encode_bytes_field(field_number, s.encode('utf-8'))
+
+
+def encode_fixed32_field(field_number, value):
+ return encode_field(field_number, 5, struct.pack('<I', value))
+
+
+# ---------------------------------------------------------------------------
+# SSTable builder (copied from generate_saved_model_malicious_overflow.py)
+# ---------------------------------------------------------------------------
+
+def build_sstable_block(entries):
+ block = bytearray()
+ restart_offsets = []
+ prev_key = b''
+ for i, (key, value) in enumerate(entries):
+ key_bytes = key.encode('utf-8') if isinstance(key, str) else key
+ shared = 0
+ for j in range(min(len(prev_key), len(key_bytes))):
+ if prev_key[j] == key_bytes[j]:
+ shared += 1
+ else:
+ break
+ non_shared = len(key_bytes) - shared
+ if i % 16 == 0:
+ restart_offsets.append(len(block))
+ shared = 0
+ non_shared = len(key_bytes)
+ block.extend(encode_varint(shared))
+ block.extend(encode_varint(non_shared))
+ block.extend(encode_varint(len(value)))
+ block.extend(key_bytes[shared:])
+ block.extend(value)
+ prev_key = key_bytes
+ if not restart_offsets:
+ restart_offsets = [0]
+ for off in restart_offsets:
+ block.extend(struct.pack('<I', off))
+ block.extend(struct.pack('<I', len(restart_offsets)))
+ return bytes(block)
+
+
+def build_sstable_footer(index_block_offset, index_block_size,
+ metaindex_block_offset=0, metaindex_block_size=0):
+ metaindex_handle = encode_varint(metaindex_block_offset) + encode_varint(metaindex_block_size)
+ index_handle = encode_varint(index_block_offset) + encode_varint(index_block_size)
+ footer = bytearray()
+ footer.extend(metaindex_handle)
+ footer.extend(index_handle)
+ while len(footer) < 40:
+ footer.append(0)
+ footer.extend(struct.pack('<Q', 0xdb4775248b80fb57))
+ return bytes(footer)
+
+
+def build_bundle_header_proto():
+ """BundleHeaderProto: num_shards=1, endianness=LITTLE, version={producer=1,min_consumer=0}"""
+ version = encode_varint_field(1, 1) + encode_varint_field(2, 0)
+ return encode_varint_field(1, 1) + encode_varint_field(2, 0) + encode_bytes_field(3, version)
+
+
+def build_minimal_variables_index():
+ """Minimal SSTable with only the bundle header key. num_shards=1."""
+ header_proto = build_bundle_header_proto()
+ data_entries = [("", header_proto)]
+ data_block = build_sstable_block(data_entries)
+ data_block_full = data_block + b'\x00' + struct.pack('<I', 0)
+
+ metaindex_block = build_sstable_block([])
+ metaindex_full = metaindex_block + b'\x00' + struct.pack('<I', 0)
+
+ last_key = ""
+ data_block_handle = encode_varint(0) + encode_varint(len(data_block))
+ index_block = build_sstable_block([(last_key, data_block_handle)])
+ index_full = index_block + b'\x00' + struct.pack('<I', 0)
+
+ metaindex_offset = len(data_block_full)
+ index_offset = metaindex_offset + len(metaindex_full)
+
+ footer = build_sstable_footer(
+ index_block_offset=index_offset,
+ index_block_size=len(index_block),
+ metaindex_block_offset=metaindex_offset,
+ metaindex_block_size=len(metaindex_block))
+
+ return data_block_full + metaindex_full + index_full + footer
+
+
+# ---------------------------------------------------------------------------
+# GraphDef / SavedModel builder
+# ---------------------------------------------------------------------------
+
+def build_node_def(name, op, inputs=None, attrs=None):
+ msg = encode_string_field(1, name) + encode_string_field(2, op)
+ if inputs:
+ for inp in inputs:
+ msg += encode_string_field(3, inp)
+ if attrs:
+ for key, val in attrs.items():
+ map_entry = encode_string_field(1, key) + encode_bytes_field(2, val)
+ msg += encode_bytes_field(5, map_entry)
+ return msg
+
+
+def build_saved_model_pb(identity_input, num_string_vals=1):
+ """
+ Build saved_model.pb with:
+ VarHandleOp("my_var")
+ Const("tensor_names") — num_string_vals string_val entries
+ RestoreV2("save/RestoreV2")
+ Identity("save/identity") — input[0] = identity_input
+ AssignVariableOp("save/Assign")
+
+ identity_input controls the RestoreV2 output index extracted by parse_node_name().
+ num_string_vals controls how many entries tensor_names has (0 = empty → OOB at index 0).
+ """
+ DT_FLOAT = 1
+ DT_STRING = 7
+
+ # VarHandleOp attrs
+ dtype_attr = encode_varint_field(6, DT_FLOAT)
+ dim2 = encode_signed_varint_field(1, 2)
+ shape_proto = encode_bytes_field(2, dim2) + encode_bytes_field(2, dim2)
+ shape_attr = encode_bytes_field(7, shape_proto)
+
+ varhandle_node = build_node_def(
+ "my_var", "VarHandleOp",
+ attrs={"dtype": dtype_attr, "shape": shape_attr,
+ "container": encode_string_field(2, ""),
+ "shared_name": encode_string_field(2, "my_var")})
+
+ # Const("tensor_names") — TensorProto with num_string_vals string_val entries
+ actual_size = max(num_string_vals, 0)
+ tensor_shape = encode_bytes_field(2, encode_signed_varint_field(1, actual_size))
+ tensor_proto = encode_varint_field(1, DT_STRING) + encode_bytes_field(4, tensor_shape)
+ for _ in range(actual_size):
+ tensor_proto += encode_bytes_field(8, b"Variable")
+ tensor_attr = encode_bytes_field(8, tensor_proto)
+ dtype_str_attr = encode_varint_field(6, DT_STRING)
+
+ const_node = build_node_def(
+ "tensor_names", "Const",
+ attrs={"value": tensor_attr, "dtype": dtype_str_attr})
+
+ # Const("shape_and_slices")
+ shape_tensor_shape = encode_bytes_field(2, encode_signed_varint_field(1, actual_size))
+ empty_shape_tensor = encode_varint_field(1, DT_STRING) + encode_bytes_field(4, shape_tensor_shape)
+ for _ in range(actual_size):
+ empty_shape_tensor += encode_bytes_field(8, b"")
+ empty_shape_attr = encode_bytes_field(8, empty_shape_tensor)
+
+ shape_slices_node = build_node_def(
+ "shape_and_slices", "Const",
+ attrs={"value": empty_shape_attr, "dtype": dtype_str_attr})
+
+ # Const("prefix")
+ scalar_shape = encode_bytes_field(4, b"")
+ prefix_tensor = (encode_varint_field(1, DT_STRING) +
+ scalar_shape +
+ encode_bytes_field(8, b"checkpoint"))
+ prefix_attr = encode_bytes_field(8, prefix_tensor)
+
+ prefix_node = build_node_def(
+ "prefix", "Const",
+ attrs={"value": prefix_attr, "dtype": dtype_str_attr})
+
+ # RestoreV2
+ list_attr = encode_bytes_field(5, encode_varint_field(6, DT_FLOAT))
+ restorev2_node = build_node_def(
+ "save/RestoreV2", "RestoreV2",
+ inputs=["prefix", "tensor_names", "shape_and_slices"],
+ attrs={"dtypes": list_attr})
+
+ # Identity
+ t_attr = encode_varint_field(6, DT_FLOAT)
+ identity_node = build_node_def(
+ "save/identity", "Identity",
+ inputs=[identity_input],
+ attrs={"T": t_attr})
+
+ # AssignVariableOp
+ assign_node = build_node_def(
+ "save/Assign", "AssignVariableOp",
+ inputs=["my_var", "save/identity"],
+ attrs={"dtype": dtype_attr})
+
+ # ReadVariableOp + Identity for model output
+ read_node = build_node_def(
+ "read_var", "ReadVariableOp",
+ inputs=["my_var"],
+ attrs={"dtype": dtype_attr})
+
+ output_identity = build_node_def(
+ "Identity", "Identity",
+ inputs=["read_var"],
+ attrs={"T": t_attr})
+
+ graph_def = (encode_bytes_field(1, varhandle_node) +
+ encode_bytes_field(1, const_node) +
+ encode_bytes_field(1, shape_slices_node) +
+ encode_bytes_field(1, prefix_node) +
+ encode_bytes_field(1, restorev2_node) +
+ encode_bytes_field(1, identity_node) +
+ encode_bytes_field(1, assign_node) +
+ encode_bytes_field(1, read_node) +
+ encode_bytes_field(1, output_identity))
+
+ meta_info_def = encode_string_field(1, "serve")
+ tensor_info = encode_string_field(1, "Identity:0") + encode_varint_field(2, DT_FLOAT)
+ sig_output_entry = encode_string_field(1, "output_0") + encode_bytes_field(2, tensor_info)
+ signature_def = encode_bytes_field(2, sig_output_entry)
+ sig_map_entry = encode_string_field(1, "serving_default") + encode_bytes_field(2, signature_def)
+ meta_graph_def = (encode_bytes_field(1, meta_info_def) +
+ encode_bytes_field(2, graph_def) +
+ encode_bytes_field(5, sig_map_entry))
+
+ return encode_signed_varint_field(1, 1) + encode_bytes_field(2, meta_graph_def)
+
+
+def build_saved_model_pb_tf1_assign(index_str, num_string_vals=1):
+ """
+ Build saved_model.pb with TF1-style topology:
+ VariableV2("my_variable")
+ Const("tensor_names") — num_string_vals string_val entries
+ RestoreV2("save/RestoreV2")
+ Assign("save/Assign") — input(1) = index_str (e.g. "save/RestoreV2:999")
+ Identity("Identity") — output node
+
+ This exercises the Assign code path in VariablesIndex::map_assignvariable()
+ rather than the AssignVariableOp path exercised by build_saved_model_pb().
+ """
+ DT_FLOAT = 1
+ DT_STRING = 7
+
+ # VariableV2 attrs
+ dtype_attr = encode_varint_field(6, DT_FLOAT)
+ dim_attr = encode_bytes_field(2, encode_signed_varint_field(1, 4))
+ shape_attr = encode_bytes_field(7, dim_attr)
+
+ variablev2_node = build_node_def(
+ "my_variable", "VariableV2",
+ attrs={"dtype": dtype_attr, "shape": shape_attr,
+ "container": encode_string_field(2, ""),
+ "shared_name": encode_string_field(2, "")})
+
+ # Const("tensor_names")
+ actual_size = max(num_string_vals, 0)
+ tensor_shape = encode_bytes_field(2, encode_signed_varint_field(1, actual_size))
+ tensor_proto = encode_varint_field(1, DT_STRING) + encode_bytes_field(4, tensor_shape)
+ for _ in range(actual_size):
+ tensor_proto += encode_bytes_field(8, b"Variable")
+ tensor_attr = encode_bytes_field(8, tensor_proto)
+ dtype_str_attr = encode_varint_field(6, DT_STRING)
+
+ const_node = build_node_def(
+ "tensor_names", "Const",
+ attrs={"value": tensor_attr, "dtype": dtype_str_attr})
+
+ # Const("shape_and_slices")
+ shape_tensor_shape = encode_bytes_field(2, encode_signed_varint_field(1, actual_size))
+ empty_shape_tensor = encode_varint_field(1, DT_STRING) + encode_bytes_field(4, shape_tensor_shape)
+ for _ in range(actual_size):
+ empty_shape_tensor += encode_bytes_field(8, b"")
+ empty_shape_attr = encode_bytes_field(8, empty_shape_tensor)
+
+ shape_slices_node = build_node_def(
+ "shape_and_slices", "Const",
+ attrs={"value": empty_shape_attr, "dtype": dtype_str_attr})
+
+ # Const("prefix")
+ scalar_shape = encode_bytes_field(4, b"")
+ prefix_tensor = (encode_varint_field(1, DT_STRING) +
+ scalar_shape +
+ encode_bytes_field(8, b"checkpoint"))
+ prefix_attr = encode_bytes_field(8, prefix_tensor)
+
+ prefix_node = build_node_def(
+ "prefix", "Const",
+ attrs={"value": prefix_attr, "dtype": dtype_str_attr})
+
+ # RestoreV2
+ list_attr = encode_bytes_field(5, encode_varint_field(6, DT_FLOAT))
+ restorev2_node = build_node_def(
+ "save/RestoreV2", "RestoreV2",
+ inputs=["prefix", "tensor_names", "shape_and_slices"],
+ attrs={"dtypes": list_attr})
+
+ # Assign: input(0) = variable ref, input(1) = RestoreV2 output with OOB index
+ t_attr = encode_varint_field(6, DT_FLOAT)
+ assign_node = build_node_def(
+ "save/Assign", "Assign",
+ inputs=["my_variable", index_str],
+ attrs={"T": t_attr})
+
+ # Identity for signature output
+ output_identity = build_node_def(
+ "Identity", "Identity",
+ inputs=["my_variable"],
+ attrs={"T": t_attr})
+
+ graph_def = (encode_bytes_field(1, variablev2_node) +
+ encode_bytes_field(1, const_node) +
+ encode_bytes_field(1, shape_slices_node) +
+ encode_bytes_field(1, prefix_node) +
+ encode_bytes_field(1, restorev2_node) +
+ encode_bytes_field(1, assign_node) +
+ encode_bytes_field(1, output_identity))
+
+ meta_info_def = encode_string_field(1, "serve")
+ tensor_info = encode_string_field(1, "Identity:0") + encode_varint_field(2, DT_FLOAT)
+ sig_output_entry = encode_string_field(1, "output_0") + encode_bytes_field(2, tensor_info)
+ signature_def = encode_bytes_field(2, sig_output_entry)
+ sig_map_entry = encode_string_field(1, "serving_default") + encode_bytes_field(2, signature_def)
+ meta_graph_def = (encode_bytes_field(1, meta_info_def) +
+ encode_bytes_field(2, graph_def) +
+ encode_bytes_field(5, sig_map_entry))
+
+ return encode_signed_varint_field(1, 1) + encode_bytes_field(2, meta_graph_def)
+
+
+def write_savedmodel(output_dir, identity_input, num_string_vals=1):
+ os.makedirs(os.path.join(output_dir, "variables"), exist_ok=True)
+ with open(os.path.join(output_dir, "saved_model.pb"), 'wb') as f:
+ f.write(build_saved_model_pb(identity_input, num_string_vals))
+ with open(os.path.join(output_dir, "variables", "variables.index"), 'wb') as f:
+ f.write(build_minimal_variables_index())
+ with open(os.path.join(output_dir, "variables", "variables.data-00000-of-00001"), 'wb') as f:
+ f.write(b'\x00' * 64)
+
+
+def write_savedmodel_tf1_assign(output_dir, index_str, num_string_vals=1):
+ os.makedirs(os.path.join(output_dir, "variables"), exist_ok=True)
+ with open(os.path.join(output_dir, "saved_model.pb"), 'wb') as f:
+ f.write(build_saved_model_pb_tf1_assign(index_str, num_string_vals))
+ with open(os.path.join(output_dir, "variables", "variables.index"), 'wb') as f:
+ f.write(build_minimal_variables_index())
+ with open(os.path.join(output_dir, "variables", "variables.data-00000-of-00001"), 'wb') as f:
+ f.write(b'\x00' * 64)
+
+
+def build_saved_model_pb_restorev2_short_inputs():
+ """
+ Build saved_model.pb where RestoreV2 declares only 1 input ('prefix') in the
+ GraphDef itself, so node->input_size()==1. Triggers the
+ 'RestoreV2 node is missing tensor_names input' guard in get_variable_name().
+ """
+ DT_FLOAT = 1
+ DT_STRING = 7
+
+ dtype_attr = encode_varint_field(6, DT_FLOAT)
+ dim2 = encode_signed_varint_field(1, 2)
+ shape_proto = encode_bytes_field(2, dim2) + encode_bytes_field(2, dim2)
+ shape_attr = encode_bytes_field(7, shape_proto)
+
+ varhandle_node = build_node_def(
+ "my_var", "VarHandleOp",
+ attrs={"dtype": dtype_attr, "shape": shape_attr,
+ "container": encode_string_field(2, ""),
+ "shared_name": encode_string_field(2, "my_var")})
+
+ scalar_shape = encode_bytes_field(4, b"")
+ prefix_tensor = (encode_varint_field(1, DT_STRING) +
+ scalar_shape +
+ encode_bytes_field(8, b"checkpoint"))
+ dtype_str_attr = encode_varint_field(6, DT_STRING)
+ prefix_attr = encode_bytes_field(8, prefix_tensor)
+ prefix_node = build_node_def(
+ "prefix", "Const",
+ attrs={"value": prefix_attr, "dtype": dtype_str_attr})
+
+ # RestoreV2 with only 1 declared input — no tensor_names, no shape_and_slices.
+ # node->input_size() == 1 in the GraphDef itself.
+ list_attr = encode_bytes_field(5, encode_varint_field(6, DT_FLOAT))
+ restorev2_node = build_node_def(
+ "save/RestoreV2", "RestoreV2",
+ inputs=["prefix"],
+ attrs={"dtypes": list_attr})
+
+ t_attr = encode_varint_field(6, DT_FLOAT)
+ identity_node = build_node_def(
+ "save/identity", "Identity",
+ inputs=["save/RestoreV2:0"],
+ attrs={"T": t_attr})
+ assign_node = build_node_def(
+ "save/Assign", "AssignVariableOp",
+ inputs=["my_var", "save/identity"],
+ attrs={"dtype": dtype_attr})
+ read_node = build_node_def(
+ "read_var", "ReadVariableOp",
+ inputs=["my_var"],
+ attrs={"dtype": dtype_attr})
+ output_identity = build_node_def(
+ "Identity", "Identity",
+ inputs=["read_var"],
+ attrs={"T": t_attr})
+
+ graph_def = (encode_bytes_field(1, varhandle_node) +
+ encode_bytes_field(1, prefix_node) +
+ encode_bytes_field(1, restorev2_node) +
+ encode_bytes_field(1, identity_node) +
+ encode_bytes_field(1, assign_node) +
+ encode_bytes_field(1, read_node) +
+ encode_bytes_field(1, output_identity))
+
+ meta_info_def = encode_string_field(1, "serve")
+ tensor_info = encode_string_field(1, "Identity:0") + encode_varint_field(2, DT_FLOAT)
+ sig_output_entry = encode_string_field(1, "output_0") + encode_bytes_field(2, tensor_info)
+ signature_def = encode_bytes_field(2, sig_output_entry)
+ sig_map_entry = encode_string_field(1, "serving_default") + encode_bytes_field(2, signature_def)
+ meta_graph_def = (encode_bytes_field(1, meta_info_def) +
+ encode_bytes_field(2, graph_def) +
+ encode_bytes_field(5, sig_map_entry))
+
+ return encode_signed_varint_field(1, 1) + encode_bytes_field(2, meta_graph_def)
+
+
+def write_savedmodel_restorev2_short_inputs(output_dir):
+ os.makedirs(os.path.join(output_dir, "variables"), exist_ok=True)
+ with open(os.path.join(output_dir, "saved_model.pb"), 'wb') as f:
+ f.write(build_saved_model_pb_restorev2_short_inputs())
+ with open(os.path.join(output_dir, "variables", "variables.index"), 'wb') as f:
+ f.write(build_minimal_variables_index())
+ with open(os.path.join(output_dir, "variables", "variables.data-00000-of-00001"), 'wb') as f:
+ f.write(b'\x00' * 64)
+
+
+def build_saved_model_pb_wrong_input_at_port1():
+ """
+ Build saved_model.pb where RestoreV2.input(1) refers to 'tensor_names' but no
+ node named 'tensor_names' exists in the GraphDef. shape_and_slices IS present
+ and is a Const with a 'value' attribute, so a buggy implementation that
+ consults the compacted PtrNode::inputs vector would pick up shape_and_slices
+ at index 1 and silently use the wrong Const. The correct implementation
+ resolves tensor_names by name through the nodes dictionary and throws.
+ """
+ DT_FLOAT = 1
+ DT_STRING = 7
+
+ dtype_attr = encode_varint_field(6, DT_FLOAT)
+ dim2 = encode_signed_varint_field(1, 2)
+ shape_proto = encode_bytes_field(2, dim2) + encode_bytes_field(2, dim2)
+ shape_attr = encode_bytes_field(7, shape_proto)
+
+ varhandle_node = build_node_def(
+ "my_var", "VarHandleOp",
+ attrs={"dtype": dtype_attr, "shape": shape_attr,
+ "container": encode_string_field(2, ""),
+ "shared_name": encode_string_field(2, "my_var")})
+
+ dtype_str_attr = encode_varint_field(6, DT_STRING)
+ scalar_shape = encode_bytes_field(4, b"")
+ prefix_tensor = (encode_varint_field(1, DT_STRING) +
+ scalar_shape +
+ encode_bytes_field(8, b"checkpoint"))
+ prefix_attr = encode_bytes_field(8, prefix_tensor)
+ prefix_node = build_node_def(
+ "prefix", "Const",
+ attrs={"value": prefix_attr, "dtype": dtype_str_attr})
+
+ # shape_and_slices declared with a non-empty string_val so a buggy
+ # implementation using inputs[1] would silently succeed.
+ shape_tensor_shape = encode_bytes_field(2, encode_signed_varint_field(1, 1))
+ shape_tensor = (encode_varint_field(1, DT_STRING) +
+ encode_bytes_field(4, shape_tensor_shape) +
+ encode_bytes_field(8, b"fake_var"))
+ shape_attr_const = encode_bytes_field(8, shape_tensor)
+ shape_slices_node = build_node_def(
+ "shape_and_slices", "Const",
+ attrs={"value": shape_attr_const, "dtype": dtype_str_attr})
+
+ # RestoreV2 references "tensor_names" at port 1, but the node is missing
+ # from the GraphDef entirely. prefix and shape_and_slices ARE in the dict
+ # at the time associate_node runs, so RestoreV2->inputs ends up as
+ # [prefix, shape_and_slices] (size==2) — buggy implementation indexes [1].
+ list_attr = encode_bytes_field(5, encode_varint_field(6, DT_FLOAT))
+ restorev2_node = build_node_def(
+ "save/RestoreV2", "RestoreV2",
+ inputs=["prefix", "tensor_names", "shape_and_slices"],
+ attrs={"dtypes": list_attr})
+
+ t_attr = encode_varint_field(6, DT_FLOAT)
+ identity_node = build_node_def(
+ "save/identity", "Identity",
+ inputs=["save/RestoreV2:0"],
+ attrs={"T": t_attr})
+ assign_node = build_node_def(
+ "save/Assign", "AssignVariableOp",
+ inputs=["my_var", "save/identity"],
+ attrs={"dtype": dtype_attr})
+ read_node = build_node_def(
+ "read_var", "ReadVariableOp",
+ inputs=["my_var"],
+ attrs={"dtype": dtype_attr})
+ output_identity = build_node_def(
+ "Identity", "Identity",
+ inputs=["read_var"],
+ attrs={"T": t_attr})
+
+ # prefix and shape_and_slices declared BEFORE RestoreV2 so they get linked
+ # into RestoreV2->inputs by associate_node (which only links nodes already
+ # in the dictionary).
+ graph_def = (encode_bytes_field(1, varhandle_node) +
+ encode_bytes_field(1, prefix_node) +
+ encode_bytes_field(1, shape_slices_node) +
+ encode_bytes_field(1, restorev2_node) +
+ encode_bytes_field(1, identity_node) +
+ encode_bytes_field(1, assign_node) +
+ encode_bytes_field(1, read_node) +
+ encode_bytes_field(1, output_identity))
+
+ meta_info_def = encode_string_field(1, "serve")
+ tensor_info = encode_string_field(1, "Identity:0") + encode_varint_field(2, DT_FLOAT)
+ sig_output_entry = encode_string_field(1, "output_0") + encode_bytes_field(2, tensor_info)
+ signature_def = encode_bytes_field(2, sig_output_entry)
+ sig_map_entry = encode_string_field(1, "serving_default") + encode_bytes_field(2, signature_def)
+ meta_graph_def = (encode_bytes_field(1, meta_info_def) +
+ encode_bytes_field(2, graph_def) +
+ encode_bytes_field(5, sig_map_entry))
+
+ return encode_signed_varint_field(1, 1) + encode_bytes_field(2, meta_graph_def)
+
+
+def write_savedmodel_wrong_input_at_port1(output_dir):
+ os.makedirs(os.path.join(output_dir, "variables"), exist_ok=True)
+ with open(os.path.join(output_dir, "saved_model.pb"), 'wb') as f:
+ f.write(build_saved_model_pb_wrong_input_at_port1())
+ with open(os.path.join(output_dir, "variables", "variables.index"), 'wb') as f:
+ f.write(build_minimal_variables_index())
+ with open(os.path.join(output_dir, "variables", "variables.data-00000-of-00001"), 'wb') as f:
+ f.write(b'\x00' * 64)
+
+
+def build_saved_model_pb_control_dep_at_port1():
+ """
+ Build saved_model.pb where RestoreV2 is declared with inputs
+ ["prefix", "^bogus"]: only one data input plus a control dependency on
+ 'bogus'. 'bogus' is a Const with a non-empty string_val and is declared
+ before RestoreV2 so associate_node() links it into rv2_node->inputs.
+
+ A buggy implementation that resolves tensor_names through node->input(1)
+ blindly would parse the control-dep token (parse_node_name strips '^'),
+ find 'bogus' among the linked inputs, observe it is a Const with 'value',
+ and silently bind the variable to bogus's first string_val — a security
+ regression (silent variable mis-mapping). The correct implementation
+ iterates node->input() and skips control inputs (those starting with '^'),
+ finds only one data input ('prefix'), and throws "missing tensor_names
+ input".
+ """
+ DT_FLOAT = 1
+ DT_STRING = 7
+
+ dtype_attr = encode_varint_field(6, DT_FLOAT)
+ dim2 = encode_signed_varint_field(1, 2)
+ shape_proto = encode_bytes_field(2, dim2) + encode_bytes_field(2, dim2)
+ shape_attr = encode_bytes_field(7, shape_proto)
+
+ varhandle_node = build_node_def(
+ "my_var", "VarHandleOp",
+ attrs={"dtype": dtype_attr, "shape": shape_attr,
+ "container": encode_string_field(2, ""),
+ "shared_name": encode_string_field(2, "my_var")})
+
+ dtype_str_attr = encode_varint_field(6, DT_STRING)
+ scalar_shape = encode_bytes_field(4, b"")
+ prefix_tensor = (encode_varint_field(1, DT_STRING) +
+ scalar_shape +
+ encode_bytes_field(8, b"checkpoint"))
+ prefix_attr = encode_bytes_field(8, prefix_tensor)
+ prefix_node = build_node_def(
+ "prefix", "Const",
+ attrs={"value": prefix_attr, "dtype": dtype_str_attr})
+
+ # 'bogus' is a Const with a non-empty string_val; it would satisfy every
+ # current guard (Const + 'value' attr + idx 0 in range) if a buggy
+ # implementation accepted it as tensor_names.
+ bogus_tensor_shape = encode_bytes_field(2, encode_signed_varint_field(1, 1))
+ bogus_tensor = (encode_varint_field(1, DT_STRING) +
+ encode_bytes_field(4, bogus_tensor_shape) +
+ encode_bytes_field(8, b"fake_var"))
+ bogus_attr = encode_bytes_field(8, bogus_tensor)
+ bogus_node = build_node_def(
+ "bogus", "Const",
+ attrs={"value": bogus_attr, "dtype": dtype_str_attr})
+
+ list_attr = encode_bytes_field(5, encode_varint_field(6, DT_FLOAT))
+ restorev2_node = build_node_def(
+ "save/RestoreV2", "RestoreV2",
+ inputs=["prefix", "^bogus"],
+ attrs={"dtypes": list_attr})
+
+ t_attr = encode_varint_field(6, DT_FLOAT)
+ identity_node = build_node_def(
+ "save/identity", "Identity",
+ inputs=["save/RestoreV2:0"],
+ attrs={"T": t_attr})
+ assign_node = build_node_def(
+ "save/Assign", "AssignVariableOp",
+ inputs=["my_var", "save/identity"],
+ attrs={"dtype": dtype_attr})
+ read_node = build_node_def(
+ "read_var", "ReadVariableOp",
+ inputs=["my_var"],
+ attrs={"dtype": dtype_attr})
+ output_identity = build_node_def(
+ "Identity", "Identity",
+ inputs=["read_var"],
+ attrs={"T": t_attr})
+
+ # 'prefix' and 'bogus' declared BEFORE RestoreV2 so associate_node() links
+ # them into rv2_node->inputs (associate_node strips '^' before lookup, so
+ # the control dep is reachable via rv2_node->inputs in a buggy lookup).
+ graph_def = (encode_bytes_field(1, varhandle_node) +
+ encode_bytes_field(1, prefix_node) +
+ encode_bytes_field(1, bogus_node) +
+ encode_bytes_field(1, restorev2_node) +
+ encode_bytes_field(1, identity_node) +
+ encode_bytes_field(1, assign_node) +
+ encode_bytes_field(1, read_node) +
+ encode_bytes_field(1, output_identity))
+
+ meta_info_def = encode_string_field(1, "serve")
+ tensor_info = encode_string_field(1, "Identity:0") + encode_varint_field(2, DT_FLOAT)
+ sig_output_entry = encode_string_field(1, "output_0") + encode_bytes_field(2, tensor_info)
+ signature_def = encode_bytes_field(2, sig_output_entry)
+ sig_map_entry = encode_string_field(1, "serving_default") + encode_bytes_field(2, signature_def)
+ meta_graph_def = (encode_bytes_field(1, meta_info_def) +
+ encode_bytes_field(2, graph_def) +
+ encode_bytes_field(5, sig_map_entry))
+
+ return encode_signed_varint_field(1, 1) + encode_bytes_field(2, meta_graph_def)
+
+
+def write_savedmodel_control_dep_at_port1(output_dir):
+ os.makedirs(os.path.join(output_dir, "variables"), exist_ok=True)
+ with open(os.path.join(output_dir, "saved_model.pb"), 'wb') as f:
+ f.write(build_saved_model_pb_control_dep_at_port1())
+ with open(os.path.join(output_dir, "variables", "variables.index"), 'wb') as f:
+ f.write(build_minimal_variables_index())
+ with open(os.path.join(output_dir, "variables", "variables.data-00000-of-00001"), 'wb') as f:
+ f.write(b'\x00' * 64)
+
+
+def main():
+ if len(sys.argv) < 2:
+ print(f"Usage: {sys.argv[0]} <output_dir>")
+ sys.exit(1)
+
+ base = sys.argv[1]
+
+ # Positive OOB: index 999 into a tensor with 1 string_val
+ write_savedmodel(os.path.join(base, "saved_model_oob_pos_index"), "save/RestoreV2:999")
+
+ # Negative OOB: index -1 into a tensor with 1 string_val
+ write_savedmodel(os.path.join(base, "saved_model_oob_neg_index"), "save/RestoreV2:-1")
+
+ # Empty tensor_names: index 0 into a tensor with 0 string_val entries;
+ # exercises the upper-bound guard on the implicit-0 code path
+ write_savedmodel(os.path.join(base, "saved_model_oob_empty_names"), "save/RestoreV2:0",
+ num_string_vals=0)
+
+ # TF1-style Assign path: OOB positive index in the Assign branch of map_assignvariable()
+ write_savedmodel_tf1_assign(os.path.join(base, "saved_model_oob_assign_path"),
+ "save/RestoreV2:999")
+
+ # RestoreV2 declared with only 1 input ('prefix') in the GraphDef itself —
+ # node->input_size()==1, exercises the "missing tensor_names input" guard.
+ write_savedmodel_restorev2_short_inputs(
+ os.path.join(base, "saved_model_oob_restorev2_short_inputs"))
+
+ # RestoreV2 references tensor_names by name at port 1 but no node named
+ # tensor_names exists; shape_and_slices is present and would shift into
+ # the compacted inputs[1] slot in a buggy implementation.
+ write_savedmodel_wrong_input_at_port1(
+ os.path.join(base, "saved_model_oob_wrong_input_at_port1"))
+
+ # RestoreV2 declared with inputs ["prefix", "^bogus"]: control dep at
+ # node->input(1). A buggy implementation would parse the control token,
+ # match 'bogus' (a Const with non-empty string_val) and silently bind the
+ # variable to the wrong name. Data-port iteration must skip control deps.
+ write_savedmodel_control_dep_at_port1(
+ os.path.join(base, "saved_model_oob_control_dep_at_port1"))
+
+
+if __name__ == '__main__':
+ main()