-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
render_frame_host_impl.cc
11425 lines (9992 loc) · 470 KB
/
render_frame_host_impl.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 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <unordered_map>
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/containers/queue.h"
#include "base/debug/alias.h"
#include "base/debug/crash_logging.h"
#include "base/debug/dump_without_crashing.h"
#include "base/i18n/character_encoding.h"
#include "base/lazy_instance.h"
#include "base/memory/memory_pressure_monitor.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/metrics_hashes.h"
#include "base/metrics/user_metrics.h"
#include "base/no_destructor.h"
#include "base/numerics/safe_conversions.h"
#include "base/process/kill.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/current_thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/base_tracing.h"
#include "base/trace_event/optional_trace_event.h"
#include "base/trace_event/trace_conversion_helper.h"
#include "base/trace_event/traced_value.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/download/public/common/download_url_parameters.h"
#include "content/browser/about_url_loader_factory.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "content/browser/accessibility/browser_accessibility_state_impl.h"
#include "content/browser/appcache/appcache_navigation_handle.h"
#include "content/browser/bad_message.h"
#include "content/browser/bluetooth/web_bluetooth_service_impl.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/compute_pressure/compute_pressure_manager.h"
#include "content/browser/contacts/contacts_manager_impl.h"
#include "content/browser/data_url_loader_factory.h"
#include "content/browser/devtools/devtools_instrumentation.h"
#include "content/browser/devtools/protocol/audits.h"
#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
#include "content/browser/download/data_url_blob_reader.h"
#include "content/browser/download/mhtml_generation_manager.h"
#include "content/browser/file_system/file_system_manager_impl.h"
#include "content/browser/file_system/file_system_url_loader_factory.h"
#include "content/browser/file_system_access/file_system_access_manager_impl.h"
#include "content/browser/generic_sensor/sensor_provider_proxy_impl.h"
#include "content/browser/geolocation/geolocation_service_impl.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/idle/idle_manager_impl.h"
#include "content/browser/installedapp/installed_app_provider_impl.h"
#include "content/browser/loader/file_url_loader_factory.h"
#include "content/browser/loader/navigation_early_hints_manager.h"
#include "content/browser/loader/navigation_url_loader_impl.h"
#include "content/browser/loader/prefetch_url_loader_service.h"
#include "content/browser/log_console_message.h"
#include "content/browser/manifest/manifest_manager_host.h"
#include "content/browser/media/media_interface_proxy.h"
#include "content/browser/media/webaudio/audio_context_manager_impl.h"
#include "content/browser/navigation_subresource_loader_params.h"
#include "content/browser/net/cross_origin_embedder_policy_reporter.h"
#include "content/browser/net/cross_origin_opener_policy_reporter.h"
#include "content/browser/payments/payment_app_context_impl.h"
#include "content/browser/permissions/permission_controller_impl.h"
#include "content/browser/permissions/permission_service_context.h"
#include "content/browser/permissions/permission_service_impl.h"
#include "content/browser/portal/portal.h"
#include "content/browser/prerender/prerender_metrics.h"
#include "content/browser/prerender/prerender_processor.h"
#include "content/browser/presentation/presentation_service_impl.h"
#include "content/browser/push_messaging/push_messaging_manager.h"
#include "content/browser/renderer_host/agent_scheduling_group_host.h"
#include "content/browser/renderer_host/back_forward_cache_disable.h"
#include "content/browser/renderer_host/back_forward_cache_impl.h"
#include "content/browser/renderer_host/cookie_utils.h"
#include "content/browser/renderer_host/cross_process_frame_connector.h"
#include "content/browser/renderer_host/debug_urls.h"
#include "content/browser/renderer_host/dip_util.h"
#include "content/browser/renderer_host/frame_tree.h"
#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/browser/renderer_host/input/input_injector_impl.h"
#include "content/browser/renderer_host/input/input_router.h"
#include "content/browser/renderer_host/input/timeout_monitor.h"
#include "content/browser/renderer_host/ipc_utils.h"
#include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
#include "content/browser/renderer_host/modal_close_listener_host.h"
#include "content/browser/renderer_host/navigation_controller_impl.h"
#include "content/browser/renderer_host/navigation_entry_impl.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/navigator.h"
#include "content/browser/renderer_host/page_lifecycle_state_manager.h"
#include "content/browser/renderer_host/recently_destroyed_hosts.h"
#include "content/browser/renderer_host/render_frame_host_delegate.h"
#include "content/browser/renderer_host/render_frame_proxy_host.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate.h"
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_factory.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
#include "content/browser/scoped_active_url.h"
#include "content/browser/screen_enumeration/screen_enumeration_impl.h"
#include "content/browser/service_worker/service_worker_container_host.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_object_host.h"
#include "content/browser/sms/webotp_service.h"
#include "content/browser/speech/speech_synthesis_impl.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/url_loader_factory_params_helper.h"
#include "content/browser/web_exposed_isolation_info.h"
#include "content/browser/web_package/prefetched_signed_exchange_cache.h"
#include "content/browser/web_package/subresource_web_bundle_navigation_info.h"
#include "content/browser/web_package/web_bundle_handle.h"
#include "content/browser/web_package/web_bundle_handle_tracker.h"
#include "content/browser/web_package/web_bundle_navigation_info.h"
#include "content/browser/web_package/web_bundle_source.h"
#include "content/browser/webauth/authenticator_environment_impl.h"
#include "content/browser/webauth/authenticator_impl.h"
#include "content/browser/webauth/webauth_request_security_checker.h"
#include "content/browser/webid/federated_auth_request_impl.h"
#include "content/browser/webid/federated_auth_response_impl.h"
#include "content/browser/webid/flags.h"
#include "content/browser/websockets/websocket_connector_impl.h"
#include "content/browser/webtransport/web_transport_connector_impl.h"
#include "content/browser/webui/url_data_manager_backend.h"
#include "content/browser/webui/web_ui_controller_factory_registry.h"
#include "content/browser/worker_host/dedicated_worker_host_factory_impl.h"
#include "content/browser/worker_host/shared_worker_service_impl.h"
#include "content/common/associated_interfaces.mojom.h"
#include "content/common/content_constants_internal.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/frame.mojom.h"
#include "content/common/navigation_client.mojom.h"
#include "content/common/navigation_params.h"
#include "content/common/navigation_params_mojom_traits.h"
#include "content/common/navigation_params_utils.h"
#include "content/common/render_message_filter.mojom.h"
#include "content/common/renderer.mojom.h"
#include "content/common/state_transitions.h"
#include "content/public/browser/ax_event_notification_details.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_plugin_guest_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/idle_manager.h"
#include "content/public/browser/media_player_watch_time.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/sms_fetcher.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_ui_url_loader_factory.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/isolated_world_ids.h"
#include "content/public/common/network_service_util.h"
#include "content/public/common/origin_util.h"
#include "content/public/common/page_visibility_state.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/three_d_api_types.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
#include "device/gamepad/gamepad_monitor.h"
#include "media/audio/audio_manager.h"
#include "media/base/media_switches.h"
#include "media/base/user_input_monitor.h"
#include "media/learning/common/value.h"
#include "media/media_buildflags.h"
#include "media/mojo/mojom/remoting.mojom.h"
#include "media/mojo/services/video_decode_perf_history.h"
#include "mojo/public/cpp/bindings/message.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/base/schemeful_site.h"
#include "net/cookies/cookie_constants.h"
#include "services/device/public/cpp/device_features.h"
#include "services/device/public/mojom/sensor_provider.mojom.h"
#include "services/device/public/mojom/wake_lock.mojom.h"
#include "services/device/public/mojom/wake_lock_context.mojom.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/is_potentially_trustworthy.h"
#include "services/network/public/cpp/not_implemented_url_loader_factory.h"
#include "services/network/public/cpp/trust_token_operation_authorization.h"
#include "services/network/public/cpp/web_sandbox_flags.h"
#include "services/network/public/cpp/wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/cookie_access_observer.mojom.h"
#include "services/network/public/mojom/ip_address_space.mojom.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "services/network/public/mojom/url_loader.mojom-shared.h"
#include "services/network/public/mojom/web_sandbox_flags.mojom-shared.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/blob/blob_utils.h"
#include "third_party/blink/public/common/chrome_debug_urls.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/frame/frame_policy.h"
#include "third_party/blink/public/common/loader/inter_process_time_ticks_converter.h"
#include "third_party/blink/public/common/loader/resource_type_util.h"
#include "third_party/blink/public/common/messaging/transferable_message.h"
#include "third_party/blink/public/common/permissions_policy/document_policy_features.h"
#include "third_party/blink/public/common/permissions_policy/permissions_policy.h"
#include "third_party/blink/public/mojom/appcache/appcache.mojom.h"
#include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom.h"
#include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom.h"
#include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h"
#include "third_party/blink/public/mojom/choosers/popup_menu.mojom.h"
#include "third_party/blink/public/mojom/compute_pressure/compute_pressure.mojom.h"
#include "third_party/blink/public/mojom/frame/frame.mojom.h"
#include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/frame/media_player_action.mojom.h"
#include "third_party/blink/public/mojom/frame/user_activation_update_types.mojom.h"
#include "third_party/blink/public/mojom/geolocation/geolocation_service.mojom.h"
#include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h"
#include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h"
#include "third_party/blink/public/mojom/loader/url_loader_factory_bundle.mojom.h"
#include "third_party/blink/public/mojom/security_context/insecure_request_policy.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
#include "third_party/blink/public/mojom/sms/webotp_service.mojom.h"
#include "third_party/blink/public/mojom/timing/resource_timing.mojom.h"
#include "third_party/blink/public/mojom/usb/web_usb_service.mojom.h"
#include "third_party/blink/public/mojom/webauthn/virtual_authenticator.mojom.h"
#include "ui/accessibility/ax_action_handler_registry.h"
#include "ui/accessibility/ax_common.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_update.h"
#include "ui/events/event_constants.h"
#include "ui/gfx/geometry/quad_f.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/url_constants.h"
#if defined(OS_ANDROID)
#include "content/browser/android/content_url_loader_factory.h"
#include "content/browser/android/java_interfaces_impl.h"
#include "content/browser/renderer_host/render_frame_host_android.h"
#include "content/public/browser/android/java_interfaces.h"
#else
#include "content/browser/hid/hid_service.h"
#include "content/browser/host_zoom_map_impl.h"
#include "content/browser/serial/serial_service.h"
#endif
#if defined(OS_MAC)
#include "content/browser/renderer_host/popup_menu_helper_mac.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/browser/plugin_service_impl.h"
#include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
#endif
namespace content {
#if defined(AX_FAIL_FAST_BUILD)
// Enable fast fails on clusterfuzz and other builds used to debug Chrome,
// which should help narrow down illegal ax trees more quickly.
// static
int RenderFrameHostImpl::max_accessibility_resets_ = 0;
#else
int RenderFrameHostImpl::max_accessibility_resets_ = 4;
#endif // AX_FAIL_FAST_BUILD
class RenderFrameHostOrProxy {
public:
RenderFrameHostOrProxy(RenderFrameHostImpl* frame,
RenderFrameProxyHost* proxy) {
DCHECK(!frame || !proxy)
<< "Both frame and proxy can't be non-null at the same time";
if (proxy) {
frame_or_proxy_ = proxy;
return;
}
if (frame) {
frame_or_proxy_ = frame;
return;
}
}
explicit operator bool() { return frame_or_proxy_.index() > 0; }
FrameTreeNode* GetFrameTreeNode() {
if (auto* proxy = GetProxy()) {
return proxy->frame_tree_node();
} else if (auto* frame = GetFrame()) {
return frame->frame_tree_node();
}
return nullptr;
}
RenderFrameHostImpl* GetCurrentFrameHost() {
if (auto* proxy = GetProxy()) {
return proxy->frame_tree_node()->current_frame_host();
} else if (auto* frame = GetFrame()) {
return frame;
}
return nullptr;
}
private:
RenderFrameProxyHost* GetProxy() {
if (auto** proxy = absl::get_if<RenderFrameProxyHost*>(&frame_or_proxy_)) {
return *proxy;
}
return nullptr;
}
RenderFrameHostImpl* GetFrame() {
if (auto** frame = absl::get_if<RenderFrameHostImpl*>(&frame_or_proxy_)) {
return *frame;
}
return nullptr;
}
absl::variant<absl::monostate, RenderFrameHostImpl*, RenderFrameProxyHost*>
frame_or_proxy_;
};
namespace {
#if defined(OS_ANDROID)
const void* const kRenderFrameHostAndroidKey = &kRenderFrameHostAndroidKey;
#endif // OS_ANDROID
// The next value to use for the accessibility reset token.
int g_next_accessibility_reset_token = 1;
// Whether to allow injecting javascript into any kind of frame, for Android
// WebView, WebLayer, Fuchsia web.ContextProvider and CastOS content shell.
bool g_allow_injecting_javascript = false;
const char kDotGoogleDotCom[] = ".google.com";
typedef std::unordered_map<GlobalFrameRoutingId,
RenderFrameHostImpl*,
GlobalFrameRoutingIdHasher>
RoutingIDFrameMap;
base::LazyInstance<RoutingIDFrameMap>::DestructorAtExit g_routing_id_frame_map =
LAZY_INSTANCE_INITIALIZER;
using TokenFrameMap = std::unordered_map<blink::LocalFrameToken,
RenderFrameHostImpl*,
blink::LocalFrameToken::Hasher>;
base::LazyInstance<TokenFrameMap>::Leaky g_token_frame_map =
LAZY_INSTANCE_INITIALIZER;
BackForwardCacheMetrics::NotRestoredReason
RendererEvictionReasonToNotRestoredReason(
blink::mojom::RendererEvictionReason reason) {
switch (reason) {
case blink::mojom::RendererEvictionReason::kJavaScriptExecution:
return BackForwardCacheMetrics::NotRestoredReason::kJavaScriptExecution;
case blink::mojom::RendererEvictionReason::
kNetworkRequestDatapipeDrainedAsBytesConsumer:
return BackForwardCacheMetrics::NotRestoredReason::
kNetworkRequestDatapipeDrainedAsBytesConsumer;
case blink::mojom::RendererEvictionReason::kNetworkRequestRedirected:
return BackForwardCacheMetrics::NotRestoredReason::
kNetworkRequestRedirected;
case blink::mojom::RendererEvictionReason::kNetworkRequestTimeout:
return BackForwardCacheMetrics::NotRestoredReason::kNetworkRequestTimeout;
case blink::mojom::RendererEvictionReason::kNetworkExceedsBufferLimit:
return BackForwardCacheMetrics::NotRestoredReason::
kNetworkExceedsBufferLimit;
}
NOTREACHED();
return BackForwardCacheMetrics::NotRestoredReason::kUnknown;
}
// Ensure that we reset nav_entry_id_ in DidCommitProvisionalLoad if any of
// the validations fail and lead to an early return. Call disable() once we
// know the commit will be successful. Resetting nav_entry_id_ avoids acting on
// any UpdateState or UpdateTitle messages after an ignored commit.
class ScopedCommitStateResetter {
public:
explicit ScopedCommitStateResetter(RenderFrameHostImpl* render_frame_host)
: render_frame_host_(render_frame_host), disabled_(false) {}
~ScopedCommitStateResetter() {
if (!disabled_) {
render_frame_host_->set_nav_entry_id(0);
}
}
void disable() { disabled_ = true; }
private:
RenderFrameHostImpl* render_frame_host_;
bool disabled_;
};
class ActiveURLMessageFilter : public mojo::MessageFilter {
public:
explicit ActiveURLMessageFilter(RenderFrameHostImpl* render_frame_host)
: render_frame_host_(render_frame_host) {}
~ActiveURLMessageFilter() override {
if (debug_url_set_) {
GetContentClient()->SetActiveURL(GURL(), "");
}
}
// mojo::MessageFilter overrides.
bool WillDispatch(mojo::Message* message) override {
debug_url_set_ = true;
auto* frame_tree_node = render_frame_host_->frame_tree_node();
GetContentClient()->SetActiveURL(frame_tree_node->current_url(),
frame_tree_node->frame_tree()
->root()
->current_origin()
.GetDebugString());
return true;
}
void DidDispatchOrReject(mojo::Message* message, bool accepted) override {
GetContentClient()->SetActiveURL(GURL(), "");
debug_url_set_ = false;
}
private:
RenderFrameHostImpl* render_frame_host_;
bool debug_url_set_ = false;
};
// This class can be added as a MessageFilter to a mojo receiver to detect
// messages received while the the associated frame is in the Back-Forward
// Cache. Documents that are in the bfcache should not be sending mojo messages
// back to the browser.
class BackForwardCacheMessageFilter : public mojo::MessageFilter {
public:
explicit BackForwardCacheMessageFilter(
RenderFrameHostImpl* render_frame_host,
const char* interface_name,
BackForwardCacheImpl::MessageHandlingPolicyWhenCached policy)
: render_frame_host_(render_frame_host),
interface_name_(interface_name),
policy_(policy) {}
~BackForwardCacheMessageFilter() override = default;
private:
// mojo::MessageFilter overrides.
bool WillDispatch(mojo::Message* message) override {
if (!render_frame_host_->render_view_host())
return false;
if (render_frame_host_->render_view_host()
->GetPageLifecycleStateManager()
->RendererExpectedToSendChannelAssociatedIpcs() ||
ProcessHoldsNonCachedPages() ||
policy_ == BackForwardCacheImpl::kMessagePolicyNone) {
return true;
}
DLOG(ERROR) << "Received message " << message->name() << " on interface "
<< interface_name_ << " from frame in bfcache.";
TRACE_EVENT2(
"content", "BackForwardCacheMessageFilter::WillDispatch bad_message",
"interface_name", interface_name_, "message_name", message->name());
base::UmaHistogramSparse(
"BackForwardCache.UnexpectedRendererToBrowserMessage.InterfaceName",
static_cast<int32_t>(base::HashMetricName(interface_name_)));
switch (policy_) {
case BackForwardCacheImpl::kMessagePolicyNone:
case BackForwardCacheImpl::kMessagePolicyLog:
return true;
case BackForwardCacheImpl::kMessagePolicyDump:
base::debug::DumpWithoutCrashing();
return true;
}
}
void DidDispatchOrReject(mojo::Message* message, bool accepted) override {}
// TODO(https://crbug.com/1125996): Remove once a well-behaved frozen
// RenderFrame never send IPCs messages, even if there are active pages in the
// process.
bool ProcessHoldsNonCachedPages() {
return RenderViewHostImpl::HasNonBackForwardCachedInstancesForProcess(
render_frame_host_->GetProcess());
}
RenderFrameHostImpl* const render_frame_host_;
const char* const interface_name_;
const BackForwardCacheImpl::MessageHandlingPolicyWhenCached policy_;
};
// This class is used to chain multiple mojo::MessageFilter. Messages will be
// processed by the filters in the same order as the filters are added with the
// Add() method. WillDispatch() might not be called for all filters or might see
// a modified message if a filter earlier in the chain discards or modifies it.
// Similarly a given filter instance might not receive a DidDispatchOrReject()
// call even if WillDispatch() was called if a filter further down the chain
// discarded it. Long story short, the order in which filters are added is
// important!
class MessageFilterChain final : public mojo::MessageFilter {
public:
MessageFilterChain() = default;
~MessageFilterChain() final = default;
bool WillDispatch(mojo::Message* message) override {
for (auto& filter : filters_) {
if (!filter->WillDispatch(message))
return false;
}
return true;
}
void DidDispatchOrReject(mojo::Message* message, bool accepted) override {
for (auto& filter : filters_) {
filter->DidDispatchOrReject(message, accepted);
}
}
// Adds a filter to the end of the chain. See class description for ordering
// implications.
void Add(std::unique_ptr<mojo::MessageFilter> filter) {
filters_.push_back(std::move(filter));
}
private:
std::vector<std::unique_ptr<mojo::MessageFilter>> filters_;
};
std::unique_ptr<mojo::MessageFilter>
CreateMessageFilterForAssociatedReceiverImpl(
RenderFrameHostImpl* render_frame_host,
const char* interface_name,
BackForwardCacheImpl::MessageHandlingPolicyWhenCached policy) {
auto filter_chain = std::make_unique<MessageFilterChain>();
filter_chain->Add(std::make_unique<BackForwardCacheMessageFilter>(
render_frame_host, interface_name, policy));
// BackForwardCacheMessageFilter might drop messages so add
// ActiveURLMessageFilter at the end of the chain as we need to make sure that
// the debug url is reset, that is, DidDispatchOrReject() is called if
// WillDispatch().
filter_chain->Add(
std::make_unique<ActiveURLMessageFilter>(render_frame_host));
return filter_chain;
}
void GrantFileAccess(int child_id,
const std::vector<base::FilePath>& file_paths) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
for (const auto& file : file_paths) {
if (!policy->CanReadFile(child_id, file))
policy->GrantReadFile(child_id, file);
}
}
#if BUILDFLAG(ENABLE_MEDIA_REMOTING)
// RemoterFactory that delegates Create() calls to the ContentBrowserClient.
//
// Since Create() could be called at any time, perhaps by a stray task being run
// after a RenderFrameHost has been destroyed, the RemoterFactoryImpl uses the
// process/routing IDs as a weak reference to the RenderFrameHostImpl.
class RemoterFactoryImpl final : public media::mojom::RemoterFactory {
public:
RemoterFactoryImpl(int process_id, int routing_id)
: process_id_(process_id), routing_id_(routing_id) {}
private:
void Create(mojo::PendingRemote<media::mojom::RemotingSource> source,
mojo::PendingReceiver<media::mojom::Remoter> receiver) final {
if (auto* host = RenderFrameHostImpl::FromID(process_id_, routing_id_)) {
GetContentClient()->browser()->CreateMediaRemoter(host, std::move(source),
std::move(receiver));
}
}
const int process_id_;
const int routing_id_;
DISALLOW_COPY_AND_ASSIGN(RemoterFactoryImpl);
};
#endif // BUILDFLAG(ENABLE_MEDIA_REMOTING)
RenderFrameHostOrProxy LookupRenderFrameHostOrProxy(int process_id,
int routing_id) {
RenderFrameHostImpl* rfh =
RenderFrameHostImpl::FromID(process_id, routing_id);
RenderFrameProxyHost* proxy = nullptr;
if (!rfh)
proxy = RenderFrameProxyHost::FromID(process_id, routing_id);
return RenderFrameHostOrProxy(rfh, proxy);
}
RenderFrameHostOrProxy LookupRenderFrameHostOrProxy(
int process_id,
const blink::FrameToken& frame_token) {
if (frame_token.Is<blink::LocalFrameToken>()) {
auto it = g_token_frame_map.Get().find(
frame_token.GetAs<blink::LocalFrameToken>());
// The check against |process_id| isn't strictly necessary, but represents
// an extra level of protection against a renderer trying to force a frame
// token.
if (it == g_token_frame_map.Get().end() ||
process_id != it->second->GetProcess()->GetID()) {
return RenderFrameHostOrProxy(nullptr, nullptr);
}
return RenderFrameHostOrProxy(it->second, nullptr);
}
DCHECK(frame_token.Is<blink::RemoteFrameToken>());
return RenderFrameHostOrProxy(
nullptr, RenderFrameProxyHost::FromFrameToken(
process_id, frame_token.GetAs<blink::RemoteFrameToken>()));
}
// Takes the lower 31 bits of the metric-name-hash of a Mojo interface |name|.
base::Histogram::Sample HashInterfaceNameToHistogramSample(
base::StringPiece name) {
return base::strict_cast<base::Histogram::Sample>(
static_cast<int32_t>(base::HashMetricName(name) & 0x7fffffffull));
}
// Set crash keys that will help understand the circumstances of a renderer
// kill. Note that the commit URL is already reported in a crash key, and
// additional keys are logged in RenderProcessHostImpl::ShutdownForBadMessage.
void LogRendererKillCrashKeys(const SiteInfo& site_info) {
static auto* site_info_key = base::debug::AllocateCrashKeyString(
"current_site_info", base::debug::CrashKeySize::Size256);
base::debug::SetCrashKeyString(site_info_key, site_info.GetDebugString());
}
void LogCanCommitOriginAndUrlFailureReason(const std::string& failure_reason) {
static auto* failure_reason_key = base::debug::AllocateCrashKeyString(
"rfhi_can_commit_failure_reason", base::debug::CrashKeySize::Size64);
base::debug::SetCrashKeyString(failure_reason_key, failure_reason);
}
std::unique_ptr<blink::PendingURLLoaderFactoryBundle> CloneFactoryBundle(
scoped_refptr<blink::URLLoaderFactoryBundle> bundle) {
return base::WrapUnique(static_cast<blink::PendingURLLoaderFactoryBundle*>(
bundle->Clone().release()));
}
// Helper method to download a URL on UI thread.
void StartDownload(
std::unique_ptr<download::DownloadUrlParameters> parameters,
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RenderProcessHost* render_process_host =
RenderProcessHost::FromID(parameters->render_process_host_id());
if (!render_process_host)
return;
BrowserContext* browser_context = render_process_host->GetBrowserContext();
DownloadManager* download_manager =
BrowserContext::GetDownloadManager(browser_context);
parameters->set_download_source(download::DownloadSource::FROM_RENDERER);
download_manager->DownloadUrl(std::move(parameters),
std::move(blob_url_loader_factory));
}
// Called on the UI thread when the data URL in the BlobDataHandle
// is read.
void OnDataURLRetrieved(
std::unique_ptr<download::DownloadUrlParameters> parameters,
GURL data_url) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!data_url.is_valid())
return;
parameters->set_url(std::move(data_url));
StartDownload(std::move(parameters), nullptr);
}
// Subframe navigations can optionally have associated Trust Tokens operations
// (https://github.com/wicg/trust-token-api). If the operation's type is
// "redemption" or "signing" (as opposed to "issuance"), the parent's frame
// needs to have the trust-token-redemption Permissions Policy feature enabled.
bool ParentNeedsTrustTokenPermissionsPolicy(
const mojom::BeginNavigationParams& begin_params) {
if (!begin_params.trust_token_params)
return false;
return network::DoesTrustTokenOperationRequirePermissionsPolicy(
begin_params.trust_token_params->type);
}
// Analyzes trusted sources of a frame's trust-token-redemption Permissions
// Policy feature to see if the feature is definitely disabled or potentially
// enabled.
//
// This information will be bound to a URLLoaderFactory; if the answer is
// "definitely disabled," the network service will report a bad message if it
// receives a request from the renderer to execute a Trust Tokens redemption or
// signing operation in the frame.
//
// A return value of kForbid denotes that the feature is disabled for the
// frame. A return value of kPotentiallyPermit means that all trusted
// information sources say that the policy is enabled.
network::mojom::TrustTokenRedemptionPolicy
DetermineWhetherToForbidTrustTokenRedemption(
const RenderFrameHostImpl* parent,
const mojom::CommitNavigationParams& commit_params,
const url::Origin& subframe_origin) {
// For main frame loads, the frame's permissions policy is determined entirely
// by response headers, which are provided by the renderer.
if (!parent)
return network::mojom::TrustTokenRedemptionPolicy::kPotentiallyPermit;
const blink::PermissionsPolicy* parent_policy = parent->permissions_policy();
blink::ParsedPermissionsPolicy container_policy =
commit_params.frame_policy.container_policy;
auto subframe_policy = blink::PermissionsPolicy::CreateFromParentPolicy(
parent_policy, container_policy, subframe_origin);
if (subframe_policy->IsFeatureEnabled(
blink::mojom::PermissionsPolicyFeature::kTrustTokenRedemption)) {
return network::mojom::TrustTokenRedemptionPolicy::kPotentiallyPermit;
}
return network::mojom::TrustTokenRedemptionPolicy::kForbid;
}
// When a frame creates its initial subresource loaders, it needs to know
// whether the trust-token-redemption Permissions Policy feature will be enabled
// after the commit finishes, which is a little involved (see
// DetermineWhetherToForbidTrustTokenRedemption). In contrast, if it needs to
// make this decision once the frame has committted---for instance, to create
// more loaders after the network service crashes---it can directly consult the
// current Permissions Policy state to determine whether the feature is enabled.
network::mojom::TrustTokenRedemptionPolicy
DetermineAfterCommitWhetherToForbidTrustTokenRedemption(
RenderFrameHostImpl* impl) {
return impl->IsFeatureEnabled(
blink::mojom::PermissionsPolicyFeature::kTrustTokenRedemption)
? network::mojom::TrustTokenRedemptionPolicy::kPotentiallyPermit
: network::mojom::TrustTokenRedemptionPolicy::kForbid;
}
// Returns the string corresponding to LifecycleStateImpl, used for logging
// crash keys.
const char* LifecycleStateImplToString(
RenderFrameHostImpl::LifecycleStateImpl state) {
using LifecycleStateImpl = RenderFrameHostImpl::LifecycleStateImpl;
switch (state) {
case LifecycleStateImpl::kSpeculative:
return "Speculative";
case LifecycleStateImpl::kPrerendering:
return "Prerendering";
case LifecycleStateImpl::kPendingCommit:
return "PendingCommit";
case LifecycleStateImpl::kActive:
return "Active";
case LifecycleStateImpl::kInBackForwardCache:
return "InBackForwardCache";
case LifecycleStateImpl::kRunningUnloadHandlers:
return "RunningUnloadHandlers";
case LifecycleStateImpl::kReadyToBeDeleted:
return "ReadyToDeleted";
}
}
// Verify that |browser_side_origin| and |renderer_side_origin| match. See also
// https://crbug.com/888079.
void VerifyThatBrowserAndRendererCalculatedOriginsToCommitMatch(
NavigationRequest* navigation_request,
const mojom::DidCommitProvisionalLoadParams& params) {
DCHECK(navigation_request);
DCHECK(!navigation_request->IsSameDocument());
DCHECK(!navigation_request->IsServedFromBackForwardCache());
// Ignore for now cases where the NavigationRequest is in an unexpectedly
// early state. Triggered by the following tests:
// NavigationBrowserTest.OpenerNavigation_DownloadPolicy,
// WebContentsImplBrowserTest.NewNamedWindow.
if (navigation_request->state() < NavigationRequest::WILL_PROCESS_RESPONSE)
return;
// Check if both the renderer and browser expect an opaque origin. This
// effectively ignores the following:
// - precursor origins
// - TODO(https://crbug.com/1041376): mismatched nonces (even if precursor
// origins would have matched)
const url::Origin& renderer_side_origin = params.origin;
url::Origin browser_side_origin =
navigation_request->GetOriginForURLLoaderFactory();
if (renderer_side_origin.opaque() && browser_side_origin.opaque())
return;
// Navigating to file://localhost/... on windows causes `browser_side_origin`
// and `renderer_side_origin` to be different (file://localhost/ vs file:///).
// In particular, without the following block the test
// ContentSecurityPolicyBrowserTest.FileURLs fails.
if ((browser_side_origin.opaque() == renderer_side_origin.opaque()) &&
browser_side_origin.scheme() == url::kFileScheme &&
renderer_side_origin.scheme() == url::kFileScheme) {
return;
}
DCHECK_EQ(browser_side_origin, renderer_side_origin)
<< "; navigation_request->GetURL() = " << navigation_request->GetURL();
}
// Enum used for Navigation.VerifyDidCommitParams histogram, to indicate which
// DidCommitProvisionalLoadParams differ when comparing browser- vs
// renderer-calculated values.
// Do NOT delete or reorder existing entries.
enum class VerifyDidCommitParamsDifference {
kIntendedAsNewEntry = 0,
kMethod = 1,
kURLIsUnreachable = 2,
kBaseURL = 3,
kPostID = 4,
kIsOverridingUserAgent = 5,
kHTTPStatusCode = 6,
kShouldUpdateHistory = 7,
kGesture = 8,
kShouldReplaceCurrentEntry = 9,
kMaxValue = kShouldReplaceCurrentEntry,
};
bool ValidateCSPAttribute(const std::string& value) {
if (!base::IsStringASCII(value))
return false;
if (value.find('\n') != std::string::npos ||
value.find('\r') != std::string::npos) {
return false;
}
return true;
}
perfetto::protos::pbzero::FrameDeleteIntention FrameDeleteIntentionToProto(
mojom::FrameDeleteIntention intent) {
using ProtoLevel = perfetto::protos::pbzero::FrameDeleteIntention;
switch (intent) {
case mojom::FrameDeleteIntention::kNotMainFrame:
return ProtoLevel::FRAME_DELETE_INTENTION_NOT_MAIN_FRAME;
case mojom::FrameDeleteIntention::kSpeculativeMainFrameForShutdown:
return ProtoLevel::
FRAME_DELETE_INTENTION_SPECULATIVE_MAIN_FRAME_FOR_SHUTDOWN;
case mojom::FrameDeleteIntention::
kSpeculativeMainFrameForNavigationCancelled:
return ProtoLevel::
FRAME_DELETE_INTENTION_SPECULATIVE_MAIN_FRAME_FOR_NAVIGATION_CANCELLED;
}
// All cases should've been handled by the switch case above.
NOTREACHED();
return ProtoLevel::FRAME_DELETE_INTENTION_NOT_MAIN_FRAME;
}
void WriteRenderFrameImplDeletion(perfetto::EventContext& ctx,
RenderFrameHostImpl* rfh,
mojom::FrameDeleteIntention intent) {
auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
auto* data = event->set_render_frame_impl_deletion();
data->set_has_pending_commit(rfh->HasPendingCommitNavigation());
data->set_has_pending_cross_document_commit(
rfh->HasPendingCommitForCrossDocumentNavigation());
data->set_frame_tree_node_id(rfh->GetFrameTreeNodeId());
data->set_intent(FrameDeleteIntentionToProto(intent));
}
// Returns an experimental process shutdown delay if the SubframeShutdownDelay
// experiment is enabled, 0 if not or if under memory pressure. This experiment
// keeps subframe processes alive for a few seconds in case they can be reused.
base::TimeDelta GetSubframeProcessShutdownDelay(
BrowserContext* browser_context) {
static constexpr base::TimeDelta kZeroDelay;
if (!base::FeatureList::IsEnabled(features::kSubframeShutdownDelay))
return kZeroDelay;
// Don't delay process shutdown under memory pressure. Does not cancel
// existing shutdown delays for processes already in delayed-shutdown state.
const auto* const memory_monitor = base::MemoryPressureMonitor::Get();
if (memory_monitor &&
memory_monitor->GetCurrentPressureLevel() >=
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) {
return kZeroDelay;
}
static constexpr base::TimeDelta kShortDelay =
base::TimeDelta::FromSeconds(2);
static constexpr base::TimeDelta kLongDelay = base::TimeDelta::FromSeconds(8);
// Added to delay if based on recent performance (i.e., |kHistoryBased| and
// |kHistoryBasedLong|) to account for small variations in timing.
static constexpr base::TimeDelta kDelayBuffer =
base::TimeDelta::FromSeconds(1);
switch (features::kSubframeShutdownDelayTypeParam.Get()) {
case features::SubframeShutdownDelayType::kConstant: {
return kShortDelay;
}
case features::SubframeShutdownDelayType::kConstantLong: {
return kLongDelay;
}
case features::SubframeShutdownDelayType::kHistoryBased: {
const base::TimeDelta reuse_interval =
RecentlyDestroyedHosts::GetPercentileReuseInterval(50,
browser_context);
// If no subframe reuse has happened recently, don't delay process
// shutdown at all.
if (reuse_interval.is_zero())
return kZeroDelay;
return std::min(reuse_interval + kDelayBuffer, kLongDelay);
}
case features::SubframeShutdownDelayType::kHistoryBasedLong: {
const base::TimeDelta reuse_interval =
RecentlyDestroyedHosts::GetPercentileReuseInterval(75,
browser_context);
// If no subframe reuse has happened recently, don't delay process
// shutdown at all.
if (reuse_interval.is_zero())
return kZeroDelay;
return std::min(reuse_interval + kDelayBuffer, kLongDelay);
}
case features::SubframeShutdownDelayType::kMemoryBased: {
// See subframe-reuse design doc for more detail on these values.
// docs.google.com/document/d/1x_h4Gg4ForILEj8A4rMBX6d84uHWyQ9RSXmGVqMlBTk
static constexpr int64_t kHighMemoryThreshold = 8000000000;
static constexpr int64_t kMaxMemoryThreshold = 16000000000;
const int64_t available_memory =
base::SysInfo::AmountOfAvailablePhysicalMemory();
if (available_memory <= kHighMemoryThreshold)
return kShortDelay;
if (available_memory >= kMaxMemoryThreshold)
return kLongDelay;
// Scale delay linearly based on where |available_memory| lies between
// |kHighMemoryThreshold| and |kMaxMemoryThreshold|.
const int64_t available_memory_factor =
(available_memory - kHighMemoryThreshold) /
(kMaxMemoryThreshold - kHighMemoryThreshold);
return kShortDelay + (kLongDelay - kShortDelay) * available_memory_factor;
}
}
NOTREACHED();
}
} // namespace
#if BUILDFLAG(ENABLE_PLUGINS)
class PepperPluginInstanceHost : public mojom::PepperPluginInstanceHost {
public:
PepperPluginInstanceHost(
int32_t instance_id,
RenderFrameHostImpl* frame_host,
mojo::PendingAssociatedRemote<mojom::PepperPluginInstance> instance,
mojo::PendingAssociatedReceiver<mojom::PepperPluginInstanceHost> host)
: instance_id_(instance_id),
frame_host_(frame_host),
receiver_(this, std::move(host)),
remote_(std::move(instance)) {
frame_host_->delegate()->OnPepperInstanceCreated(frame_host_, instance_id);
remote_.set_disconnect_handler(
base::BindOnce(&RenderFrameHostImpl::PepperInstanceClosed,
base::Unretained(frame_host), instance_id_));
}
~PepperPluginInstanceHost() override = default;
// mojom::PepperPluginInstanceHost overrides.
void StartsPlayback() override {
frame_host_->delegate()->OnPepperStartsPlayback(frame_host_, instance_id_);
}