This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathmozJSComponentLoader.cpp
More file actions
1445 lines (1199 loc) · 42.9 KB
/
Copy pathmozJSComponentLoader.cpp
File metadata and controls
1445 lines (1199 loc) · 42.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- 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 "mozilla/Attributes.h"
#include "mozilla/Utf8.h" // mozilla::Utf8Unit
#include <cstdarg>
#include "mozilla/Logging.h"
#ifdef ANDROID
# include <android/log.h>
#endif
#ifdef XP_WIN
# include <windows.h>
#endif
#include "jsapi.h"
#include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h"
#include "js/Printf.h"
#include "js/PropertySpec.h"
#include "js/SourceText.h" // JS::SourceText
#include "nsCOMPtr.h"
#include "nsAutoPtr.h"
#include "nsExceptionHandler.h"
#include "nsIComponentManager.h"
#include "mozilla/Module.h"
#include "nsIFile.h"
#include "mozJSComponentLoader.h"
#include "mozJSLoaderUtils.h"
#include "nsIXPConnect.h"
#include "nsIScriptSecurityManager.h"
#include "nsIFileURL.h"
#include "nsIJARURI.h"
#include "nsNetUtil.h"
#include "nsJSPrincipals.h"
#include "nsJSUtils.h"
#include "xpcprivate.h"
#include "xpcpublic.h"
#include "nsContentUtils.h"
#include "nsReadableUtils.h"
#include "nsXULAppAPI.h"
#include "GeckoProfiler.h"
#include "WrapperFactory.h"
#include "AutoMemMap.h"
#include "ScriptPreloader-inl.h"
#include "mozilla/scache/StartupCache.h"
#include "mozilla/scache/StartupCacheUtils.h"
#include "mozilla/MacroForEach.h"
#include "mozilla/Preferences.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/ScriptPreloader.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/UniquePtrExtensions.h"
#include "mozilla/Unused.h"
using namespace mozilla;
using namespace mozilla::scache;
using namespace mozilla::loader;
using namespace xpc;
using namespace JS;
#define JS_CACHE_PREFIX(aType) "jsloader/" aType
/**
* Buffer sizes for serialization and deserialization of scripts.
* FIXME: bug #411579 (tune this macro!) Last updated: Jan 2008
*/
#define XPC_SERIALIZATION_BUFFER_SIZE (64 * 1024)
#define XPC_DESERIALIZATION_BUFFER_SIZE (12 * 8192)
// MOZ_LOG=JSComponentLoader:5
static LazyLogModule gJSCLLog("JSComponentLoader");
#define LOG(args) MOZ_LOG(gJSCLLog, mozilla::LogLevel::Debug, args)
// Components.utils.import error messages
#define ERROR_SCOPE_OBJ "%s - Second argument must be an object."
#define ERROR_NO_TARGET_OBJECT "%s - Couldn't find target object for import."
#define ERROR_NOT_PRESENT "%s - EXPORTED_SYMBOLS is not present."
#define ERROR_NOT_AN_ARRAY "%s - EXPORTED_SYMBOLS is not an array."
#define ERROR_GETTING_ARRAY_LENGTH \
"%s - Error getting array length of EXPORTED_SYMBOLS."
#define ERROR_ARRAY_ELEMENT "%s - EXPORTED_SYMBOLS[%d] is not a string."
#define ERROR_GETTING_SYMBOL "%s - Could not get symbol '%s'."
#define ERROR_SETTING_SYMBOL "%s - Could not set symbol '%s' on target object."
static bool Dump(JSContext* cx, unsigned argc, Value* vp) {
if (!nsJSUtils::DumpEnabled()) {
return true;
}
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() == 0) {
return true;
}
RootedString str(cx, JS::ToString(cx, args[0]));
if (!str) {
return false;
}
JS::UniqueChars utf8str = JS_EncodeStringToUTF8(cx, str);
if (!utf8str) {
return false;
}
#ifdef ANDROID
__android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", utf8str.get());
#endif
#ifdef XP_WIN
if (IsDebuggerPresent()) {
nsAutoJSString wstr;
if (!wstr.init(cx, str)) {
return false;
}
OutputDebugStringW(wstr.get());
}
#endif
fputs(utf8str.get(), stdout);
fflush(stdout);
return true;
}
static bool Debug(JSContext* cx, unsigned argc, Value* vp) {
#ifdef DEBUG
return Dump(cx, argc, vp);
#else
return true;
#endif
}
static const JSFunctionSpec gGlobalFun[] = {
JS_FN("dump", Dump, 1, 0), JS_FN("debug", Debug, 1, 0),
JS_FN("atob", Atob, 1, 0), JS_FN("btoa", Btoa, 1, 0), JS_FS_END};
class MOZ_STACK_CLASS JSCLContextHelper {
public:
explicit JSCLContextHelper(JSContext* aCx);
~JSCLContextHelper();
void reportErrorAfterPop(UniqueChars&& buf);
private:
JSContext* mContext;
UniqueChars mBuf;
// prevent copying and assignment
JSCLContextHelper(const JSCLContextHelper&) = delete;
const JSCLContextHelper& operator=(const JSCLContextHelper&) = delete;
};
static nsresult MOZ_FORMAT_PRINTF(2, 3)
ReportOnCallerUTF8(JSContext* callerContext, const char* format, ...) {
if (!callerContext) {
return NS_ERROR_FAILURE;
}
va_list ap;
va_start(ap, format);
UniqueChars buf = JS_vsmprintf(format, ap);
if (!buf) {
va_end(ap);
return NS_ERROR_OUT_OF_MEMORY;
}
JS_ReportErrorUTF8(callerContext, "%s", buf.get());
va_end(ap);
return NS_OK;
}
mozJSComponentLoader::mozJSComponentLoader()
: mModules(16),
mImports(16),
mInProgressImports(16),
mLocations(16),
mInitialized(false),
mShareLoaderGlobal(false),
mLoaderGlobal(dom::RootingCx()) {
MOZ_ASSERT(!sSelf, "mozJSComponentLoader should be a singleton");
}
#define ENSURE_DEP(name) \
{ \
nsresult rv = Ensure##name(); \
NS_ENSURE_SUCCESS(rv, rv); \
}
#define ENSURE_DEPS(...) MOZ_FOR_EACH(ENSURE_DEP, (), (__VA_ARGS__));
#define BEGIN_ENSURE(self, ...) \
{ \
if (m##self) return NS_OK; \
ENSURE_DEPS(__VA_ARGS__); \
}
class MOZ_STACK_CLASS ComponentLoaderInfo {
public:
explicit ComponentLoaderInfo(const nsACString& aLocation)
: mLocation(aLocation) {}
nsIIOService* IOService() {
MOZ_ASSERT(mIOService);
return mIOService;
}
nsresult EnsureIOService() {
if (mIOService) {
return NS_OK;
}
nsresult rv;
mIOService = do_GetIOService(&rv);
return rv;
}
nsIURI* URI() {
MOZ_ASSERT(mURI);
return mURI;
}
nsresult EnsureURI() {
BEGIN_ENSURE(URI, IOService);
return mIOService->NewURI(mLocation, nullptr, nullptr,
getter_AddRefs(mURI));
}
nsIChannel* ScriptChannel() {
MOZ_ASSERT(mScriptChannel);
return mScriptChannel;
}
nsresult EnsureScriptChannel() {
BEGIN_ENSURE(ScriptChannel, IOService, URI);
return NS_NewChannel(getter_AddRefs(mScriptChannel), mURI,
nsContentUtils::GetSystemPrincipal(),
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
nsIContentPolicy::TYPE_SCRIPT,
nullptr, // nsICookieSettings
nullptr, // aPerformanceStorage
nullptr, // aLoadGroup
nullptr, // aCallbacks
nsIRequest::LOAD_NORMAL, mIOService);
}
nsIURI* ResolvedURI() {
MOZ_ASSERT(mResolvedURI);
return mResolvedURI;
}
nsresult EnsureResolvedURI() {
BEGIN_ENSURE(ResolvedURI, URI);
return ResolveURI(mURI, getter_AddRefs(mResolvedURI));
}
const nsACString& Key() { return mLocation; }
nsresult EnsureKey() { return NS_OK; }
MOZ_MUST_USE nsresult GetLocation(nsCString& aLocation) {
nsresult rv = EnsureURI();
NS_ENSURE_SUCCESS(rv, rv);
return mURI->GetSpec(aLocation);
}
private:
const nsACString& mLocation;
nsCOMPtr<nsIIOService> mIOService;
nsCOMPtr<nsIURI> mURI;
nsCOMPtr<nsIChannel> mScriptChannel;
nsCOMPtr<nsIURI> mResolvedURI;
};
template <typename... Args>
static nsresult ReportOnCallerUTF8(JSCLContextHelper& helper,
const char* format,
ComponentLoaderInfo& info, Args... args) {
nsCString location;
MOZ_TRY(info.GetLocation(location));
UniqueChars buf = JS_smprintf(format, location.get(), args...);
if (!buf) {
return NS_ERROR_OUT_OF_MEMORY;
}
helper.reportErrorAfterPop(std::move(buf));
return NS_ERROR_FAILURE;
}
#undef BEGIN_ENSURE
#undef ENSURE_DEPS
#undef ENSURE_DEP
mozJSComponentLoader::~mozJSComponentLoader() {
if (mInitialized) {
NS_ERROR(
"UnloadModules() was not explicitly called before cleaning up "
"mozJSComponentLoader");
UnloadModules();
}
sSelf = nullptr;
}
StaticRefPtr<mozJSComponentLoader> mozJSComponentLoader::sSelf;
nsresult mozJSComponentLoader::ReallyInit() {
MOZ_ASSERT(!mInitialized);
const char* shareGlobal = PR_GetEnv("MOZ_LOADER_SHARE_GLOBAL");
if (shareGlobal && *shareGlobal) {
nsDependentCString val(shareGlobal);
mShareLoaderGlobal =
!(val.EqualsLiteral("0") || val.LowerCaseEqualsLiteral("no") ||
val.LowerCaseEqualsLiteral("false") ||
val.LowerCaseEqualsLiteral("off"));
} else {
mShareLoaderGlobal = Preferences::GetBool("jsloader.shareGlobal");
}
mInitialized = true;
return NS_OK;
}
// For terrible compatibility reasons, we need to consider both the global
// lexical environment and the global of modules when searching for exported
// symbols.
static JSObject* ResolveModuleObjectProperty(JSContext* aCx,
HandleObject aModObj,
const char* name) {
if (JS_HasExtensibleLexicalEnvironment(aModObj)) {
RootedObject lexical(aCx, JS_ExtensibleLexicalEnvironment(aModObj));
bool found;
if (!JS_HasOwnProperty(aCx, lexical, name, &found)) {
return nullptr;
}
if (found) {
return lexical;
}
}
return aModObj;
}
static mozilla::Result<nsCString, nsresult> ReadScript(
ComponentLoaderInfo& aInfo);
static nsresult AnnotateScriptContents(CrashReporter::Annotation aName,
const nsACString& aURI) {
ComponentLoaderInfo info(aURI);
nsCString str;
MOZ_TRY_VAR(str, ReadScript(info));
// The crash reporter won't accept any strings with embedded nuls. We
// shouldn't have any here, but if we do because of data corruption, we
// still want the annotation. So replace any embedded nuls before
// annotating.
str.ReplaceSubstring(NS_LITERAL_CSTRING("\0"), NS_LITERAL_CSTRING("\\0"));
CrashReporter::AnnotateCrashReport(aName, str);
return NS_OK;
}
nsresult mozJSComponentLoader::AnnotateCrashReport() {
Unused << AnnotateScriptContents(
CrashReporter::Annotation::nsAsyncShutdownComponent,
NS_LITERAL_CSTRING("resource://gre/components/nsAsyncShutdown.js"));
Unused << AnnotateScriptContents(
CrashReporter::Annotation::AsyncShutdownModule,
NS_LITERAL_CSTRING("resource://gre/modules/AsyncShutdown.jsm"));
return NS_OK;
}
const mozilla::Module* mozJSComponentLoader::LoadModule(FileLocation& aFile) {
if (!NS_IsMainThread()) {
MOZ_ASSERT(false, "Don't use JS components off the main thread");
return nullptr;
}
nsCOMPtr<nsIFile> file = aFile.GetBaseFile();
nsCString spec;
aFile.GetURIString(spec);
ComponentLoaderInfo info(spec);
nsresult rv = info.EnsureURI();
NS_ENSURE_SUCCESS(rv, nullptr);
if (!mInitialized) {
rv = ReallyInit();
if (NS_FAILED(rv)) {
return nullptr;
}
}
AUTO_PROFILER_TEXT_MARKER_CAUSE("JS XPCOM", spec, JS,
profiler_get_backtrace());
AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING("mozJSComponentLoader::LoadModule",
OTHER, spec);
ModuleEntry* mod;
if (mModules.Get(spec, &mod)) {
return mod;
}
dom::AutoJSAPI jsapi;
jsapi.Init();
JSContext* cx = jsapi.cx();
bool isCriticalModule =
StringEndsWith(spec, NS_LITERAL_CSTRING("/nsAsyncShutdown.js"));
nsAutoPtr<ModuleEntry> entry(new ModuleEntry(RootingContext::get(cx)));
RootedValue exn(cx);
rv = ObjectForLocation(info, file, &entry->obj, &entry->thisObjectKey,
&entry->location, isCriticalModule, &exn);
if (NS_FAILED(rv)) {
// Temporary debugging assertion for bug 1403348:
if (isCriticalModule && !exn.isUndefined()) {
AnnotateCrashReport();
JSAutoRealm ar(cx, xpc::PrivilegedJunkScope());
JS_WrapValue(cx, &exn);
nsAutoCString file;
uint32_t line;
uint32_t column;
nsAutoString msg;
nsContentUtils::ExtractErrorValues(cx, exn, file, &line, &column, msg);
NS_ConvertUTF16toUTF8 cMsg(msg);
MOZ_CRASH_UNSAFE_PRINTF(
"Failed to load module \"%s\": "
"[\"%s\" {file: \"%s\", line: %u}]",
spec.get(), cMsg.get(), file.get(), line);
}
return nullptr;
}
nsCOMPtr<nsIComponentManager> cm;
rv = NS_GetComponentManager(getter_AddRefs(cm));
if (NS_FAILED(rv)) {
return nullptr;
}
JSAutoRealm ar(cx, entry->obj);
RootedObject entryObj(cx, entry->obj);
RootedObject NSGetFactoryHolder(
cx, ResolveModuleObjectProperty(cx, entryObj, "NSGetFactory"));
RootedValue NSGetFactory_val(cx);
if (!NSGetFactoryHolder ||
!JS_GetProperty(cx, NSGetFactoryHolder, "NSGetFactory",
&NSGetFactory_val) ||
NSGetFactory_val.isUndefined()) {
return nullptr;
}
if (JS_TypeOfValue(cx, NSGetFactory_val) != JSTYPE_FUNCTION) {
/*
* spec's encoding is ASCII unless it's zip file, otherwise it's
* random encoding. Latin1 variant is safe for random encoding.
*/
JS_ReportErrorLatin1(
cx, "%s has NSGetFactory property that is not a function", spec.get());
return nullptr;
}
RootedObject jsGetFactoryObj(cx);
if (!JS_ValueToObject(cx, NSGetFactory_val, &jsGetFactoryObj) ||
!jsGetFactoryObj) {
/* XXX report error properly */
return nullptr;
}
rv = nsXPConnect::XPConnect()->WrapJS(cx, jsGetFactoryObj,
NS_GET_IID(xpcIJSGetFactory),
getter_AddRefs(entry->getfactoryobj));
if (NS_FAILED(rv)) {
/* XXX report error properly */
#ifdef DEBUG
fprintf(stderr, "mJCL: couldn't get nsIModule from jsval\n");
#endif
return nullptr;
}
#if defined(NIGHTLY_BUILD) || defined(DEBUG)
if (Preferences::GetBool("browser.startup.record", false)) {
entry->importStack = xpc_PrintJSStack(cx, false, false, false).get();
}
#endif
// Cache this module for later
mModules.Put(spec, entry);
// The hash owns the ModuleEntry now, forget about it
return entry.forget();
}
void mozJSComponentLoader::FindTargetObject(JSContext* aCx,
MutableHandleObject aTargetObject) {
aTargetObject.set(js::GetJSMEnvironmentOfScriptedCaller(aCx));
// The above could fail if the scripted caller is not a component/JSM (it
// could be a DOM scope, for instance).
//
// If the target object was not in the JSM shared global, return the global
// instead. This is needed when calling the subscript loader within a frame
// script, since it the FrameScript NSVO will have been found.
if (!aTargetObject ||
!IsLoaderGlobal(JS::GetNonCCWObjectGlobal(aTargetObject))) {
aTargetObject.set(JS::GetScriptedCallerGlobal(aCx));
// Return nullptr if the scripted caller is in a different compartment.
if (js::GetObjectCompartment(aTargetObject) !=
js::GetContextCompartment(aCx)) {
aTargetObject.set(nullptr);
}
}
}
void mozJSComponentLoader::InitStatics() {
MOZ_ASSERT(!sSelf);
sSelf = new mozJSComponentLoader();
}
void mozJSComponentLoader::Unload() {
if (sSelf) {
sSelf->UnloadModules();
}
}
void mozJSComponentLoader::Shutdown() {
MOZ_ASSERT(sSelf);
sSelf = nullptr;
}
// This requires that the keys be strings and the values be pointers.
template <class Key, class Data, class UserData>
static size_t SizeOfTableExcludingThis(
const nsBaseHashtable<Key, Data, UserData>& aTable,
MallocSizeOf aMallocSizeOf) {
size_t n = aTable.ShallowSizeOfExcludingThis(aMallocSizeOf);
for (auto iter = aTable.ConstIter(); !iter.Done(); iter.Next()) {
n += iter.Key().SizeOfExcludingThisIfUnshared(aMallocSizeOf);
n += iter.Data()->SizeOfIncludingThis(aMallocSizeOf);
}
return n;
}
size_t mozJSComponentLoader::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) {
size_t n = aMallocSizeOf(this);
n += SizeOfTableExcludingThis(mModules, aMallocSizeOf);
n += SizeOfTableExcludingThis(mImports, aMallocSizeOf);
n += mLocations.ShallowSizeOfExcludingThis(aMallocSizeOf);
n += SizeOfTableExcludingThis(mInProgressImports, aMallocSizeOf);
return n;
}
void mozJSComponentLoader::CreateLoaderGlobal(JSContext* aCx,
const nsACString& aLocation,
MutableHandleObject aGlobal) {
RefPtr<BackstagePass> backstagePass;
nsresult rv = NS_NewBackstagePass(getter_AddRefs(backstagePass));
NS_ENSURE_SUCCESS_VOID(rv);
RealmOptions options;
options.creationOptions().setNewCompartmentInSystemZone();
xpc::SetPrefableRealmOptions(options);
// Defer firing OnNewGlobalObject until after the __URI__ property has
// been defined so the JS debugger can tell what module the global is
// for
RootedObject global(aCx);
rv = xpc::InitClassesWithNewWrappedGlobal(
aCx, static_cast<nsIGlobalObject*>(backstagePass),
nsContentUtils::GetSystemPrincipal(), xpc::DONT_FIRE_ONNEWGLOBALHOOK,
options, &global);
NS_ENSURE_SUCCESS_VOID(rv);
NS_ENSURE_TRUE_VOID(global);
backstagePass->SetGlobalObject(global);
JSAutoRealm ar(aCx, global);
if (!JS_DefineFunctions(aCx, global, gGlobalFun)) {
return;
}
// Set the location information for the new global, so that tools like
// about:memory may use that information
xpc::SetLocationForGlobal(global, aLocation);
aGlobal.set(global);
}
bool mozJSComponentLoader::ReuseGlobal(nsIURI* aURI) {
if (!mShareLoaderGlobal) {
return false;
}
nsCString spec;
NS_ENSURE_SUCCESS(aURI->GetSpec(spec), false);
// The loader calls Object.freeze on global properties, which
// causes problems if the global is shared with other code.
if (spec.EqualsASCII("resource://gre/modules/commonjs/toolkit/loader.js")) {
return false;
}
// Various tests call addDebuggerToGlobal on the result of
// importing this JSM, which would be annoying to fix.
if (spec.EqualsASCII("resource://gre/modules/jsdebugger.jsm")) {
return false;
}
// BrowserTestUtils.jsm calls Cu.permitCPOWsInScope(this) which sets a
// per-compartment flag to permit CPOWs. We don't want to set this flag for
// all other JSMs.
if (spec.EqualsASCII("resource://testing-common/BrowserTestUtils.jsm")) {
return false;
}
// Some SpecialPowers jsms call Cu.forcePermissiveCOWs(),
// which sets a per-compartment flag that disables certain
// security wrappers, so don't use the shared global for them
// to avoid breaking tests.
if (FindInReadable(NS_LITERAL_CSTRING("resource://specialpowers/"), spec)) {
return false;
}
return true;
}
JSObject* mozJSComponentLoader::GetSharedGlobal(JSContext* aCx) {
if (!mLoaderGlobal) {
JS::RootedObject globalObj(aCx);
CreateLoaderGlobal(aCx, NS_LITERAL_CSTRING("shared JSM global"),
&globalObj);
// If we fail to create a module global this early, we're not going to
// get very far, so just bail out now.
MOZ_RELEASE_ASSERT(globalObj);
mLoaderGlobal = globalObj;
// AutoEntryScript required to invoke debugger hook, which is a
// Gecko-specific concept at present.
dom::AutoEntryScript aes(globalObj, "component loader report global");
JS_FireOnNewGlobalObject(aes.cx(), globalObj);
}
return mLoaderGlobal;
}
JSObject* mozJSComponentLoader::PrepareObjectForLocation(
JSContext* aCx, nsIFile* aComponentFile, nsIURI* aURI, bool* aReuseGlobal,
bool* aRealFile) {
nsAutoCString nativePath;
NS_ENSURE_SUCCESS(aURI->GetSpec(nativePath), nullptr);
bool reuseGlobal = ReuseGlobal(aURI);
*aReuseGlobal = reuseGlobal;
bool createdNewGlobal = false;
RootedObject globalObj(aCx);
if (reuseGlobal) {
globalObj = GetSharedGlobal(aCx);
} else if (!globalObj) {
CreateLoaderGlobal(aCx, nativePath, &globalObj);
createdNewGlobal = true;
}
// |thisObj| is the object we set properties on for a particular .jsm.
RootedObject thisObj(aCx, globalObj);
NS_ENSURE_TRUE(thisObj, nullptr);
JSAutoRealm ar(aCx, thisObj);
if (reuseGlobal) {
thisObj = js::NewJSMEnvironment(aCx);
NS_ENSURE_TRUE(thisObj, nullptr);
}
*aRealFile = false;
// need to be extra careful checking for URIs pointing to files
// EnsureFile may not always get called, especially on resource URIs
// so we need to call GetFile to make sure this is a valid file
nsresult rv = NS_OK;
nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(aURI, &rv);
nsCOMPtr<nsIFile> testFile;
if (NS_SUCCEEDED(rv)) {
fileURL->GetFile(getter_AddRefs(testFile));
}
if (testFile) {
*aRealFile = true;
if (XRE_IsParentProcess()) {
RootedObject locationObj(aCx);
rv = nsXPConnect::XPConnect()->WrapNative(aCx, thisObj, aComponentFile,
NS_GET_IID(nsIFile),
locationObj.address());
NS_ENSURE_SUCCESS(rv, nullptr);
NS_ENSURE_TRUE(locationObj, nullptr);
if (!JS_DefineProperty(aCx, thisObj, "__LOCATION__", locationObj, 0)) {
return nullptr;
}
}
}
// Expose the URI from which the script was imported through a special
// variable that we insert into the JSM.
RootedString exposedUri(
aCx, JS_NewStringCopyN(aCx, nativePath.get(), nativePath.Length()));
NS_ENSURE_TRUE(exposedUri, nullptr);
if (!JS_DefineProperty(aCx, thisObj, "__URI__", exposedUri, 0)) {
return nullptr;
}
if (createdNewGlobal) {
// AutoEntryScript required to invoke debugger hook, which is a
// Gecko-specific concept at present.
dom::AutoEntryScript aes(globalObj, "component loader report global");
JS_FireOnNewGlobalObject(aes.cx(), globalObj);
}
return thisObj;
}
static mozilla::Result<nsCString, nsresult> ReadScript(
ComponentLoaderInfo& aInfo) {
MOZ_TRY(aInfo.EnsureScriptChannel());
nsCOMPtr<nsIInputStream> scriptStream;
MOZ_TRY(NS_MaybeOpenChannelUsingOpen(aInfo.ScriptChannel(),
getter_AddRefs(scriptStream)));
uint64_t len64;
uint32_t bytesRead;
MOZ_TRY(scriptStream->Available(&len64));
NS_ENSURE_TRUE(len64 < UINT32_MAX, Err(NS_ERROR_FILE_TOO_BIG));
NS_ENSURE_TRUE(len64, Err(NS_ERROR_FAILURE));
uint32_t len = (uint32_t)len64;
/* malloc an internal buf the size of the file */
nsCString str;
if (!str.SetLength(len, fallible)) {
return Err(NS_ERROR_OUT_OF_MEMORY);
}
/* read the file in one swoop */
MOZ_TRY(scriptStream->Read(str.BeginWriting(), len, &bytesRead));
if (bytesRead != len) {
return Err(NS_BASE_STREAM_OSERROR);
}
return std::move(str);
}
nsresult mozJSComponentLoader::ObjectForLocation(
ComponentLoaderInfo& aInfo, nsIFile* aComponentFile,
MutableHandleObject aObject, MutableHandleScript aTableScript,
char** aLocation, bool aPropagateExceptions,
MutableHandleValue aException) {
MOZ_ASSERT(NS_IsMainThread(), "Must be on main thread.");
dom::AutoJSAPI jsapi;
jsapi.Init();
JSContext* cx = jsapi.cx();
bool realFile = false;
nsresult rv = aInfo.EnsureURI();
NS_ENSURE_SUCCESS(rv, rv);
bool reuseGlobal = false;
RootedObject obj(cx, PrepareObjectForLocation(cx, aComponentFile, aInfo.URI(),
&reuseGlobal, &realFile));
NS_ENSURE_TRUE(obj, NS_ERROR_FAILURE);
MOZ_ASSERT(JS_IsGlobalObject(obj) == !reuseGlobal);
JSAutoRealm ar(cx, obj);
RootedScript script(cx);
nsAutoCString nativePath;
rv = aInfo.URI()->GetSpec(nativePath);
NS_ENSURE_SUCCESS(rv, rv);
// Before compiling the script, first check to see if we have it in
// the startupcache. Note: as a rule, startupcache errors are not fatal
// to loading the script, since we can always slow-load.
bool writeToCache = false;
StartupCache* cache = StartupCache::GetSingleton();
aInfo.EnsureResolvedURI();
nsAutoCString cachePath(reuseGlobal ? JS_CACHE_PREFIX("non-syntactic")
: JS_CACHE_PREFIX("global"));
rv = PathifyURI(aInfo.ResolvedURI(), cachePath);
NS_ENSURE_SUCCESS(rv, rv);
script = ScriptPreloader::GetSingleton().GetCachedScript(cx, cachePath);
if (!script && cache) {
ReadCachedScript(cache, cachePath, cx, &script);
}
if (script) {
LOG(("Successfully loaded %s from startupcache\n", nativePath.get()));
} else if (cache) {
// This is ok, it just means the script is not yet in the
// cache. Could mean that the cache was corrupted and got removed,
// but either way we're going to write this out.
writeToCache = true;
// ReadCachedScript may have set a pending exception.
JS_ClearPendingException(cx);
}
if (!script) {
// The script wasn't in the cache , so compile it now.
LOG(("Slow loading %s\n", nativePath.get()));
// If we are debugging a replaying process and have diverged from the
// recording, trying to load and compile new code will cause the
// debugger operation to fail, so just abort now.
if (recordreplay::HasDivergedFromRecording()) {
return NS_ERROR_FAILURE;
}
// Use lazy source if we're using the startup cache. Non-lazy source +
// startup cache regresses installer size (due to source code stored in
// XDR encoded modules in omni.ja). Also, XDR decoding is relatively
// fast. When we're not using the startup cache, we want to use non-lazy
// source code so that we can use lazy parsing.
// See bug 1303754.
CompileOptions options(cx);
options.setNoScriptRval(true)
.setForceStrictMode()
.setFileAndLine(nativePath.get(), 1)
.setSourceIsLazy(cache || ScriptPreloader::GetSingleton().Active());
if (realFile) {
AutoMemMap map;
MOZ_TRY(map.init(aComponentFile));
// Note: exceptions will get handled further down;
// don't early return for them here.
auto buf = map.get<char>();
JS::SourceText<mozilla::Utf8Unit> srcBuf;
if (srcBuf.init(cx, buf.get(), map.size(),
JS::SourceOwnership::Borrowed)) {
script = reuseGlobal ? CompileForNonSyntacticScopeDontInflate(
cx, options, srcBuf)
: CompileDontInflate(cx, options, srcBuf);
} else {
MOZ_ASSERT(!script);
}
} else {
nsCString str;
MOZ_TRY_VAR(str, ReadScript(aInfo));
JS::SourceText<mozilla::Utf8Unit> srcBuf;
if (srcBuf.init(cx, str.get(), str.Length(),
JS::SourceOwnership::Borrowed)) {
script = reuseGlobal ? CompileForNonSyntacticScopeDontInflate(
cx, options, srcBuf)
: CompileDontInflate(cx, options, srcBuf);
} else {
MOZ_ASSERT(!script);
}
}
// Propagate the exception, if one exists. Also, don't leave the stale
// exception on this context.
if (!script && aPropagateExceptions && jsapi.HasException()) {
if (!jsapi.StealException(aException)) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
}
if (!script) {
return NS_ERROR_FAILURE;
}
ScriptPreloader::GetSingleton().NoteScript(nativePath, cachePath, script);
if (writeToCache) {
// We successfully compiled the script, so cache it.
rv = WriteCachedScript(cache, cachePath, cx, script);
// Don't treat failure to write as fatal, since we might be working
// with a read-only cache.
if (NS_SUCCEEDED(rv)) {
LOG(("Successfully wrote to cache\n"));
} else {
LOG(("Failed to write to cache\n"));
}
}
// Assign aObject here so that it's available to recursive imports.
// See bug 384168.
aObject.set(obj);
aTableScript.set(script);
{ // Scope for AutoEntryScript
// We're going to run script via JS_ExecuteScript, so we need an
// AutoEntryScript. This is Gecko-specific and not in any spec.
dom::AutoEntryScript aes(CurrentGlobalOrNull(cx),
"component loader load module");
JSContext* aescx = aes.cx();
bool executeOk = false;
if (JS_IsGlobalObject(obj)) {
JS::RootedValue rval(cx);
executeOk = JS::CloneAndExecuteScript(aescx, script, &rval);
} else {
executeOk = js::ExecuteInJSMEnvironment(aescx, script, obj);
}
if (!executeOk) {
if (aPropagateExceptions && aes.HasException()) {
// Ignore return value because we're returning an error code
// anyway.
Unused << aes.StealException(aException);
}
aObject.set(nullptr);
aTableScript.set(nullptr);
return NS_ERROR_FAILURE;
}
}
/* Freed when we remove from the table. */
*aLocation = ToNewCString(nativePath);
if (!*aLocation) {
aObject.set(nullptr);
aTableScript.set(nullptr);
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
void mozJSComponentLoader::UnloadModules() {
mInitialized = false;
if (mLoaderGlobal) {
MOZ_ASSERT(JS_HasExtensibleLexicalEnvironment(mLoaderGlobal));
JS::RootedObject lexicalEnv(dom::RootingCx(),
JS_ExtensibleLexicalEnvironment(mLoaderGlobal));
JS_SetAllNonReservedSlotsToUndefined(lexicalEnv);
JS_SetAllNonReservedSlotsToUndefined(mLoaderGlobal);
mLoaderGlobal = nullptr;
}
mInProgressImports.Clear();
mImports.Clear();
mLocations.Clear();
for (auto iter = mModules.Iter(); !iter.Done(); iter.Next()) {
iter.Data()->Clear();
iter.Remove();
}
}
nsresult mozJSComponentLoader::ImportInto(const nsACString& registryLocation,
HandleValue targetValArg,
JSContext* cx, uint8_t optionalArgc,
MutableHandleValue retval) {
MOZ_ASSERT(nsContentUtils::IsCallerChrome());
RootedValue targetVal(cx, targetValArg);
RootedObject targetObject(cx, nullptr);
if (optionalArgc) {
// The caller passed in the optional second argument. Get it.
if (targetVal.isObject()) {
// If we're passing in something like a content DOM window, chances
// are the caller expects the properties to end up on the object
// proper and not on the Xray holder. This is dubious, but can be used
// during testing. Given that dumb callers can already leak JSMs into
// content by passing a raw content JS object (where Xrays aren't
// possible), we aim for consistency here. Waive xray.
if (WrapperFactory::IsXrayWrapper(&targetVal.toObject()) &&
!WrapperFactory::WaiveXrayAndWrap(cx, &targetVal)) {
return NS_ERROR_FAILURE;
}
targetObject = &targetVal.toObject();