Skip to content

fix: add crc check on TFRecord data #107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 1.8
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/pipemode_op/RecordReader/TFRecordReader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// language governing permissions and limitations under the License.
#include <iostream>
#include <string>
#include <cstdio>
#include "tensorflow/core/lib/hash/crc32c.h"
#include "TFRecordReader.hpp"

Expand All @@ -20,7 +21,16 @@ using sagemaker::tensorflow::TFRecordReader;
inline void ValidateLength(const std::uint64_t& length, const std::uint32_t masked_crc32_of_length) {
if (tensorflow::crc32c::Unmask(masked_crc32_of_length)
!= tensorflow::crc32c::Value(reinterpret_cast<const char*>(&(length)), sizeof(length))) {
throw std::runtime_error("Invalid header crc");
throw std::runtime_error("CRC check on header failed.");
}
}

inline void ValidateData(const std::string* storage, const std::uint64_t& length,
const std::uint32_t masked_crc32_of_data) {
auto unmasked_crc = tensorflow::crc32c::Unmask(masked_crc32_of_data);
auto data_crc = tensorflow::crc32c::Value(storage->data(), length);
if (unmasked_crc != data_crc) {
throw std::runtime_error("CRC check on data failed.");
}
}

Expand All @@ -36,5 +46,6 @@ bool TFRecordReader::ReadRecord(std::string* storage) {
Read(&(storage->at(0)), length);
std::uint32_t footer;
Read(&footer, sizeof(footer));
ValidateData(storage, length, footer);
return true;
}
5 changes: 4 additions & 1 deletion src/pipemode_op/test/testRecordReader/TestTFRecordReader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,15 @@ std::string ToTFRecord(const std::string& data) {
result.push_back(header[i]);
}
result += data;
auto data_crc = tensorflow::crc32c::Mask(tensorflow::crc32c::Value(data.c_str(), length));
masked_crc_ptr = reinterpret_cast<char*>(&data_crc);
for (int i = 0; i < 4; i++) {
result.push_back('f');
result.push_back(masked_crc_ptr[i]);
}
return result;
}


TEST_F(TFRecordReaderTest, ReadRecord) {
std::string encoded = ToTFRecord("hello");
std::unique_ptr<TFRecordReader> reader = MakeTFRecordReader(
Expand Down