-
Notifications
You must be signed in to change notification settings - Fork 25.3k
Expand file tree
/
Copy pathRCTTurboModuleManager.mm
More file actions
1110 lines (936 loc) · 38.2 KB
/
Copy pathRCTTurboModuleManager.mm
File metadata and controls
1110 lines (936 loc) · 38.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RCTTurboModuleManager.h"
#import "RCTInteropTurboModule.h"
#import <atomic>
#import <cassert>
#import <condition_variable>
#import <mutex>
#import <objc/runtime.h>
#import <React/RCTBridge+Private.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTBridgeProxy.h>
#import <React/RCTCallInvoker.h>
#import <React/RCTCallInvokerModule.h>
#import <React/RCTConstants.h>
#import <React/RCTCxxModule.h>
#import <React/RCTInitializing.h>
#import <React/RCTLog.h>
#import <React/RCTModuleData.h>
#import <React/RCTPerformanceLogger.h>
#import <React/RCTUtils.h>
#import <ReactCommon/CxxTurboModuleUtils.h>
#import <ReactCommon/RCTTurboModuleWithJSIBindings.h>
#import <ReactCommon/TurboCxxModule.h>
#import <ReactCommon/TurboModulePerfLogger.h>
#import <ReactCommon/TurboModuleUtils.h>
#import <react/featureflags/ReactNativeFeatureFlags.h>
using namespace facebook;
using namespace facebook::react;
/**
* A global variable whose address we use to associate method queues to id<RCTBridgeModule> objects.
*/
static char kAssociatedMethodQueueKey;
namespace {
int32_t getUniqueId()
{
static std::atomic<int32_t> counter{0};
return counter++;
}
class ModuleHolder {
private:
const int32_t moduleId_;
id<RCTBridgeModule> module_;
bool isTryingToCreateModule_;
bool isDoneCreatingModule_;
std::mutex mutex_;
std::condition_variable cv_;
public:
ModuleHolder() : moduleId_(getUniqueId()), module_(nil), isTryingToCreateModule_(false), isDoneCreatingModule_(false)
{
}
int32_t getModuleId() const
{
return moduleId_;
}
void setModule(id<RCTBridgeModule> module)
{
module_ = module;
}
id<RCTBridgeModule> getModule() const
{
return module_;
}
void startCreatingModule()
{
isTryingToCreateModule_ = true;
}
void endCreatingModule()
{
isTryingToCreateModule_ = false;
isDoneCreatingModule_ = true;
}
bool isDoneCreatingModule() const
{
return isDoneCreatingModule_;
}
bool isCreatingModule() const
{
return isTryingToCreateModule_;
}
std::mutex &mutex()
{
return mutex_;
}
std::condition_variable &cv()
{
return cv_;
}
};
class ModuleNativeMethodCallInvoker : public NativeMethodCallInvoker {
private:
dispatch_queue_t methodQueue_;
public:
ModuleNativeMethodCallInvoker(dispatch_queue_t methodQueue) : methodQueue_(methodQueue) {}
void invokeAsync(const std::string &methodName, std::function<void()> &&work) noexcept override
{
if (methodQueue_ == RCTJSThread) {
work();
return;
}
__block auto retainedWork = std::move(work);
dispatch_async(methodQueue_, ^{
retainedWork();
});
}
void invokeSync(const std::string &methodName, std::function<void()> &&work) override
{
work();
}
};
class LegacyModuleNativeMethodCallInvoker : public ModuleNativeMethodCallInvoker {
bool requiresMainQueueSetup_;
public:
LegacyModuleNativeMethodCallInvoker(dispatch_queue_t methodQueue, bool requiresMainQueueSetup)
: ModuleNativeMethodCallInvoker(methodQueue), requiresMainQueueSetup_(requiresMainQueueSetup)
{
}
void invokeSync(const std::string &methodName, std::function<void()> &&work) override
{
if (requiresMainQueueSetup_ && methodName == "getConstants") {
__block auto retainedWork = std::move(work);
RCTUnsafeExecuteOnMainQueueSync(^{
retainedWork();
});
return;
}
ModuleNativeMethodCallInvoker::invokeSync(methodName, std::move(work));
}
};
bool isTurboModuleClass(Class cls)
{
return [cls conformsToProtocol:@protocol(RCTTurboModule)];
}
bool isTurboModuleInstance(id module)
{
return isTurboModuleClass([module class]);
}
} // namespace
// Fallback lookup since RCT class prefix is sometimes stripped in the existing NativeModule system.
// This will be removed in the future.
static Class getFallbackClassFromName(const char *name)
{
Class moduleClass = NSClassFromString([NSString stringWithUTF8String:name]);
if (!moduleClass) {
moduleClass = NSClassFromString([NSString stringWithFormat:@"RCT%s", name]);
}
return moduleClass;
}
typedef struct {
id<RCTBridgeModule> module;
dispatch_queue_t methodQueue;
} ModuleQueuePair;
@implementation RCTTurboModuleManager {
std::shared_ptr<CallInvoker> _jsInvoker;
__weak id<RCTTurboModuleManagerDelegate> _delegate;
__weak RCTBridge *_bridge;
/**
* TODO(T48018690):
* All modules are currently long-lived.
* We need to come up with a mechanism to allow modules to specify whether
* they want to be long-lived or short-lived.
*
* All instances of ModuleHolder are owned by the _moduleHolders map.
* We only reference ModuleHolders via pointers to entries in the _moduleHolders map.
*/
std::unordered_map<std::string, ModuleHolder> _moduleHolders;
std::unordered_map<std::string, std::shared_ptr<TurboModule>> _turboModuleCache;
std::unordered_map<std::string, std::shared_ptr<TurboModule>> _legacyModuleCache;
// Enforce synchronous access into _delegate
std::mutex _turboModuleManagerDelegateMutex;
// Enforce synchronous access to _invalidating and _moduleHolders
std::mutex _moduleHoldersMutex;
std::atomic<bool> _invalidating;
NSDictionary<NSString *, id<RCTBridgeModule>> *_legacyEagerlyInitializedModules;
NSDictionary<NSString *, Class> *_legacyEagerlyRegisteredModuleClasses;
RCTBridgeProxy *_bridgeProxy;
RCTBridgeModuleDecorator *_bridgeModuleDecorator;
dispatch_queue_t _sharedModuleQueue;
}
- (instancetype)initWithBridge:(RCTBridge *)bridge
bridgeProxy:(RCTBridgeProxy *)bridgeProxy
bridgeModuleDecorator:(RCTBridgeModuleDecorator *)bridgeModuleDecorator
delegate:(id<RCTTurboModuleManagerDelegate>)delegate
jsInvoker:(std::shared_ptr<CallInvoker>)jsInvoker
{
if (self = [super init]) {
_jsInvoker = std::move(jsInvoker);
_delegate = delegate;
_bridge = bridge;
_bridgeProxy = bridgeProxy;
_bridgeModuleDecorator = bridgeModuleDecorator;
_invalidating = false;
_sharedModuleQueue = dispatch_queue_create("com.meta.react.turbomodulemanager.queue", DISPATCH_QUEUE_SERIAL);
if (RCTTurboModuleInteropEnabled()) {
// TODO(T174674274): Implement lazy loading of legacy modules in the new architecture.
NSMutableDictionary<NSString *, id<RCTBridgeModule>> *legacyInitializedModules = [NSMutableDictionary new];
if ([_delegate respondsToSelector:@selector(extraModulesForBridge:)]) {
for (id<RCTBridgeModule> module in [_delegate extraModulesForBridge:nil]) {
if (!isTurboModuleInstance(module)) {
[legacyInitializedModules setObject:module forKey:RCTBridgeModuleNameForClass([module class])];
}
}
}
_legacyEagerlyInitializedModules = legacyInitializedModules;
NSMutableDictionary<NSString *, Class> *legacyEagerlyRegisteredModuleClasses = [NSMutableDictionary new];
for (Class moduleClass in RCTGetModuleClasses()) {
if (!isTurboModuleClass(moduleClass)) {
[legacyEagerlyRegisteredModuleClasses setObject:moduleClass forKey:RCTBridgeModuleNameForClass(moduleClass)];
}
}
_legacyEagerlyRegisteredModuleClasses = legacyEagerlyRegisteredModuleClasses;
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(bridgeWillInvalidateModules:)
name:RCTBridgeWillInvalidateModulesNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(bridgeDidInvalidateModules:)
name:RCTBridgeDidInvalidateModulesNotification
object:nil];
}
return self;
}
- (instancetype)initWithBridge:(RCTBridge *)bridge
delegate:(id<RCTTurboModuleManagerDelegate>)delegate
jsInvoker:(std::shared_ptr<CallInvoker>)jsInvoker
{
return [self initWithBridge:bridge
bridgeProxy:nil
bridgeModuleDecorator:[bridge bridgeModuleDecorator]
delegate:delegate
jsInvoker:jsInvoker];
}
- (instancetype)initWithBridgeProxy:(RCTBridgeProxy *)bridgeProxy
bridgeModuleDecorator:(RCTBridgeModuleDecorator *)bridgeModuleDecorator
delegate:(id<RCTTurboModuleManagerDelegate>)delegate
jsInvoker:(std::shared_ptr<CallInvoker>)jsInvoker
{
return [self initWithBridge:nil
bridgeProxy:bridgeProxy
bridgeModuleDecorator:bridgeModuleDecorator
delegate:delegate
jsInvoker:jsInvoker];
}
/**
* Given a name for a TurboModule, return a C++ object which is the instance
* of that TurboModule C++ class. This class wraps the TurboModule's ObjC instance.
* If no TurboModule ObjC class exist with the provided name, abort program.
*
* Note: All TurboModule instances are cached, which means they're all long-lived
* (for now).
*/
- (std::shared_ptr<TurboModule>)provideTurboModule:(const char *)moduleName runtime:(jsi::Runtime *)runtime
{
auto turboModuleLookup = _turboModuleCache.find(moduleName);
if (turboModuleLookup != _turboModuleCache.end()) {
TurboModulePerfLogger::moduleJSRequireBeginningCacheHit(moduleName);
TurboModulePerfLogger::moduleJSRequireBeginningEnd(moduleName);
return turboModuleLookup->second;
}
TurboModulePerfLogger::moduleJSRequireBeginningEnd(moduleName);
/**
* Step 1: Look for pure C++ modules.
* Pure C++ modules get priority.
*/
if ([_delegate respondsToSelector:@selector(getTurboModule:jsInvoker:)]) {
int32_t moduleId = getUniqueId();
TurboModulePerfLogger::moduleCreateStart(moduleName, moduleId);
auto turboModule = [_delegate getTurboModule:moduleName jsInvoker:_jsInvoker];
if (turboModule != nullptr) {
_turboModuleCache.insert({moduleName, turboModule});
TurboModulePerfLogger::moduleCreateEnd(moduleName, moduleId);
return turboModule;
}
TurboModulePerfLogger::moduleCreateFail(moduleName, moduleId);
}
auto &cxxTurboModuleMapProvider = globalExportedCxxTurboModuleMap();
auto it = cxxTurboModuleMapProvider.find(moduleName);
if (it != cxxTurboModuleMapProvider.end()) {
auto turboModule = it->second(_jsInvoker);
_turboModuleCache.insert({moduleName, turboModule});
return turboModule;
}
/**
* Step 2: Look for platform-specific modules.
*/
id<RCTModuleProvider> module = [self _moduleProviderForName:moduleName];
TurboModulePerfLogger::moduleJSRequireEndingStart(moduleName);
// If we request that a TurboModule be created, its respective ObjC class must exist
// If the class doesn't exist, then _provideObjCModule returns nil
if (!module) {
return nullptr;
}
std::shared_ptr<NativeMethodCallInvoker> nativeMethodCallInvoker = nullptr;
dispatch_queue_t methodQueue = (dispatch_queue_t)objc_getAssociatedObject(module, &kAssociatedMethodQueueKey);
if (methodQueue) {
/**
* Step 2c: Create and native CallInvoker from the TurboModule's method queue.
*/
nativeMethodCallInvoker = std::make_shared<ModuleNativeMethodCallInvoker>(methodQueue);
/**
* Have RCTCxxBridge decorate native CallInvoker, so that it's aware of TurboModule async method calls.
* This helps the bridge fire onBatchComplete as readily as it should.
*/
if ([_bridge respondsToSelector:@selector(decorateNativeMethodCallInvoker:)]) {
nativeMethodCallInvoker = [_bridge decorateNativeMethodCallInvoker:nativeMethodCallInvoker];
}
}
/**
* Step 2d: If the moduleClass is a legacy CxxModule, return a TurboCxxModule instance that
* wraps CxxModule.
*/
Class moduleClass = [module class];
if ([moduleClass isSubclassOfClass:RCTCxxModule.class]) {
// Use TurboCxxModule compat class to wrap the CxxModule instance.
// This is only for migration convenience, despite less performant.
auto turboModule = std::make_shared<TurboCxxModule>([((RCTCxxModule *)module) createModule], _jsInvoker);
_turboModuleCache.insert({moduleName, turboModule});
return turboModule;
}
/**
* Step 2e: Return an exact sub-class of ObjC TurboModule
*
* Use respondsToSelector: below to infer conformance to @protocol(RCTTurboModule). Using conformsToProtocol: is
* expensive.
*/
if ([module respondsToSelector:@selector(getTurboModule:)]) {
ObjCTurboModule::InitParams params = {
.moduleName = moduleName,
.instance = (id<RCTBridgeModule>)module,
.jsInvoker = _jsInvoker,
.nativeMethodCallInvoker = nativeMethodCallInvoker,
.isSyncModule = methodQueue == RCTJSThread,
.shouldVoidMethodsExecuteSync = (bool)RCTTurboModuleSyncVoidMethodsEnabled(),
};
auto turboModule = [(id<RCTTurboModule>)module getTurboModule:params];
if (turboModule == nullptr) {
RCTLogError(@"TurboModule \"%@\"'s getTurboModule: method returned nil.", moduleClass);
}
_turboModuleCache.insert({moduleName, turboModule});
if ([module respondsToSelector:@selector(installJSIBindingsWithRuntime:callInvoker:)]) {
[(id<RCTTurboModuleWithJSIBindings>)module installJSIBindingsWithRuntime:*runtime callInvoker:_jsInvoker];
} else if ([module respondsToSelector:@selector(installJSIBindingsWithRuntime:)]) {
// Old API without CallInvoker (deprecated)
[(id<RCTTurboModuleWithJSIBindings>)module installJSIBindingsWithRuntime:*runtime];
}
return turboModule;
}
return nullptr;
}
- (std::shared_ptr<TurboModule>)provideLegacyModule:(const char *)moduleName
{
auto legacyModuleLookup = _legacyModuleCache.find(moduleName);
if (legacyModuleLookup != _legacyModuleCache.end()) {
TurboModulePerfLogger::moduleJSRequireBeginningCacheHit(moduleName);
TurboModulePerfLogger::moduleJSRequireBeginningEnd(moduleName);
return legacyModuleLookup->second;
}
TurboModulePerfLogger::moduleJSRequireBeginningEnd(moduleName);
// Create platform-specific native module object
id<RCTBridgeModule> module =
[self _isLegacyModule:moduleName] ? [self _provideObjCModule:moduleName moduleProvider:nil] : nil;
TurboModulePerfLogger::moduleJSRequireEndingStart(moduleName);
// If we request that a TurboModule be created, its respective ObjC class must exist
// If the class doesn't exist, then provideRCTBridgeModule returns nil
if (!module) {
return nullptr;
}
Class moduleClass = [module class];
dispatch_queue_t methodQueue = (dispatch_queue_t)objc_getAssociatedObject(module, &kAssociatedMethodQueueKey);
if (methodQueue == nil) {
RCTLogError(@"Legacy NativeModule \"%@\" was not associated with a method queue.", moduleClass);
}
// Create a native call invoker from module's method queue
std::shared_ptr<NativeMethodCallInvoker> nativeMethodCallInvoker =
std::make_shared<LegacyModuleNativeMethodCallInvoker>(methodQueue, [self _requiresMainQueueSetup:moduleClass]);
// If module is a legacy cxx module, return TurboCxxModule
if ([moduleClass isSubclassOfClass:RCTCxxModule.class]) {
// Use TurboCxxModule compat class to wrap the CxxModule instance.
// This is only for migration convenience, despite less performant.
auto turboModule = std::make_shared<TurboCxxModule>([((RCTCxxModule *)module) createModule], _jsInvoker);
_legacyModuleCache.insert({moduleName, turboModule});
return turboModule;
}
// Create interop module
ObjCTurboModule::InitParams params = {
.moduleName = moduleName,
.instance = module,
.jsInvoker = _jsInvoker,
.nativeMethodCallInvoker = std::move(nativeMethodCallInvoker),
.isSyncModule = methodQueue == RCTJSThread,
.shouldVoidMethodsExecuteSync = (bool)RCTTurboModuleSyncVoidMethodsEnabled(),
};
auto turboModule = std::make_shared<ObjCInteropTurboModule>(params);
_legacyModuleCache.insert({moduleName, turboModule});
return turboModule;
}
#pragma mark - Private Methods
- (BOOL)_isTurboModule:(const char *)moduleName
{
Class moduleClass = [self _getModuleClassFromName:moduleName];
return moduleClass != nil && (isTurboModuleClass(moduleClass) && ![moduleClass isSubclassOfClass:RCTCxxModule.class]);
}
- (BOOL)_isLegacyModule:(const char *)moduleName
{
Class moduleClass = [self _getModuleClassFromName:moduleName];
return [self _isLegacyModuleClass:moduleClass];
}
- (BOOL)_isLegacyModuleClass:(Class)moduleClass
{
return moduleClass != nil && (!isTurboModuleClass(moduleClass) || [moduleClass isSubclassOfClass:RCTCxxModule.class]);
}
- (id<RCTModuleProvider>)_moduleProviderForName:(const char *)moduleName
{
id<RCTModuleProvider> moduleProvider = nil;
if ([_delegate respondsToSelector:@selector(getModuleProvider:)]) {
moduleProvider = [_delegate getModuleProvider:moduleName];
}
if (RCTTurboModuleInteropEnabled() && ![self _isTurboModule:moduleName] && !moduleProvider) {
return nil;
}
if (moduleProvider) {
if ([moduleProvider conformsToProtocol:@protocol(RCTTurboModule)]) {
// moduleProvider is also a TM, we need to initialize objectiveC properties, like the dispatch queue
return (id<RCTModuleProvider>)[self _provideObjCModule:moduleName moduleProvider:moduleProvider];
}
// module is Cxx module
return moduleProvider;
}
// No module provider, the Module is registered without Codegen
return (id<RCTModuleProvider>)[self _provideObjCModule:moduleName moduleProvider:nil];
}
- (ModuleHolder *)_getOrCreateModuleHolder:(const char *)moduleName
{
std::lock_guard<std::mutex> guard(_moduleHoldersMutex);
if (_invalidating) {
return nullptr;
}
return &_moduleHolders[moduleName];
}
/**
* Given a name for a NativeModule, return an ObjC object which is the instance
* of that NativeModule ObjC class. If no NativeModule exist with the provided name,
* return nil.
*
* Note: All NativeModule instances are cached, which means they're all long-lived
* (for now).
*/
- (id<RCTBridgeModule>)_provideObjCModule:(const char *)moduleName moduleProvider:(id<RCTModuleProvider>)moduleProvider
{
if (strncmp("RCT", moduleName, 3) == 0) {
moduleName = [[[NSString stringWithUTF8String:moduleName] substringFromIndex:3] UTF8String];
}
ModuleHolder *moduleHolder = [self _getOrCreateModuleHolder:moduleName];
if (!moduleHolder) {
return nil;
}
TurboModulePerfLogger::moduleCreateStart(moduleName, moduleHolder->getModuleId());
id<RCTBridgeModule> module = [self _provideObjCModule:moduleName
moduleHolder:moduleHolder
shouldPerfLog:YES
moduleProvider:moduleProvider];
if (module) {
TurboModulePerfLogger::moduleCreateEnd(moduleName, moduleHolder->getModuleId());
} else {
TurboModulePerfLogger::moduleCreateFail(moduleName, moduleHolder->getModuleId());
}
return module;
}
- (id<RCTBridgeModule>)_provideObjCModule:(const char *)moduleName
moduleHolder:(ModuleHolder *)moduleHolder
shouldPerfLog:(BOOL)shouldPerfLog
moduleProvider:(id<RCTModuleProvider>)moduleProvider
{
bool shouldCreateModule = false;
{
std::lock_guard<std::mutex> guard(moduleHolder->mutex());
if (moduleHolder->isDoneCreatingModule()) {
if (shouldPerfLog) {
TurboModulePerfLogger::moduleCreateCacheHit(moduleName, moduleHolder->getModuleId());
}
return moduleHolder->getModule();
}
if (!moduleHolder->isCreatingModule()) {
shouldCreateModule = true;
moduleHolder->startCreatingModule();
}
}
if (shouldCreateModule) {
/**
* Step 2a: Resolve platform-specific class.
*/
Class moduleClass = moduleProvider ? [moduleProvider class] : [self _getModuleClassFromName:moduleName];
__block id<RCTBridgeModule> module = nil;
if ([self _shouldCreateObjCModule:moduleClass]) {
__weak __typeof(self) weakSelf = self;
dispatch_block_t work = ^{
auto strongSelf = weakSelf;
if (!strongSelf) {
return;
}
module = [strongSelf _createAndSetUpObjCModule:moduleClass moduleName:moduleName moduleId:moduleHolder
->getModuleId()];
};
if ([self _requiresMainQueueSetup:moduleClass]) {
NSString *message = [NSString
stringWithFormat:
@"Lazily setting up TurboModule \"%s\" on the main queue. This could deadlock react native, if it happens during sync rendering. Please fix this by avoiding lazy main queue setup.",
moduleName];
RCTUnsafeExecuteOnMainQueueSyncWithError(work, message);
} else {
work();
}
}
{
std::lock_guard<std::mutex> guard(moduleHolder->mutex());
moduleHolder->setModule(module);
moduleHolder->endCreatingModule();
}
moduleHolder->cv().notify_all();
return module;
}
std::unique_lock<std::mutex> guard(moduleHolder->mutex());
while (moduleHolder->isCreatingModule()) {
/**
* TODO(T65905574):
* If the thread responsible for creating and initializing the NativeModule stalls, we'll wait here indefinitely.
* This is the behaviour in legacy NativeModules. Changing this now could lead to more crashes/problems in
* TurboModules than in NativeModules, which'll make it more difficult to test the TurboModules infra. Therefore,
* we should consider making it post TurboModule 100% rollout.
*/
moduleHolder->cv().wait(guard);
}
return moduleHolder->getModule();
}
- (BOOL)_shouldCreateObjCModule:(Class)moduleClass
{
if (RCTTurboModuleInteropEnabled()) {
return [moduleClass conformsToProtocol:@protocol(RCTBridgeModule)];
}
return [moduleClass conformsToProtocol:@protocol(RCTTurboModule)];
}
/**
* Given a NativeModule class, and its name, create and initialize it synchronously.
*
* This method can be called synchronously from two different contexts:
* - The thread that calls _provideObjCModule:
* - The main thread (if the NativeModule requires main queue init), blocking the thread that calls
* _provideObjCModule:.
*/
- (id<RCTBridgeModule>)_createAndSetUpObjCModule:(Class)moduleClass
moduleName:(const char *)moduleName
moduleId:(int32_t)moduleId
{
id<RCTBridgeModule> module = nil;
/**
* Step 2b: Ask hosting application/delegate to instantiate this class
*/
TurboModulePerfLogger::moduleCreateConstructStart(moduleName, moduleId);
module = [self _getModuleInstanceFromClass:moduleClass];
TurboModulePerfLogger::moduleCreateConstructEnd(moduleName, moduleId);
TurboModulePerfLogger::moduleCreateSetUpStart(moduleName, moduleId);
/**
* It is reasonable for NativeModules to not want/need the bridge.
* In such cases, they won't have `@synthesize bridge = _bridge` in their
* implementation, and a `- (RCTBridge *) bridge { ... }` method won't be
* generated by the ObjC runtime. The property will also not be backed
* by an ivar, which makes writing to it unsafe. Therefore, we check if
* this method exists to know if we can safely set the bridge to the
* NativeModule.
*/
if ([module respondsToSelector:@selector(bridge)] && (_bridge || _bridgeProxy)) {
/**
* Just because a NativeModule has the `bridge` method, it doesn't mean
* that it has synthesized the bridge in its implementation. Therefore,
* we need to surround the code that sets the bridge to the NativeModule
* inside a try/catch. This catches the cases where the NativeModule
* author specifies a `bridge` method manually.
*/
@try {
/**
* RCTBridgeModule declares the bridge property as readonly.
* Therefore, when authors of NativeModules synthesize the bridge
* via @synthesize bridge = bridge;, the ObjC runtime generates
* only a - (RCTBridge *) bridge: { ... } method. No setter is
* generated, so we have have to rely on the KVC API of ObjC to set
* the bridge property of these NativeModules.
*/
if (_bridge) {
[(id)module setValue:_bridge forKey:@"bridge"];
} else if (_bridgeProxy) {
[(id)module setValue:_bridgeProxy forKey:@"bridge"];
}
} @catch (NSException *exception) {
RCTLogError(
@"%@ has no setter or ivar for its bridge, which is not "
"permitted. You must either @synthesize the bridge property, "
"or provide your own setter method.",
RCTBridgeModuleNameForClass([module class]));
}
}
// This is a more performant alternative for conformsToProtocol:@protocol(RCTCallInvokerModule)
if ([module respondsToSelector:@selector(setCallInvoker:)]) {
RCTCallInvoker *callInvoker = [[RCTCallInvoker alloc] initWithCallInvoker:_jsInvoker];
[(id<RCTCallInvokerModule>)module setCallInvoker:callInvoker];
}
/**
* Some modules need their own queues, but don't provide any, so we need to create it for them.
* These modules typically have the following:
* `@synthesize methodQueue = _methodQueue`
*/
dispatch_queue_t methodQueue = nil;
BOOL moduleHasMethodQueueGetter = [module respondsToSelector:@selector(methodQueue)];
if (moduleHasMethodQueueGetter) {
methodQueue = [(id<RCTBridgeModule>)module methodQueue];
}
/**
* Note: RCTJSThread, which is a valid method queue, is defined as (id)kCFNull. It should rightfully not enter the
* following if condition's block.
*/
if (!methodQueue) {
methodQueue = _sharedModuleQueue;
if (moduleHasMethodQueueGetter) {
/**
* If the module has a method queue getter, two cases are possible:
* - We @synthesized the method queue. In this case, the getter will initially return nil.
* - We had a custom methodQueue function on the NativeModule. If we got this far, then that getter returned
* nil.
*
* Therefore, we do a try/catch and use ObjC's KVC API and try to assign the method queue to the NativeModule.
* In case 1, we'll succeed. In case 2, an exception will be thrown, which we'll ignore.
*/
@try {
[(id)module setValue:methodQueue forKey:@"methodQueue"];
} @catch (NSException *exception) {
RCTLogError(
@"%@ has no setter or ivar for its methodQueue, which is not "
"permitted. You must either @synthesize the methodQueue property, "
"or provide your own setter method.",
RCTBridgeModuleNameForClass([module class]));
}
}
}
/**
* Decorate NativeModules with bridgeless-compatible APIs that call into the bridge.
*/
if (_bridgeModuleDecorator) {
[_bridgeModuleDecorator attachInteropAPIsToModule:module];
}
/**
* If the NativeModule conforms to RCTInitializing, invoke its initialize method.
*/
if ([module respondsToSelector:@selector(initialize)]) {
[(id<RCTInitializing>)module initialize];
}
/**
* Attach method queue to id<RCTBridgeModule> object.
* This is necessary because the id<RCTBridgeModule> object can be eagerly created/initialized before the method
* queue is required. The method queue is required for an id<RCTBridgeModule> for JS -> Native calls. So, we need it
* before we create the id<RCTBridgeModule>'s TurboModule jsi::HostObject in provideTurboModule:runtime:.
*/
objc_setAssociatedObject(module, &kAssociatedMethodQueueKey, methodQueue, OBJC_ASSOCIATION_RETAIN);
/**
* NativeModules that implement the RCTFrameUpdateObserver protocol
* require registration with RCTDisplayLink.
*
* TODO(T55504345): Investigate whether we can improve this after TM
* rollout.
*/
if (_bridge) {
RCTModuleData *data = [[RCTModuleData alloc] initWithModuleInstance:(id<RCTBridgeModule>)module
bridge:_bridge
moduleRegistry:_bridge.moduleRegistry
viewRegistry_DEPRECATED:nil
bundleManager:nil
callableJSModules:nil];
[_bridge registerModuleForFrameUpdates:(id<RCTBridgeModule>)module withModuleData:data];
}
/**
* Broadcast that this NativeModule was created.
*
* TODO(T41180176): Investigate whether we can delete this after TM
* rollout.
*/
[[NSNotificationCenter defaultCenter]
postNotificationName:RCTDidInitializeModuleNotification
object:_bridge
userInfo:@{@"module" : module, @"bridge" : RCTNullIfNil([_bridge parentBridge])}];
TurboModulePerfLogger::moduleCreateSetUpEnd(moduleName, moduleId);
return module;
}
- (Class)_getModuleClassFromName:(const char *)moduleName
{
NSString *moduleNameStr = @(moduleName);
if (_legacyEagerlyInitializedModules && _legacyEagerlyInitializedModules[moduleNameStr]) {
return [_legacyEagerlyInitializedModules[moduleNameStr] class];
}
if (_legacyEagerlyRegisteredModuleClasses && _legacyEagerlyRegisteredModuleClasses[moduleNameStr]) {
return _legacyEagerlyRegisteredModuleClasses[moduleNameStr];
}
Class moduleClass = [_delegate getModuleClassFromName:moduleName];
if (moduleClass != nil) {
return moduleClass;
}
moduleClass = getFallbackClassFromName(moduleName);
if (moduleClass != nil) {
return moduleClass;
}
// fallback on modules registered throught RCT_EXPORT_MODULE with custom names
NSString *objcModuleName = [NSString stringWithUTF8String:moduleName];
NSArray<Class> *modules = RCTGetModuleClasses();
for (Class current in modules) {
NSString *currentModuleName = [current moduleName];
if ([objcModuleName isEqualToString:currentModuleName]) {
return current;
}
}
return moduleClass;
}
- (id<RCTBridgeModule>)_getModuleInstanceFromClass:(Class)moduleClass
{
NSString *moduleNameStr = RCTBridgeModuleNameForClass(moduleClass);
if (_legacyEagerlyInitializedModules && _legacyEagerlyInitializedModules[moduleNameStr]) {
return _legacyEagerlyInitializedModules[moduleNameStr];
}
if (_legacyEagerlyRegisteredModuleClasses && _legacyEagerlyRegisteredModuleClasses[moduleNameStr]) {
return [_legacyEagerlyRegisteredModuleClasses[moduleNameStr] new];
}
id<RCTBridgeModule> module = (id<RCTBridgeModule>)[_delegate getModuleInstanceFromClass:moduleClass];
if (!module) {
module = [moduleClass new];
}
return module;
}
/**
* Should this NativeModule be created and initialized on the main queue?
*
* For NativeModule ObjC classes that implement requiresMainQueueInit, return the result of this method.
* For NativeModule ObjC classes that don't. Return true if they have a custom init or constantsToExport method.
*/
- (BOOL)_requiresMainQueueSetup:(Class)moduleClass
{
const BOOL implementsRequireMainQueueSetup = [moduleClass respondsToSelector:@selector(requiresMainQueueSetup)];
if (implementsRequireMainQueueSetup) {
return [moduleClass requiresMainQueueSetup];
}
/**
* WARNING!
* This following logic exists for backwards compatibility with the legacy NativeModule system.
*
* TODO(T65864302) Remove the following logic after TM 100% rollout
*/
/**
* If a module overrides `constantsToExport` and doesn't implement `requiresMainQueueSetup`, then we must assume
* that it must be called on the main thread, because it may need to access UIKit.
*/
BOOL hasConstantsToExport = [moduleClass instancesRespondToSelector:@selector(constantsToExport)];
static IMP objectInitMethod;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
objectInitMethod = [NSObject instanceMethodForSelector:@selector(init)];
});
/**
* If a module overrides `init` then we must assume that it expects to be initialized on the main thread, because it
* may need to access UIKit.
*/
const BOOL hasCustomInit = [moduleClass instanceMethodForSelector:@selector(init)] != objectInitMethod;
return hasConstantsToExport || hasCustomInit;
}
- (void)installJSBindings:(facebook::jsi::Runtime &)runtime
{
/**
* We keep TurboModuleManager alive until the JS VM is deleted.
* It is perfectly valid to only use/create TurboModules from JS.
* In such a case, we shouldn't dealloc TurboModuleManager if there
* aren't any strong references to it in ObjC. Hence, we give
* __turboModuleProxy a strong reference to TurboModuleManager.
*/
auto turboModuleProvider = [self,
runtime = &runtime](const std::string &name) -> std::shared_ptr<react::TurboModule> {
auto moduleName = name.c_str();
TurboModulePerfLogger::moduleJSRequireBeginningStart(moduleName);
auto moduleWasNotInitialized = ![self moduleIsInitialized:moduleName];
if (moduleWasNotInitialized) {
[self->_bridge.performanceLogger markStartForTag:RCTPLTurboModuleSetup];
}
/**
* By default, all TurboModules are long-lived.
* Additionally, if a TurboModule with the name `name` isn't found, then we
* trigger an assertion failure.
*/
auto turboModule = [self provideTurboModule:moduleName runtime:runtime];
if (moduleWasNotInitialized && [self moduleIsInitialized:moduleName]) {
[self->_bridge.performanceLogger markStopForTag:RCTPLTurboModuleSetup];
}
if (turboModule) {
TurboModulePerfLogger::moduleJSRequireEndingEnd(moduleName);
} else {
TurboModulePerfLogger::moduleJSRequireEndingFail(moduleName);
}
return turboModule;
};
if (RCTTurboModuleInteropEnabled()) {
auto legacyModuleProvider = [self](const std::string &name) -> std::shared_ptr<react::TurboModule> {
auto moduleName = name.c_str();
TurboModulePerfLogger::moduleJSRequireBeginningStart(moduleName);
/**
* By default, all TurboModules are long-lived.
* Additionally, if a TurboModule with the name `name` isn't found, then we
* trigger an assertion failure.
*/
auto turboModule = [self provideLegacyModule:moduleName];
if (turboModule) {
TurboModulePerfLogger::moduleJSRequireEndingEnd(moduleName);
} else {
TurboModulePerfLogger::moduleJSRequireEndingFail(moduleName);
}
return turboModule;
};
TurboModuleBinding::install(runtime, std::move(turboModuleProvider), std::move(legacyModuleProvider));
} else {
TurboModuleBinding::install(runtime, std::move(turboModuleProvider));
}
}
#pragma mark RCTTurboModuleRegistry
- (id)moduleForName:(const char *)moduleName
{
return [self moduleForName:moduleName warnOnLookupFailure:YES];
}
- (id)moduleForName:(const char *)moduleName warnOnLookupFailure:(BOOL)warnOnLookupFailure
{
// When the bridge is invalidating, TurboModules will be nil.
// Therefore, don't (1) do the lookup, and (2) warn on lookup.
if (_invalidating) {
return nil;
}
id<RCTBridgeModule> module = [self _provideObjCModule:moduleName moduleProvider:nil];
if (warnOnLookupFailure && !module) {
RCTLogError(@"Unable to find module for %@", [NSString stringWithUTF8String:moduleName]);
}
return module;