forked from Feodor2/Mypal68
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsComponentManager.cpp
2003 lines (1676 loc) · 61.5 KB
/
nsComponentManager.cpp
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <stdlib.h>
#include "nscore.h"
#include "nsISupports.h"
#include "nspr.h"
#include "nsCRT.h" // for atoll
#include "StaticComponents.h"
#include "nsCategoryManager.h"
#include "nsCOMPtr.h"
#include "nsComponentManager.h"
#include "nsDirectoryService.h"
#include "nsDirectoryServiceDefs.h"
#include "nsCategoryManager.h"
#include "nsLayoutModule.h"
#include "mozilla/MemoryReporting.h"
#include "nsIObserverService.h"
#include "nsIStringEnumerator.h"
#include "nsXPCOM.h"
#include "nsXPCOMPrivate.h"
#include "nsISupportsPrimitives.h"
#include "nsLocalFile.h"
#include "nsReadableUtils.h"
#include "nsString.h"
#include "prcmon.h"
#include "nsThreadManager.h"
#include "nsThreadUtils.h"
#include "prthread.h"
#include "private/pprthred.h"
#include "nsTArray.h"
#include "prio.h"
#include "ManifestParser.h"
#include "nsNetUtil.h"
#include "mozilla/Services.h"
#include "mozJSComponentLoader.h"
#include "mozilla/GenericFactory.h"
#include "nsSupportsPrimitives.h"
#include "nsArray.h"
#include "nsIMutableArray.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/FileUtils.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/URLPreloader.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Variant.h"
#include "nsDataHashtable.h"
#include <new> // for placement new
#include "mozilla/Omnijar.h"
#include "mozilla/Logging.h"
#include "LogModulePrefWatcher.h"
#ifdef MOZ_MEMORY
# include "mozmemory.h"
#endif
using namespace mozilla;
using namespace mozilla::xpcom;
static LazyLogModule nsComponentManagerLog("nsComponentManager");
#if 0
# define SHOW_DENIED_ON_SHUTDOWN
# define SHOW_CI_ON_EXISTING_SERVICE
#endif
namespace {
class AutoIDString : public nsAutoCStringN<NSID_LENGTH> {
public:
explicit AutoIDString(const nsID& aID) {
SetLength(NSID_LENGTH - 1);
aID.ToProvidedString(
*reinterpret_cast<char(*)[NSID_LENGTH]>(BeginWriting()));
}
};
} // namespace
namespace mozilla {
namespace xpcom {
using ProcessSelector = Module::ProcessSelector;
// Note: These must be kept in sync with the ProcessSelector definition in
// Module.h.
bool ProcessSelectorMatches(ProcessSelector aSelector) {
GeckoProcessType type = XRE_GetProcessType();
if (type == GeckoProcessType_GPU) {
return !!(aSelector & Module::ALLOW_IN_GPU_PROCESS);
}
if (type == GeckoProcessType_RDD) {
return !!(aSelector & Module::ALLOW_IN_RDD_PROCESS);
}
if (type == GeckoProcessType_Socket) {
return !!(aSelector & (Module::ALLOW_IN_SOCKET_PROCESS));
}
if (type == GeckoProcessType_VR) {
return !!(aSelector & Module::ALLOW_IN_VR_PROCESS);
}
if (aSelector & Module::MAIN_PROCESS_ONLY) {
return type == GeckoProcessType_Default;
}
if (aSelector & Module::CONTENT_PROCESS_ONLY) {
return type == GeckoProcessType_Content;
}
return true;
}
static bool gProcessMatchTable[Module::kMaxProcessSelector + 1];
bool FastProcessSelectorMatches(ProcessSelector aSelector) {
return gProcessMatchTable[size_t(aSelector)];
}
} // namespace xpcom
} // namespace mozilla
namespace {
/**
* A wrapper simple wrapper class, which can hold either a dynamic
* nsFactoryEntry instance, or a static StaticModule entry, and transparently
* forwards method calls to the wrapped object.
*
* This allows the same code to work with either static or dynamic modules
* without caring about the difference.
*/
class MOZ_STACK_CLASS EntryWrapper final {
public:
explicit EntryWrapper(nsFactoryEntry* aEntry) : mEntry(aEntry) {}
explicit EntryWrapper(const StaticModule* aEntry) : mEntry(aEntry) {}
#define MATCH(type, ifFactory, ifStatic) \
struct Matcher { \
type operator()(nsFactoryEntry* entry) { ifFactory; } \
type operator()(const StaticModule* entry) { ifStatic; } \
}; \
return mEntry.match((Matcher()))
const nsID& CID() {
MATCH(const nsID&, return *entry->mCIDEntry->cid, return entry->CID());
}
already_AddRefed<nsIFactory> GetFactory() {
MATCH(already_AddRefed<nsIFactory>, return entry->GetFactory(),
return entry->GetFactory());
}
/**
* Creates an instance of the underlying component. This should be used in
* preference to GetFactory()->CreateInstance() where appropriate, since it
* side-steps the necessity of creating a nsIFactory instance for static
* modules.
*/
nsresult CreateInstance(nsISupports* aOuter, const nsIID& aIID,
void** aResult) {
if (mEntry.is<nsFactoryEntry*>()) {
return mEntry.as<nsFactoryEntry*>()->CreateInstance(aOuter, aIID,
aResult);
}
return mEntry.as<const StaticModule*>()->CreateInstance(aOuter, aIID,
aResult);
}
/**
* Returns the cached service instance for this entry, if any. This should
* only be accessed while mLock is held.
*/
nsISupports* ServiceInstance() {
MATCH(nsISupports*, return entry->mServiceObject,
return entry->ServiceInstance());
}
void SetServiceInstance(already_AddRefed<nsISupports> aInst) {
if (mEntry.is<nsFactoryEntry*>()) {
mEntry.as<nsFactoryEntry*>()->mServiceObject = aInst;
} else {
return mEntry.as<const StaticModule*>()->SetServiceInstance(
std::move(aInst));
}
}
/**
* Returns the description string for the module this entry belongs to. For
* static entries, always returns "<unknown module>".
*/
nsCString ModuleDescription() {
MATCH(nsCString,
return entry->mModule ? entry->mModule->Description()
: "<unknown module>"_ns,
return "<unknown module>"_ns);
}
private:
Variant<nsFactoryEntry*, const StaticModule*> mEntry;
};
// GetService and a few other functions need to exit their mutex mid-function
// without reentering it later in the block. This class supports that
// style of early-exit that MutexAutoUnlock doesn't.
class MOZ_STACK_CLASS MutexLock {
public:
explicit MutexLock(SafeMutex& aMutex) : mMutex(aMutex), mLocked(false) {
Lock();
}
~MutexLock() {
if (mLocked) {
Unlock();
}
}
void Lock() {
NS_ASSERTION(!mLocked, "Re-entering a mutex");
mMutex.Lock();
mLocked = true;
}
void Unlock() {
NS_ASSERTION(mLocked, "Exiting a mutex that isn't held!");
mMutex.Unlock();
mLocked = false;
}
private:
SafeMutex& mMutex;
bool mLocked;
};
} // namespace
// this is safe to call during InitXPCOM
static already_AddRefed<nsIFile> GetLocationFromDirectoryService(
const char* aProp) {
nsCOMPtr<nsIProperties> directoryService;
nsDirectoryService::Create(nullptr, NS_GET_IID(nsIProperties),
getter_AddRefs(directoryService));
if (!directoryService) {
return nullptr;
}
nsCOMPtr<nsIFile> file;
nsresult rv =
directoryService->Get(aProp, NS_GET_IID(nsIFile), getter_AddRefs(file));
if (NS_FAILED(rv)) {
return nullptr;
}
return file.forget();
}
static already_AddRefed<nsIFile> CloneAndAppend(nsIFile* aBase,
const nsACString& aAppend) {
nsCOMPtr<nsIFile> f;
aBase->Clone(getter_AddRefs(f));
if (!f) {
return nullptr;
}
f->AppendNative(aAppend);
return f.forget();
}
////////////////////////////////////////////////////////////////////////////////
// nsComponentManagerImpl
////////////////////////////////////////////////////////////////////////////////
nsresult nsComponentManagerImpl::Create(nsISupports* aOuter, REFNSIID aIID,
void** aResult) {
if (aOuter) {
return NS_ERROR_NO_AGGREGATION;
}
if (!gComponentManager) {
return NS_ERROR_FAILURE;
}
return gComponentManager->QueryInterface(aIID, aResult);
}
static const int CONTRACTID_HASHTABLE_INITIAL_LENGTH = 32;
nsComponentManagerImpl::nsComponentManagerImpl()
: mFactories(CONTRACTID_HASHTABLE_INITIAL_LENGTH),
mContractIDs(CONTRACTID_HASHTABLE_INITIAL_LENGTH),
mLock("nsComponentManagerImpl.mLock"),
mStatus(NOT_INITIALIZED) {}
extern const mozilla::Module kNeckoModule;
extern const mozilla::Module kPowerManagerModule;
extern const mozilla::Module kContentProcessWidgetModule;
#if defined(MOZ_WIDGET_COCOA) || defined(MOZ_WIDGET_UIKIT)
extern const mozilla::Module kWidgetModule;
#endif
extern const mozilla::Module kLayoutModule;
extern const mozilla::Module kKeyValueModule;
extern const mozilla::Module kXREModule;
extern const mozilla::Module kEmbeddingModule;
static nsTArray<const mozilla::Module*>* sExtraStaticModules;
/* static */
void nsComponentManagerImpl::InitializeStaticModules() {
if (sExtraStaticModules) {
return;
}
sExtraStaticModules = new nsTArray<const mozilla::Module*>;
}
nsTArray<nsComponentManagerImpl::ComponentLocation>*
nsComponentManagerImpl::sModuleLocations;
/* static */
void nsComponentManagerImpl::InitializeModuleLocations() {
if (sModuleLocations) {
return;
}
sModuleLocations = new nsTArray<ComponentLocation>;
}
nsresult nsComponentManagerImpl::Init() {
{
gProcessMatchTable[size_t(ProcessSelector::ANY_PROCESS)] =
ProcessSelectorMatches(ProcessSelector::ANY_PROCESS);
gProcessMatchTable[size_t(ProcessSelector::MAIN_PROCESS_ONLY)] =
ProcessSelectorMatches(ProcessSelector::MAIN_PROCESS_ONLY);
gProcessMatchTable[size_t(ProcessSelector::CONTENT_PROCESS_ONLY)] =
ProcessSelectorMatches(ProcessSelector::CONTENT_PROCESS_ONLY);
gProcessMatchTable[size_t(ProcessSelector::ALLOW_IN_GPU_PROCESS)] =
ProcessSelectorMatches(ProcessSelector::ALLOW_IN_GPU_PROCESS);
gProcessMatchTable[size_t(ProcessSelector::ALLOW_IN_VR_PROCESS)] =
ProcessSelectorMatches(ProcessSelector::ALLOW_IN_VR_PROCESS);
gProcessMatchTable[size_t(ProcessSelector::ALLOW_IN_SOCKET_PROCESS)] =
ProcessSelectorMatches(ProcessSelector::ALLOW_IN_SOCKET_PROCESS);
gProcessMatchTable[size_t(ProcessSelector::ALLOW_IN_RDD_PROCESS)] =
ProcessSelectorMatches(ProcessSelector::ALLOW_IN_RDD_PROCESS);
gProcessMatchTable[size_t(ProcessSelector::ALLOW_IN_GPU_AND_VR_PROCESS)] =
ProcessSelectorMatches(ProcessSelector::ALLOW_IN_GPU_AND_VR_PROCESS);
gProcessMatchTable[size_t(
ProcessSelector::ALLOW_IN_GPU_AND_SOCKET_PROCESS)] =
ProcessSelectorMatches(
ProcessSelector::ALLOW_IN_GPU_AND_SOCKET_PROCESS);
gProcessMatchTable[size_t(
ProcessSelector::ALLOW_IN_GPU_VR_AND_SOCKET_PROCESS)] =
ProcessSelectorMatches(
ProcessSelector::ALLOW_IN_GPU_VR_AND_SOCKET_PROCESS);
gProcessMatchTable[size_t(
ProcessSelector::ALLOW_IN_RDD_AND_SOCKET_PROCESS)] =
ProcessSelectorMatches(
ProcessSelector::ALLOW_IN_RDD_AND_SOCKET_PROCESS);
gProcessMatchTable[size_t(
ProcessSelector::ALLOW_IN_GPU_RDD_AND_SOCKET_PROCESS)] =
ProcessSelectorMatches(
ProcessSelector::ALLOW_IN_GPU_RDD_AND_SOCKET_PROCESS);
gProcessMatchTable[size_t(
ProcessSelector::ALLOW_IN_GPU_RDD_VR_AND_SOCKET_PROCESS)] =
ProcessSelectorMatches(
ProcessSelector::ALLOW_IN_GPU_RDD_VR_AND_SOCKET_PROCESS);
}
MOZ_ASSERT(NOT_INITIALIZED == mStatus);
nsCOMPtr<nsIFile> greDir = GetLocationFromDirectoryService(NS_GRE_DIR);
nsCOMPtr<nsIFile> appDir =
GetLocationFromDirectoryService(NS_XPCOM_CURRENT_PROCESS_DIR);
InitializeStaticModules();
nsCategoryManager::GetSingleton()->SuppressNotifications(true);
RegisterModule(&kXPCOMModule);
RegisterModule(&kNeckoModule);
RegisterModule(&kPowerManagerModule);
RegisterModule(&kContentProcessWidgetModule);
#if defined(MOZ_WIDGET_COCOA) || defined(MOZ_WIDGET_UIKIT)
RegisterModule(&kWidgetModule);
#endif
RegisterModule(&kLayoutModule);
RegisterModule(&kKeyValueModule);
RegisterModule(&kXREModule);
RegisterModule(&kEmbeddingModule);
for (uint32_t i = 0; i < sExtraStaticModules->Length(); ++i) {
RegisterModule((*sExtraStaticModules)[i]);
}
auto* catMan = nsCategoryManager::GetSingleton();
for (const auto& cat : gStaticCategories) {
for (const auto& entry : cat) {
if (entry.Active()) {
catMan->AddCategoryEntry(cat.Name(), entry.Entry(), entry.Value());
}
}
}
bool loadChromeManifests;
switch (XRE_GetProcessType()) {
// We are going to assume that only a select few (see below) process types
// want to load chrome manifests, and that any new process types will not
// want to load them, because they're not going to be executing JS.
case GeckoProcessType_RemoteSandboxBroker:
default:
loadChromeManifests = false;
break;
// XXX The check this code replaced implicitly let through all of these
// process types, but presumably only the default (parent) and content
// processes really need chrome manifests...?
case GeckoProcessType_Default:
case GeckoProcessType_Plugin:
case GeckoProcessType_Content:
case GeckoProcessType_IPDLUnitTest:
case GeckoProcessType_GMPlugin:
loadChromeManifests = true;
break;
}
if (loadChromeManifests) {
// This needs to be called very early, before anything in nsLayoutModule is
// used, and before any calls are made into the JS engine.
nsLayoutModuleInitialize();
mJSLoaderReady = true;
// The overall order in which chrome.manifests are expected to be treated
// is the following:
// - greDir's omni.ja or greDir
// - appDir's omni.ja or appDir
InitializeModuleLocations();
ComponentLocation* cl = sModuleLocations->AppendElement();
cl->type = NS_APP_LOCATION;
RefPtr<nsZipArchive> greOmnijar =
mozilla::Omnijar::GetReader(mozilla::Omnijar::GRE);
if (greOmnijar) {
cl->location.Init(greOmnijar, "chrome.manifest");
} else {
nsCOMPtr<nsIFile> lf = CloneAndAppend(greDir, "chrome.manifest"_ns);
cl->location.Init(lf);
}
RefPtr<nsZipArchive> appOmnijar =
mozilla::Omnijar::GetReader(mozilla::Omnijar::APP);
if (appOmnijar) {
cl = sModuleLocations->AppendElement();
cl->type = NS_APP_LOCATION;
cl->location.Init(appOmnijar, "chrome.manifest");
} else {
bool equals = false;
appDir->Equals(greDir, &equals);
if (!equals) {
cl = sModuleLocations->AppendElement();
cl->type = NS_APP_LOCATION;
nsCOMPtr<nsIFile> lf = CloneAndAppend(appDir, "chrome.manifest"_ns);
cl->location.Init(lf);
}
}
RereadChromeManifests(false);
}
nsCategoryManager::GetSingleton()->SuppressNotifications(false);
RegisterWeakMemoryReporter(this);
// NB: The logging preference watcher needs to be registered late enough in
// startup that it's okay to use the preference system, but also as soon as
// possible so that log modules enabled via preferences are turned on as
// early as possible.
//
// We can't initialize the preference watcher when the log module manager is
// initialized, as a number of things attempt to start logging before the
// preference system is initialized.
//
// The preference system is registered as a component so at this point during
// component manager initialization we know it is setup and we can register
// for notifications.
LogModulePrefWatcher::RegisterPrefWatcher();
// Unfortunately, we can't register the nsCategoryManager memory reporter
// in its constructor (which is triggered by the GetSingleton() call
// above) because the memory reporter manager isn't initialized at that
// point. So we wait until now.
nsCategoryManager::GetSingleton()->InitMemoryReporter();
MOZ_LOG(nsComponentManagerLog, LogLevel::Debug,
("nsComponentManager: Initialized."));
mStatus = NORMAL;
MOZ_ASSERT(!XRE_IsContentProcess() ||
mFactories.Count() > CONTRACTID_HASHTABLE_INITIAL_LENGTH / 3,
"Initial component hashtable size is too large");
return NS_OK;
}
static const int kModuleVersionWithSelector = 51;
template <typename T>
static void AssertNotMallocAllocated(T* aPtr) {
#if defined(DEBUG) && defined(MOZ_MEMORY)
jemalloc_ptr_info_t info;
jemalloc_ptr_info((void*)aPtr, &info);
MOZ_ASSERT(info.tag == TagUnknown);
#endif
}
template <typename T>
static void AssertNotStackAllocated(T* aPtr) {
// On all of our supported platforms, the stack grows down. Any address
// located below the address of our argument is therefore guaranteed not to be
// stack-allocated by the caller.
//
// For addresses above our argument, things get trickier. The main thread
// stack is traditionally placed at the top of the program's address space,
// but that is becoming less reliable as more and more systems adopt address
// space layout randomization strategies, so we have to guess how much space
// above our argument pointer we need to care about.
//
// On most systems, we're guaranteed at least several KiB at the top of each
// stack for TLS. We'd probably be safe assuming at least 4KiB in the stack
// segment above our argument address, but safer is... well, safer.
//
// For threads with huge stacks, it's theoretically possible that we could
// wind up being passed a stack-allocated string from farther up the stack,
// but this is a best-effort thing, so we'll assume we only care about the
// immediate caller. For that case, max 2KiB per stack frame is probably a
// reasonable guess most of the time, and is less than the ~4KiB that we
// expect for TLS, so go with that to avoid the risk of bumping into heap
// data just above the stack.
#ifdef DEBUG
static constexpr size_t kFuzz = 2048;
MOZ_ASSERT(uintptr_t(aPtr) < uintptr_t(&aPtr) ||
uintptr_t(aPtr) > uintptr_t(&aPtr) + kFuzz);
#endif
}
static inline nsCString AsLiteralCString(const char* aStr) {
AssertNotMallocAllocated(aStr);
AssertNotStackAllocated(aStr);
nsCString str;
str.AssignLiteral(aStr, strlen(aStr));
return str;
}
void nsComponentManagerImpl::RegisterModule(const mozilla::Module* aModule) {
mLock.AssertNotCurrentThreadOwns();
if (aModule->mVersion >= kModuleVersionWithSelector &&
!ProcessSelectorMatches(aModule->selector)) {
return;
}
{
// Scope the monitor so that we don't hold it while calling into the
// category manager.
MutexLock lock(mLock);
KnownModule* m = new KnownModule(aModule);
mKnownStaticModules.AppendElement(m);
if (aModule->mCIDs) {
const mozilla::Module::CIDEntry* entry;
for (entry = aModule->mCIDs; entry->cid; ++entry) {
RegisterCIDEntryLocked(entry, m);
}
}
if (aModule->mContractIDs) {
const mozilla::Module::ContractIDEntry* entry;
for (entry = aModule->mContractIDs; entry->contractid; ++entry) {
RegisterContractIDLocked(entry);
}
MOZ_ASSERT(!entry->cid, "Incorrectly terminated contract list");
}
}
if (aModule->mCategoryEntries) {
const mozilla::Module::CategoryEntry* entry;
for (entry = aModule->mCategoryEntries; entry->category; ++entry)
nsCategoryManager::GetSingleton()->AddCategoryEntry(
AsLiteralCString(entry->category), AsLiteralCString(entry->entry),
AsLiteralCString(entry->value));
}
}
void nsComponentManagerImpl::RegisterCIDEntryLocked(
const mozilla::Module::CIDEntry* aEntry, KnownModule* aModule) {
mLock.AssertCurrentThreadOwns();
if (!ProcessSelectorMatches(aEntry->processSelector)) {
return;
}
#ifdef DEBUG
// If we're still in the static initialization phase, check that we're not
// registering something that was already registered.
if (mStatus != NORMAL) {
if (StaticComponents::LookupByCID(*aEntry->cid)) {
MOZ_CRASH_UNSAFE_PRINTF(
"While registering XPCOM module %s, trying to re-register CID '%s' "
"already registered by a static component.",
aModule->Description().get(), AutoIDString(*aEntry->cid).get());
}
}
#endif
mFactories.WithEntryHandle(aEntry->cid, [&](auto&& entry) {
if (entry) {
nsFactoryEntry* f = entry.Data();
NS_WARNING("Re-registering a CID?");
nsCString existing;
if (f->mModule) {
existing = f->mModule->Description();
} else {
existing = "<unknown module>";
}
SafeMutexAutoUnlock unlock(mLock);
LogMessage(
"While registering XPCOM module %s, trying to re-register CID '%s' "
"already registered by %s.",
aModule->Description().get(), AutoIDString(*aEntry->cid).get(),
existing.get());
} else {
entry.Insert(new nsFactoryEntry(aEntry, aModule));
}
});
}
void nsComponentManagerImpl::RegisterContractIDLocked(
const mozilla::Module::ContractIDEntry* aEntry) {
mLock.AssertCurrentThreadOwns();
if (!ProcessSelectorMatches(aEntry->processSelector)) {
return;
}
#ifdef DEBUG
// If we're still in the static initialization phase, check that we're not
// registering something that was already registered.
if (mStatus != NORMAL) {
if (const StaticModule* module = StaticComponents::LookupByContractID(
nsAutoCString(aEntry->contractid))) {
MOZ_CRASH_UNSAFE_PRINTF(
"Could not map contract ID '%s' to CID %s because it is already "
"mapped to CID %s.",
aEntry->contractid, AutoIDString(*aEntry->cid).get(),
AutoIDString(module->CID()).get());
}
}
#endif
nsFactoryEntry* f = mFactories.Get(aEntry->cid);
if (!f) {
NS_WARNING("No CID found when attempting to map contract ID");
SafeMutexAutoUnlock unlock(mLock);
LogMessage(
"Could not map contract ID '%s' to CID %s because no implementation of "
"the CID is registered.",
aEntry->contractid, AutoIDString(*aEntry->cid).get());
return;
}
mContractIDs.Put(AsLiteralCString(aEntry->contractid), f);
}
static void CutExtension(nsCString& aPath) {
int32_t dotPos = aPath.RFindChar('.');
if (kNotFound == dotPos) {
aPath.Truncate();
} else {
aPath.Cut(0, dotPos + 1);
}
}
static void DoRegisterManifest(NSLocationType aType, FileLocation& aFile,
bool aChromeOnly) {
auto result = URLPreloader::Read(aFile);
if (result.isOk()) {
nsCString buf(result.unwrap());
ParseManifest(aType, aFile, buf.BeginWriting(), aChromeOnly);
} else if (NS_BOOTSTRAPPED_LOCATION != aType) {
nsCString uri;
aFile.GetURIString(uri);
LogMessage("Could not read chrome manifest '%s'.", uri.get());
}
}
void nsComponentManagerImpl::RegisterManifest(NSLocationType aType,
FileLocation& aFile,
bool aChromeOnly) {
DoRegisterManifest(aType, aFile, aChromeOnly);
}
void nsComponentManagerImpl::ManifestManifest(ManifestProcessingContext& aCx,
int aLineNo, char* const* aArgv) {
char* file = aArgv[0];
FileLocation f(aCx.mFile, file);
RegisterManifest(aCx.mType, f, aCx.mChromeOnly);
}
void nsComponentManagerImpl::ManifestComponent(ManifestProcessingContext& aCx,
int aLineNo,
char* const* aArgv) {
mLock.AssertNotCurrentThreadOwns();
char* id = aArgv[0];
char* file = aArgv[1];
nsID cid;
if (!cid.Parse(id)) {
LogMessageWithContext(aCx.mFile, aLineNo, "Malformed CID: '%s'.", id);
return;
}
// Precompute the hash/file data outside of the lock
FileLocation fl(aCx.mFile, file);
nsCString hash;
fl.GetURIString(hash);
MutexLock lock(mLock);
if (Maybe<EntryWrapper> f = LookupByCID(lock, cid)) {
nsCString existing(f->ModuleDescription());
lock.Unlock();
LogMessageWithContext(
aCx.mFile, aLineNo,
"Trying to re-register CID '%s' already registered by %s.",
AutoIDString(cid).get(), existing.get());
return;
}
KnownModule* km;
km = mKnownModules.Get(hash);
if (!km) {
km = new KnownModule(fl);
mKnownModules.Put(hash, km);
}
void* place = mArena.Allocate(sizeof(nsCID));
nsID* permanentCID = static_cast<nsID*>(place);
*permanentCID = cid;
place = mArena.Allocate(sizeof(mozilla::Module::CIDEntry));
auto* e = new (KnownNotNull, place) mozilla::Module::CIDEntry();
e->cid = permanentCID;
mFactories.Put(permanentCID, new nsFactoryEntry(e, km));
}
void nsComponentManagerImpl::ManifestContract(ManifestProcessingContext& aCx,
int aLineNo, char* const* aArgv) {
mLock.AssertNotCurrentThreadOwns();
char* contract = aArgv[0];
char* id = aArgv[1];
nsID cid;
if (!cid.Parse(id)) {
LogMessageWithContext(aCx.mFile, aLineNo, "Malformed CID: '%s'.", id);
return;
}
MutexLock lock(mLock);
nsFactoryEntry* f = mFactories.Get(&cid);
if (!f) {
lock.Unlock();
LogMessageWithContext(aCx.mFile, aLineNo,
"Could not map contract ID '%s' to CID %s because no "
"implementation of the CID is registered.",
contract, id);
return;
}
nsDependentCString contractString(contract);
StaticComponents::InvalidateContractID(nsDependentCString(contractString));
mContractIDs.Put(contractString, f);
}
void nsComponentManagerImpl::ManifestCategory(ManifestProcessingContext& aCx,
int aLineNo, char* const* aArgv) {
char* category = aArgv[0];
char* key = aArgv[1];
char* value = aArgv[2];
nsCategoryManager::GetSingleton()->AddCategoryEntry(
nsDependentCString(category), nsDependentCString(key),
nsDependentCString(value));
}
void nsComponentManagerImpl::RereadChromeManifests(bool aChromeOnly) {
for (uint32_t i = 0; i < sModuleLocations->Length(); ++i) {
ComponentLocation& l = sModuleLocations->ElementAt(i);
RegisterManifest(l.type, l.location, aChromeOnly);
}
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
if (obs) {
obs->NotifyObservers(nullptr, "chrome-manifests-loaded", nullptr);
}
}
bool nsComponentManagerImpl::KnownModule::Load() {
if (mFailed) {
return false;
}
if (!mModule) {
nsCString extension;
mFile.GetURIString(extension);
CutExtension(extension);
if (!extension.Equals("js")) {
return false;
}
RefPtr<mozJSComponentLoader> loader = mozJSComponentLoader::Get();
mModule = loader->LoadModule(mFile);
if (!mModule) {
mFailed = true;
return false;
}
}
if (!mLoaded) {
if (mModule->loadProc) {
nsresult rv = mModule->loadProc();
if (NS_FAILED(rv)) {
mFailed = true;
return false;
}
}
mLoaded = true;
}
return true;
}
nsCString nsComponentManagerImpl::KnownModule::Description() const {
nsCString s;
if (mFile) {
mFile.GetURIString(s);
} else {
s = "<static module>";
}
return s;
}
nsresult nsComponentManagerImpl::Shutdown(void) {
MOZ_ASSERT(NORMAL == mStatus);
mStatus = SHUTDOWN_IN_PROGRESS;
// Shutdown the component manager
MOZ_LOG(nsComponentManagerLog, LogLevel::Debug,
("nsComponentManager: Beginning Shutdown."));
UnregisterWeakMemoryReporter(this);
// Release all cached factories
mContractIDs.Clear();
mFactories.Clear(); // XXX release the objects, don't just clear
mKnownModules.Clear();
mKnownStaticModules.Clear();
StaticComponents::Shutdown();
delete sExtraStaticModules;
delete sModuleLocations;
mStatus = SHUTDOWN_COMPLETE;
MOZ_LOG(nsComponentManagerLog, LogLevel::Debug,
("nsComponentManager: Shutdown complete."));
return NS_OK;
}
nsComponentManagerImpl::~nsComponentManagerImpl() {
MOZ_LOG(nsComponentManagerLog, LogLevel::Debug,
("nsComponentManager: Beginning destruction."));
if (SHUTDOWN_COMPLETE != mStatus) {
Shutdown();
}
MOZ_LOG(nsComponentManagerLog, LogLevel::Debug,
("nsComponentManager: Destroyed."));
}
NS_IMPL_ISUPPORTS(nsComponentManagerImpl, nsIComponentManager,
nsIServiceManager, nsIComponentRegistrar,
nsISupportsWeakReference, nsIInterfaceRequestor,
nsIMemoryReporter)
nsresult nsComponentManagerImpl::GetInterface(const nsIID& aUuid,
void** aResult) {
NS_WARNING("This isn't supported");
// fall through to QI as anything QIable is a superset of what can be
// got via the GetInterface()
return QueryInterface(aUuid, aResult);
}
Maybe<EntryWrapper> nsComponentManagerImpl::LookupByCID(const nsID& aCID) {
return LookupByCID(MutexLock(mLock), aCID);
}
Maybe<EntryWrapper> nsComponentManagerImpl::LookupByCID(const MutexLock&,
const nsID& aCID) {
if (const StaticModule* module = StaticComponents::LookupByCID(aCID)) {
return Some(EntryWrapper(module));
}
if (nsFactoryEntry* entry = mFactories.Get(&aCID)) {
return Some(EntryWrapper(entry));
}
return Nothing();
}
Maybe<EntryWrapper> nsComponentManagerImpl::LookupByContractID(
const nsACString& aContractID) {
return LookupByContractID(MutexLock(mLock), aContractID);
}
Maybe<EntryWrapper> nsComponentManagerImpl::LookupByContractID(
const MutexLock&, const nsACString& aContractID) {
if (const StaticModule* module =
StaticComponents::LookupByContractID(aContractID)) {
return Some(EntryWrapper(module));
}
if (nsFactoryEntry* entry = mContractIDs.Get(aContractID)) {
// UnregisterFactory might have left a stale nsFactoryEntry in
// mContractIDs, so we should check to see whether this entry has
// anything useful.
if (entry->mModule || entry->mFactory || entry->mServiceObject) {
return Some(EntryWrapper(entry));
}
}
return Nothing();
}
already_AddRefed<nsIFactory> nsComponentManagerImpl::FindFactory(
const nsCID& aClass) {
Maybe<EntryWrapper> e = LookupByCID(aClass);
if (!e) {
return nullptr;
}
return e->GetFactory();
}
already_AddRefed<nsIFactory> nsComponentManagerImpl::FindFactory(
const char* aContractID, uint32_t aContractIDLen) {
Maybe<EntryWrapper> entry =
LookupByContractID(nsDependentCString(aContractID, aContractIDLen));
if (!entry) {
return nullptr;
}
return entry->GetFactory();
}
/**
* GetClassObject()
*
* Given a classID, this finds the singleton ClassObject that implements the
* CID. Returns an interface of type aIID off the singleton classobject.
*/
NS_IMETHODIMP
nsComponentManagerImpl::GetClassObject(const nsCID& aClass, const nsIID& aIID,
void** aResult) {
nsresult rv;
if (MOZ_LOG_TEST(nsComponentManagerLog, LogLevel::Debug)) {
char* buf = aClass.ToString();
PR_LogPrint("nsComponentManager: GetClassObject(%s)", buf);
if (buf) {
free(buf);
}
}