Skip to content

Commit

Permalink
Protect access to RCTTurboModuleCache
Browse files Browse the repository at this point in the history
Summary: The `_rctTurboModuleCache` `std::unordered_map` can be accessed by multiple threads at the same time via the `provideRCTTurboModule` method. Since `provideRCTTurboModule` both reads and writes to `_rctTurboModuleCache`, this is really bad because we could end up reading from `_rctTurboModuleCache` while it's in an invalid state. Therefore, in this diff, I'm making it so that only one thread at a time can enter `provideRCTTurboModule`.

Reviewed By: fkgozali

Differential Revision: D15609987

fbshipit-source-id: e24e1f5cc2351d8cbb820b7a97074aacd06eec9d
  • Loading branch information
RSNara authored and facebook-github-bot committed Jun 3, 2019
1 parent d3cf756 commit a44ab29
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions ReactCommon/turbomodule/core/platform/ios/RCTTurboModuleManager.mm
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#import "RCTTurboModuleManager.h"

#import <cassert>
#import <mutex>

#import <React/RCTBridge+Private.h>
#import <React/RCTBridgeModule.h>
Expand Down Expand Up @@ -45,6 +46,18 @@ @implementation RCTTurboModuleManager {
*/
std::unordered_map<std::string, id<RCTTurboModule>> _rctTurboModuleCache;
std::unordered_map<std::string, std::shared_ptr<react::TurboModule>> _turboModuleCache;

/**
* _rctTurboModuleCache can be accessed by muitiple threads at once via
* the provideRCTTurboModule method. This can lead to races. Therefore, we
* need to protect access to this unordered_map.
*
* Note:
* There's no need to protect access to _turboModuleCache because that cache
* is only accessed within provideTurboModule, which is only invoked by the
* JS thread.
*/
std::mutex _rctTurboModuleCacheLock;
}

- (instancetype)initWithBridge:(RCTBridge *)bridge delegate:(id<RCTTurboModuleManagerDelegate>)delegate
Expand Down Expand Up @@ -198,6 +211,8 @@ - (void)notifyAboutTurboModuleSetup:(const char *)name
*/
- (id<RCTTurboModule>)provideRCTTurboModule:(const char *)moduleName
{
std::lock_guard<std::mutex> guard{_rctTurboModuleCacheLock};

auto rctTurboModuleCacheLookup = _rctTurboModuleCache.find(moduleName);
if (rctTurboModuleCacheLookup != _rctTurboModuleCache.end()) {
return rctTurboModuleCacheLookup->second;
Expand Down

0 comments on commit a44ab29

Please sign in to comment.