-
Notifications
You must be signed in to change notification settings - Fork 24.4k
/
RCTCxxBridge.mm
1654 lines (1416 loc) · 57.6 KB
/
RCTCxxBridge.mm
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.
*/
#include <atomic>
#include <future>
#import <React/RCTAssert.h>
#import <React/RCTBridge+Private.h>
#import <React/RCTBridge.h>
#import <React/RCTBridgeMethod.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTBridgeModuleDecorator.h>
#import <React/RCTConstants.h>
#import <React/RCTConvert.h>
#import <React/RCTCxxBridgeDelegate.h>
#import <React/RCTCxxModule.h>
#import <React/RCTCxxUtils.h>
#import <React/RCTDevSettings.h>
#import <React/RCTDisplayLink.h>
#import <React/RCTFollyConvert.h>
#import <React/RCTJavaScriptLoader.h>
#import <React/RCTLog.h>
#import <React/RCTModuleData.h>
#import <React/RCTPerformanceLogger.h>
#import <React/RCTProfile.h>
#import <React/RCTRedBox.h>
#import <React/RCTReloadCommand.h>
#import <React/RCTUtils.h>
#import <cxxreact/CxxNativeModule.h>
#import <cxxreact/Instance.h>
#import <cxxreact/JSBundleType.h>
#import <cxxreact/JSIndexedRAMBundle.h>
#import <cxxreact/ModuleRegistry.h>
#import <cxxreact/RAMBundleRegistry.h>
#import <cxxreact/ReactMarker.h>
#import <jsireact/JSIExecutor.h>
#import <reactperflogger/BridgeNativeModulePerfLogger.h>
#ifndef RCT_USE_HERMES
#if __has_include(<reacthermes/HermesExecutorFactory.h>)
#define RCT_USE_HERMES 1
#else
#define RCT_USE_HERMES 0
#endif
#endif
#if RCT_USE_HERMES
#import <reacthermes/HermesExecutorFactory.h>
#else
#import "JSCExecutorFactory.h"
#endif
#import "RCTJSIExecutorRuntimeInstaller.h"
#import "NSDataBigString.h"
#import "RCTMessageThread.h"
#import "RCTObjcExecutor.h"
#ifdef WITH_FBSYSTRACE
#import <React/RCTFBSystrace.h>
#endif
#if (RCT_DEV | RCT_ENABLE_LOADING_VIEW) && __has_include(<React/RCTDevLoadingViewProtocol.h>)
#import <React/RCTDevLoadingViewProtocol.h>
#endif
static NSString *const RCTJSThreadName = @"com.facebook.react.JavaScript";
typedef void (^RCTPendingCall)();
using namespace facebook::jsi;
using namespace facebook::react;
/**
* Must be kept in sync with `MessageQueue.js`.
*/
typedef NS_ENUM(NSInteger, RCTBridgeFields) {
RCTBridgeFieldRequestModuleIDs = 0,
RCTBridgeFieldMethodIDs,
RCTBridgeFieldParams,
RCTBridgeFieldCallID,
};
namespace {
int32_t getUniqueId()
{
static std::atomic<int32_t> counter{0};
return counter++;
}
class GetDescAdapter : public JSExecutorFactory {
public:
GetDescAdapter(RCTCxxBridge *bridge, std::shared_ptr<JSExecutorFactory> factory) : bridge_(bridge), factory_(factory)
{
}
std::unique_ptr<JSExecutor> createJSExecutor(
std::shared_ptr<ExecutorDelegate> delegate,
std::shared_ptr<MessageQueueThread> jsQueue) override
{
auto ret = factory_->createJSExecutor(delegate, jsQueue);
bridge_.bridgeDescription = @(ret->getDescription().c_str());
return ret;
}
private:
RCTCxxBridge *bridge_;
std::shared_ptr<JSExecutorFactory> factory_;
};
}
static void notifyAboutModuleSetup(RCTPerformanceLogger *performanceLogger, const char *tag)
{
NSString *moduleName = [[NSString alloc] initWithUTF8String:tag];
if (moduleName) {
int64_t setupTime = [performanceLogger durationForTag:RCTPLNativeModuleSetup];
[[NSNotificationCenter defaultCenter] postNotificationName:RCTDidSetupModuleNotification
object:nil
userInfo:@{
RCTDidSetupModuleNotificationModuleNameKey : moduleName,
RCTDidSetupModuleNotificationSetupTimeKey : @(setupTime)
}];
}
}
static void mapReactMarkerToPerformanceLogger(
const ReactMarker::ReactMarkerId markerId,
RCTPerformanceLogger *performanceLogger,
const char *tag)
{
switch (markerId) {
case ReactMarker::RUN_JS_BUNDLE_START:
[performanceLogger markStartForTag:RCTPLScriptExecution];
break;
case ReactMarker::RUN_JS_BUNDLE_STOP:
[performanceLogger markStopForTag:RCTPLScriptExecution];
break;
case ReactMarker::NATIVE_REQUIRE_START:
[performanceLogger appendStartForTag:RCTPLRAMNativeRequires];
break;
case ReactMarker::NATIVE_REQUIRE_STOP:
[performanceLogger appendStopForTag:RCTPLRAMNativeRequires];
[performanceLogger addValue:1 forTag:RCTPLRAMNativeRequiresCount];
break;
case ReactMarker::NATIVE_MODULE_SETUP_START:
[performanceLogger markStartForTag:RCTPLNativeModuleSetup];
break;
case ReactMarker::NATIVE_MODULE_SETUP_STOP:
[performanceLogger markStopForTag:RCTPLNativeModuleSetup];
notifyAboutModuleSetup(performanceLogger, tag);
break;
// Not needed in bridge mode.
case ReactMarker::REACT_INSTANCE_INIT_START:
case ReactMarker::REACT_INSTANCE_INIT_STOP:
// Not used on iOS.
case ReactMarker::CREATE_REACT_CONTEXT_STOP:
case ReactMarker::JS_BUNDLE_STRING_CONVERT_START:
case ReactMarker::JS_BUNDLE_STRING_CONVERT_STOP:
case ReactMarker::REGISTER_JS_SEGMENT_START:
case ReactMarker::REGISTER_JS_SEGMENT_STOP:
break;
}
}
static void registerPerformanceLoggerHooks(RCTPerformanceLogger *performanceLogger)
{
__weak RCTPerformanceLogger *weakPerformanceLogger = performanceLogger;
ReactMarker::logTaggedMarker = [weakPerformanceLogger](const ReactMarker::ReactMarkerId markerId, const char *tag) {
mapReactMarkerToPerformanceLogger(markerId, weakPerformanceLogger, tag);
};
}
@interface RCTCxxBridge ()
@property (nonatomic, weak, readonly) RCTBridge *parentBridge;
@property (nonatomic, assign, readonly) BOOL moduleSetupComplete;
- (instancetype)initWithParentBridge:(RCTBridge *)bridge;
- (void)partialBatchDidFlush;
- (void)batchDidComplete;
@end
struct RCTInstanceCallback : public InstanceCallback {
__weak RCTCxxBridge *bridge_;
RCTInstanceCallback(RCTCxxBridge *bridge) : bridge_(bridge){};
void onBatchComplete() override
{
// There's no interface to call this per partial batch
[bridge_ partialBatchDidFlush];
[bridge_ batchDidComplete];
}
};
@implementation RCTCxxBridge {
BOOL _didInvalidate;
BOOL _moduleRegistryCreated;
NSMutableArray<RCTPendingCall> *_pendingCalls;
std::atomic<NSInteger> _pendingCount;
// Native modules
NSMutableDictionary<NSString *, RCTModuleData *> *_moduleDataByName;
NSMutableArray<RCTModuleData *> *_moduleDataByID;
NSMutableArray<Class> *_moduleClassesByID;
NSUInteger _modulesInitializedOnMainQueue;
RCTDisplayLink *_displayLink;
// JS thread management
NSThread *_jsThread;
std::shared_ptr<RCTMessageThread> _jsMessageThread;
std::mutex _moduleRegistryLock;
// This is uniquely owned, but weak_ptr is used.
std::shared_ptr<Instance> _reactInstance;
// Necessary for searching in TurboModules in TurboModuleManager
id<RCTTurboModuleRegistry> _turboModuleRegistry;
RCTModuleRegistry *_objCModuleRegistry;
RCTViewRegistry *_viewRegistry_DEPRECATED;
RCTBundleManager *_bundleManager;
RCTCallableJSModules *_callableJSModules;
}
@synthesize bridgeDescription = _bridgeDescription;
@synthesize loading = _loading;
@synthesize performanceLogger = _performanceLogger;
@synthesize valid = _valid;
- (RCTModuleRegistry *)moduleRegistry
{
return _objCModuleRegistry;
}
- (void)setRCTTurboModuleRegistry:(id<RCTTurboModuleRegistry>)turboModuleRegistry
{
_turboModuleRegistry = turboModuleRegistry;
[_objCModuleRegistry setTurboModuleRegistry:_turboModuleRegistry];
}
- (void)attachBridgeAPIsToTurboModule:(id<RCTTurboModule>)module
{
RCTBridgeModuleDecorator *bridgeModuleDecorator =
[[RCTBridgeModuleDecorator alloc] initWithViewRegistry:_viewRegistry_DEPRECATED
moduleRegistry:_objCModuleRegistry
bundleManager:_bundleManager
callableJSModules:_callableJSModules];
[bridgeModuleDecorator attachInteropAPIsToModule:(id<RCTBridgeModule>)module];
}
- (std::shared_ptr<MessageQueueThread>)jsMessageThread
{
return _jsMessageThread;
}
- (BOOL)isInspectable
{
return _reactInstance ? _reactInstance->isInspectable() : NO;
}
- (instancetype)initWithParentBridge:(RCTBridge *)bridge
{
RCTAssertParam(bridge);
if ((self = [super initWithDelegate:bridge.delegate
bundleURL:bridge.bundleURL
moduleProvider:bridge.moduleProvider
launchOptions:bridge.launchOptions])) {
_parentBridge = bridge;
_performanceLogger = [bridge performanceLogger];
registerPerformanceLoggerHooks(_performanceLogger);
/**
* Set Initial State
*/
_valid = YES;
_loading = YES;
_moduleRegistryCreated = NO;
_pendingCalls = [NSMutableArray new];
_displayLink = [RCTDisplayLink new];
_moduleDataByName = [NSMutableDictionary new];
_moduleClassesByID = [NSMutableArray new];
_moduleDataByID = [NSMutableArray new];
_objCModuleRegistry = [RCTModuleRegistry new];
[_objCModuleRegistry setBridge:self];
_bundleManager = [RCTBundleManager new];
[_bundleManager setBridge:self];
_viewRegistry_DEPRECATED = [RCTViewRegistry new];
[_viewRegistry_DEPRECATED setBridge:self];
_callableJSModules = [RCTCallableJSModules new];
[_callableJSModules setBridge:self];
[RCTBridge setCurrentBridge:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleMemoryWarning)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
RCTLogSetBridgeModuleRegistry(_objCModuleRegistry);
RCTLogSetBridgeCallableJSModules(_callableJSModules);
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
+ (void)runRunLoop
{
@autoreleasepool {
RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[RCTCxxBridge runJSRunLoop] setup", nil);
// copy thread name to pthread name
pthread_setname_np([NSThread currentThread].name.UTF8String);
// Set up a dummy runloop source to avoid spinning
CFRunLoopSourceContext noSpinCtx = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
CFRunLoopSourceRef noSpinSource = CFRunLoopSourceCreate(NULL, 0, &noSpinCtx);
CFRunLoopAddSource(CFRunLoopGetCurrent(), noSpinSource, kCFRunLoopDefaultMode);
CFRelease(noSpinSource);
RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
// run the run loop
while (kCFRunLoopRunStopped !=
CFRunLoopRunInMode(
kCFRunLoopDefaultMode, ((NSDate *)[NSDate distantFuture]).timeIntervalSinceReferenceDate, NO)) {
RCTAssert(NO, @"not reached assertion"); // runloop spun. that's bad.
}
}
}
- (void)_tryAndHandleError:(dispatch_block_t)block
{
NSError *error = tryAndReturnError(block);
if (error) {
[self handleError:error];
}
}
- (void)handleMemoryWarning
{
// We only want to run garbage collector when the loading is finished
// and the instance is valid.
if (!_valid || _loading) {
return;
}
// We need to hold a local retaining pointer to react instance
// in case if some other tread resets it.
auto reactInstance = _reactInstance;
if (reactInstance) {
int unloadLevel = RCTGetMemoryPressureUnloadLevel();
reactInstance->handleMemoryPressure(unloadLevel);
}
}
/**
* Ensure block is run on the JS thread. If we're already on the JS thread, the block will execute synchronously.
* If we're not on the JS thread, the block is dispatched to that thread. Any errors encountered while executing
* the block will go through handleError:
*/
- (void)ensureOnJavaScriptThread:(dispatch_block_t)block
{
RCTAssert(_jsThread, @"This method must not be called before the JS thread is created");
// This does not use _jsMessageThread because it may be called early before the runloop reference is captured
// and _jsMessageThread is valid. _jsMessageThread also doesn't allow us to shortcut the dispatch if we're
// already on the correct thread.
if ([NSThread currentThread] == _jsThread) {
[self _tryAndHandleError:block];
} else {
[self performSelector:@selector(_tryAndHandleError:) onThread:_jsThread withObject:block waitUntilDone:NO];
}
}
- (void)start
{
RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[RCTCxxBridge start]", nil);
[[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptWillStartLoadingNotification
object:_parentBridge
userInfo:@{@"bridge" : self}];
// Set up the JS thread early
_jsThread = [[NSThread alloc] initWithTarget:[self class] selector:@selector(runRunLoop) object:nil];
_jsThread.name = RCTJSThreadName;
_jsThread.qualityOfService = NSOperationQualityOfServiceUserInteractive;
#if RCT_DEBUG
_jsThread.stackSize *= 2;
#endif
[_jsThread start];
dispatch_group_t prepareBridge = dispatch_group_create();
[_performanceLogger markStartForTag:RCTPLNativeModuleInit];
[self registerExtraModules];
// Initialize all native modules that cannot be loaded lazily
(void)[self _initializeModules:RCTGetModuleClasses() withDispatchGroup:prepareBridge lazilyDiscovered:NO];
[self registerExtraLazyModules];
[_performanceLogger markStopForTag:RCTPLNativeModuleInit];
// This doesn't really do anything. The real work happens in initializeBridge.
_reactInstance.reset(new Instance);
__weak RCTCxxBridge *weakSelf = self;
// Prepare executor factory (shared_ptr for copy into block)
std::shared_ptr<JSExecutorFactory> executorFactory;
if (!self.executorClass) {
if ([self.delegate conformsToProtocol:@protocol(RCTCxxBridgeDelegate)]) {
id<RCTCxxBridgeDelegate> cxxDelegate = (id<RCTCxxBridgeDelegate>)self.delegate;
executorFactory = [cxxDelegate jsExecutorFactoryForBridge:self];
}
if (!executorFactory) {
auto installBindings = RCTJSIExecutorRuntimeInstaller(nullptr);
#if RCT_USE_HERMES
executorFactory = std::make_shared<HermesExecutorFactory>(installBindings);
#else
executorFactory = std::make_shared<JSCExecutorFactory>(installBindings);
#endif
}
} else {
id<RCTJavaScriptExecutor> objcExecutor = [self moduleForClass:self.executorClass];
executorFactory.reset(new RCTObjcExecutorFactory(objcExecutor, ^(NSError *error) {
if (error) {
[weakSelf handleError:error];
}
}));
}
/**
* id<RCTCxxBridgeDelegate> jsExecutorFactory may create and assign an id<RCTTurboModuleRegistry> object to
* RCTCxxBridge If id<RCTTurboModuleRegistry> is assigned by this time, eagerly initialize all TurboModules
*/
if (_turboModuleRegistry && RCTTurboModuleEagerInitEnabled()) {
for (NSString *moduleName in [_turboModuleRegistry eagerInitModuleNames]) {
[_turboModuleRegistry moduleForName:[moduleName UTF8String]];
}
for (NSString *moduleName in [_turboModuleRegistry eagerInitMainQueueModuleNames]) {
if (RCTIsMainQueue()) {
[_turboModuleRegistry moduleForName:[moduleName UTF8String]];
} else {
id<RCTTurboModuleRegistry> turboModuleRegistry = _turboModuleRegistry;
dispatch_group_async(prepareBridge, dispatch_get_main_queue(), ^{
[turboModuleRegistry moduleForName:[moduleName UTF8String]];
});
}
}
}
// Dispatch the instance initialization as soon as the initial module metadata has
// been collected (see initModules)
dispatch_group_enter(prepareBridge);
[self ensureOnJavaScriptThread:^{
[weakSelf _initializeBridge:executorFactory];
dispatch_group_leave(prepareBridge);
}];
// Load the source asynchronously, then store it for later execution.
dispatch_group_enter(prepareBridge);
__block NSData *sourceCode;
#if (RCT_DEV | RCT_ENABLE_LOADING_VIEW) && __has_include(<React/RCTDevLoadingViewProtocol.h>)
{
id<RCTDevLoadingViewProtocol> loadingView = [self moduleForName:@"DevLoadingView" lazilyLoadIfNecessary:YES];
[loadingView showWithURL:self.bundleURL];
}
#endif
[self
loadSource:^(NSError *error, RCTSource *source) {
if (error) {
[weakSelf handleError:error];
}
sourceCode = source.data;
dispatch_group_leave(prepareBridge);
}
onProgress:^(RCTLoadingProgress *progressData) {
#if (RCT_DEV | RCT_ENABLE_LOADING_VIEW) && __has_include(<React/RCTDevLoadingViewProtocol.h>)
id<RCTDevLoadingViewProtocol> loadingView = [weakSelf moduleForName:@"DevLoadingView"
lazilyLoadIfNecessary:YES];
[loadingView updateProgress:progressData];
#endif
}];
// Wait for both the modules and source code to have finished loading
dispatch_group_notify(prepareBridge, dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
RCTCxxBridge *strongSelf = weakSelf;
if (sourceCode && strongSelf.loading) {
[strongSelf executeSourceCode:sourceCode sync:NO];
}
});
RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
}
- (void)loadSource:(RCTSourceLoadBlock)_onSourceLoad onProgress:(RCTSourceLoadProgressBlock)onProgress
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotificationName:RCTBridgeWillDownloadScriptNotification object:_parentBridge];
[_performanceLogger markStartForTag:RCTPLScriptDownload];
NSUInteger cookie = RCTProfileBeginAsyncEvent(0, @"JavaScript download", nil);
// Suppress a warning if RCTProfileBeginAsyncEvent gets compiled out
(void)cookie;
RCTPerformanceLogger *performanceLogger = _performanceLogger;
RCTSourceLoadBlock onSourceLoad = ^(NSError *error, RCTSource *source) {
RCTProfileEndAsyncEvent(0, @"native", cookie, @"JavaScript download", @"JS async");
[performanceLogger markStopForTag:RCTPLScriptDownload];
[performanceLogger setValue:source.length forTag:RCTPLBundleSize];
NSDictionary *userInfo = @{
RCTBridgeDidDownloadScriptNotificationSourceKey : source ?: [NSNull null],
RCTBridgeDidDownloadScriptNotificationBridgeDescriptionKey : self->_bridgeDescription ?: [NSNull null],
};
[center postNotificationName:RCTBridgeDidDownloadScriptNotification object:self->_parentBridge userInfo:userInfo];
_onSourceLoad(error, source);
};
if ([self.delegate respondsToSelector:@selector(loadSourceForBridge:onProgress:onComplete:)]) {
[self.delegate loadSourceForBridge:_parentBridge onProgress:onProgress onComplete:onSourceLoad];
} else if ([self.delegate respondsToSelector:@selector(loadSourceForBridge:withBlock:)]) {
[self.delegate loadSourceForBridge:_parentBridge withBlock:onSourceLoad];
} else if (!self.bundleURL) {
NSError *error = RCTErrorWithMessage(
@"No bundle URL present.\n\nMake sure you're running a packager "
"server or have included a .jsbundle file in your application bundle.");
onSourceLoad(error, nil);
} else {
__weak RCTCxxBridge *weakSelf = self;
[RCTJavaScriptLoader loadBundleAtURL:self.bundleURL
onProgress:onProgress
onComplete:^(NSError *error, RCTSource *source) {
if (error) {
[weakSelf handleError:error];
return;
}
onSourceLoad(error, source);
}];
}
}
- (NSArray<Class> *)moduleClasses
{
if (RCT_DEBUG && _valid && _moduleClassesByID == nil) {
RCTLogError(
@"Bridge modules have not yet been initialized. You may be "
"trying to access a module too early in the startup procedure.");
}
return _moduleClassesByID;
}
/**
* Used by RCTUIManager
*/
- (RCTModuleData *)moduleDataForName:(NSString *)moduleName
{
return _moduleDataByName[moduleName];
}
- (id)moduleForName:(NSString *)moduleName
{
return [self moduleForName:moduleName lazilyLoadIfNecessary:NO];
}
- (id)moduleForName:(NSString *)moduleName lazilyLoadIfNecessary:(BOOL)lazilyLoad
{
if (RCTTurboModuleEnabled() && _turboModuleRegistry) {
const char *moduleNameCStr = [moduleName UTF8String];
if (lazilyLoad || [_turboModuleRegistry moduleIsInitialized:moduleNameCStr]) {
id<RCTTurboModule> module = [_turboModuleRegistry moduleForName:moduleNameCStr warnOnLookupFailure:NO];
if (module != nil) {
return module;
}
}
}
if (!lazilyLoad) {
return _moduleDataByName[moduleName].instance;
}
RCTModuleData *moduleData = _moduleDataByName[moduleName];
if (moduleData) {
if (![moduleData isKindOfClass:[RCTModuleData class]]) {
// There is rare race condition where the data stored in the dictionary
// may have been deallocated, which means the module instance is no longer
// usable.
return nil;
}
return moduleData.instance;
}
// Module may not be loaded yet, so attempt to force load it here.
// Do this only if the bridge is still valid.
if (_didInvalidate) {
return nil;
}
const BOOL result = [self.delegate respondsToSelector:@selector(bridge:didNotFindModule:)] &&
[self.delegate bridge:self didNotFindModule:moduleName];
if (result) {
// Try again.
moduleData = _moduleDataByName[moduleName];
#if RCT_DEV
// If the `_moduleDataByName` is nil, it must have been cleared by the reload.
} else if (_moduleDataByName != nil) {
RCTLogError(@"Unable to find module for %@", moduleName);
}
#else
} else {
RCTLogError(@"Unable to find module for %@", moduleName);
}
#endif
return moduleData.instance;
}
- (BOOL)moduleIsInitialized:(Class)moduleClass
{
NSString *moduleName = RCTBridgeModuleNameForClass(moduleClass);
if (_moduleDataByName[moduleName].hasInstance) {
return YES;
}
if (_turboModuleRegistry) {
return [_turboModuleRegistry moduleIsInitialized:[moduleName UTF8String]];
}
return NO;
}
- (id)moduleForClass:(Class)moduleClass
{
return [self moduleForName:RCTBridgeModuleNameForClass(moduleClass) lazilyLoadIfNecessary:YES];
}
- (std::shared_ptr<ModuleRegistry>)_buildModuleRegistryUnlocked
{
if (!self.valid) {
return {};
}
[_performanceLogger markStartForTag:RCTPLNativeModulePrepareConfig];
RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[RCTCxxBridge buildModuleRegistry]", nil);
__weak __typeof(self) weakSelf = self;
ModuleRegistry::ModuleNotFoundCallback moduleNotFoundCallback = ^bool(const std::string &name) {
__strong __typeof(weakSelf) strongSelf = weakSelf;
return [strongSelf.delegate respondsToSelector:@selector(bridge:didNotFindModule:)] &&
[strongSelf.delegate bridge:strongSelf didNotFindModule:@(name.c_str())];
};
auto registry = std::make_shared<ModuleRegistry>(
createNativeModules(_moduleDataByID, self, _reactInstance), moduleNotFoundCallback);
[_performanceLogger markStopForTag:RCTPLNativeModulePrepareConfig];
RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
return registry;
}
- (void)_initializeBridge:(std::shared_ptr<JSExecutorFactory>)executorFactory
{
if (!self.valid) {
return;
}
__weak RCTCxxBridge *weakSelf = self;
_jsMessageThread = std::make_shared<RCTMessageThread>([NSRunLoop currentRunLoop], ^(NSError *error) {
if (error) {
[weakSelf handleError:error];
}
});
RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[RCTCxxBridge initializeBridge:]", nil);
// This can only be false if the bridge was invalidated before startup completed
if (_reactInstance) {
#if RCT_DEV
executorFactory = std::make_shared<GetDescAdapter>(self, executorFactory);
#endif
[self _initializeBridgeLocked:executorFactory];
#if RCT_PROFILE
if (RCTProfileIsProfiling()) {
_reactInstance->setGlobalVariable("__RCTProfileIsProfiling", std::make_unique<JSBigStdString>("true"));
}
#endif
}
RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
}
- (void)_initializeBridgeLocked:(std::shared_ptr<JSExecutorFactory>)executorFactory
{
std::lock_guard<std::mutex> guard(_moduleRegistryLock);
// This is async, but any calls into JS are blocked by the m_syncReady CV in Instance
_reactInstance->initializeBridge(
std::make_unique<RCTInstanceCallback>(self),
executorFactory,
_jsMessageThread,
[self _buildModuleRegistryUnlocked]);
_moduleRegistryCreated = YES;
}
- (void)updateModuleWithInstance:(id<RCTBridgeModule>)instance
{
NSString *const moduleName = RCTBridgeModuleNameForClass([instance class]);
if (moduleName) {
RCTModuleData *const moduleData = _moduleDataByName[moduleName];
if (moduleData) {
moduleData.instance = instance;
}
}
}
- (NSArray<RCTModuleData *> *)registerModulesForClasses:(NSArray<Class> *)moduleClasses
{
return [self _registerModulesForClasses:moduleClasses lazilyDiscovered:NO];
}
- (NSArray<RCTModuleData *> *)_registerModulesForClasses:(NSArray<Class> *)moduleClasses
lazilyDiscovered:(BOOL)lazilyDiscovered
{
RCT_PROFILE_BEGIN_EVENT(
RCTProfileTagAlways, @"-[RCTCxxBridge initModulesWithDispatchGroup:] autoexported moduleData", nil);
NSArray *moduleClassesCopy = [moduleClasses copy];
NSMutableArray<RCTModuleData *> *moduleDataByID = [NSMutableArray arrayWithCapacity:moduleClassesCopy.count];
for (Class moduleClass in moduleClassesCopy) {
if (RCTTurboModuleEnabled() && [moduleClass conformsToProtocol:@protocol(RCTTurboModule)]) {
continue;
}
NSString *moduleName = RCTBridgeModuleNameForClass(moduleClass);
// Check for module name collisions
RCTModuleData *moduleData = _moduleDataByName[moduleName];
if (moduleData) {
if (moduleData.hasInstance || lazilyDiscovered) {
// Existing module was preregistered, so it takes precedence
continue;
} else if ([moduleClass new] == nil) {
// The new module returned nil from init, so use the old module
continue;
} else if ([moduleData.moduleClass new] != nil) {
// Both modules were non-nil, so it's unclear which should take precedence
RCTLogWarn(
@"Attempted to register RCTBridgeModule class %@ for the "
"name '%@', but name was already registered by class %@",
moduleClass,
moduleName,
moduleData.moduleClass);
}
}
// Instantiate moduleData
// TODO #13258411: can we defer this until config generation?
int32_t moduleDataId = getUniqueId();
BridgeNativeModulePerfLogger::moduleDataCreateStart([moduleName UTF8String], moduleDataId);
moduleData = [[RCTModuleData alloc] initWithModuleClass:moduleClass
bridge:self
moduleRegistry:_objCModuleRegistry
viewRegistry_DEPRECATED:_viewRegistry_DEPRECATED
bundleManager:_bundleManager
callableJSModules:_callableJSModules];
BridgeNativeModulePerfLogger::moduleDataCreateEnd([moduleName UTF8String], moduleDataId);
_moduleDataByName[moduleName] = moduleData;
[_moduleClassesByID addObject:moduleClass];
[moduleDataByID addObject:moduleData];
}
[_moduleDataByID addObjectsFromArray:moduleDataByID];
RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
return moduleDataByID;
}
- (void)registerExtraModules
{
RCT_PROFILE_BEGIN_EVENT(RCTProfileTagAlways, @"-[RCTCxxBridge initModulesWithDispatchGroup:] extraModules", nil);
NSArray<id<RCTBridgeModule>> *appExtraModules = nil;
if ([self.delegate respondsToSelector:@selector(extraModulesForBridge:)]) {
appExtraModules = [self.delegate extraModulesForBridge:_parentBridge];
} else if (self.moduleProvider) {
appExtraModules = self.moduleProvider();
}
NSMutableArray<id<RCTBridgeModule>> *extraModules = [NSMutableArray new];
// Prevent TurboModules from appearing the the NativeModule system
for (id<RCTBridgeModule> module in appExtraModules) {
if (!(RCTTurboModuleEnabled() && [module conformsToProtocol:@protocol(RCTTurboModule)])) {
[extraModules addObject:module];
}
}
RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
RCT_PROFILE_BEGIN_EVENT(
RCTProfileTagAlways, @"-[RCTCxxBridge initModulesWithDispatchGroup:] preinitialized moduleData", nil);
// Set up moduleData for pre-initialized module instances
for (id<RCTBridgeModule> module in extraModules) {
Class moduleClass = [module class];
NSString *moduleName = RCTBridgeModuleNameForClass(moduleClass);
if (RCT_DEBUG) {
// Check for name collisions between preregistered modules
RCTModuleData *moduleData = _moduleDataByName[moduleName];
if (moduleData) {
RCTLogError(
@"Attempted to register RCTBridgeModule class %@ for the "
"name '%@', but name was already registered by class %@",
moduleClass,
moduleName,
moduleData.moduleClass);
continue;
}
}
if (RCTTurboModuleEnabled() && [module conformsToProtocol:@protocol(RCTTurboModule)]) {
#if RCT_DEBUG
// TODO: don't ask for extra module for when TurboModule is enabled.
RCTLogError(
@"NativeModule '%@' was marked as TurboModule, but provided as an extra NativeModule "
"by the class '%@', ignoring.",
moduleName,
moduleClass);
#endif
continue;
}
// Instantiate moduleData container
int32_t moduleDataId = getUniqueId();
BridgeNativeModulePerfLogger::moduleDataCreateStart([moduleName UTF8String], moduleDataId);
RCTModuleData *moduleData = [[RCTModuleData alloc] initWithModuleInstance:module
bridge:self
moduleRegistry:_objCModuleRegistry
viewRegistry_DEPRECATED:_viewRegistry_DEPRECATED
bundleManager:_bundleManager
callableJSModules:_callableJSModules];
BridgeNativeModulePerfLogger::moduleDataCreateEnd([moduleName UTF8String], moduleDataId);
_moduleDataByName[moduleName] = moduleData;
[_moduleClassesByID addObject:moduleClass];
[_moduleDataByID addObject:moduleData];
}
RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
}
- (void)registerExtraLazyModules
{
#if RCT_DEBUG
// This is debug-only and only when Chrome is attached, since it expects all modules to be already
// available on start up. Otherwise, we can let the lazy module discovery to load them on demand.
Class executorClass = [_parentBridge executorClass];
if (executorClass && [NSStringFromClass(executorClass) isEqualToString:@"RCTWebSocketExecutor"]) {
NSDictionary<NSString *, Class> *moduleClasses = nil;
if ([self.delegate respondsToSelector:@selector(extraLazyModuleClassesForBridge:)]) {
moduleClasses = [self.delegate extraLazyModuleClassesForBridge:_parentBridge];
}
if (!moduleClasses) {
return;
}
// This logic is mostly copied from `registerModulesForClasses:`, but with one difference:
// we must use the names provided by the delegate method here.
for (NSString *moduleName in moduleClasses) {
Class moduleClass = moduleClasses[moduleName];
if (RCTTurboModuleEnabled() && [moduleClass conformsToProtocol:@protocol(RCTTurboModule)]) {
continue;
}
// Check for module name collisions
RCTModuleData *moduleData = _moduleDataByName[moduleName];
if (moduleData) {
if (moduleData.hasInstance) {
// Existing module was preregistered, so it takes precedence
continue;
} else if ([moduleClass new] == nil) {
// The new module returned nil from init, so use the old module
continue;
} else if ([moduleData.moduleClass new] != nil) {
// Use existing module since it was already loaded but not yet instantiated.
continue;
}
}
int32_t moduleDataId = getUniqueId();
BridgeNativeModulePerfLogger::moduleDataCreateStart([moduleName UTF8String], moduleDataId);
moduleData = [[RCTModuleData alloc] initWithModuleClass:moduleClass
bridge:self
moduleRegistry:_objCModuleRegistry
viewRegistry_DEPRECATED:_viewRegistry_DEPRECATED
bundleManager:_bundleManager
callableJSModules:_callableJSModules];
BridgeNativeModulePerfLogger::moduleDataCreateEnd([moduleName UTF8String], moduleDataId);
_moduleDataByName[moduleName] = moduleData;
[_moduleClassesByID addObject:moduleClass];
[_moduleDataByID addObject:moduleData];
}
}
#endif
}
- (NSArray<RCTModuleData *> *)_initializeModules:(NSArray<Class> *)modules
withDispatchGroup:(dispatch_group_t)dispatchGroup
lazilyDiscovered:(BOOL)lazilyDiscovered
{
// Set up moduleData for automatically-exported modules
NSArray<RCTModuleData *> *moduleDataById = [self _registerModulesForClasses:modules
lazilyDiscovered:lazilyDiscovered];
if (lazilyDiscovered) {
#if RCT_DEBUG
// Lazily discovered modules do not require instantiation here,
// as they are not allowed to have pre-instantiated instance
// and must not require the main queue.
for (RCTModuleData *moduleData in moduleDataById) {
RCTAssert(
!(moduleData.requiresMainQueueSetup || moduleData.hasInstance),
@"Module \'%@\' requires initialization on the Main Queue or has pre-instantiated, which is not supported for the lazily discovered modules.",
moduleData.name);
}
#endif
} else {
RCT_PROFILE_BEGIN_EVENT(
RCTProfileTagAlways, @"-[RCTCxxBridge initModulesWithDispatchGroup:] moduleData.hasInstance", nil);
// Dispatch module init onto main thread for those modules that require it
// For non-lazily discovered modules we run through the entire set of modules
// that we have, otherwise some modules coming from the delegate
// or module provider block, will not be properly instantiated.
for (RCTModuleData *moduleData in _moduleDataByID) {
if (moduleData.hasInstance && (!moduleData.requiresMainQueueSetup || RCTIsMainQueue())) {
// Modules that were pre-initialized should ideally be set up before
// bridge init has finished, otherwise the caller may try to access the
// module directly rather than via `[bridge moduleForClass:]`, which won't
// trigger the lazy initialization process. If the module cannot safely be
// set up on the current thread, it will instead be async dispatched
// to the main thread to be set up in _prepareModulesWithDispatchGroup:.
(void)[moduleData instance];
}
}
RCT_PROFILE_END_EVENT(RCTProfileTagAlways, @"");
// From this point on, RCTDidInitializeModuleNotification notifications will
// be sent the first time a module is accessed.
_moduleSetupComplete = YES;
[self _prepareModulesWithDispatchGroup:dispatchGroup];
}
#if RCT_PROFILE
if (RCTProfileIsProfiling()) {
// Depends on moduleDataByID being loaded
RCTProfileHookModules(self);
}
#endif
return moduleDataById;
}
- (void)registerAdditionalModuleClasses:(NSArray<Class> *)modules
{
std::lock_guard<std::mutex> guard(_moduleRegistryLock);
if (_moduleRegistryCreated) {
NSArray<RCTModuleData *> *newModules = [self _initializeModules:modules
withDispatchGroup:NULL
lazilyDiscovered:YES];
assert(_reactInstance); // at this point you must have reactInstance as you already called
// reactInstance->initialzeBridge
_reactInstance->getModuleRegistry().registerModules(createNativeModules(newModules, self, _reactInstance));
} else {
[self registerModulesForClasses:modules];
}
}
- (void)_prepareModulesWithDispatchGroup:(dispatch_group_t)dispatchGroup
{
RCT_PROFILE_BEGIN_EVENT(0, @"-[RCTCxxBridge _prepareModulesWithDispatchGroup]", nil);