forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathContentChild.cpp
5009 lines (4281 loc) · 166 KB
/
ContentChild.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
/* -*- 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/. */
#ifdef MOZ_WIDGET_ANDROID
# include "AndroidDecoderModule.h"
#endif
#include "BrowserChild.h"
#include "nsNSSComponent.h"
#include "ContentChild.h"
#include "GeckoProfiler.h"
#include "HandlerServiceChild.h"
#include "nsXPLookAndFeel.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/Attributes.h"
#include "mozilla/BackgroundHangMonitor.h"
#include "mozilla/BenchmarkStorageChild.h"
#include "mozilla/ContentBlocking.h"
#include "mozilla/FOGIPC.h"
#include "GMPServiceChild.h"
#include "Geolocation.h"
#include "imgLoader.h"
#include "ScrollingMetrics.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/Components.h"
#include "mozilla/HangDetails.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/Logging.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MemoryTelemetry.h"
#include "mozilla/NullPrincipal.h"
#include "mozilla/PerfStats.h"
#include "mozilla/PerformanceMetricsCollector.h"
#include "mozilla/PerformanceUtils.h"
#include "mozilla/Preferences.h"
#include "mozilla/ProcessHangMonitorIPC.h"
#include "mozilla/RemoteDecoderManagerChild.h"
#include "mozilla/RemoteLazyInputStreamChild.h"
#include "mozilla/SchedulerGroup.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/SharedStyleSheetCache.h"
#include "mozilla/SimpleEnumerator.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "mozilla/StaticPrefs_accessibility.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_fission.h"
#include "mozilla/StaticPrefs_media.h"
#include "mozilla/TelemetryIPC.h"
#include "mozilla/Unused.h"
#include "mozilla/WebBrowserPersistDocumentChild.h"
#include "mozilla/devtools/HeapSnapshotTempFileHelperChild.h"
#include "mozilla/dom/AutoSuppressEventHandlingAndSuspend.h"
#include "mozilla/dom/BlobImpl.h"
#include "mozilla/dom/BrowserBridgeHost.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/BrowsingContextGroup.h"
#include "mozilla/dom/ChildProcessChannelListener.h"
#include "mozilla/dom/ChildProcessMessageManager.h"
#include "mozilla/dom/ClientManager.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ContentProcessManager.h"
#include "mozilla/dom/ContentPlaybackController.h"
#include "mozilla/dom/ContentProcessMessageManager.h"
#include "mozilla/dom/DataTransfer.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/ExternalHelperAppChild.h"
#include "mozilla/dom/GetFilesHelper.h"
#include "mozilla/dom/IPCBlobUtils.h"
#include "mozilla/dom/InProcessChild.h"
#include "mozilla/dom/JSActorService.h"
#include "mozilla/dom/JSProcessActorBinding.h"
#include "mozilla/dom/JSProcessActorChild.h"
#include "mozilla/dom/LSObject.h"
#include "mozilla/dom/MemoryReportRequest.h"
#include "mozilla/dom/PLoginReputationChild.h"
#include "mozilla/dom/PSessionStorageObserverChild.h"
#include "mozilla/dom/PostMessageEvent.h"
#include "mozilla/dom/PushNotifier.h"
#include "mozilla/dom/RemoteWorkerService.h"
#include "mozilla/dom/ScreenOrientation.h"
#include "mozilla/dom/ServiceWorkerManager.h"
#include "mozilla/dom/SessionStorageManager.h"
#include "mozilla/dom/URLClassifierChild.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "mozilla/dom/WorkerDebugger.h"
#include "mozilla/dom/WorkerDebuggerManager.h"
#include "mozilla/dom/ipc/SharedMap.h"
#include "mozilla/extensions/ExtensionsChild.h"
#include "mozilla/extensions/StreamFilterParent.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/hal_sandbox/PHalChild.h"
#include "mozilla/intl/L10nRegistry.h"
#include "mozilla/intl/LocaleService.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/Endpoint.h"
#include "mozilla/ipc/FileDescriptorSetChild.h"
#include "mozilla/ipc/FileDescriptorUtils.h"
#include "mozilla/ipc/GeckoChildProcessHost.h"
#include "mozilla/ipc/PChildToParentStreamChild.h"
#include "mozilla/ipc/PParentToChildStreamChild.h"
#include "mozilla/ipc/ProcessChild.h"
#include "mozilla/ipc/TestShellChild.h"
#include "mozilla/layers/APZChild.h"
#include "mozilla/layers/CompositorManagerChild.h"
#include "mozilla/layers/ContentProcessController.h"
#include "mozilla/layers/ImageBridgeChild.h"
#include "mozilla/loader/ScriptCacheActors.h"
#include "mozilla/media/MediaChild.h"
#include "mozilla/net/CaptivePortalService.h"
#include "mozilla/net/CookieServiceChild.h"
#include "mozilla/net/DocumentChannelChild.h"
#include "mozilla/net/HttpChannelChild.h"
#include "mozilla/widget/RemoteLookAndFeel.h"
#include "mozilla/widget/ScreenManager.h"
#include "mozilla/widget/WidgetMessageUtils.h"
#include "nsBaseDragService.h"
#include "nsDocShellLoadTypes.h"
#include "nsFocusManager.h"
#include "nsHttpHandler.h"
#include "nsIConsoleService.h"
#include "nsIInputStreamChannel.h"
#include "nsILoadGroup.h"
#include "nsIOpenWindowInfo.h"
#include "nsISimpleEnumerator.h"
#include "nsIStringBundle.h"
#include "nsIURIMutator.h"
#include "nsQueryObject.h"
#include "nsSandboxFlags.h"
#if !defined(XP_WIN)
# include "mozilla/Omnijar.h"
#endif
#include "ChildProfilerController.h"
#if defined(MOZ_SANDBOX)
# include "mozilla/SandboxSettings.h"
# if defined(XP_WIN)
# include "mozilla/sandboxTarget.h"
# elif defined(XP_LINUX)
# include "CubebUtils.h"
# include "mozilla/Sandbox.h"
# include "mozilla/SandboxInfo.h"
# elif defined(XP_MACOSX)
# include "mozilla/Sandbox.h"
# include "mozilla/gfx/QuartzSupport.h"
# elif defined(__OpenBSD__)
# include <err.h>
# include <sys/stat.h>
# include <unistd.h>
# include <fstream>
# include "SpecialSystemDirectory.h"
# include "nsILineInputStream.h"
# endif
# if defined(MOZ_DEBUG) && defined(ENABLE_TESTS)
# include "mozilla/SandboxTestingChild.h"
# endif
#endif
#include "SandboxHal.h"
#include "mozInlineSpellChecker.h"
#include "mozilla/GlobalStyleSheetCache.h"
#include "nsAnonymousTemporaryFile.h"
#include "nsClipboardProxy.h"
#include "nsContentPermissionHelper.h"
#include "nsDebugImpl.h"
#include "nsDirectoryService.h"
#include "nsDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsDocShell.h"
#include "nsDocShellLoadState.h"
#include "nsHashPropertyBag.h"
#include "nsIConsoleListener.h"
#include "nsIContentViewer.h"
#include "nsICycleCollectorListener.h"
#include "nsIDocShellTreeOwner.h"
#include "nsIDragService.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIMemoryInfoDumper.h"
#include "nsIMemoryReporter.h"
#include "nsIObserverService.h"
#include "nsIScriptError.h"
#include "nsIScriptSecurityManager.h"
#include "nsJSEnvironment.h"
#include "nsMemoryInfoDumper.h"
#include "nsPluginHost.h"
#include "nsServiceManagerUtils.h"
#include "nsStyleSheetService.h"
#include "nsThreadManager.h"
#include "nsVariant.h"
#include "nsXULAppAPI.h"
#ifdef NS_PRINTING
# include "nsPrintingProxy.h"
#endif
#include "IHistory.h"
#include "ReferrerInfo.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/task.h"
#include "mozilla/dom/BlobURLProtocolHandler.h"
#include "mozilla/dom/PCycleCollectWithLogsChild.h"
#include "mozilla/dom/PerformanceStorage.h"
#include "nsChromeRegistryContent.h"
#include "nsFrameMessageManager.h"
#include "nsNetUtil.h"
#include "nsWindowMemoryReporter.h"
#ifdef MOZ_WEBRTC
# include "jsapi/WebrtcGlobalChild.h"
#endif
#include "PermissionMessageUtils.h"
#include "mozilla/Permission.h"
#include "mozilla/PermissionManager.h"
#if defined(MOZ_WIDGET_ANDROID)
# include "APKOpen.h"
#endif
#ifdef XP_WIN
# include <process.h>
# define getpid _getpid
# include "mozilla/WinDllServices.h"
# include "mozilla/widget/AudioSession.h"
# include "mozilla/widget/WinContentSystemParameters.h"
#endif
#if defined(XP_MACOSX)
# include "nsMacUtilsImpl.h"
#endif /* XP_MACOSX */
#ifdef MOZ_X11
# include "mozilla/X11Util.h"
#endif
#ifdef ACCESSIBILITY
# include "nsAccessibilityService.h"
# ifdef XP_WIN
# include "mozilla/a11y/AccessibleWrap.h"
# endif
# include "mozilla/a11y/DocAccessible.h"
# include "mozilla/a11y/DocManager.h"
# include "mozilla/a11y/OuterDocAccessible.h"
#endif
#include "mozilla/dom/File.h"
#include "mozilla/dom/MediaControllerBinding.h"
#include "mozilla/ipc/IPCStreamAlloc.h"
#include "mozilla/ipc/IPCStreamDestination.h"
#include "mozilla/ipc/IPCStreamSource.h"
#ifdef MOZ_WEBSPEECH
# include "mozilla/dom/PSpeechSynthesisChild.h"
#endif
#include "ClearOnShutdown.h"
#include "DomainPolicy.h"
#include "GfxInfoBase.h"
#include "MMPrinter.h"
#include "mozilla/ipc/ProcessUtils.h"
#include "mozilla/ipc/URIUtils.h"
#include "VRManagerChild.h"
#include "gfxPlatform.h"
#include "gfxPlatformFontList.h"
#include "mozilla/RemoteSpellCheckEngineChild.h"
#include "mozilla/dom/TabContext.h"
#include "mozilla/dom/ipc/StructuredCloneData.h"
#include "mozilla/ipc/CrashReporterClient.h"
#include "mozilla/net/NeckoMessageUtils.h"
#include "mozilla/widget/PuppetBidiKeyboard.h"
#include "nsContentUtils.h"
#include "nsIPrincipal.h"
#include "nsString.h"
#include "nscore.h" // for NS_FREE_PERMANENT_DATA
#include "private/pprio.h"
#ifdef MOZ_WIDGET_GTK
# include "mozilla/WidgetUtilsGtk.h"
# include "nsAppRunner.h"
# include <gtk/gtk.h>
#endif
#ifdef MOZ_CODE_COVERAGE
# include "mozilla/CodeCoverageHandler.h"
#endif
extern mozilla::LazyLogModule gSHIPBFCacheLog;
using namespace mozilla;
using namespace mozilla::dom::ipc;
using namespace mozilla::media;
using namespace mozilla::embedding;
using namespace mozilla::gmp;
using namespace mozilla::hal_sandbox;
using namespace mozilla::ipc;
using namespace mozilla::intl;
using namespace mozilla::layers;
using namespace mozilla::layout;
using namespace mozilla::net;
using namespace mozilla::widget;
using mozilla::loader::PScriptCacheChild;
namespace geckoprofiler::markers {
struct ProcessPriorityChange {
static constexpr Span<const char> MarkerTypeName() {
return MakeStringSpan("ProcessPriorityChange");
}
static void StreamJSONMarkerData(baseprofiler::SpliceableJSONWriter& aWriter,
const ProfilerString8View& aPreviousPriority,
const ProfilerString8View& aNewPriority) {
aWriter.StringProperty("Before", aPreviousPriority);
aWriter.StringProperty("After", aNewPriority);
}
static MarkerSchema MarkerTypeDisplay() {
using MS = MarkerSchema;
MS schema{MS::Location::MarkerChart, MS::Location::MarkerTable};
schema.AddKeyFormat("Before", MS::Format::String);
schema.AddKeyFormat("After", MS::Format::String);
schema.AddStaticLabelValue("Note",
"This is a notification of the priority change "
"that was done by the parent process");
schema.SetAllLabels(
"priority: {marker.data.Before} -> {marker.data.After}");
return schema;
}
};
struct ProcessPriority {
static constexpr Span<const char> MarkerTypeName() {
return MakeStringSpan("ProcessPriority");
}
static void StreamJSONMarkerData(baseprofiler::SpliceableJSONWriter& aWriter,
const ProfilerString8View& aPriority,
const ProfilingState& aProfilingState) {
aWriter.StringProperty("Priority", aPriority);
aWriter.StringProperty("Marker cause",
ProfilerString8View::WrapNullTerminatedString(
ProfilingStateToString(aProfilingState)));
}
static MarkerSchema MarkerTypeDisplay() {
using MS = MarkerSchema;
MS schema{MS::Location::MarkerChart, MS::Location::MarkerTable};
schema.AddKeyFormat("Priority", MS::Format::String);
schema.AddKeyFormat("Marker cause", MS::Format::String);
schema.SetAllLabels("priority: {marker.data.Priority}");
return schema;
}
};
} // namespace geckoprofiler::markers
namespace mozilla {
namespace dom {
// IPC sender for remote GC/CC logging.
class CycleCollectWithLogsChild final : public PCycleCollectWithLogsChild {
public:
NS_INLINE_DECL_REFCOUNTING(CycleCollectWithLogsChild)
class Sink final : public nsICycleCollectorLogSink {
NS_DECL_ISUPPORTS
Sink(CycleCollectWithLogsChild* aActor, const FileDescriptor& aGCLog,
const FileDescriptor& aCCLog) {
mActor = aActor;
mGCLog = FileDescriptorToFILE(aGCLog, "w");
mCCLog = FileDescriptorToFILE(aCCLog, "w");
}
NS_IMETHOD Open(FILE** aGCLog, FILE** aCCLog) override {
if (NS_WARN_IF(!mGCLog) || NS_WARN_IF(!mCCLog)) {
return NS_ERROR_FAILURE;
}
*aGCLog = mGCLog;
*aCCLog = mCCLog;
return NS_OK;
}
NS_IMETHOD CloseGCLog() override {
MOZ_ASSERT(mGCLog);
fclose(mGCLog);
mGCLog = nullptr;
mActor->SendCloseGCLog();
return NS_OK;
}
NS_IMETHOD CloseCCLog() override {
MOZ_ASSERT(mCCLog);
fclose(mCCLog);
mCCLog = nullptr;
mActor->SendCloseCCLog();
return NS_OK;
}
NS_IMETHOD GetFilenameIdentifier(nsAString& aIdentifier) override {
return UnimplementedProperty();
}
NS_IMETHOD SetFilenameIdentifier(const nsAString& aIdentifier) override {
return UnimplementedProperty();
}
NS_IMETHOD GetProcessIdentifier(int32_t* aIdentifier) override {
return UnimplementedProperty();
}
NS_IMETHOD SetProcessIdentifier(int32_t aIdentifier) override {
return UnimplementedProperty();
}
NS_IMETHOD GetGcLog(nsIFile** aPath) override {
return UnimplementedProperty();
}
NS_IMETHOD GetCcLog(nsIFile** aPath) override {
return UnimplementedProperty();
}
private:
~Sink() {
if (mGCLog) {
fclose(mGCLog);
mGCLog = nullptr;
}
if (mCCLog) {
fclose(mCCLog);
mCCLog = nullptr;
}
// The XPCOM refcount drives the IPC lifecycle;
Unused << mActor->Send__delete__(mActor);
}
nsresult UnimplementedProperty() {
MOZ_ASSERT(false,
"This object is a remote GC/CC logger;"
" this property isn't meaningful.");
return NS_ERROR_UNEXPECTED;
}
RefPtr<CycleCollectWithLogsChild> mActor;
FILE* mGCLog;
FILE* mCCLog;
};
private:
~CycleCollectWithLogsChild() = default;
};
NS_IMPL_ISUPPORTS(CycleCollectWithLogsChild::Sink, nsICycleCollectorLogSink);
class AlertObserver {
public:
AlertObserver(nsIObserver* aObserver, const nsString& aData)
: mObserver(aObserver), mData(aData) {}
~AlertObserver() = default;
nsCOMPtr<nsIObserver> mObserver;
nsString mData;
};
class ConsoleListener final : public nsIConsoleListener {
public:
explicit ConsoleListener(ContentChild* aChild) : mChild(aChild) {}
NS_DECL_ISUPPORTS
NS_DECL_NSICONSOLELISTENER
private:
~ConsoleListener() = default;
ContentChild* mChild;
friend class ContentChild;
};
NS_IMPL_ISUPPORTS(ConsoleListener, nsIConsoleListener)
// Before we send the error to the parent process (which
// involves copying the memory), truncate any long lines. CSS
// errors in particular share the memory for long lines with
// repeated errors, but the IPC communication we're about to do
// will break that sharing, so we better truncate now.
static void TruncateString(nsAString& aString) {
if (aString.Length() > 1000) {
aString.Truncate(1000);
}
}
NS_IMETHODIMP
ConsoleListener::Observe(nsIConsoleMessage* aMessage) {
if (!mChild) {
return NS_OK;
}
nsCOMPtr<nsIScriptError> scriptError = do_QueryInterface(aMessage);
if (scriptError) {
nsAutoString msg, sourceName, sourceLine;
nsCString category;
uint32_t lineNum, colNum, flags;
bool fromPrivateWindow, fromChromeContext;
nsresult rv = scriptError->GetErrorMessage(msg);
NS_ENSURE_SUCCESS(rv, rv);
TruncateString(msg);
rv = scriptError->GetSourceName(sourceName);
NS_ENSURE_SUCCESS(rv, rv);
TruncateString(sourceName);
rv = scriptError->GetSourceLine(sourceLine);
NS_ENSURE_SUCCESS(rv, rv);
TruncateString(sourceLine);
rv = scriptError->GetCategory(getter_Copies(category));
NS_ENSURE_SUCCESS(rv, rv);
rv = scriptError->GetLineNumber(&lineNum);
NS_ENSURE_SUCCESS(rv, rv);
rv = scriptError->GetColumnNumber(&colNum);
NS_ENSURE_SUCCESS(rv, rv);
rv = scriptError->GetFlags(&flags);
NS_ENSURE_SUCCESS(rv, rv);
rv = scriptError->GetIsFromPrivateWindow(&fromPrivateWindow);
NS_ENSURE_SUCCESS(rv, rv);
rv = scriptError->GetIsFromChromeContext(&fromChromeContext);
NS_ENSURE_SUCCESS(rv, rv);
{
AutoJSAPI jsapi;
jsapi.Init();
JSContext* cx = jsapi.cx();
JS::RootedValue stack(cx);
rv = scriptError->GetStack(&stack);
NS_ENSURE_SUCCESS(rv, rv);
if (stack.isObject()) {
// Because |stack| might be a cross-compartment wrapper, we can't use it
// with JSAutoRealm. Use the stackGlobal for that.
JS::RootedValue stackGlobal(cx);
rv = scriptError->GetStackGlobal(&stackGlobal);
NS_ENSURE_SUCCESS(rv, rv);
JSAutoRealm ar(cx, &stackGlobal.toObject());
StructuredCloneData data;
ErrorResult err;
data.Write(cx, stack, err);
if (err.Failed()) {
return err.StealNSResult();
}
ClonedMessageData cloned;
if (!data.BuildClonedMessageDataForChild(mChild, cloned)) {
return NS_ERROR_FAILURE;
}
mChild->SendScriptErrorWithStack(
msg, sourceName, sourceLine, lineNum, colNum, flags, category,
fromPrivateWindow, fromChromeContext, cloned);
return NS_OK;
}
}
mChild->SendScriptError(msg, sourceName, sourceLine, lineNum, colNum, flags,
category, fromPrivateWindow, 0, fromChromeContext);
return NS_OK;
}
nsString msg;
nsresult rv = aMessage->GetMessageMoz(msg);
NS_ENSURE_SUCCESS(rv, rv);
mChild->SendConsoleMessage(msg);
return NS_OK;
}
#ifdef NIGHTLY_BUILD
/**
* The singleton of this class is registered with the BackgroundHangMonitor as
* an annotator, so that the hang monitor can record whether or not there were
* pending input events when the thread hung.
*/
class PendingInputEventHangAnnotator final : public BackgroundHangAnnotator {
public:
virtual void AnnotateHang(BackgroundHangAnnotations& aAnnotations) override {
int32_t pending = ContentChild::GetSingleton()->GetPendingInputEvents();
if (pending > 0) {
aAnnotations.AddAnnotation(u"PendingInput"_ns, pending);
}
}
static PendingInputEventHangAnnotator sSingleton;
};
PendingInputEventHangAnnotator PendingInputEventHangAnnotator::sSingleton;
#endif
class ContentChild::ShutdownCanary final {};
ContentChild* ContentChild::sSingleton;
StaticAutoPtr<ContentChild::ShutdownCanary> ContentChild::sShutdownCanary;
ContentChild::ContentChild()
: mID(uint64_t(-1))
#if defined(XP_WIN) && defined(ACCESSIBILITY)
,
mMainChromeTid(0),
mMsaaID(0)
#endif
,
mIsForBrowser(false),
mIsAlive(true),
mShuttingDown(false) {
// This process is a content process, so it's clearly running in
// multiprocess mode!
nsDebugImpl::SetMultiprocessMode("Child");
// Our static analysis doesn't allow capturing ref-counted pointers in
// lambdas, so we need to hide it in a uintptr_t. This is safe because this
// lambda will be destroyed in ~ContentChild().
uintptr_t self = reinterpret_cast<uintptr_t>(this);
profiler_add_state_change_callback(
AllProfilingStates(),
[self](ProfilingState aProfilingState) {
const ContentChild* selfPtr =
reinterpret_cast<const ContentChild*>(self);
PROFILER_MARKER("Process Priority", OTHER,
mozilla::MarkerThreadId::MainThread(), ProcessPriority,
ProfilerString8View::WrapNullTerminatedString(
ProcessPriorityToString(selfPtr->mProcessPriority)),
aProfilingState);
},
self);
// When ContentChild is created, the observer service does not even exist.
// When ContentChild::RecvSetXPCOMProcessAttributes is called (the first
// IPDL call made on this object), shutdown may have already happened. Thus
// we create a canary here that relies upon getting cleared if shutdown
// happens without requiring the observer service at this time.
if (!sShutdownCanary) {
sShutdownCanary = new ShutdownCanary();
ClearOnShutdown(&sShutdownCanary, ShutdownPhase::XPCOMShutdown);
}
}
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning( \
disable : 4722) /* Silence "destructor never returns" warning \
*/
#endif
ContentChild::~ContentChild() {
profiler_remove_state_change_callback(reinterpret_cast<uintptr_t>(this));
#ifndef NS_FREE_PERMANENT_DATA
MOZ_CRASH("Content Child shouldn't be destroyed.");
#endif
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif
NS_INTERFACE_MAP_BEGIN(ContentChild)
NS_INTERFACE_MAP_ENTRY(nsIDOMProcessChild)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMProcessChild)
NS_INTERFACE_MAP_END
mozilla::ipc::IPCResult ContentChild::RecvSetXPCOMProcessAttributes(
XPCOMInitData&& aXPCOMInit, const StructuredCloneData& aInitialData,
FullLookAndFeel&& aLookAndFeelData, dom::SystemFontList&& aFontList,
Maybe<SharedMemoryHandle>&& aSharedUASheetHandle,
const uintptr_t& aSharedUASheetAddress,
nsTArray<SharedMemoryHandle>&& aSharedFontListBlocks) {
if (!sShutdownCanary) {
return IPC_OK();
}
mLookAndFeelData = std::move(aLookAndFeelData);
mFontList = std::move(aFontList);
mSharedFontListBlocks = std::move(aSharedFontListBlocks);
#ifdef XP_WIN
widget::WinContentSystemParameters::GetSingleton()->SetContentValues(
aXPCOMInit.systemParameters());
#endif
gfx::gfxVars::SetValuesForInitialize(aXPCOMInit.gfxNonDefaultVarUpdates());
InitSharedUASheets(std::move(aSharedUASheetHandle), aSharedUASheetAddress);
InitXPCOM(std::move(aXPCOMInit), aInitialData);
InitGraphicsDeviceData(aXPCOMInit.contentDeviceData());
return IPC_OK();
}
class nsGtkNativeInitRunnable : public Runnable {
public:
nsGtkNativeInitRunnable() : Runnable("nsGtkNativeInitRunnable") {}
NS_IMETHOD Run() override {
LookAndFeel::NativeInit();
return NS_OK;
}
};
void ContentChild::Init(base::ProcessId aParentPid, const char* aParentBuildID,
mozilla::ipc::ScopedPort aPort, uint64_t aChildID,
bool aIsForBrowser) {
#ifdef MOZ_WIDGET_GTK
// When running X11 only build we need to pass a display down
// to gtk_init because it's not going to use the one from the environment
// on its own when deciding which backend to use, and when starting under
// XWayland, it may choose to start with the wayland backend
// instead of the x11 backend.
// The DISPLAY environment variable is normally set by the parent process.
// The MOZ_GDK_DISPLAY environment variable is set from nsAppRunner.cpp
// when --display is set by the command line.
if (!gfxPlatform::IsHeadless()) {
const char* display_name = PR_GetEnv("MOZ_GDK_DISPLAY");
if (!display_name) {
bool waylandEnabled = false;
# ifdef MOZ_WAYLAND
waylandEnabled = IsWaylandEnabled();
# endif
if (!waylandEnabled) {
display_name = PR_GetEnv("DISPLAY");
}
}
if (display_name) {
int argc = 3;
char option_name[] = "--display";
char* argv[] = {
// argv0 is unused because g_set_prgname() was called in
// XRE_InitChildProcess().
nullptr, option_name, const_cast<char*>(display_name), nullptr};
char** argvp = argv;
gtk_init(&argc, &argvp);
} else {
gtk_init(nullptr, nullptr);
}
}
#endif
#ifdef MOZ_X11
if (!gfxPlatform::IsHeadless()) {
// Do this after initializing GDK, or GDK will install its own handler.
XRE_InstallX11ErrorHandler();
}
#endif
MOZ_ASSERT(!sSingleton, "only one ContentChild per child");
// Once we start sending IPC messages, we need the thread manager to be
// initialized so we can deal with the responses. Do that here before we
// try to construct the crash reporter.
nsresult rv = nsThreadManager::get().Init();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_CRASH("Failed to initialize the thread manager in ContentChild::Init");
}
if (!Open(std::move(aPort), aParentPid)) {
MOZ_CRASH("Open failed in ContentChild::Init");
}
sSingleton = this;
// If communications with the parent have broken down, take the process
// down so it's not hanging around.
GetIPCChannel()->SetAbortOnError(true);
#if defined(XP_WIN) && defined(ACCESSIBILITY)
GetIPCChannel()->SetChannelFlags(MessageChannel::REQUIRE_A11Y_REENTRY);
#endif
// This must be checked before any IPDL message, which may hit sentinel
// errors due to parent and content processes having different
// versions.
MessageChannel* channel = GetIPCChannel();
if (channel && !channel->SendBuildIDsMatchMessage(aParentBuildID)) {
// We need to quit this process if the buildID doesn't match the parent's.
// This can occur when an update occurred in the background.
ProcessChild::QuickExit();
}
#if defined(__OpenBSD__) && defined(MOZ_SANDBOX)
StartOpenBSDSandbox(GeckoProcessType_Content);
#endif
#ifdef MOZ_X11
# ifdef MOZ_WIDGET_GTK
if (GdkIsX11Display() && !gfxPlatform::IsHeadless()) {
// Send the parent our X socket to act as a proxy reference for our X
// resources.
int xSocketFd = ConnectionNumber(DefaultXDisplay());
SendBackUpXResources(FileDescriptor(xSocketFd));
}
# endif
#endif
CrashReporterClient::InitSingleton(this);
mID = aChildID;
mIsForBrowser = aIsForBrowser;
#ifdef NS_PRINTING
// Force the creation of the nsPrintingProxy so that it's IPC counterpart,
// PrintingParent, is always available for printing initiated from the parent.
RefPtr<nsPrintingProxy> printingProxy = nsPrintingProxy::GetInstance();
#endif
SetProcessName("Web Content"_ns);
#ifdef NIGHTLY_BUILD
// NOTE: We have to register the annotator on the main thread, as annotators
// only affect a single thread.
SchedulerGroup::Dispatch(
TaskCategory::Other,
NS_NewRunnableFunction("RegisterPendingInputEventHangAnnotator", [] {
BackgroundHangMonitor::RegisterAnnotator(
PendingInputEventHangAnnotator::sSingleton);
}));
#endif
}
void ContentChild::SetProcessName(const nsACString& aName,
const nsACString* aSite) {
char* name;
if ((name = PR_GetEnv("MOZ_DEBUG_APP_PROCESS")) && aName.EqualsASCII(name)) {
#ifdef OS_POSIX
printf_stderr("\n\nCHILDCHILDCHILDCHILD\n [%s] debug me @%d\n\n", name,
getpid());
sleep(30);
#elif defined(OS_WIN)
// Windows has a decent JIT debugging story, so NS_DebugBreak does the
// right thing.
NS_DebugBreak(NS_DEBUG_BREAK,
"Invoking NS_DebugBreak() to debug child process", nullptr,
__FILE__, __LINE__);
#endif
}
if (aSite) {
profiler_set_process_name(aName, aSite);
} else {
profiler_set_process_name(aName);
}
// Requires pref flip
if (aSite && StaticPrefs::fission_processSiteNames()) {
nsCOMPtr<nsIPrincipal> isolationPrincipal =
ContentParent::CreateRemoteTypeIsolationPrincipal(mRemoteType);
if (isolationPrincipal) {
// DEFAULT_PRIVATE_BROWSING_ID is the value when it's not private
MOZ_LOG(ContentParent::GetLog(), LogLevel::Debug,
("private = %d, pref = %d",
isolationPrincipal->OriginAttributesRef().mPrivateBrowsingId !=
nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID,
StaticPrefs::fission_processPrivateWindowSiteNames()));
if (isolationPrincipal->OriginAttributesRef().mPrivateBrowsingId ==
nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID
#ifdef NIGHTLY_BUILD
// Nightly can show site names for private windows, with a second pref
|| StaticPrefs::fission_processPrivateWindowSiteNames()
#endif
) {
#if !defined(XP_MACOSX)
// Mac doesn't have the 15-character limit Linux does
// Sets profiler process name
if (isolationPrincipal->SchemeIs("https")) {
nsAutoCString schemeless;
isolationPrincipal->GetHostPort(schemeless);
nsAutoCString originSuffix;
isolationPrincipal->GetOriginSuffix(originSuffix);
schemeless.Append(originSuffix);
mozilla::ipc::SetThisProcessName(schemeless.get());
MOZ_LOG(ContentParent::GetLog(), LogLevel::Debug,
("Changed name of process %d to %s", getpid(),
PromiseFlatCString(schemeless).get()));
} else
#endif
{
mozilla::ipc::SetThisProcessName(PromiseFlatCString(*aSite).get());
MOZ_LOG(ContentParent::GetLog(), LogLevel::Debug,
("Changed name of process %d to %s", getpid(),
PromiseFlatCString(*aSite).get()));
}
mProcessName = *aSite;
return;
}
}
}
// else private window, don't change process name, or the pref isn't set
// mProcessName is always flat
mProcessName = aName;
mozilla::ipc::SetThisProcessName(mProcessName.get());
}
static nsresult GetCreateWindowParams(nsIOpenWindowInfo* aOpenWindowInfo,
nsDocShellLoadState* aLoadState,
bool aForceNoReferrer,
nsIReferrerInfo** aReferrerInfo,
nsIPrincipal** aTriggeringPrincipal,
nsIContentSecurityPolicy** aCsp) {
if (!aTriggeringPrincipal || !aCsp) {
NS_ERROR("aTriggeringPrincipal || aCsp is null");
return NS_ERROR_FAILURE;
}
if (!aReferrerInfo) {
NS_ERROR("aReferrerInfo is null");
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIReferrerInfo> referrerInfo;
if (aForceNoReferrer) {
referrerInfo = new ReferrerInfo(nullptr, ReferrerPolicy::_empty, false);
}
if (aLoadState && !referrerInfo) {
referrerInfo = aLoadState->GetReferrerInfo();
}
RefPtr<BrowsingContext> parent = aOpenWindowInfo->GetParent();
nsCOMPtr<nsPIDOMWindowOuter> opener =
parent ? parent->GetDOMWindow() : nullptr;
if (!opener) {
nsCOMPtr<nsIPrincipal> nullPrincipal =
NullPrincipal::Create(aOpenWindowInfo->GetOriginAttributes());
if (!referrerInfo) {
referrerInfo = new ReferrerInfo(nullptr, ReferrerPolicy::_empty);
}
referrerInfo.swap(*aReferrerInfo);
NS_ADDREF(*aTriggeringPrincipal = nullPrincipal);
return NS_OK;
}
nsCOMPtr<Document> doc = opener->GetDoc();
NS_ADDREF(*aTriggeringPrincipal = doc->NodePrincipal());
nsCOMPtr<nsIContentSecurityPolicy> csp = doc->GetCsp();
if (csp) {
csp.forget(aCsp);
}
nsCOMPtr<nsIURI> baseURI = doc->GetDocBaseURI();
if (!baseURI) {
NS_ERROR("Document didn't return a base URI");
return NS_ERROR_FAILURE;
}
if (!referrerInfo) {
referrerInfo = new ReferrerInfo(*doc);
}
referrerInfo.swap(*aReferrerInfo);
return NS_OK;
}
nsresult ContentChild::ProvideWindowCommon(
BrowserChild* aTabOpener, nsIOpenWindowInfo* aOpenWindowInfo,
uint32_t aChromeFlags, bool aCalledFromJS, nsIURI* aURI,
const nsAString& aName, const nsACString& aFeatures, bool aForceNoOpener,
bool aForceNoReferrer, bool aIsPopupRequested,
nsDocShellLoadState* aLoadState, bool* aWindowIsNew,
BrowsingContext** aReturn) {
MOZ_DIAGNOSTIC_ASSERT(aTabOpener, "We must have a tab opener");
*aReturn = nullptr;
nsAutoCString features(aFeatures);
nsAutoString name(aName);
nsresult rv;
RefPtr<BrowsingContext> parent = aOpenWindowInfo->GetParent();
MOZ_DIAGNOSTIC_ASSERT(parent, "We must have a parent BC");
// Block the attempt to open a new window if the opening BrowsingContext is
// not marked to use remote tabs. This ensures that the newly opened window is
// correctly remote.
if (NS_WARN_IF(!parent->UseRemoteTabs())) {
return NS_ERROR_ABORT;
}
bool useRemoteSubframes =
aChromeFlags & nsIWebBrowserChrome::CHROME_FISSION_WINDOW;
uint32_t parentSandboxFlags = parent->SandboxFlags();
if (Document* doc = parent->GetDocument()) {
parentSandboxFlags = doc->GetSandboxFlags();
}
// Certain conditions complicate the process of creating the new
// BrowsingContext, and prevent us from using the
// "CreateWindowInDifferentProcess" codepath.
// * With Fission enabled, process selection will happen during the load, so
// switching processes eagerly will not provide a benefit.
// * Windows created for printing must be created within the current process
// so that a static clone of the source document can be created.
// * Sandboxed popups require the full window creation codepath.