summaryrefslogtreecommitdiffstats
path: root/xpcom/components/nsComponentManager.cpp
blob: 515fc82312b2c2cb9a3b51f102464fb2e8cee057 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "mozilla/GenericFactory.h"
#include "nsSupportsPrimitives.h"
#include "nsArray.h"
#include "nsIMutableArray.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/FileUtils.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/ProfilerMarkers.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/URLPreloader.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Variant.h"

#include <new>  // for placement new

#include "mozilla/Omnijar.h"

#include "mozilla/Logging.h"
#include "LogModulePrefWatcher.h"
#include "xpcpublic.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 (type == GeckoProcessType_Utility) {
    return !!(aSelector & Module::ALLOW_IN_UTILITY_PROCESS);
  }

  if (type == GeckoProcessType_GMPlugin) {
    return !!(aSelector & Module::ALLOW_IN_GMPLUGIN_PROCESS);
  }

  // Only allow XPCOM modules which can be loaded in all processes to be loaded
  // in the IPDLUnitTest process.
  if (type == GeckoProcessType_IPDLUnitTest) {
    return size_t(aSelector) == Module::kMaxProcessSelector;
  }

  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->mCID, 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(const nsIID& aIID, void** aResult) {
    if (mEntry.is<nsFactoryEntry*>()) {
      return mEntry.as<nsFactoryEntry*>()->CreateInstance(aIID, aResult);
    }
    return mEntry.as<const StaticModule*>()->CreateInstance(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.
   * Currently always returns "<unknown module>".
   */
  nsCString ModuleDescription() { return "<unknown module>"_ns; }

 private:
  Variant<nsFactoryEntry*, const StaticModule*> mEntry;
};

}  // namespace

// this is safe to call during InitXPCOM
static already_AddRefed<nsIFile> GetLocationFromDirectoryService(
    const char* aProp) {
  nsCOMPtr<nsIProperties> directoryService;
  nsDirectoryService::Create(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(REFNSIID aIID, void** aResult) {
  if (!gComponentManager) {
    return NS_ERROR_FAILURE;
  }

  return gComponentManager->QueryInterface(aIID, aResult);
}

static const int CONTRACTID_HASHTABLE_INITIAL_LENGTH = 8;

nsComponentManagerImpl::nsComponentManagerImpl()
    : mFactories(CONTRACTID_HASHTABLE_INITIAL_LENGTH),
      mContractIDs(CONTRACTID_HASHTABLE_INITIAL_LENGTH),
      mLock("nsComponentManagerImpl.mLock"),
      mStatus(NOT_INITIALIZED) {}

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_GMPLUGIN_PROCESS)] =
        ProcessSelectorMatches(ProcessSelector::ALLOW_IN_GMPLUGIN_PROCESS);
    gProcessMatchTable[size_t(ProcessSelector::ALLOW_IN_GPU_AND_MAIN_PROCESS)] =
        ProcessSelectorMatches(ProcessSelector::ALLOW_IN_GPU_AND_MAIN_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_SOCKET_AND_UTILITY_PROCESS)] =
        ProcessSelectorMatches(
            ProcessSelector::ALLOW_IN_GPU_RDD_SOCKET_AND_UTILITY_PROCESS);
    gProcessMatchTable[size_t(
        ProcessSelector::ALLOW_IN_GPU_RDD_VR_AND_SOCKET_PROCESS)] =
        ProcessSelectorMatches(
            ProcessSelector::ALLOW_IN_GPU_RDD_VR_AND_SOCKET_PROCESS);
    gProcessMatchTable[size_t(
        ProcessSelector::ALLOW_IN_GPU_RDD_VR_SOCKET_AND_UTILITY_PROCESS)] =
        ProcessSelectorMatches(
            ProcessSelector::ALLOW_IN_GPU_RDD_VR_SOCKET_AND_UTILITY_PROCESS);
    gProcessMatchTable[size_t(
        ProcessSelector::
            ALLOW_IN_GPU_RDD_VR_SOCKET_UTILITY_AND_GMPLUGIN_PROCESS)] =
        ProcessSelectorMatches(
            ProcessSelector::
                ALLOW_IN_GPU_RDD_VR_SOCKET_UTILITY_AND_GMPLUGIN_PROCESS);
  }

  MOZ_ASSERT(NOT_INITIALIZED == mStatus);

  nsCOMPtr<nsIFile> greDir = GetLocationFromDirectoryService(NS_GRE_DIR);
  nsCOMPtr<nsIFile> appDir =
      GetLocationFromDirectoryService(NS_XPCOM_CURRENT_PROCESS_DIR);

  nsCategoryManager::GetSingleton()->SuppressNotifications(true);

  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());
      }
    }
  }

  // This needs to be initialized late enough, so that preferences service can
  // be accessed but before the IO service, and we want it in all process types.
  xpc::ReadOnlyPage::Init();

  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_Content:
      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() ||
                 CONTRACTID_HASHTABLE_INITIAL_LENGTH <= 8 ||
                 mFactories.Count() > CONTRACTID_HASHTABLE_INITIAL_LENGTH / 3,
             "Initial component hashtable size is too large");

  return NS_OK;
}

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 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::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);
  }
}

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

  StaticComponents::Shutdown();

  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(MonitorAutoLock(mLock), aCID);
}

Maybe<EntryWrapper> nsComponentManagerImpl::LookupByCID(const MonitorAutoLock&,
                                                        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(MonitorAutoLock(mLock), aContractID);
}

Maybe<EntryWrapper> nsComponentManagerImpl::LookupByContractID(
    const MonitorAutoLock&, 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->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[NSID_LENGTH];
    aClass.ToProvidedString(buf);
    PR_LogPrint("nsComponentManager: GetClassObject(%s)", buf);
  }

  MOZ_ASSERT(aResult != nullptr);

  nsCOMPtr<nsIFactory> factory = FindFactory(aClass);
  if (!factory) {
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }

  rv = factory->QueryInterface(aIID, aResult);

  MOZ_LOG(
      nsComponentManagerLog, LogLevel::Warning,
      ("\t\tGetClassObject() %s", NS_SUCCEEDED(rv) ? "succeeded" : "FAILED"));

  return rv;
}

NS_IMETHODIMP
nsComponentManagerImpl::GetClassObjectByContractID(const char* aContractID,
                                                   const nsIID& aIID,
                                                   void** aResult) {
  if (NS_WARN_IF(!aResult) || NS_WARN_IF(!aContractID)) {
    return NS_ERROR_INVALID_ARG;
  }

  nsresult rv;

  MOZ_LOG(nsComponentManagerLog, LogLevel::Debug,
          ("nsComponentManager: GetClassObjectByContractID(%s)", aContractID));

  nsCOMPtr<nsIFactory> factory = FindFactory(aContractID, strlen(aContractID));
  if (!factory) {
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }

  rv = factory->QueryInterface(aIID, aResult);

  MOZ_LOG(nsComponentManagerLog, LogLevel::Warning,
          ("\t\tGetClassObjectByContractID() %s",
           NS_SUCCEEDED(rv) ? "succeeded" : "FAILED"));

  return rv;
}

/**
 * CreateInstance()
 *
 * Create an instance of an object that implements an interface and belongs
 * to the implementation aClass using the factory. The factory is immediately
 * released and not held onto for any longer.
 */
NS_IMETHODIMP
nsComponentManagerImpl::CreateInstance(const nsCID& aClass, const nsIID& aIID,
                                       void** aResult) {
  // test this first, since there's no point in creating a component during
  // shutdown -- whether it's available or not would depend on the order it
  // occurs in the list
  if (gXPCOMShuttingDown) {
    // When processing shutdown, don't process new GetService() requests
#ifdef SHOW_DENIED_ON_SHUTDOWN
    fprintf(stderr,
            "Creating new instance on shutdown. Denied.\n"
            "         CID: %s\n         IID: %s\n",
            AutoIDString(aClass).get(), AutoIDString(aIID).get());
#endif /* SHOW_DENIED_ON_SHUTDOWN */
    return NS_ERROR_UNEXPECTED;
  }

  if (!aResult) {
    return NS_ERROR_NULL_POINTER;
  }
  *aResult = nullptr;

  Maybe<EntryWrapper> entry = LookupByCID(aClass);

  if (!entry) {
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }

#ifdef SHOW_CI_ON_EXISTING_SERVICE
  if (entry->ServiceInstance()) {
    nsAutoCString message;
    message = "You are calling CreateInstance \""_ns + AutoIDString(aClass) +
              "\" when a service for this CID already exists!"_ns;
    NS_ERROR(message.get());
  }
#endif

  nsresult rv;
  nsCOMPtr<nsIFactory> factory = entry->GetFactory();
  if (factory) {
    rv = factory->CreateInstance(aIID, aResult);
    if (NS_SUCCEEDED(rv) && !*aResult) {
      NS_ERROR("Factory did not return an object but returned success!");
      rv = NS_ERROR_SERVICE_NOT_AVAILABLE;
    }
  } else {
    // Translate error values
    rv = NS_ERROR_FACTORY_NOT_REGISTERED;
  }

  if (MOZ_LOG_TEST(nsComponentManagerLog, LogLevel::Warning)) {
    char buf[NSID_LENGTH];
    aClass.ToProvidedString(buf);
    MOZ_LOG(nsComponentManagerLog, LogLevel::Warning,
            ("nsComponentManager: CreateInstance(%s) %s", buf,
             NS_SUCCEEDED(rv) ? "succeeded" : "FAILED"));
  }

  return rv;
}

/**
 * CreateInstanceByContractID()
 *
 * A variant of CreateInstance() that creates an instance of the object that
 * implements the interface aIID and whose implementation has a contractID
 * aContractID.
 *
 * This is only a convenience routine that turns around can calls the
 * CreateInstance() with classid and iid.
 */
NS_IMETHODIMP
nsComponentManagerImpl::CreateInstanceByContractID(const char* aContractID,
                                                   const nsIID& aIID,
                                                   void** aResult) {
  if (NS_WARN_IF(!aContractID)) {
    return NS_ERROR_INVALID_ARG;
  }

  // test this first, since there's no point in creating a component during
  // shutdown -- whether it's available or not would depend on the order it
  // occurs in the list
  if (gXPCOMShuttingDown) {
    // When processing shutdown, don't process new GetService() requests
#ifdef SHOW_DENIED_ON_SHUTDOWN
    fprintf(stderr,
            "Creating new instance on shutdown. Denied.\n"
            "  ContractID: %s\n         IID: %s\n",
            aContractID, AutoIDString(aIID).get());
#endif /* SHOW_DENIED_ON_SHUTDOWN */
    return NS_ERROR_UNEXPECTED;
  }

  if (!aResult) {
    return NS_ERROR_NULL_POINTER;
  }
  *aResult = nullptr;

  Maybe<EntryWrapper> entry =
      LookupByContractID(nsDependentCString(aContractID));

  if (!entry) {
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }

#ifdef SHOW_CI_ON_EXISTING_SERVICE
  if (entry->ServiceInstance()) {
    nsAutoCString message;
    message =
        "You are calling CreateInstance \""_ns +
        nsDependentCString(aContractID) +
        nsLiteralCString(
            "\" when a service for this CID already exists! "
            "Add it to abusedContracts to track down the service consumer.");
    NS_ERROR(message.get());
  }
#endif

  nsresult rv;
  nsCOMPtr<nsIFactory> factory = entry->GetFactory();
  if (factory) {
    rv = factory->CreateInstance(aIID, aResult);
    if (NS_SUCCEEDED(rv) && !*aResult) {
      NS_ERROR("Factory did not return an object but returned success!");
      rv = NS_ERROR_SERVICE_NOT_AVAILABLE;
    }
  } else {
    // Translate error values
    rv = NS_ERROR_FACTORY_NOT_REGISTERED;
  }

  MOZ_LOG(nsComponentManagerLog, LogLevel::Warning,
          ("nsComponentManager: CreateInstanceByContractID(%s) %s", aContractID,
           NS_SUCCEEDED(rv) ? "succeeded" : "FAILED"));

  return rv;
}

nsresult nsComponentManagerImpl::FreeServices() {
  NS_ASSERTION(gXPCOMShuttingDown,
               "Must be shutting down in order to free all services");

  if (!gXPCOMShuttingDown) {
    return NS_ERROR_FAILURE;
  }

  for (nsFactoryEntry* entry : mFactories.Values()) {
    entry->mFactory = nullptr;
    entry->mServiceObject = nullptr;
  }

  for (const auto& module : gStaticModules) {
    module.SetServiceInstance(nullptr);
  }

  return NS_OK;
}

// This should only ever be called within the monitor!
nsComponentManagerImpl::PendingServiceInfo*
nsComponentManagerImpl::AddPendingService(const nsCID& aServiceCID,
                                          PRThread* aThread) {
  PendingServiceInfo* newInfo = mPendingServices.AppendElement();
  if (newInfo) {
    newInfo->cid = &aServiceCID;
    newInfo->thread = aThread;
  }
  return newInfo;
}

// This should only ever be called within the monitor!
void nsComponentManagerImpl::RemovePendingService(MonitorAutoLock& aLock,
                                                  const nsCID& aServiceCID) {
  uint32_t pendingCount = mPendingServices.Length();
  for (uint32_t index = 0; index < pendingCount; ++index) {
    const PendingServiceInfo& info = mPendingServices.ElementAt(index);
    if (info.cid->Equals(aServiceCID)) {
      mPendingServices.RemoveElementAt(index);
      aLock.NotifyAll();
      return;
    }
  }
}

// This should only ever be called within the monitor!
PRThread* nsComponentManagerImpl::GetPendingServiceThread(
    const nsCID& aServiceCID) const {
  uint32_t pendingCount = mPendingServices.Length();
  for (uint32_t index = 0; index < pendingCount; ++index) {
    const PendingServiceInfo& info = mPendingServices.ElementAt(index);
    if (info.cid->Equals(aServiceCID)) {
      return info.thread;
    }
  }
  return nullptr;
}

nsresult nsComponentManagerImpl::GetServiceLocked(Maybe<MonitorAutoLock>& aLock,
                                                  EntryWrapper& aEntry,
                                                  const nsIID& aIID,
                                                  void** aResult) {
  MOZ_ASSERT(aLock.isSome());
  if (!aLock.isSome()) {
    return NS_ERROR_INVALID_ARG;
  }

  if (auto* service = aEntry.ServiceInstance()) {
    aLock.reset();
    return service->QueryInterface(aIID, aResult);
  }

  PRThread* currentPRThread = PR_GetCurrentThread();
  MOZ_ASSERT(currentPRThread, "This should never be null!");

  PRThread* pendingPRThread;
  while ((pendingPRThread = GetPendingServiceThread(aEntry.CID()))) {
    if (pendingPRThread == currentPRThread) {
      NS_ERROR("Recursive GetService!");
      return NS_ERROR_NOT_AVAILABLE;
    }

    aLock->Wait();
  }

  // It's still possible that the other thread failed to create the
  // service so we're not guaranteed to have an entry or service yet.
  if (auto* service = aEntry.ServiceInstance()) {
    aLock.reset();
    return service->QueryInterface(aIID, aResult);
  }

  DebugOnly<PendingServiceInfo*> newInfo =
      AddPendingService(aEntry.CID(), currentPRThread);
  NS_ASSERTION(newInfo, "Failed to add info to the array!");

  // We need to not be holding the service manager's lock while calling
  // CreateInstance, because it invokes user code which could try to re-enter
  // the service manager:

  nsCOMPtr<nsISupports> service;
  auto cleanup = MakeScopeExit([&]() {
    // `service` must be released after the lock is released, so if we fail and
    // still have a reference, release the lock before releasing it.
    if (service) {
      MOZ_ASSERT(aLock.isSome());
      aLock.reset();
      service = nullptr;
    }
  });
  nsresult rv;
  mLock.AssertCurrentThreadOwns();
  {
    MonitorAutoUnlock unlock(mLock);
    AUTO_PROFILER_MARKER_TEXT(
        "GetService", OTHER, MarkerStack::Capture(),
        nsDependentCString(nsIDToCString(aEntry.CID()).get()));
    rv = aEntry.CreateInstance(aIID, getter_AddRefs(service));
  }
  if (NS_SUCCEEDED(rv) && !service) {
    NS_ERROR("Factory did not return an object but returned success");
    return NS_ERROR_SERVICE_NOT_AVAILABLE;
  }

#ifdef DEBUG
  pendingPRThread = GetPendingServiceThread(aEntry.CID());
  MOZ_ASSERT(pendingPRThread == currentPRThread,
             "Pending service array has been changed!");
#endif
  MOZ_ASSERT(aLock.isSome());
  RemovePendingService(*aLock, aEntry.CID());

  if (NS_FAILED(rv)) {
    return rv;
  }

  NS_ASSERTION(!aEntry.ServiceInstance(),
               "Created two instances of a service!");

  aEntry.SetServiceInstance(service.forget());

  aLock.reset();

  *aResult = do_AddRef(aEntry.ServiceInstance()).take();
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::GetService(const nsCID& aClass, const nsIID& aIID,
                                   void** aResult) {
  // test this first, since there's no point in returning a service during
  // shutdown -- whether it's available or not would depend on the order it
  // occurs in the list
  if (gXPCOMShuttingDown) {
    // When processing shutdown, don't process new GetService() requests
#ifdef SHOW_DENIED_ON_SHUTDOWN
    fprintf(stderr,
            "Getting service on shutdown. Denied.\n"
            "         CID: %s\n         IID: %s\n",
            AutoIDString(aClass).get(), AutoIDString(aIID).get());
#endif /* SHOW_DENIED_ON_SHUTDOWN */
    return NS_ERROR_UNEXPECTED;
  }

  Maybe<MonitorAutoLock> lock(std::in_place, mLock);

  Maybe<EntryWrapper> entry = LookupByCID(*lock, aClass);
  if (!entry) {
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }

  return GetServiceLocked(lock, *entry, aIID, aResult);
}

nsresult nsComponentManagerImpl::GetService(ModuleID aId, const nsIID& aIID,
                                            void** aResult) {
  const auto& entry = gStaticModules[size_t(aId)];

  // test this first, since there's no point in returning a service during
  // shutdown -- whether it's available or not would depend on the order it
  // occurs in the list
  if (gXPCOMShuttingDown) {
    // When processing shutdown, don't process new GetService() requests
#ifdef SHOW_DENIED_ON_SHUTDOWN
    fprintf(stderr,
            "Getting service on shutdown. Denied.\n"
            "         CID: %s\n         IID: %s\n",
            AutoIDString(entry.CID()).get(), AutoIDString(aIID).get());
#endif /* SHOW_DENIED_ON_SHUTDOWN */
    return NS_ERROR_UNEXPECTED;
  }

  Maybe<MonitorAutoLock> lock(std::in_place, mLock);

  Maybe<EntryWrapper> wrapper;
  if (entry.Overridable()) {
    // If we expect this service to be overridden by test code, we need to look
    // it up by contract ID every time.
    wrapper = LookupByContractID(*lock, entry.ContractID());
    if (!wrapper) {
      return NS_ERROR_FACTORY_NOT_REGISTERED;
    }
  } else if (!entry.Active()) {
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  } else {
    wrapper.emplace(&entry);
  }
  return GetServiceLocked(lock, *wrapper, aIID, aResult);
}

NS_IMETHODIMP
nsComponentManagerImpl::IsServiceInstantiated(const nsCID& aClass,
                                              const nsIID& aIID,
                                              bool* aResult) {
  // Now we want to get the service if we already got it. If not, we don't want
  // to create an instance of it. mmh!

  // test this first, since there's no point in returning a service during
  // shutdown -- whether it's available or not would depend on the order it
  // occurs in the list
  if (gXPCOMShuttingDown) {
    // When processing shutdown, don't process new GetService() requests
#ifdef SHOW_DENIED_ON_SHUTDOWN
    fprintf(stderr,
            "Checking for service on shutdown. Denied.\n"
            "         CID: %s\n         IID: %s\n",
            AutoIDString(aClass).get(), AutoIDString(aIID).get());
#endif /* SHOW_DENIED_ON_SHUTDOWN */
    return NS_ERROR_UNEXPECTED;
  }

  if (Maybe<EntryWrapper> entry = LookupByCID(aClass)) {
    if (auto* service = entry->ServiceInstance()) {
      nsCOMPtr<nsISupports> instance;
      nsresult rv = service->QueryInterface(aIID, getter_AddRefs(instance));
      *aResult = (instance != nullptr);
      return rv;
    }
  }

  *aResult = false;
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::IsServiceInstantiatedByContractID(
    const char* aContractID, const nsIID& aIID, bool* aResult) {
  // Now we want to get the service if we already got it. If not, we don't want
  // to create an instance of it. mmh!

  // test this first, since there's no point in returning a service during
  // shutdown -- whether it's available or not would depend on the order it
  // occurs in the list
  if (gXPCOMShuttingDown) {
    // When processing shutdown, don't process new GetService() requests
#ifdef SHOW_DENIED_ON_SHUTDOWN
    fprintf(stderr,
            "Checking for service on shutdown. Denied.\n"
            "  ContractID: %s\n         IID: %s\n",
            aContractID, AutoIDString(aIID).get());
#endif /* SHOW_DENIED_ON_SHUTDOWN */
    return NS_ERROR_UNEXPECTED;
  }

  if (Maybe<EntryWrapper> entry =
          LookupByContractID(nsDependentCString(aContractID))) {
    if (auto* service = entry->ServiceInstance()) {
      nsCOMPtr<nsISupports> instance;
      nsresult rv = service->QueryInterface(aIID, getter_AddRefs(instance));
      *aResult = (instance != nullptr);
      return rv;
    }
  }

  *aResult = false;
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::GetServiceByContractID(const char* aContractID,
                                               const nsIID& aIID,
                                               void** aResult) {
  // test this first, since there's no point in returning a service during
  // shutdown -- whether it's available or not would depend on the order it
  // occurs in the list
  if (gXPCOMShuttingDown) {
    // When processing shutdown, don't process new GetService() requests
#ifdef SHOW_DENIED_ON_SHUTDOWN
    fprintf(stderr,
            "Getting service on shutdown. Denied.\n"
            "  ContractID: %s\n         IID: %s\n",
            aContractID, AutoIDString(aIID).get());
#endif /* SHOW_DENIED_ON_SHUTDOWN */
    return NS_ERROR_UNEXPECTED;
  }

  AUTO_PROFILER_LABEL_DYNAMIC_CSTR_NONSENSITIVE("GetServiceByContractID", OTHER,
                                                aContractID);
  Maybe<MonitorAutoLock> lock(std::in_place, mLock);

  Maybe<EntryWrapper> entry =
      LookupByContractID(*lock, nsDependentCString(aContractID));
  if (!entry) {
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }

  return GetServiceLocked(lock, *entry, aIID, aResult);
}

NS_IMETHODIMP
nsComponentManagerImpl::RegisterFactory(const nsCID& aClass, const char* aName,
                                        const char* aContractID,
                                        nsIFactory* aFactory) {
  if (!aFactory) {
    // If a null factory is passed in, this call just wants to reset
    // the contract ID to point to an existing CID entry.
    if (!aContractID) {
      return NS_ERROR_INVALID_ARG;
    }

    nsDependentCString contractID(aContractID);

    MonitorAutoLock lock(mLock);
    nsFactoryEntry* oldf = mFactories.Get(&aClass);
    if (oldf) {
      StaticComponents::InvalidateContractID(contractID);
      mContractIDs.InsertOrUpdate(contractID, oldf);
      return NS_OK;
    }

    if (StaticComponents::LookupByCID(aClass)) {
      // If this is the CID of a static module, just reset the invalid bit of
      // the static entry for this contract ID, and assume it points to the
      // correct class.
      if (StaticComponents::InvalidateContractID(contractID, false)) {
        mContractIDs.Remove(contractID);
        return NS_OK;
      }
    }
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }

  auto f = MakeUnique<nsFactoryEntry>(aClass, aFactory);

  MonitorAutoLock lock(mLock);
  return mFactories.WithEntryHandle(&f->mCID, [&](auto&& entry) {
    if (entry) {
      return NS_ERROR_FACTORY_EXISTS;
    }
    if (StaticComponents::LookupByCID(f->mCID)) {
      return NS_ERROR_FACTORY_EXISTS;
    }
    if (aContractID) {
      nsDependentCString contractID(aContractID);
      mContractIDs.InsertOrUpdate(contractID, f.get());
      // We allow dynamically-registered contract IDs to override static
      // entries, so invalidate any static entry for this contract ID.
      StaticComponents::InvalidateContractID(contractID);
    }
    entry.Insert(f.release());

    return NS_OK;
  });
}

NS_IMETHODIMP
nsComponentManagerImpl::UnregisterFactory(const nsCID& aClass,
                                          nsIFactory* aFactory) {
  // Don't release the dying factory or service object until releasing
  // the component manager monitor.
  nsCOMPtr<nsIFactory> dyingFactory;
  nsCOMPtr<nsISupports> dyingServiceObject;

  {
    MonitorAutoLock lock(mLock);
    auto entry = mFactories.Lookup(&aClass);
    nsFactoryEntry* f = entry ? entry.Data() : nullptr;
    if (!f || f->mFactory != aFactory) {
      // Note: We do not support unregistering static factories.
      return NS_ERROR_FACTORY_NOT_REGISTERED;
    }

    entry.Remove();

    // This might leave a stale contractid -> factory mapping in
    // place, so null out the factory entry (see
    // nsFactoryEntry::GetFactory)
    f->mFactory.swap(dyingFactory);
    f->mServiceObject.swap(dyingServiceObject);
  }

  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::AutoRegister(nsIFile* aLocation) {
  XRE_AddManifestLocation(NS_EXTENSION_LOCATION, aLocation);
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::IsCIDRegistered(const nsCID& aClass, bool* aResult) {
  *aResult = LookupByCID(aClass).isSome();
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::IsContractIDRegistered(const char* aClass,
                                               bool* aResult) {
  if (NS_WARN_IF(!aClass)) {
    return NS_ERROR_INVALID_ARG;
  }

  Maybe<EntryWrapper> entry = LookupByContractID(nsDependentCString(aClass));

  *aResult = entry.isSome();
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::GetContractIDs(nsTArray<nsCString>& aResult) {
  aResult = ToTArray<nsTArray<nsCString>>(mContractIDs.Keys());

  for (const auto& entry : gContractEntries) {
    if (!entry.Invalid()) {
      aResult.AppendElement(entry.ContractID());
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::ContractIDToCID(const char* aContractID,
                                        nsCID** aResult) {
  {
    MonitorAutoLock lock(mLock);
    Maybe<EntryWrapper> entry =
        LookupByContractID(lock, nsDependentCString(aContractID));
    if (entry) {
      *aResult = (nsCID*)moz_xmalloc(sizeof(nsCID));
      **aResult = entry->CID();
      return NS_OK;
    }
  }
  *aResult = nullptr;
  return NS_ERROR_FACTORY_NOT_REGISTERED;
}

MOZ_DEFINE_MALLOC_SIZE_OF(ComponentManagerMallocSizeOf)

NS_IMETHODIMP
nsComponentManagerImpl::CollectReports(nsIHandleReportCallback* aHandleReport,
                                       nsISupports* aData, bool aAnonymize) {
  MOZ_COLLECT_REPORT("explicit/xpcom/component-manager", KIND_HEAP, UNITS_BYTES,
                     SizeOfIncludingThis(ComponentManagerMallocSizeOf),
                     "Memory used for the XPCOM component manager.");

  return NS_OK;
}

size_t nsComponentManagerImpl::SizeOfIncludingThis(
    mozilla::MallocSizeOf aMallocSizeOf) const {
  size_t n = aMallocSizeOf(this);

  n += mFactories.ShallowSizeOfExcludingThis(aMallocSizeOf);
  for (const auto& data : mFactories.Values()) {
    n += data->SizeOfIncludingThis(aMallocSizeOf);
  }

  n += mContractIDs.ShallowSizeOfExcludingThis(aMallocSizeOf);
  for (const auto& key : mContractIDs.Keys()) {
    // We don't measure the nsFactoryEntry data because it's owned by
    // mFactories (which is measured above).
    n += key.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
  }

  if (sModuleLocations) {
    n += sModuleLocations->ShallowSizeOfIncludingThis(aMallocSizeOf);
  }

  n += mPendingServices.ShallowSizeOfExcludingThis(aMallocSizeOf);

  // Measurement of the following members may be added later if DMD finds it is
  // worthwhile:
  // - mMon
  // - sModuleLocations' entries

  return n;
}

////////////////////////////////////////////////////////////////////////////////
// nsFactoryEntry
////////////////////////////////////////////////////////////////////////////////

nsFactoryEntry::nsFactoryEntry(const nsCID& aCID, nsIFactory* aFactory)
    : mCID(aCID), mFactory(aFactory) {}

already_AddRefed<nsIFactory> nsFactoryEntry::GetFactory() {
  nsComponentManagerImpl::gComponentManager->mLock.AssertNotCurrentThreadOwns();

  nsCOMPtr<nsIFactory> factory = mFactory;
  return factory.forget();
}

nsresult nsFactoryEntry::CreateInstance(const nsIID& aIID, void** aResult) {
  nsCOMPtr<nsIFactory> factory = GetFactory();
  NS_ENSURE_TRUE(factory, NS_ERROR_FAILURE);
  return factory->CreateInstance(aIID, aResult);
}

size_t nsFactoryEntry::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) {
  size_t n = aMallocSizeOf(this);

  // Measurement of the following members may be added later if DMD finds it is
  // worthwhile:
  // - mCID;
  // - mFactory;
  // - mServiceObject;

  return n;
}

////////////////////////////////////////////////////////////////////////////////
// Static Access Functions
////////////////////////////////////////////////////////////////////////////////

nsresult NS_GetComponentManager(nsIComponentManager** aResult) {
  if (!nsComponentManagerImpl::gComponentManager) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  NS_ADDREF(*aResult = nsComponentManagerImpl::gComponentManager);
  return NS_OK;
}

nsresult NS_GetServiceManager(nsIServiceManager** aResult) {
  if (!nsComponentManagerImpl::gComponentManager) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  NS_ADDREF(*aResult = nsComponentManagerImpl::gComponentManager);
  return NS_OK;
}

nsresult NS_GetComponentRegistrar(nsIComponentRegistrar** aResult) {
  if (!nsComponentManagerImpl::gComponentManager) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  NS_ADDREF(*aResult = nsComponentManagerImpl::gComponentManager);
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::AddBootstrappedManifestLocation(nsIFile* aLocation) {
  NS_ENSURE_ARG_POINTER(aLocation);

  nsString path;
  nsresult rv = aLocation->GetPath(path);
  if (NS_FAILED(rv)) {
    return rv;
  }

  if (Substring(path, path.Length() - 4).EqualsLiteral(".xpi")) {
    return XRE_AddJarManifestLocation(NS_BOOTSTRAPPED_LOCATION, aLocation);
  }

  nsCOMPtr<nsIFile> manifest = CloneAndAppend(aLocation, "chrome.manifest"_ns);
  return XRE_AddManifestLocation(NS_BOOTSTRAPPED_LOCATION, manifest);
}

NS_IMETHODIMP
nsComponentManagerImpl::RemoveBootstrappedManifestLocation(nsIFile* aLocation) {
  NS_ENSURE_ARG_POINTER(aLocation);

  nsCOMPtr<nsIChromeRegistry> cr = mozilla::services::GetChromeRegistry();
  if (!cr) {
    return NS_ERROR_FAILURE;
  }

  nsString path;
  nsresult rv = aLocation->GetPath(path);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsComponentManagerImpl::ComponentLocation elem;
  elem.type = NS_BOOTSTRAPPED_LOCATION;

  if (Substring(path, path.Length() - 4).EqualsLiteral(".xpi")) {
    elem.location.Init(aLocation, "chrome.manifest");
  } else {
    nsCOMPtr<nsIFile> lf = CloneAndAppend(aLocation, "chrome.manifest"_ns);
    elem.location.Init(lf);
  }

  // Remove reference.
  nsComponentManagerImpl::sModuleLocations->RemoveElement(
      elem, ComponentLocationComparator());

  rv = cr->CheckForNewChrome();
  return rv;
}

NS_IMETHODIMP
nsComponentManagerImpl::GetComponentJSMs(nsIUTF8StringEnumerator** aJSMs) {
  nsCOMPtr<nsIUTF8StringEnumerator> result =
      StaticComponents::GetComponentJSMs();
  result.forget(aJSMs);
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::GetComponentESModules(
    nsIUTF8StringEnumerator** aESModules) {
  nsCOMPtr<nsIUTF8StringEnumerator> result =
      StaticComponents::GetComponentESModules();
  result.forget(aESModules);
  return NS_OK;
}

NS_IMETHODIMP
nsComponentManagerImpl::GetManifestLocations(nsIArray** aLocations) {
  NS_ENSURE_ARG_POINTER(aLocations);
  *aLocations = nullptr;

  if (!sModuleLocations) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  nsCOMPtr<nsIMutableArray> locations = nsArray::Create();
  nsresult rv;
  for (uint32_t i = 0; i < sModuleLocations->Length(); ++i) {
    ComponentLocation& l = sModuleLocations->ElementAt(i);
    FileLocation loc = l.location;
    nsCString uriString;
    loc.GetURIString(uriString);
    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), uriString);
    if (NS_SUCCEEDED(rv)) {
      locations->AppendElement(uri);
    }
  }

  locations.forget(aLocations);
  return NS_OK;
}

EXPORT_XPCOM_API(nsresult)
XRE_AddManifestLocation(NSLocationType aType, nsIFile* aLocation) {
  nsComponentManagerImpl::InitializeModuleLocations();
  nsComponentManagerImpl::ComponentLocation* c =
      nsComponentManagerImpl::sModuleLocations->AppendElement();
  c->type = aType;
  c->location.Init(aLocation);

  if (nsComponentManagerImpl::gComponentManager &&
      nsComponentManagerImpl::NORMAL ==
          nsComponentManagerImpl::gComponentManager->mStatus) {
    nsComponentManagerImpl::gComponentManager->RegisterManifest(
        aType, c->location, false);
  }

  return NS_OK;
}

EXPORT_XPCOM_API(nsresult)
XRE_AddJarManifestLocation(NSLocationType aType, nsIFile* aLocation) {
  nsComponentManagerImpl::InitializeModuleLocations();
  nsComponentManagerImpl::ComponentLocation* c =
      nsComponentManagerImpl::sModuleLocations->AppendElement();

  c->type = aType;
  c->location.Init(aLocation, "chrome.manifest");

  if (nsComponentManagerImpl::gComponentManager &&
      nsComponentManagerImpl::NORMAL ==
          nsComponentManagerImpl::gComponentManager->mStatus) {
    nsComponentManagerImpl::gComponentManager->RegisterManifest(
        aType, c->location, false);
  }

  return NS_OK;
}

// Expose some important global interfaces to rust for the rust xpcom API. These
// methods return a non-owning reference to the component manager, which should
// live for the lifetime of XPCOM.
extern "C" {

const nsIComponentManager* Gecko_GetComponentManager() {
  return nsComponentManagerImpl::gComponentManager;
}

const nsIServiceManager* Gecko_GetServiceManager() {
  return nsComponentManagerImpl::gComponentManager;
}

const nsIComponentRegistrar* Gecko_GetComponentRegistrar() {
  return nsComponentManagerImpl::gComponentManager;
}

// FFI-compatible version of `GetServiceHelper::operator()`.
nsresult Gecko_GetServiceByModuleID(ModuleID aId, const nsIID* aIID,
                                    void** aResult) {
  return nsComponentManagerImpl::gComponentManager->GetService(aId, *aIID,
                                                               aResult);
}

// FFI-compatible version of `CreateInstanceHelper::operator()`.
nsresult Gecko_CreateInstanceByModuleID(ModuleID aId, const nsIID* aIID,
                                        void** aResult) {
  const auto& entry = gStaticModules[size_t(aId)];
  if (!entry.Active()) {
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }

  nsresult rv = entry.CreateInstance(*aIID, aResult);
  return rv;
}
}