From e69f1c9f50c64bfcaeb684d763f02b9ccadec960 Mon Sep 17 00:00:00 2001 From: Igor Klemenski Date: Tue, 9 Mar 2021 08:44:26 -0800 Subject: [PATCH] Fix unsafe cast and detect resize overflow. (#31106) Summary: Removing unsafe cast from `int` to `uint16_t`. Also, adding code to detect multiplication overflow during buffer resize. ## Changelog [General] [Fix] - Fix unsafe cast and detect overflow in MapBuffer. Pull Request resolved: https://github.com/facebook/react-native/pull/31106 Test Plan: Code compiles in Visual Studio 2019 without the unsafe cast warning (or error depending on the configuration). Reviewed By: mdvacca Differential Revision: D26865138 Pulled By: rozele fbshipit-source-id: 4692a38b05fc873e31fbbe94d70803244e82de5d --- ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp | 9 ++++++++- ReactCommon/react/renderer/mapbuffer/MapBuffer.h | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp b/ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp index e95bdd7509d..1de97351553 100644 --- a/ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp +++ b/ReactCommon/react/renderer/mapbuffer/MapBuffer.cpp @@ -12,7 +12,7 @@ using namespace facebook::react; namespace facebook { namespace react { -MapBuffer::MapBuffer(int initialSize) { +MapBuffer::MapBuffer(uint16_t initialSize) { _dataSize = initialSize; _data = new Byte[_dataSize]; // TODO: Should we clean up memory here? @@ -20,6 +20,13 @@ MapBuffer::MapBuffer(int initialSize) { void MapBuffer::makeSpace() { int oldDataSize = _dataSize; + if (_dataSize >= std::numeric_limits::max() / 2) { + LOG(ERROR) + << "Error: trying to assign a value beyond the capacity of uint16_t" + << static_cast(_dataSize) * 2; + throw "Error: trying to assign a value beyond the capacity of uint16_t" + + std::to_string(static_cast(_dataSize) * 2); + } _dataSize *= 2; uint8_t *_newdata = new Byte[_dataSize]; uint8_t *_oldData = _data; diff --git a/ReactCommon/react/renderer/mapbuffer/MapBuffer.h b/ReactCommon/react/renderer/mapbuffer/MapBuffer.h index a56074737d6..e6c8d4a2673 100644 --- a/ReactCommon/react/renderer/mapbuffer/MapBuffer.h +++ b/ReactCommon/react/renderer/mapbuffer/MapBuffer.h @@ -13,7 +13,7 @@ namespace facebook { namespace react { // 506 = 5 entries = 50*10 + 6 sizeof(header) -const int INITIAL_SIZE = 506; +constexpr uint16_t INITIAL_SIZE = 506; /** * MapBuffer is an optimized map format for transferring data like props between @@ -46,7 +46,7 @@ class MapBuffer { public: MapBuffer() : MapBuffer(INITIAL_SIZE) {} - MapBuffer(int initialSize); + MapBuffer(uint16_t initialSize); ~MapBuffer();