1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  *
4  * This source code is licensed under the MIT license found in the
5  * LICENSE file in the root directory of this source tree.
6  */
7 
8 #include "ABI49_0_0ModuleRegistry.h"
9 
10 #include <glog/logging.h>
11 #include <ABI49_0_0Reactperflogger/ABI49_0_0BridgeNativeModulePerfLogger.h>
12 
13 #include "ABI49_0_0NativeModule.h"
14 #include "ABI49_0_0SystraceSection.h"
15 
16 namespace ABI49_0_0facebook {
17 namespace ABI49_0_0React {
18 
19 namespace {
20 
normalizeName(std::string name)21 std::string normalizeName(std::string name) {
22   if (name.compare(0, 9, "ABI49_0_0") == 0) {
23     name = name.substr(9);
24   }
25 
26   // TODO mhorowitz #10487027: This is super ugly.  We should just
27   // change iOS to emit normalized names, drop the "RK..." from
28   // names hardcoded in Android, and then delete this and the
29   // similar hacks in js.
30   if (name.compare(0, 3, "RCT") == 0) {
31     return name.substr(3);
32   } else if (name.compare(0, 2, "RK") == 0) {
33     return name.substr(2);
34   }
35   return name;
36 }
37 
38 } // namespace
39 
ModuleRegistry(std::vector<std::unique_ptr<NativeModule>> modules,ModuleNotFoundCallback callback)40 ModuleRegistry::ModuleRegistry(
41     std::vector<std::unique_ptr<NativeModule>> modules,
42     ModuleNotFoundCallback callback)
43     : modules_{std::move(modules)}, moduleNotFoundCallback_{callback} {}
44 
updateModuleNamesFromIndex(size_t index)45 void ModuleRegistry::updateModuleNamesFromIndex(size_t index) {
46   for (; index < modules_.size(); index++) {
47     std::string name = normalizeName(modules_[index]->getName());
48     modulesByName_[name] = index;
49   }
50 }
51 
registerModules(std::vector<std::unique_ptr<NativeModule>> modules)52 void ModuleRegistry::registerModules(
53     std::vector<std::unique_ptr<NativeModule>> modules) {
54   SystraceSection s_("ModuleRegistry::registerModules");
55   // Noop if there are no NativeModules to add
56   if (modules.empty()) {
57     return;
58   }
59 
60   if (modules_.empty() && unknownModules_.empty()) {
61     modules_ = std::move(modules);
62   } else {
63     size_t modulesSize = modules_.size();
64     size_t addModulesSize = modules.size();
65     bool addToNames = !modulesByName_.empty();
66     modules_.reserve(modulesSize + addModulesSize);
67     std::move(modules.begin(), modules.end(), std::back_inserter(modules_));
68     if (!unknownModules_.empty()) {
69       for (size_t index = modulesSize; index < modulesSize + addModulesSize;
70            index++) {
71         std::string name = normalizeName(modules_[index]->getName());
72         auto it = unknownModules_.find(name);
73         if (it != unknownModules_.end()) {
74           throw std::runtime_error(folly::to<std::string>(
75               "module ",
76               name,
77               " was required without being registered and is now being registered."));
78         } else if (addToNames) {
79           modulesByName_[name] = index;
80         }
81       }
82     } else if (addToNames) {
83       updateModuleNamesFromIndex(modulesSize);
84     }
85   }
86 }
87 
moduleNames()88 std::vector<std::string> ModuleRegistry::moduleNames() {
89   SystraceSection s_("ModuleRegistry::moduleNames");
90   std::vector<std::string> names;
91   for (size_t i = 0; i < modules_.size(); i++) {
92     std::string name = normalizeName(modules_[i]->getName());
93     modulesByName_[name] = i;
94     names.push_back(std::move(name));
95   }
96   return names;
97 }
98 
getConfig(const std::string & name)99 std::optional<ModuleConfig> ModuleRegistry::getConfig(const std::string &name) {
100   SystraceSection s("ModuleRegistry::getConfig", "module", name);
101 
102   // Initialize modulesByName_
103   if (modulesByName_.empty() && !modules_.empty()) {
104     moduleNames();
105   }
106 
107   auto it = modulesByName_.find(name);
108 
109   if (it == modulesByName_.end()) {
110     if (unknownModules_.find(name) != unknownModules_.end()) {
111       BridgeNativeModulePerfLogger::moduleJSRequireBeginningFail(name.c_str());
112       BridgeNativeModulePerfLogger::moduleJSRequireEndingStart(name.c_str());
113       return std::nullopt;
114     }
115 
116     if (!moduleNotFoundCallback_) {
117       unknownModules_.insert(name);
118       BridgeNativeModulePerfLogger::moduleJSRequireBeginningFail(name.c_str());
119       BridgeNativeModulePerfLogger::moduleJSRequireEndingStart(name.c_str());
120       return std::nullopt;
121     }
122 
123     BridgeNativeModulePerfLogger::moduleJSRequireBeginningEnd(name.c_str());
124 
125     bool wasModuleLazilyLoaded = moduleNotFoundCallback_(name);
126     it = modulesByName_.find(name);
127 
128     bool wasModuleRegisteredWithRegistry =
129         wasModuleLazilyLoaded && it != modulesByName_.end();
130 
131     if (!wasModuleRegisteredWithRegistry) {
132       BridgeNativeModulePerfLogger::moduleJSRequireEndingStart(name.c_str());
133       unknownModules_.insert(name);
134       return std::nullopt;
135     }
136   } else {
137     BridgeNativeModulePerfLogger::moduleJSRequireBeginningEnd(name.c_str());
138   }
139 
140   // If we've gotten this far, then we've signaled moduleJSRequireBeginningEnd
141 
142   size_t index = it->second;
143 
144   CHECK(index < modules_.size());
145   NativeModule *module = modules_[index].get();
146 
147   // string name, object constants, array methodNames (methodId is index),
148   // [array promiseMethodIds], [array syncMethodIds]
149   folly::dynamic config = folly::dynamic::array(name);
150 
151   {
152     SystraceSection s_("ModuleRegistry::getConstants", "module", name);
153     /**
154      * In the case that there are constants, we'll initialize the NativeModule,
155      * and signal moduleJSRequireEndingStart. Otherwise, we'll simply signal the
156      * event. The Module will be initialized when we invoke one of its
157      * NativeModule methods.
158      */
159     config.push_back(module->getConstants());
160   }
161 
162   {
163     SystraceSection s_("ModuleRegistry::getMethods", "module", name);
164     std::vector<MethodDescriptor> methods = module->getMethods();
165 
166     folly::dynamic methodNames = folly::dynamic::array;
167     folly::dynamic promiseMethodIds = folly::dynamic::array;
168     folly::dynamic syncMethodIds = folly::dynamic::array;
169 
170     for (auto &descriptor : methods) {
171       // TODO: #10487027 compare tags instead of doing string comparison?
172       methodNames.push_back(std::move(descriptor.name));
173       if (descriptor.type == "promise") {
174         promiseMethodIds.push_back(methodNames.size() - 1);
175       } else if (descriptor.type == "sync") {
176         syncMethodIds.push_back(methodNames.size() - 1);
177       }
178     }
179 
180     if (!methodNames.empty()) {
181       config.push_back(std::move(methodNames));
182       if (!promiseMethodIds.empty() || !syncMethodIds.empty()) {
183         config.push_back(std::move(promiseMethodIds));
184         if (!syncMethodIds.empty()) {
185           config.push_back(std::move(syncMethodIds));
186         }
187       }
188     }
189   }
190 
191   if (config.size() == 2 && config[1].empty()) {
192     // no constants or methods
193     return std::nullopt;
194   } else {
195     return ModuleConfig{index, std::move(config)};
196   }
197 }
198 
getModuleName(unsigned int moduleId)199 std::string ModuleRegistry::getModuleName(unsigned int moduleId) {
200   if (moduleId >= modules_.size()) {
201     throw std::runtime_error(folly::to<std::string>(
202         "moduleId ", moduleId, " out of range [0..", modules_.size(), ")"));
203   }
204 
205   return modules_[moduleId]->getName();
206 }
207 
getModuleSyncMethodName(unsigned int moduleId,unsigned int methodId)208 std::string ModuleRegistry::getModuleSyncMethodName(
209     unsigned int moduleId,
210     unsigned int methodId) {
211   if (moduleId >= modules_.size()) {
212     throw std::runtime_error(folly::to<std::string>(
213         "moduleId ", moduleId, " out of range [0..", modules_.size(), ")"));
214   }
215 
216   return modules_[moduleId]->getSyncMethodName(methodId);
217 }
218 
callNativeMethod(unsigned int moduleId,unsigned int methodId,folly::dynamic && params,int callId)219 void ModuleRegistry::callNativeMethod(
220     unsigned int moduleId,
221     unsigned int methodId,
222     folly::dynamic &&params,
223     int callId) {
224   if (moduleId >= modules_.size()) {
225     throw std::runtime_error(folly::to<std::string>(
226         "moduleId ", moduleId, " out of range [0..", modules_.size(), ")"));
227   }
228   modules_[moduleId]->invoke(methodId, std::move(params), callId);
229 }
230 
callSerializableNativeHook(unsigned int moduleId,unsigned int methodId,folly::dynamic && params)231 MethodCallResult ModuleRegistry::callSerializableNativeHook(
232     unsigned int moduleId,
233     unsigned int methodId,
234     folly::dynamic &&params) {
235   if (moduleId >= modules_.size()) {
236     throw std::runtime_error(folly::to<std::string>(
237         "moduleId ", moduleId, "out of range [0..", modules_.size(), ")"));
238   }
239   return modules_[moduleId]->callSerializableNativeHook(
240       methodId, std::move(params));
241 }
242 
243 } // namespace ABI49_0_0React
244 } // namespace ABI49_0_0facebook
245