/
chrome_main_delegate.cc
1799 lines (1586 loc) · 70.4 KB
/
chrome_main_delegate.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/chrome_constants.h"
#include "chrome/app/chrome_main_delegate.h"
#include "chrome/chrome_elf/chrome_elf_main.h"
#include "base/files/file_util.h"
#include <stddef.h>
#include <string>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/check.h"
#include "base/command_line.h"
#include "base/cpu.h"
#include "base/cpu_reduction_experiment.h"
#include "base/dcheck_is_on.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/i18n/rtl.h"
#include "base/immediate_crash.h"
#include "base/lazy_instance.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/path_service.h"
#include "base/process/memory.h"
#include "base/process/process.h"
#include "base/process/process_handle.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequence_manager/sequence_manager_impl.h"
#include "base/task/sequence_manager/thread_controller_power_monitor.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/threading/hang_watcher.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/trace_event/trace_event_impl.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/chrome_resource_bundle_helper.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/lifetime/browser_shutdown.h"
#include "chrome/browser/metrics/chrome_feature_list_creator.h"
#include "chrome/browser/startup_data.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/chrome_content_client.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/profiler/process_type.h"
#include "chrome/common/profiler/unwind_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/gpu/chrome_content_gpu_client.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/renderer/chrome_content_renderer_client.h"
#include "chrome/utility/chrome_content_utility_client.h"
#include "components/component_updater/component_updater_paths.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/crash/core/app/crash_reporter_client.h"
#include "components/crash/core/common/crash_key.h"
#include "components/crash/core/common/crash_keys.h"
#include "components/gwp_asan/buildflags/buildflags.h"
#include "components/heap_profiling/in_process/heap_profiler_controller.h"
#include "components/nacl/common/buildflags.h"
#include "components/services/heap_profiling/public/cpp/profiling_client.h"
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#include "components/version_info/channel.h"
#include "components/version_info/version_info.h"
#include "content/public/app/initialize_mojo_core.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/profiling.h"
#include "content/public/common/url_constants.h"
#include "extensions/buildflags/buildflags.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request.h"
#include "pdf/buildflags.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "third_party/blink/public/common/features.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/resource/scoped_startup_resource_bundle.h"
#include "ui/base/ui_base_switches.h"
#include "content/nw/src/nw_base.h"
#if BUILDFLAG(IS_WIN)
#include <malloc.h>
#include <algorithm>
#include "base/files/important_file_writer_cleaner.h"
#include "base/threading/platform_thread_win.h"
#include "base/win/atl.h"
#include "chrome/child/v8_crashpad_support_win.h"
#include "chrome/chrome_elf/chrome_elf_main.h"
#include "chrome/common/child_process_logging.h"
#include "chrome/common/win/delay_load_failure_hook.h"
#include "chrome/install_static/install_util.h"
#include "components/browser_watcher/extended_crash_reporting.h"
#include "sandbox/win/src/sandbox.h"
#include "sandbox/win/src/sandbox_factory.h"
#include "ui/base/resource/resource_bundle_win.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "base/mac/foundation_util.h"
#include "base/message_loop/message_pump_mac.h"
#include "chrome/app/chrome_main_mac.h"
#include "chrome/browser/chrome_browser_application_mac.h"
#include "chrome/browser/mac/relauncher.h"
#include "chrome/browser/shell_integration.h"
#include "components/crash/core/common/objc_zombie.h"
#include "ui/base/l10n/l10n_util_mac.h"
#endif
#if BUILDFLAG(IS_POSIX)
#include <locale.h>
#include <signal.h>
#include "chrome/app/chrome_crash_reporter_client.h"
#include "components/about_ui/credit_utils.h"
#endif
#if BUILDFLAG(ENABLE_NACL) && (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS))
#include "components/nacl/common/nacl_paths.h"
#include "components/nacl/zygote/nacl_fork_delegate_linux.h"
#endif
#if BUILDFLAG(IS_CHROMEOS)
#include "chromeos/dbus/constants/dbus_paths.h"
#include "components/crash/core/app/breakpad_linux.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/constants/ash_paths.h"
#include "ash/constants/ash_switches.h"
#include "base/system/sys_info.h"
#include "chrome/browser/ash/boot_times_recorder.h"
#include "chrome/browser/ash/dbus/ash_dbus_helper.h"
#include "chrome/browser/ash/startup_settings_cache.h"
#include "chromeos/ash/components/memory/kstaled.h"
#include "chromeos/ash/components/memory/memory.h"
#include "chromeos/ash/components/memory/swap_configuration.h"
#include "chromeos/hugepage_text/hugepage_text.h"
#include "ui/lottie/resource.h" // nogncheck
#endif
#if BUILDFLAG(IS_ANDROID)
#include "base/android/java_exception_reporter.h"
#include "base/android/library_loader/library_loader_hooks.h"
#include "chrome/browser/android/metrics/uma_session_stats.h"
#include "chrome/browser/flags/android/cached_feature_flags.h"
#include "chrome/browser/flags/android/chrome_feature_list.h"
#include "chrome/common/chrome_descriptors.h"
#include "components/crash/android/pure_java_exception_handler.h"
#include "net/android/network_change_notifier_factory_android.h"
#else // BUILDFLAG(IS_ANDROID)
// Diagnostics is only available on non-android platforms.
#include "chrome/browser/diagnostics/diagnostics_controller.h"
#include "chrome/browser/diagnostics/diagnostics_writer.h"
#endif
#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_ANDROID)
#include "v8/include/v8-wasm-trap-handler-posix.h"
#include "v8/include/v8.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#include "base/environment.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
#include "base/message_loop/message_pump_libevent.h"
#endif
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID) || \
BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/policy/policy_path_parser.h"
#include "components/crash/core/app/crashpad.h"
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/startup_helper.h"
#include "extensions/common/constants.h"
#endif
#if BUILDFLAG(ENABLE_NACL)
#include "components/nacl/common/nacl_switches.h"
#include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
#endif
#if BUILDFLAG(ENABLE_PDF)
#include "chrome/child/pdf_child_init.h"
#endif
#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/chrome_process_singleton.h"
#include "chrome/browser/process_singleton.h"
#endif // !BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(ENABLE_GWP_ASAN)
#include "components/gwp_asan/client/gwp_asan.h" // nogncheck
#endif
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#include "chrome/common/chrome_paths_lacros.h"
#include "chromeos/crosapi/cpp/crosapi_constants.h" // nogncheck
#include "chromeos/crosapi/mojom/crosapi.mojom.h" // nogncheck
#include "chromeos/lacros/dbus/lacros_dbus_helper.h"
#include "chromeos/lacros/lacros_paths.h"
#include "chromeos/lacros/lacros_service.h"
#include "chromeos/startup/browser_params_proxy.h" // nogncheck
#include "media/base/media_switches.h"
#include "ui/base/resource/data_pack_with_resource_sharing_lacros.h"
#endif
#include "third_party/node-nw/src/node_webkit.h"
#include "third_party/zlib/google/zip_reader.h"
#include "base/native_library.h"
#include "base/strings/utf_string_conversions.h"
#if defined(OS_MAC)
#include "base/mac/bundle_locations.h"
#include "base/strings/sys_string_conversions.h"
#endif
base::LazyInstance<ChromeContentGpuClient>::DestructorAtExit
g_chrome_content_gpu_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ChromeContentRendererClient>::DestructorAtExit
g_chrome_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
extern int NaClMain(content::MainFunctionParams);
const char* const ChromeMainDelegate::kNonWildcardDomainNonPortSchemes[] = {
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::kExtensionScheme,
#endif
chrome::kChromeSearchScheme, content::kChromeDevToolsScheme,
content::kChromeUIScheme, content::kChromeUIUntrustedScheme};
const size_t ChromeMainDelegate::kNonWildcardDomainNonPortSchemesSize =
std::size(kNonWildcardDomainNonPortSchemes);
#if defined(COMPONENT_BUILD)
CONTENT_EXPORT NodeStartFn g_node_start_fn;
#else
extern NodeStartFn g_node_start_fn;
#endif
SetBlobPathFn g_set_blob_path_fn = nullptr;
namespace {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
const base::FilePath::CharType kUserHomeDirPrefix[] =
FILE_PATH_LITERAL("/home/user");
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
#if BUILDFLAG(IS_WIN)
// Early versions of Chrome incorrectly registered a chromehtml: URL handler,
// which gives us nothing but trouble. Avoid launching chrome this way since
// some apps fail to properly escape arguments.
bool HasDeprecatedArguments(const std::wstring& command_line) {
const wchar_t kChromeHtml[] = L"chromehtml:";
std::wstring command_line_lower = base::ToLowerASCII(command_line);
// We are only searching for ASCII characters so this is OK.
return (command_line_lower.find(kChromeHtml) != std::wstring::npos);
}
// If we try to access a path that is not currently available, we want the call
// to fail rather than show an error dialog.
void SuppressWindowsErrorDialogs() {
UINT new_flags = SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX;
// Preserve existing error mode.
UINT existing_flags = SetErrorMode(new_flags);
SetErrorMode(existing_flags | new_flags);
}
bool IsSandboxedProcess() {
typedef bool (*IsSandboxedProcessFunc)();
IsSandboxedProcessFunc is_sandboxed_process_func =
reinterpret_cast<IsSandboxedProcessFunc>(
GetProcAddress(GetModuleHandle(NULL), "IsSandboxedProcess"));
return is_sandboxed_process_func && is_sandboxed_process_func();
}
void SetUpExtendedCrashReporting(bool is_browser_process) {
browser_watcher::ExtendedCrashReporting* extended_crash_reporting =
browser_watcher::ExtendedCrashReporting::SetUpIfEnabled(
is_browser_process
? browser_watcher::ExtendedCrashReporting::kBrowserProcess
: browser_watcher::ExtendedCrashReporting::kOther);
if (!extended_crash_reporting)
return;
// Record product, version, channel and special build strings.
wchar_t exe_file[MAX_PATH] = {};
CHECK(::GetModuleFileName(nullptr, exe_file, std::size(exe_file)));
std::wstring product_name, version_number, channel_name, special_build;
install_static::GetExecutableVersionDetails(
exe_file, &product_name, &version_number, &special_build, &channel_name);
extended_crash_reporting->SetProductStrings(
base::WideToUTF16(product_name), base::WideToUTF16(version_number),
base::WideToUTF16(channel_name), base::WideToUTF16(special_build));
}
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
void AdjustLinuxOOMScore(const std::string& process_type) {
int score = -1;
if (process_type == switches::kPpapiPluginProcess) {
score = content::kPluginOomScore;
} else if (process_type == switches::kUtilityProcess ||
process_type == switches::kGpuProcess) {
score = content::kMiscOomScore;
#if BUILDFLAG(ENABLE_NACL)
} else if (process_type == switches::kNaClLoaderProcess) {
score = content::kPluginOomScore;
#endif
} else if (process_type == switches::kZygoteProcess || process_type.empty()) {
// For zygotes and unlabeled process types, we want to still make
// them killable by the OOM killer.
score = content::kZygoteOomScore;
} else if (process_type == switches::kRendererProcess) {
LOG(WARNING) << "process type 'renderer' "
<< "should be created through the zygote.";
// When debugging, this process type can end up being run directly, but
// this isn't the typical path for assigning the OOM score for it. Still,
// we want to assign a score that is somewhat representative for debugging.
score = content::kLowestRendererOomScore;
} else {
NOTREACHED() << "Unknown process type";
}
// In the case of a 0 score, still try to adjust it. Most likely the score is
// 0 already, but it may not be if this process inherited a higher score from
// its parent process.
if (score > -1)
base::AdjustOOMScore(base::GetCurrentProcId(), score);
}
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// Returns true if this subprocess type needs the ResourceBundle initialized
// and resources loaded.
bool SubprocessNeedsResourceBundle(const std::string& process_type) {
return
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// The zygote process opens the resources for the renderers.
process_type == switches::kZygoteProcess ||
#endif
#if BUILDFLAG(IS_MAC)
// Mac needs them too for scrollbar related images and for sandbox
// profiles.
#if BUILDFLAG(ENABLE_NACL)
process_type == switches::kNaClLoaderProcess ||
#endif
process_type == switches::kGpuProcess ||
#endif
process_type == switches::kPpapiPluginProcess ||
process_type == switches::kRendererProcess ||
process_type == switches::kUtilityProcess;
}
#if BUILDFLAG(IS_POSIX)
bool HandleCreditsSwitch(const base::CommandLine& command_line) {
if (!command_line.HasSwitch(switches::kCredits))
return false;
// Load resources: about_credits.html is in component_resources.pak that is
// re-packed into resources.pak.
base::FilePath resource_dir;
bool result = base::PathService::Get(base::DIR_ASSETS, &resource_dir);
DCHECK(result);
// Ensure there is an instance of ResourceBundle that is initialized for
// localized string resource accesses.
ui::ScopedStartupResourceBundle ensure_startup_resource_bundle;
base::FilePath resources_pak =
resource_dir.Append(FILE_PATH_LITERAL("resources.pak"));
#if BUILDFLAG(IS_MAC) && !defined(COMPONENT_BUILD)
// In non-component builds, check if a fallback in Resources/ folder is
// available.
if (!base::PathExists(resources_pak)) {
resources_pak =
resource_dir.Append(FILE_PATH_LITERAL("Resources/resources.pak"));
}
#endif
ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
resources_pak, ui::kScaleFactorNone);
auto credits = about_ui::GetCredits(/**include_scripts=*/false);
// If resources failed to load, about_ui::GetCredits returns
// a malformed HTML doc containing `</body>\n</html>`.
// When the resources loaded successfully, we get a huge document
// (~8 MiB) instead.
// We use a threshold of 100 characters to see if the resources
// were loaded successfully.
size_t resource_loading_threshold = 100;
if (credits.size() < resource_loading_threshold)
printf("%s\n", "Failed to load credits.");
else
printf("%s\n", credits.c_str());
return true;
}
// Check for --version and --product-version; return true if we encountered
// one of these switches and should exit now.
bool HandleVersionSwitches(const base::CommandLine& command_line) {
#if !BUILDFLAG(IS_MAC)
if (command_line.HasSwitch(switches::kProductVersion)) {
printf("%s\n", version_info::GetVersionNumber().c_str());
return true;
}
#endif
if (command_line.HasSwitch(switches::kVersion)) {
printf("%s %s %s\n", version_info::GetProductName().c_str(),
version_info::GetVersionNumber().c_str(),
chrome::GetChannelName(chrome::WithExtendedStable(true)).c_str());
return true;
}
return false;
}
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
// Show the man page if --help or -h is on the command line.
void HandleHelpSwitches(const base::CommandLine& command_line) {
if (command_line.HasSwitch(switches::kHelp) ||
command_line.HasSwitch(switches::kHelpShort)) {
base::FilePath binary(command_line.argv()[0]);
execlp("man", "man", binary.BaseName().value().c_str(), NULL);
PLOG(FATAL) << "execlp failed";
}
}
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_ANDROID)
void SIGTERMProfilingShutdown(int signal) {
content::Profiling::Stop();
struct sigaction sigact;
memset(&sigact, 0, sizeof(sigact));
sigact.sa_handler = SIG_DFL;
CHECK_EQ(sigaction(SIGTERM, &sigact, nullptr), 0);
raise(signal);
}
void SetUpProfilingShutdownHandler() {
struct sigaction sigact;
sigact.sa_handler = SIGTERMProfilingShutdown;
sigact.sa_flags = SA_RESETHAND;
sigemptyset(&sigact.sa_mask);
CHECK_EQ(sigaction(SIGTERM, &sigact, nullptr), 0);
}
#endif // !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_ANDROID)
#endif // BUILDFLAG(IS_POSIX)
#if BUILDFLAG(ENABLE_EXTENSIONS)
absl::optional<int> HandlePackExtensionSwitches(
const base::CommandLine& command_line) {
// If the command line specifies --pack-extension, attempt the pack extension
// startup action and exit.
if (!command_line.HasSwitch(switches::kPackExtension))
return absl::nullopt;
// Ensure there is an instance of ResourceBundle that is initialized for
// localized string resource accesses.
ui::ScopedStartupResourceBundle ensure_startup_resource_bundle;
extensions::StartupHelper extension_startup_helper;
std::string error_message;
if (!extension_startup_helper.PackExtension(command_line, &error_message)) {
if (!error_message.empty()) {
LOG(ERROR) << error_message.c_str();
}
return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
}
return chrome::RESULT_CODE_NORMAL_EXIT_PACK_EXTENSION_SUCCESS;
}
#endif // !BUILDFLAG(ENABLE_EXTENSIONS)
struct MainFunction {
const char* name;
int (*function)(content::MainFunctionParams);
};
// Initializes the user data dir. Must be called before InitializeLocalState().
void InitializeUserDataDir(base::CommandLine* command_line) {
#if 0
// Reach out to chrome_elf for the truth on the user data directory.
// Note that in tests, this links to chrome_elf_test_stubs.
wchar_t user_data_dir_buf[MAX_PATH], invalid_user_data_dir_buf[MAX_PATH];
// In tests this may return false, implying the user data dir should be unset.
if (GetUserDataDirectoryThunk(user_data_dir_buf, std::size(user_data_dir_buf),
invalid_user_data_dir_buf,
std::size(invalid_user_data_dir_buf))) {
base::FilePath user_data_dir(user_data_dir_buf);
if (invalid_user_data_dir_buf[0] != 0) {
chrome::SetInvalidSpecifiedUserDataDir(
base::FilePath(invalid_user_data_dir_buf));
command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
}
CHECK(base::PathService::OverrideAndCreateIfNeeded(
chrome::DIR_USER_DATA, user_data_dir, false, true));
}
#else // BUILDFLAG(IS_WIN)
base::FilePath user_data_dir =
command_line->GetSwitchValuePath(switches::kUserDataDir);
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// On Linux, Chrome does not support running multiple copies under different
// DISPLAYs, so the profile directory can be specified in the environment to
// support the virtual desktop use-case.
if (user_data_dir.empty()) {
std::string user_data_dir_string;
std::unique_ptr<base::Environment> environment(base::Environment::Create());
if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
base::IsStringUTF8(user_data_dir_string)) {
user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
}
}
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
#endif // BUILDFLAG(IS_MAC)
// On Windows, trailing separators leave Chrome in a bad state.
// See crbug.com/464616.
if (user_data_dir.EndsWithSeparator())
user_data_dir = user_data_dir.StripTrailingSeparators();
const bool specified_directory_was_invalid =
!user_data_dir.empty() &&
!base::PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
user_data_dir, false, true);
// Save inaccessible or invalid paths so the user may be prompted later.
if (specified_directory_was_invalid)
chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
// Warn and fail early if the process fails to get a user data directory.
if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
// If an invalid command-line or policy override was specified, the user
// will be given an error with that value. Otherwise, use the directory
// returned by PathService (or the fallback default directory) in the error.
if (!specified_directory_was_invalid) {
// base::PathService::Get() returns false and yields an empty path if it
// fails to create DIR_USER_DATA. Retrieve the default value manually to
// display a more meaningful error to the user in that case.
if (user_data_dir.empty())
chrome::GetDefaultUserDataDirectory(&user_data_dir);
chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
}
// The browser process (which is identified by an empty |process_type|) will
// handle the error later; other processes that need the dir crash here.
CHECK(process_type.empty()) << "Unable to get the user data directory "
<< "for process type: " << process_type;
}
// Append the fallback user data directory to the commandline. Otherwise,
// child or service processes will attempt to use the invalid directory.
//if (specified_directory_was_invalid)
command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
#endif // BUILDFLAG(IS_WIN)
}
#if !BUILDFLAG(IS_ANDROID)
void InitLogging(const std::string& process_type) {
logging::OldFileDeletionState file_state = logging::APPEND_TO_OLD_LOG_FILE;
if (process_type.empty()) {
file_state = logging::DELETE_OLD_LOG_FILE;
}
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
logging::InitChromeLogging(command_line, file_state);
}
#endif
void RecordMainStartupMetrics(base::TimeTicks application_start_time) {
const base::TimeTicks now = base::TimeTicks::Now();
#if BUILDFLAG(IS_WIN)
DCHECK(!application_start_time.is_null());
startup_metric_utils::RecordApplicationStartTime(application_start_time);
#elif BUILDFLAG(IS_ANDROID)
// On Android the main entry point time is the time when the Java code starts.
// This happens before the shared library containing this code is even loaded.
// The Java startup code has recorded that time, but the C++ code can't fetch
// it from the Java side until it has initialized the JNI. See
// ChromeMainDelegateAndroid.
#else
// On other platforms, |application_start_time| == |now| since the application
// starts with ChromeMain().
startup_metric_utils::RecordApplicationStartTime(now);
#endif
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || \
BUILDFLAG(IS_CHROMEOS)
// Record the startup process creation time on supported platforms. On Android
// this is recorded in ChromeMainDelegateAndroid.
startup_metric_utils::RecordStartupProcessCreationTime(
base::Process::Current().CreationTime());
#endif
startup_metric_utils::RecordChromeMainEntryTime(now);
}
} // namespace
ChromeMainDelegate::ChromeMainDelegate()
: ChromeMainDelegate(base::TimeTicks()) {}
ChromeMainDelegate::ChromeMainDelegate(base::TimeTicks exe_entry_point_ticks) {
// Record startup metrics in the browser process. For component builds, there
// is no way to know the type of process (process command line is not yet
// initialized), so the function below will also be called in renderers.
// This doesn't matter as it simply sets global variables.
RecordMainStartupMetrics(exe_entry_point_ticks);
}
ChromeMainDelegate::~ChromeMainDelegate() = default;
absl::optional<int> ChromeMainDelegate::PostEarlyInitialization(
InvokedIn invoked_in) {
DCHECK(base::ThreadPoolInstance::Get());
const auto* invoked_in_browser =
absl::get_if<InvokedInBrowserProcess>(&invoked_in);
if (!invoked_in_browser) {
CommonEarlyInitialization();
return absl::nullopt;
}
#if !BUILDFLAG(IS_ANDROID)
// Configure the early process singleton experiment.
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
ChromeProcessSingleton::SetupEarlySingletonFeature(command_line);
if (ChromeProcessSingleton::IsEarlySingletonFeatureEnabled()) {
// Take the Chrome process singleton lock. The process can become the
// Browser process if it succeed to take the lock. Otherwise, the
// command-line is sent to the actual Browser process and the current
// process can be exited.
base::FilePath user_data_dir;
if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
return chrome::RESULT_CODE_MISSING_DATA;
}
ChromeProcessSingleton::CreateInstance(user_data_dir);
ProcessSingleton::NotifyResult notify_result =
ChromeProcessSingleton::GetInstance()->NotifyOtherProcessOrCreate();
UMA_HISTOGRAM_ENUMERATION("Chrome.ProcessSingleton.NotifyResult",
notify_result,
ProcessSingleton::kNumNotifyResults);
switch (notify_result) {
case ProcessSingleton::PROCESS_NONE:
// No process already running, continue on to starting a new one.
break;
case ProcessSingleton::PROCESS_NOTIFIED: {
// Ensure there is an instance of ResourceBundle that is initialized for
// localized string resource accesses.
ui::ScopedStartupResourceBundle startup_resource_bundle;
printf("%s\n", base::SysWideToNativeMB(
base::UTF16ToWide(l10n_util::GetStringUTF16(
IDS_USED_EXISTING_BROWSER)))
.c_str());
return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
}
case ProcessSingleton::PROFILE_IN_USE:
return chrome::RESULT_CODE_PROFILE_IN_USE;
case ProcessSingleton::LOCK_ERROR:
LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
"directory. This means that running multiple instances "
"would start multiple browser processes rather than "
"opening a new window in the existing process. Aborting "
"now to avoid profile corruption.";
return chrome::RESULT_CODE_PROFILE_IN_USE;
}
}
#endif
#if BUILDFLAG(IS_WIN)
// Initialize the cleaner of left-behind tmp files now that the main thread
// has its SequencedTaskRunner; see https://crbug.com/1075917.
base::ImportantFileWriterCleaner::GetInstance().Initialize();
// For now, do not enable delay load failure hooks for browser process except
// in tests, where failures really shouldn't happen.
if (invoked_in_browser->is_running_test)
chrome::DisableDelayLoadFailureHooksForCurrentModule();
#endif
// Chrome disallows cookies by default. All code paths that want to use
// cookies need to go through one of Chrome's URLRequestContexts which have
// a ChromeNetworkDelegate attached that selectively allows cookies again.
net::URLRequest::SetDefaultCookiePolicyToBlock();
// On Chrome OS, IPC (D-Bus, Crosapi) is required to create the FeatureList,
// which depends on policy from an OS service. So, initialize it at this
// timing.
#if BUILDFLAG(IS_CHROMEOS_ASH)
// The feature list depends on BrowserPolicyConnectorAsh which depends
// on DBus, so initialize it here. Some D-Bus clients may depend on feature
// list, so initialize them separately later at the end of this function.
ash::InitializeDBus();
#elif BUILDFLAG(IS_CHROMEOS_LACROS)
// Initialize D-Bus for Lacros.
chromeos::LacrosInitializeDBus();
#endif
// The DBus initialization above is needed for FeatureList creation here;
// features are needed for Mojo initialization; and Mojo initialization is
// needed for LacrosService initialization below.
ChromeFeatureListCreator* chrome_feature_list_creator =
chrome_content_browser_client_->startup_data()
->chrome_feature_list_creator();
chrome_feature_list_creator->CreateFeatureList();
content::InitializeMojoCore();
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// LacrosService instance needs the sequence of the main thread,
// and needs to be created earlier than incoming Mojo invitation handling.
// This also needs ThreadPool sequences to post some tasks internally.
// However, the tasks can be suspended until actual start of the ThreadPool
// sequences later.
lacros_service_ = std::make_unique<chromeos::LacrosService>();
{
const chromeos::BrowserParamsProxy* init_params =
chromeos::BrowserParamsProxy::Get();
// This lives here rather than in ChromeBrowserMainExtraPartsLacros due to
// timing constraints. If we relocate it, then the flags aren't propagated
// to the GPU process.
if (init_params->BuildFlags().has_value()) {
for (auto flag : init_params->BuildFlags().value()) {
switch (flag) {
case crosapi::mojom::BuildFlag::kUnknown:
break;
case crosapi::mojom::BuildFlag::kEnablePlatformEncryptedHevc:
// This was deprecated.
break;
case crosapi::mojom::BuildFlag::kEnablePlatformHevc:
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kLacrosEnablePlatformHevc);
break;
case crosapi::mojom::BuildFlag::kUseChromeosProtectedMedia:
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kLacrosUseChromeosProtectedMedia);
break;
case crosapi::mojom::BuildFlag::kUseChromeosProtectedAv1:
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kLacrosUseChromeosProtectedAv1);
break;
}
}
}
}
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
CommonEarlyInitialization();
// Initializes the resource bundle and determines the locale.
std::string actual_locale = LoadLocalState(
chrome_feature_list_creator, invoked_in_browser->is_running_test);
chrome_feature_list_creator->SetApplicationLocale(actual_locale);
chrome_feature_list_creator->OverrideCachedUIStrings();
// On Chrome OS, initialize D-Bus clients that depend on feature list.
#if BUILDFLAG(IS_CHROMEOS_ASH)
ash::InitializeFeatureListDependentDBus();
#elif BUILDFLAG(IS_CHROMEOS_LACROS)
chromeos::LacrosInitializeFeatureListDependentDBus();
#endif
#if BUILDFLAG(IS_ANDROID)
chrome_content_browser_client_->startup_data()->CreateProfilePrefService();
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
#endif
if (base::FeatureList::IsEnabled(
features::kWriteBasicSystemProfileToPersistentHistogramsFile)) {
bool record = true;
#if BUILDFLAG(IS_ANDROID)
record =
base::FeatureList::IsEnabled(chrome::android::kUmaBackgroundSessions);
#endif
if (record)
chrome_content_browser_client_->startup_data()->RecordCoreSystemProfile();
}
#if BUILDFLAG(IS_ANDROID)
UmaSessionStats::OnStartup();
#endif
#if BUILDFLAG(IS_MAC)
chrome::CacheChannelInfo();
#endif
// TODO(https://crbug.com/1360376): Consider deferring this to run after
// startup.
RequestUnwindPrerequisitesInstallation(chrome::GetChannel());
return absl::nullopt;
}
bool ChromeMainDelegate::ShouldCreateFeatureList(InvokedIn invoked_in) {
// In the browser process Chrome creates the FeatureList, so content should
// not.
return absl::holds_alternative<InvokedInChildProcess>(invoked_in);
}
bool ChromeMainDelegate::ShouldInitializeMojo(InvokedIn invoked_in) {
return ShouldCreateFeatureList(invoked_in);
}
void ChromeMainDelegate::CommonEarlyInitialization() {
std::string process_type =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kProcessType);
bool is_browser_process = process_type.empty();
// Enable Split cache by default here and not in content/ so as to not
// impact non-Chrome embedders like WebView, Cronet etc. This only enables
// it if not already overridden by command line, field trial etc.
net::HttpCache::SplitCacheFeatureEnableByDefault();
#if BUILDFLAG(IS_CHROMEOS)
// Threading features.
base::PlatformThread::InitFeaturesPostFieldTrial();
#endif
version_info::Channel channel = chrome::GetChannel();
[[maybe_unused]] bool is_canary_dev =
(channel == version_info::Channel::CANARY ||
channel == version_info::Channel::DEV);
// GWP-ASAN requires crashpad to gather alloc/dealloc stack traces, which is
// not always enabled on ChromeOS.
#if BUILDFLAG(IS_CHROMEOS)
bool enable_gwp_asan = crash_reporter::IsCrashpadEnabled();
#else
bool enable_gwp_asan = true;
#endif
if (enable_gwp_asan) {
#if BUILDFLAG(ENABLE_GWP_ASAN_MALLOC)
gwp_asan::EnableForMalloc(is_canary_dev || is_browser_process,
process_type.c_str());
#endif
#if BUILDFLAG(ENABLE_GWP_ASAN_PARTITIONALLOC)
gwp_asan::EnableForPartitionAlloc(is_canary_dev || is_browser_process,
process_type.c_str());
#endif
}
// Start heap profiling as early as possible so it can start recording
// memory allocations.
heap_profiler_controller_ =
std::make_unique<heap_profiling::HeapProfilerController>(
channel,
GetProfileParamsProcess(*base::CommandLine::ForCurrentProcess()));
heap_profiler_controller_->StartIfEnabled();
if (is_browser_process) {
#if BUILDFLAG(IS_CHROMEOS_ASH)
ash::ConfigureSwap();
ash::InitializeKstaled();
// If we're in an experimental group that locks the browser text we will do
// that now.
ash::LockMainProgramText();
#endif
}
#if BUILDFLAG(IS_WIN)
SetUpExtendedCrashReporting(is_browser_process);
base::sequence_manager::internal::ThreadControllerPowerMonitor::
InitializeOnMainThread();
base::InitializePlatformThreadFeatures();
#endif
// Initialize the HangWatcher.
base::HangWatcher::ProcessType hang_watcher_process_type;
if (process_type.empty()) {
hang_watcher_process_type = base::HangWatcher::ProcessType::kBrowserProcess;
} else if (process_type == switches::kGpuProcess) {
hang_watcher_process_type = base::HangWatcher::ProcessType::kGPUProcess;
} else if (process_type == switches::kRendererProcess) {
hang_watcher_process_type =
base::HangWatcher::ProcessType::kRendererProcess;
} else if (process_type == switches::kUtilityProcess) {
hang_watcher_process_type = base::HangWatcher::ProcessType::kUtilityProcess;
} else {
hang_watcher_process_type = base::HangWatcher::ProcessType::kUnknownProcess;
}
base::HangWatcher::InitializeOnMainThread(hang_watcher_process_type);
base::internal::TimerBase::InitializeFeatures();
base::InitializeCpuReductionExperiment();
base::sequence_manager::internal::SequenceManagerImpl::InitializeFeatures();
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
base::MessagePumpLibevent::InitializeFeatures();
#elif BUILDFLAG(IS_MAC)
base::PlatformThread::InitFeaturesPostFieldTrial();
base::MessagePumpCFRunLoopBase::InitializeFeatures();
#endif
}
#if BUILDFLAG(IS_WIN)
bool ChromeMainDelegate::ShouldHandleConsoleControlEvents() {
// Handle console control events so that orderly shutdown can be performed by
// ChromeContentBrowserClient's override of SessionEnding.
return true;
}
#endif
absl::optional<int> ChromeMainDelegate::BasicStartupComplete() {
#if BUILDFLAG(IS_CHROMEOS_ASH)
ash::BootTimesRecorder::Get()->SaveChromeMainStats();
#endif
base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
// Only allow disabling web security via the command-line flag if the user has
// specified a distinct profile directory. This still enables tests to disable
// web security by setting the kWebKitWebSecurityEnabled pref directly.
//
// Note that this is done in ChromeMainDelegate::BasicStartupComplete()
// because this is the earliest callback. Many places in Chromium gate
// security features around kDisableWebSecurity, and it is unreasonable to
// expect them all to properly also check for kUserDataDir.
if (command_line.HasSwitch(switches::kDisableWebSecurity)) {
base::FilePath default_user_data_dir;
chrome::GetDefaultUserDataDirectory(&default_user_data_dir);
const base::FilePath specified_user_data_dir =
command_line.GetSwitchValuePath(switches::kUserDataDir)
.StripTrailingSeparators();
if (specified_user_data_dir.empty() ||
specified_user_data_dir == default_user_data_dir) {
LOG(ERROR) << "Web security may only be disabled if '--user-data-dir' is "
"also specified with a non-default value.";
base::CommandLine::ForCurrentProcess()->RemoveSwitch(
switches::kDisableWebSecurity);
}
}
#if BUILDFLAG(IS_WIN)
// Browser should not be sandboxed.
const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
if (is_browser && IsSandboxedProcess())
return chrome::RESULT_CODE_INVALID_SANDBOX_STATE;
#endif
#if BUILDFLAG(IS_MAC)
// Give the browser process a longer treadmill, since crashes
// there have more impact.
const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
#endif
content::Profiling::ProcessStarted();