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

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://github.com/facebook/react-native/wiki/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
This commit is contained in:
Igor Klemenski
2021-03-09 08:47:31 -08:00
committed by Facebook GitHub Bot
parent d4d2e90ec6
commit e69f1c9f50
2 changed files with 10 additions and 3 deletions
@@ -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<uint16_t>::max() / 2) {
LOG(ERROR)
<< "Error: trying to assign a value beyond the capacity of uint16_t"
<< static_cast<uint32_t>(_dataSize) * 2;
throw "Error: trying to assign a value beyond the capacity of uint16_t" +
std::to_string(static_cast<uint32_t>(_dataSize) * 2);
}
_dataSize *= 2;
uint8_t *_newdata = new Byte[_dataSize];
uint8_t *_oldData = _data;
@@ -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();