blob: 956085eaaf10e59a6b229fc37c17b4903e35ff20 [file] [log] [blame]
// 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/renderer/render_frame_impl.h"
#include <string.h>
#include <algorithm>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "base/auto_reset.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/debug/alias.h"
#include "base/debug/asan_invalid_access.h"
#include "base/debug/crash_logging.h"
#include "base/debug/dump_without_crashing.h"
#include "base/feature_list.h"
#include "base/files/file.h"
#include "base/i18n/char_iterator.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/optional.h"
#include "base/process/process.h"
#include "base/stl_util.h"
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "content/common/accessibility_messages.h"
#include "content/common/associated_interface_provider_impl.h"
#include "content/common/associated_interfaces.mojom.h"
#include "content/common/content_constants_internal.h"
#include "content/common/content_security_policy/csp_context.h"
#include "content/common/content_security_policy_header.h"
#include "content/common/download/mhtml_save_status.h"
#include "content/common/edit_command.h"
#include "content/common/frame_messages.h"
#include "content/common/frame_owner_properties.h"
#include "content/common/frame_replication_state.h"
#include "content/common/input_messages.h"
#include "content/common/navigation_params.h"
#include "content/common/page_messages.h"
#include "content/common/renderer_host.mojom.h"
#include "content/common/savable_subframe.h"
#include "content/common/service_worker/service_worker_types.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/common/swapped_out_messages.h"
#include "content/common/view_messages.h"
#include "content/common/weak_wrapper_shared_url_loader_factory.h"
#include "content/public/common/appcache_info.h"
#include "content/public/common/bind_interface_helpers.h"
#include "content/public/common/bindings_policy.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/context_menu_params.h"
#include "content/public/common/favicon_url.h"
#include "content/public/common/file_chooser_file_info.h"
#include "content/public/common/file_chooser_params.h"
#include "content/public/common/isolated_world_ids.h"
#include "content/public/common/page_state.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_loader_throttle.h"
#include "content/public/common/url_utils.h"
#include "content/public/renderer/browser_plugin_delegate.h"
#include "content/public/renderer/child_url_loader_factory_getter.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/renderer/context_menu_client.h"
#include "content/public/renderer/document_state.h"
#include "content/public/renderer/navigation_state.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_visitor.h"
#include "content/public/renderer/renderer_ppapi_host.h"
#include "content/renderer/accessibility/render_accessibility_impl.h"
#include "content/renderer/appcache/appcache_dispatcher.h"
#include "content/renderer/browser_plugin/browser_plugin.h"
#include "content/renderer/browser_plugin/browser_plugin_manager.h"
#include "content/renderer/content_security_policy_util.h"
#include "content/renderer/context_menu_params_builder.h"
#include "content/renderer/dom_automation_controller.h"
#include "content/renderer/effective_connection_type_helper.h"
#include "content/renderer/external_popup_menu.h"
#include "content/renderer/frame_owner_properties.h"
#include "content/renderer/gpu/gpu_benchmarking_extension.h"
#include "content/renderer/gpu/render_widget_compositor.h"
#include "content/renderer/history_entry.h"
#include "content/renderer/history_serialization.h"
#include "content/renderer/image_downloader/image_downloader_impl.h"
#include "content/renderer/ime_event_guard.h"
#include "content/renderer/input/frame_input_handler_impl.h"
#include "content/renderer/input/input_handler_manager.h"
#include "content/renderer/input/input_target_client_impl.h"
#include "content/renderer/installedapp/related_apps_fetcher.h"
#include "content/renderer/internal_document_state_data.h"
#include "content/renderer/loader/request_extra_data.h"
#include "content/renderer/loader/web_url_loader_impl.h"
#include "content/renderer/loader/web_url_request_util.h"
#include "content/renderer/loader/weburlresponse_extradata_impl.h"
#include "content/renderer/manifest/manifest_change_notifier.h"
#include "content/renderer/manifest/manifest_manager.h"
#include "content/renderer/media/audio_device_factory.h"
#include "content/renderer/media/audio_output_ipc_factory.h"
#include "content/renderer/media/media_devices_listener_impl.h"
#include "content/renderer/media/media_permission_dispatcher.h"
#include "content/renderer/media/media_stream_device_observer.h"
#include "content/renderer/media/user_media_client_impl.h"
#include "content/renderer/mojo/blink_interface_registry_impl.h"
#include "content/renderer/navigation_state_impl.h"
#include "content/renderer/pepper/pepper_audio_controller.h"
#include "content/renderer/pepper/plugin_instance_throttler_impl.h"
#include "content/renderer/presentation/presentation_dispatcher.h"
#include "content/renderer/push_messaging/push_messaging_client.h"
#include "content/renderer/quota_dispatcher.h"
#include "content/renderer/render_frame_proxy.h"
#include "content/renderer/render_process.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_view_impl.h"
#include "content/renderer/render_widget_fullscreen_pepper.h"
#include "content/renderer/renderer_blink_platform_impl.h"
#include "content/renderer/renderer_webapplicationcachehost_impl.h"
#include "content/renderer/resource_timing_info_conversions.h"
#include "content/renderer/savable_resources.h"
#include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
#include "content/renderer/service_worker/service_worker_handle_reference.h"
#include "content/renderer/service_worker/service_worker_network_provider.h"
#include "content/renderer/service_worker/service_worker_provider_context.h"
#include "content/renderer/service_worker/web_service_worker_provider_impl.h"
#include "content/renderer/service_worker/worker_fetch_context_impl.h"
#include "content/renderer/shared_worker/shared_worker_repository.h"
#include "content/renderer/skia_benchmarking_extension.h"
#include "content/renderer/stats_collection_controller.h"
#include "content/renderer/v8_value_converter_impl.h"
#include "content/renderer/web_frame_utils.h"
#include "content/renderer/web_ui_extension.h"
#include "content/renderer/web_ui_extension_data.h"
#include "crypto/sha2.h"
#include "media/blink/webmediaplayer_util.h"
#include "net/base/data_url.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_util.h"
#include "ppapi/features/features.h"
#include "services/network/public/interfaces/request_context_frame_type.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/service_manager/public/interfaces/interface_provider.mojom.h"
#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/WebKit/common/frame_policy.h"
#include "third_party/WebKit/common/page/page_visibility_state.mojom.h"
#include "third_party/WebKit/common/quota/quota_types.mojom.h"
#include "third_party/WebKit/common/sandbox_flags.h"
#include "third_party/WebKit/public/platform/FilePathConversion.h"
#include "third_party/WebKit/public/platform/InterfaceProvider.h"
#include "third_party/WebKit/public/platform/URLConversion.h"
#include "third_party/WebKit/public/platform/WebData.h"
#include "third_party/WebKit/public/platform/WebFocusType.h"
#include "third_party/WebKit/public/platform/WebKeyboardEvent.h"
#include "third_party/WebKit/public/platform/WebMediaPlayer.h"
#include "third_party/WebKit/public/platform/WebMediaPlayerSource.h"
#include "third_party/WebKit/public/platform/WebPoint.h"
#include "third_party/WebKit/public/platform/WebScrollIntoViewParams.h"
#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/platform/WebVector.h"
#include "third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
#include "third_party/WebKit/public/platform/modules/permissions/permission.mojom.h"
#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerNetworkProvider.h"
#include "third_party/WebKit/public/web/WebAutofillClient.h"
#include "third_party/WebKit/public/web/WebConsoleMessage.h"
#include "third_party/WebKit/public/web/WebContextFeatures.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElementCollection.h"
#include "third_party/WebKit/public/web/WebFindOptions.h"
#include "third_party/WebKit/public/web/WebFrameOwnerProperties.h"
#include "third_party/WebKit/public/web/WebFrameSerializer.h"
#include "third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h"
#include "third_party/WebKit/public/web/WebFrameWidget.h"
#include "third_party/WebKit/public/web/WebInputMethodController.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
#include "third_party/WebKit/public/web/WebNavigationPolicy.h"
#include "third_party/WebKit/public/web/WebPlugin.h"
#include "third_party/WebKit/public/web/WebPluginContainer.h"
#include "third_party/WebKit/public/web/WebPluginDocument.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebRange.h"
#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebSearchableFormData.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
#include "third_party/WebKit/public/web/WebSettings.h"
#include "third_party/WebKit/public/web/WebSurroundingText.h"
#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "third_party/WebKit/public/web/WebWidget.h"
#include "ui/events/base_event_utils.h"
#include "url/origin.h"
#include "url/url_constants.h"
#include "url/url_util.h"
#include "v8/include/v8.h"
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/renderer/pepper/pepper_browser_connection.h"
#include "content/renderer/pepper/pepper_plugin_instance_impl.h"
#include "content/renderer/pepper/pepper_plugin_registry.h"
#include "content/renderer/pepper/pepper_webplugin_impl.h"
#include "content/renderer/pepper/plugin_module.h"
#endif
#if BUILDFLAG(ENABLE_WEBRTC)
#include "content/renderer/media/rtc_peer_connection_handler.h"
#endif
#if defined(OS_ANDROID)
#include <cpu-features.h>
#include "content/renderer/java/gin_java_bridge_dispatcher.h"
#include "third_party/WebKit/public/platform/WebFloatPoint.h"
#endif
using base::Time;
using base::TimeDelta;
using blink::WebContentDecryptionModule;
using blink::WebContextMenuData;
using blink::WebData;
using blink::WebDocumentLoader;
using blink::WebDocument;
using blink::WebDOMEvent;
using blink::WebDOMMessageEvent;
using blink::WebElement;
using blink::WebElementCollection;
using blink::WebExternalPopupMenu;
using blink::WebExternalPopupMenuClient;
using blink::WebFindOptions;
using blink::WebFrame;
using blink::WebFrameLoadType;
using blink::WebFrameSerializer;
using blink::WebFrameSerializerClient;
using blink::WebHistoryItem;
using blink::WebHTTPBody;
using blink::WebLayerTreeView;
using blink::WebLocalFrame;
using blink::WebMediaPlayer;
using blink::WebMediaPlayerClient;
using blink::WebMediaPlayerEncryptedMediaClient;
using blink::WebNavigationPolicy;
using blink::WebNavigationType;
using blink::WebNode;
using blink::WebPluginDocument;
using blink::WebPluginParams;
using blink::WebPoint;
using blink::WebPopupMenuInfo;
using blink::WebRange;
using blink::WebRect;
using blink::WebReferrerPolicy;
using blink::WebScriptSource;
using blink::WebSearchableFormData;
using blink::WebSecurityOrigin;
using blink::WebSecurityPolicy;
using blink::WebSerializedScriptValue;
using blink::WebServiceWorkerProvider;
using blink::WebSettings;
using blink::WebString;
using blink::WebThreadSafeData;
using blink::WebURL;
using blink::WebURLError;
using blink::WebURLRequest;
using blink::WebURLResponse;
using blink::WebUserGestureIndicator;
using blink::WebVector;
using blink::WebView;
using blink::mojom::SelectionMenuBehavior;
#if defined(OS_ANDROID)
using blink::WebFloatPoint;
using blink::WebFloatRect;
#endif
namespace content {
namespace {
const base::Feature kConsumeGestureOnNavigation = {
"ConsumeGestureOnNavigation", base::FEATURE_DISABLED_BY_DEFAULT};
const int kExtraCharsBeforeAndAfterSelection = 100;
const PreviewsState kDisabledPreviewsBits =
PREVIEWS_OFF | PREVIEWS_NO_TRANSFORM;
typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
static base::LazyInstance<RoutingIDFrameMap>::DestructorAtExit
g_routing_id_frame_map = LAZY_INSTANCE_INITIALIZER;
typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
base::LazyInstance<FrameMap>::DestructorAtExit g_frame_map =
LAZY_INSTANCE_INITIALIZER;
int64_t ExtractPostId(const WebHistoryItem& item) {
if (item.IsNull() || item.HttpBody().IsNull())
return -1;
return item.HttpBody().Identifier();
}
WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
const WebURLResponse& response) {
return static_cast<WebURLResponseExtraDataImpl*>(response.GetExtraData());
}
void GetRedirectChain(WebDocumentLoader* document_loader,
std::vector<GURL>* result) {
WebVector<WebURL> urls;
document_loader->RedirectChain(urls);
result->reserve(urls.size());
for (size_t i = 0; i < urls.size(); ++i) {
result->push_back(urls[i]);
}
}
// Gets URL that should override the default getter for this data source
// (if any), storing it in |output|. Returns true if there is an override URL.
bool MaybeGetOverriddenURL(WebDocumentLoader* document_loader, GURL* output) {
DocumentState* document_state =
DocumentState::FromDocumentLoader(document_loader);
// If load was from a data URL, then the saved data URL, not the history
// URL, should be the URL of the data source.
if (document_state->was_load_data_with_base_url_request()) {
*output = document_state->data_url();
return true;
}
// WebDocumentLoader has unreachable URL means that the frame is loaded
// through blink::WebFrame::loadData(), and the base URL will be in the
// redirect chain. However, we never visited the baseURL. So in this case, we
// should use the unreachable URL as the original URL.
if (document_loader->HasUnreachableURL()) {
*output = document_loader->UnreachableURL();
return true;
}
return false;
}
// Returns the original request url. If there is no redirect, the original
// url is the same as ds->getRequest()->url(). If the WebDocumentLoader belongs
// to a frame was loaded by loadData, the original url will be
// ds->unreachableURL()
GURL GetOriginalRequestURL(WebDocumentLoader* document_loader) {
GURL overriden_url;
if (MaybeGetOverriddenURL(document_loader, &overriden_url))
return overriden_url;
std::vector<GURL> redirects;
GetRedirectChain(document_loader, &redirects);
if (!redirects.empty())
return redirects.at(0);
return document_loader->OriginalRequest().Url();
}
bool IsBrowserInitiated(NavigationParams* pending) {
// A navigation resulting from loading a javascript URL should not be treated
// as a browser initiated event. Instead, we want it to look as if the page
// initiated any load resulting from JS execution.
return pending &&
!pending->common_params.url.SchemeIs(url::kJavaScriptScheme);
}
// Returns false unless this is a top-level navigation.
bool IsTopLevelNavigation(WebFrame* frame) {
return frame->Parent() == nullptr;
}
WebURLRequest CreateURLRequestForNavigation(
const CommonNavigationParams& common_params,
const RequestNavigationParams& request_params,
std::unique_ptr<StreamOverrideParameters> stream_override,
bool is_view_source_mode_enabled,
bool is_same_document_navigation) {
// Use the original navigation url to construct the WebURLRequest. The
// WebURLloaderImpl will replay the redirects afterwards and will eventually
// commit the final url.
const GURL navigation_url = !request_params.original_url.is_empty()
? request_params.original_url
: common_params.url;
const std::string navigation_method = !request_params.original_method.empty()
? request_params.original_method
: common_params.method;
WebURLRequest request(navigation_url);
request.SetHTTPMethod(WebString::FromUTF8(navigation_method));
if (is_view_source_mode_enabled)
request.SetCacheMode(blink::mojom::FetchCacheMode::kForceCache);
WebString web_referrer;
if (common_params.referrer.url.is_valid()) {
web_referrer = WebSecurityPolicy::GenerateReferrerHeader(
common_params.referrer.policy, common_params.url,
WebString::FromUTF8(common_params.referrer.url.spec()));
request.SetHTTPReferrer(web_referrer, common_params.referrer.policy);
if (!web_referrer.IsEmpty()) {
request.AddHTTPOriginIfNeeded(
WebSecurityOrigin(url::Origin::Create(common_params.referrer.url)));
}
}
if (!web_referrer.IsEmpty() ||
common_params.referrer.policy != blink::kWebReferrerPolicyDefault) {
request.SetHTTPReferrer(web_referrer, common_params.referrer.policy);
}
request.SetIsSameDocumentNavigation(is_same_document_navigation);
request.SetPreviewsState(
static_cast<WebURLRequest::PreviewsState>(common_params.previews_state));
RequestExtraData* extra_data = new RequestExtraData();
extra_data->set_stream_override(std::move(stream_override));
extra_data->set_navigation_initiated_by_renderer(
request_params.nav_entry_id == 0);
request.SetExtraData(extra_data);
// Set the ui timestamp for this navigation. Currently the timestamp here is
// only non empty when the navigation was triggered by an Android intent. The
// timestamp is converted to a double version supported by blink. It will be
// passed back to the browser in the DidCommitProvisionalLoad and the
// DocumentLoadComplete IPCs.
base::TimeDelta ui_timestamp = common_params.ui_timestamp - base::TimeTicks();
request.SetUiStartTime(ui_timestamp.InSecondsF());
request.SetInputPerfMetricReportPolicy(
static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy>(
common_params.report_type));
return request;
}
// Sanitizes the navigation_start timestamp for browser-initiated navigations,
// where the browser possibly has a better notion of start time than the
// renderer. In the case of cross-process navigations, this carries over the
// time of finishing the onbeforeunload handler of the previous page.
// TimeTicks is sometimes not monotonic across processes, and because
// |browser_navigation_start| is likely before this process existed,
// InterProcessTimeTicksConverter won't help. The timestamp is sanitized by
// clamping it to renderer_navigation_start, initialized earlier in the call
// stack.
base::TimeTicks SanitizeNavigationTiming(
const base::TimeTicks& browser_navigation_start,
const base::TimeTicks& renderer_navigation_start) {
DCHECK(!browser_navigation_start.is_null());
return std::min(browser_navigation_start, renderer_navigation_start);
}
CommonNavigationParams MakeCommonNavigationParams(
const blink::WebFrameClient::NavigationPolicyInfo& info,
int load_flags) {
Referrer referrer(
GURL(info.url_request.HttpHeaderField(WebString::FromUTF8("Referer"))
.Latin1()),
info.url_request.GetReferrerPolicy());
// Set the ui timestamp for this navigation. Currently the timestamp here is
// only non empty when the navigation was triggered by an Android intent, or
// by the user clicking on a link. The timestamp is converted from a double
// version supported by blink. It will be passed back to the renderer in the
// CommitNavigation IPC, and then back to the browser again in the
// DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
base::TimeTicks ui_timestamp =
base::TimeTicks() +
base::TimeDelta::FromSecondsD(info.url_request.UiStartTime());
FrameMsg_UILoadMetricsReportType::Value report_type =
static_cast<FrameMsg_UILoadMetricsReportType::Value>(
info.url_request.InputPerfMetricReportPolicy());
// No history-navigation is expected to happen.
DCHECK(info.navigation_type != blink::kWebNavigationTypeBackForward);
// Determine the navigation type. No same-document navigation is expected
// because it is loaded immediately by the FrameLoader.
FrameMsg_Navigate_Type::Value navigation_type =
FrameMsg_Navigate_Type::DIFFERENT_DOCUMENT;
if (info.navigation_type == blink::kWebNavigationTypeReload) {
if (load_flags & net::LOAD_BYPASS_CACHE)
navigation_type = FrameMsg_Navigate_Type::RELOAD_BYPASSING_CACHE;
else
navigation_type = FrameMsg_Navigate_Type::RELOAD;
}
base::Optional<SourceLocation> source_location;
if (!info.source_location.url.IsNull()) {
source_location = SourceLocation(info.source_location.url.Latin1(),
info.source_location.line_number,
info.source_location.column_number);
}
CSPDisposition should_check_main_world_csp =
info.should_check_main_world_content_security_policy ==
blink::kWebContentSecurityPolicyDispositionCheck
? CSPDisposition::CHECK
: CSPDisposition::DO_NOT_CHECK;
const RequestExtraData* extra_data =
static_cast<RequestExtraData*>(info.url_request.GetExtraData());
DCHECK(extra_data);
return CommonNavigationParams(
info.url_request.Url(), referrer, extra_data->transition_type(),
navigation_type, true, info.replaces_current_history_item, ui_timestamp,
report_type, GURL(), GURL(),
static_cast<PreviewsState>(info.url_request.GetPreviewsState()),
base::TimeTicks::Now(), info.url_request.HttpMethod().Latin1(),
GetRequestBodyForWebURLRequest(info.url_request), source_location,
should_check_main_world_csp, false /* started_from_context_menu */,
info.url_request.HasUserGesture());
}
WebFrameLoadType ReloadFrameLoadTypeFor(
FrameMsg_Navigate_Type::Value navigation_type) {
switch (navigation_type) {
case FrameMsg_Navigate_Type::RELOAD:
case FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL:
return WebFrameLoadType::kReload;
case FrameMsg_Navigate_Type::RELOAD_BYPASSING_CACHE:
return WebFrameLoadType::kReloadBypassingCache;
default:
NOTREACHED();
return WebFrameLoadType::kStandard;
}
}
RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl =
nullptr;
WebString ConvertRelativePathToHtmlAttribute(const base::FilePath& path) {
DCHECK(!path.IsAbsolute());
return WebString::FromUTF8(
std::string("./") +
path.NormalizePathSeparatorsTo(FILE_PATH_LITERAL('/')).AsUTF8Unsafe());
}
// Implementation of WebFrameSerializer::LinkRewritingDelegate that responds
// based on the payload of FrameMsg_GetSerializedHtmlWithLocalLinks.
class LinkRewritingDelegate : public WebFrameSerializer::LinkRewritingDelegate {
public:
LinkRewritingDelegate(
const std::map<GURL, base::FilePath>& url_to_local_path,
const std::map<int, base::FilePath>& frame_routing_id_to_local_path)
: url_to_local_path_(url_to_local_path),
frame_routing_id_to_local_path_(frame_routing_id_to_local_path) {}
bool RewriteFrameSource(WebFrame* frame, WebString* rewritten_link) override {
int routing_id = RenderFrame::GetRoutingIdForWebFrame(frame);
auto it = frame_routing_id_to_local_path_.find(routing_id);
if (it == frame_routing_id_to_local_path_.end())
return false; // This can happen because of https://crbug.com/541354.
const base::FilePath& local_path = it->second;
*rewritten_link = ConvertRelativePathToHtmlAttribute(local_path);
return true;
}
bool RewriteLink(const WebURL& url, WebString* rewritten_link) override {
auto it = url_to_local_path_.find(url);
if (it == url_to_local_path_.end())
return false;
const base::FilePath& local_path = it->second;
*rewritten_link = ConvertRelativePathToHtmlAttribute(local_path);
return true;
}
private:
const std::map<GURL, base::FilePath>& url_to_local_path_;
const std::map<int, base::FilePath>& frame_routing_id_to_local_path_;
};
// Implementation of WebFrameSerializer::MHTMLPartsGenerationDelegate that
// 1. Bases shouldSkipResource and getContentID responses on contents of
// FrameMsg_SerializeAsMHTML_Params.
// 2. Stores digests of urls of serialized resources (i.e. urls reported via
// shouldSkipResource) into |serialized_resources_uri_digests| passed
// to the constructor.
class MHTMLPartsGenerationDelegate
: public WebFrameSerializer::MHTMLPartsGenerationDelegate {
public:
MHTMLPartsGenerationDelegate(
const FrameMsg_SerializeAsMHTML_Params& params,
std::set<std::string>* serialized_resources_uri_digests)
: params_(params),
serialized_resources_uri_digests_(serialized_resources_uri_digests) {
DCHECK(serialized_resources_uri_digests_);
}
bool ShouldSkipResource(const WebURL& url) override {
std::string digest =
crypto::SHA256HashString(params_.salt + GURL(url).spec());
// Skip if the |url| already covered by serialization of an *earlier* frame.
if (base::ContainsKey(params_.digests_of_uris_to_skip, digest))
return true;
// Let's record |url| as being serialized for the *current* frame.
auto pair = serialized_resources_uri_digests_->insert(digest);
bool insertion_took_place = pair.second;
DCHECK(insertion_took_place); // Blink should dedupe within a frame.
return false;
}
WebString GetContentID(WebFrame* frame) override {
int routing_id = RenderFrame::GetRoutingIdForWebFrame(frame);
auto it = params_.frame_routing_id_to_content_id.find(routing_id);
if (it == params_.frame_routing_id_to_content_id.end())
return WebString();
const std::string& content_id = it->second;
return WebString::FromUTF8(content_id);
}
blink::WebFrameSerializerCacheControlPolicy CacheControlPolicy() override {
return params_.mhtml_cache_control_policy;
}
bool UseBinaryEncoding() override { return params_.mhtml_binary_encoding; }
bool RemovePopupOverlay() override {
return params_.mhtml_popup_overlay_removal;
}
bool UsePageProblemDetectors() override {
return params_.mhtml_problem_detection;
}
private:
const FrameMsg_SerializeAsMHTML_Params& params_;
std::set<std::string>* serialized_resources_uri_digests_;
DISALLOW_COPY_AND_ASSIGN(MHTMLPartsGenerationDelegate);
};
bool IsHttpPost(const blink::WebURLRequest& request) {
return request.HttpMethod().Utf8() == "POST";
}
// Writes to file the serialized and encoded MHTML data from WebThreadSafeData
// instances.
MhtmlSaveStatus WriteMHTMLToDisk(std::vector<WebThreadSafeData> mhtml_contents,
base::File file) {
TRACE_EVENT0("page-serialization", "WriteMHTMLToDisk (RenderFrameImpl)");
SCOPED_UMA_HISTOGRAM_TIMER(
"PageSerialization.MhtmlGeneration.WriteToDiskTime.SingleFrame");
DCHECK(!RenderThread::Get()) << "Should not run in the main renderer thread";
MhtmlSaveStatus save_status = MhtmlSaveStatus::SUCCESS;
for (const WebThreadSafeData& data : mhtml_contents) {
if (!data.IsEmpty() &&
file.WriteAtCurrentPos(data.Data(), data.size()) < 0) {
save_status = MhtmlSaveStatus::FILE_WRITTING_ERROR;
break;
}
}
// Explicitly close |file| here to make sure to include any flush operations
// in the UMA metric.
file.Close();
return save_status;
}
double ConvertToBlinkTime(const base::TimeTicks& time_ticks) {
return (time_ticks - base::TimeTicks()).InSecondsF();
}
FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
switch (type) {
case blink::WebIconURL::kTypeFavicon:
return FaviconURL::IconType::kFavicon;
case blink::WebIconURL::kTypeTouch:
return FaviconURL::IconType::kTouchIcon;
case blink::WebIconURL::kTypeTouchPrecomposed:
return FaviconURL::IconType::kTouchPrecomposedIcon;
case blink::WebIconURL::kTypeInvalid:
return FaviconURL::IconType::kInvalid;
}
NOTREACHED();
return FaviconURL::IconType::kInvalid;
}
std::vector<gfx::Size> ConvertToFaviconSizes(
const blink::WebVector<blink::WebSize>& web_sizes) {
std::vector<gfx::Size> result;
result.reserve(web_sizes.size());
for (const blink::WebSize& web_size : web_sizes)
result.push_back(gfx::Size(web_size));
return result;
}
// Use this for histograms with dynamically generated names, which otherwise
// can't use the UMA_HISTOGRAM_MEMORY_MB macro without code duplication.
void RecordSuffixedMemoryMBHistogram(base::StringPiece name,
base::StringPiece suffix,
int sample_mb) {
std::string name_with_suffix;
name.CopyToString(&name_with_suffix);
suffix.AppendToString(&name_with_suffix);
base::UmaHistogramMemoryMB(name_with_suffix, sample_mb);
}
void RecordSuffixedRendererMemoryMetrics(
const RenderThreadImpl::RendererMemoryMetrics& memory_metrics,
base::StringPiece suffix) {
RecordSuffixedMemoryMBHistogram("Memory.Experimental.Renderer.PartitionAlloc",
suffix,
memory_metrics.partition_alloc_kb / 1024);
RecordSuffixedMemoryMBHistogram("Memory.Experimental.Renderer.BlinkGC",
suffix, memory_metrics.blink_gc_kb / 1024);
RecordSuffixedMemoryMBHistogram("Memory.Experimental.Renderer.Malloc", suffix,
memory_metrics.malloc_mb);
RecordSuffixedMemoryMBHistogram("Memory.Experimental.Renderer.Discardable",
suffix, memory_metrics.discardable_kb / 1024);
RecordSuffixedMemoryMBHistogram(
"Memory.Experimental.Renderer.V8MainThreadIsolate", suffix,
memory_metrics.v8_main_thread_isolate_mb);
RecordSuffixedMemoryMBHistogram("Memory.Experimental.Renderer.TotalAllocated",
suffix, memory_metrics.total_allocated_mb);
RecordSuffixedMemoryMBHistogram(
"Memory.Experimental.Renderer.NonDiscardableTotalAllocated", suffix,
memory_metrics.non_discardable_total_allocated_mb);
RecordSuffixedMemoryMBHistogram(
"Memory.Experimental.Renderer.TotalAllocatedPerRenderView", suffix,
memory_metrics.total_allocated_per_render_view_mb);
}
} // namespace
class RenderFrameImpl::FrameURLLoaderFactory
: public blink::WebURLLoaderFactory {
public:
FrameURLLoaderFactory(
base::WeakPtr<RenderFrameImpl> frame,
scoped_refptr<ChildURLLoaderFactoryGetter> loader_factory_getter)
: frame_(std::move(frame)),
loader_factory_getter_(std::move(loader_factory_getter)) {}
~FrameURLLoaderFactory() override = default;
std::unique_ptr<blink::WebURLLoader> CreateURLLoader(
const WebURLRequest& request,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
// This should not be called if the frame is detached.
DCHECK(frame_);
frame_->UpdatePeakMemoryStats();
// TODO(crbug.com/796425): Temporarily wrap the raw mojom::URLLoaderFactory
// pointer into SharedURLLoaderFactory.
scoped_refptr<SharedURLLoaderFactory> factory;
if (base::FeatureList::IsEnabled(features::kNetworkService)) {
factory = base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
frame_->GetSubresourceLoaderFactories().GetFactoryForRequest(
request.Url()));
} else {
factory = base::MakeRefCounted<WeakWrapperSharedURLLoaderFactory>(
frame_->GetDefaultURLLoaderFactoryGetter()->GetFactoryForURL(
request.Url(), frame_->custom_url_loader_factory()));
}
DCHECK(factory);
mojom::KeepAliveHandlePtr keep_alive_handle;
if (base::FeatureList::IsEnabled(
features::kKeepAliveRendererForKeepaliveRequests) &&
request.GetKeepalive()) {
frame_->GetFrameHost()->IssueKeepAliveHandle(
mojo::MakeRequest(&keep_alive_handle));
}
return std::make_unique<WebURLLoaderImpl>(
RenderThreadImpl::current()->resource_dispatcher(),
std::move(task_runner),
std::move(factory), std::move(keep_alive_handle));
}
private:
base::WeakPtr<RenderFrameImpl> frame_;
scoped_refptr<ChildURLLoaderFactoryGetter> loader_factory_getter_;
DISALLOW_COPY_AND_ASSIGN(FrameURLLoaderFactory);
};
// The following methods are outside of the anonymous namespace to ensure that
// the corresponding symbols get emmitted even on symbol_level 1.
NOINLINE void ExhaustMemory() {
volatile void* ptr = nullptr;
do {
ptr = malloc(0x10000000);
base::debug::Alias(&ptr);
} while (ptr);
}
NOINLINE void CrashIntentionally() {
// NOTE(shess): Crash directly rather than using NOTREACHED() so
// that the signature is easier to triage in crash reports.
//
// Linker's ICF feature may merge this function with other functions with the
// same definition and it may confuse the crash report processing system.
static int static_variable_to_make_this_function_unique = 0;
base::debug::Alias(&static_variable_to_make_this_function_unique);
volatile int* zero = nullptr;
*zero = 0;
}
NOINLINE void BadCastCrashIntentionally() {
class A {
virtual void f() {}
};
class B {
virtual void f() {}
};
A a;
(void)(B*) & a;
}
#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
NOINLINE void MaybeTriggerAsanError(const GURL& url) {
// NOTE(rogerm): We intentionally perform an invalid heap access here in
// order to trigger an Address Sanitizer (ASAN) error report.
if (url == kChromeUICrashHeapOverflowURL) {
LOG(ERROR) << "Intentionally causing ASAN heap overflow"
<< " because user navigated to " << url.spec();
base::debug::AsanHeapOverflow();
} else if (url == kChromeUICrashHeapUnderflowURL) {
LOG(ERROR) << "Intentionally causing ASAN heap underflow"
<< " because user navigated to " << url.spec();
base::debug::AsanHeapUnderflow();
} else if (url == kChromeUICrashUseAfterFreeURL) {
LOG(ERROR) << "Intentionally causing ASAN heap use-after-free"
<< " because user navigated to " << url.spec();
base::debug::AsanHeapUseAfterFree();
#if defined(SYZYASAN)
} else if (url == kChromeUICrashCorruptHeapBlockURL) {
LOG(ERROR) << "Intentionally causing ASAN corrupt heap block"
<< " because user navigated to " << url.spec();
base::debug::AsanCorruptHeapBlock();
} else if (url == kChromeUICrashCorruptHeapURL) {
LOG(ERROR) << "Intentionally causing ASAN corrupt heap"
<< " because user navigated to " << url.spec();
base::debug::AsanCorruptHeap();
} else if (url == kChromeUICrashDcheckURL) {
LOG(ERROR) << "Intentionally DCHECKING because user navigated to "
<< url.spec();
DCHECK(false) << "Intentional DCHECK.";
#endif
}
}
#endif // ADDRESS_SANITIZER || SYZYASAN
// Returns true if the URL is a debug URL, false otherwise. These URLs do not
// commit, though they are intentionally left in the address bar above the
// effect they cause (e.g., a sad tab).
bool MaybeHandleDebugURL(const GURL& url) {
if (!url.SchemeIs(kChromeUIScheme))
return false;
bool is_debug_url =
IsRendererDebugURL(url) && !url.SchemeIs(url::kJavaScriptScheme);
if (url == kChromeUIBadCastCrashURL) {
LOG(ERROR) << "Intentionally crashing (with bad cast)"
<< " because user navigated to " << url.spec();
BadCastCrashIntentionally();
} else if (url == kChromeUICrashURL) {
LOG(ERROR) << "Intentionally crashing (with null pointer dereference)"
<< " because user navigated to " << url.spec();
CrashIntentionally();
} else if (url == kChromeUIDumpURL) {
// This URL will only correctly create a crash dump file if content is
// hosted in a process that has correctly called
// base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
// of base::debug::DumpWithoutCrashing for more details.
base::debug::DumpWithoutCrashing();
} else if (url == kChromeUIKillURL) {
LOG(ERROR) << "Intentionally issuing kill signal to current process"
<< " because user navigated to " << url.spec();
base::Process::Current().Terminate(1, false);
} else if (url == kChromeUIHangURL) {
LOG(ERROR) << "Intentionally hanging ourselves with sleep infinite loop"
<< " because user navigated to " << url.spec();
for (;;) {
base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
}
} else if (url == kChromeUIShorthangURL) {
LOG(ERROR) << "Intentionally sleeping renderer for 20 seconds"
<< " because user navigated to " << url.spec();
base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
} else if (url == kChromeUIMemoryExhaustURL) {
LOG(ERROR)
<< "Intentionally exhausting renderer memory because user navigated to "
<< url.spec();
ExhaustMemory();
} else if (url == kChromeUICheckCrashURL) {
LOG(ERROR) << "Intentionally causing CHECK because user navigated to "
<< url.spec();
CHECK(false);
}
#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
MaybeTriggerAsanError(url);
#endif // ADDRESS_SANITIZER || SYZYASAN
return is_debug_url;
}
struct RenderFrameImpl::PendingFileChooser {
PendingFileChooser(const FileChooserParams& p,
blink::WebFileChooserCompletion* c)
: params(p), completion(c) {}
FileChooserParams params;
blink::WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
};
const std::string& UniqueNameForWebFrame(blink::WebFrame* frame) {
return frame->IsWebLocalFrame()
? RenderFrameImpl::FromWebFrame(frame)->unique_name()
: RenderFrameProxy::FromWebFrame(frame->ToWebRemoteFrame())
->unique_name();
}
RenderFrameImpl::UniqueNameFrameAdapter::UniqueNameFrameAdapter(
RenderFrameImpl* render_frame)
: render_frame_(render_frame) {}
RenderFrameImpl::UniqueNameFrameAdapter::~UniqueNameFrameAdapter() {}
bool RenderFrameImpl::UniqueNameFrameAdapter::IsMainFrame() const {
return render_frame_->IsMainFrame();
}
bool RenderFrameImpl::UniqueNameFrameAdapter::IsCandidateUnique(
base::StringPiece name) const {
// This method is currently O(N), where N = number of frames in the tree.
DCHECK(!name.empty());
for (blink::WebFrame* frame = GetWebFrame()->Top(); frame;
frame = frame->TraverseNext()) {
if (UniqueNameForWebFrame(frame) == name)
return false;
}
return true;
}
int RenderFrameImpl::UniqueNameFrameAdapter::GetSiblingCount() const {
int sibling_count = 0;
for (blink::WebFrame* frame = GetWebFrame()->Parent()->FirstChild(); frame;
frame = frame->NextSibling()) {
if (frame == GetWebFrame())
continue;
++sibling_count;
}
return sibling_count;
}
int RenderFrameImpl::UniqueNameFrameAdapter::GetChildCount() const {
int child_count = 0;
for (blink::WebFrame* frame = GetWebFrame()->FirstChild(); frame;
frame = frame->NextSibling()) {
++child_count;
}
return child_count;
}
std::vector<base::StringPiece>
RenderFrameImpl::UniqueNameFrameAdapter::CollectAncestorNames(
BeginPoint begin_point,
bool (*should_stop)(base::StringPiece)) const {
std::vector<base::StringPiece> result;
for (blink::WebFrame* frame = begin_point == BeginPoint::kParentFrame
? GetWebFrame()->Parent()
: GetWebFrame();
frame; frame = frame->Parent()) {
result.push_back(UniqueNameForWebFrame(frame));
if (should_stop(result.back()))
break;
}
return result;
}
std::vector<int> RenderFrameImpl::UniqueNameFrameAdapter::GetFramePosition(
BeginPoint begin_point) const {
std::vector<int> result;
blink::WebFrame* parent = begin_point == BeginPoint::kParentFrame
? GetWebFrame()->Parent()
: GetWebFrame();
blink::WebFrame* child =
begin_point == BeginPoint::kParentFrame ? GetWebFrame() : nullptr;
while (parent) {
int position_in_parent = 0;
blink::WebFrame* sibling = parent->FirstChild();
while (sibling != child) {
sibling = sibling->NextSibling();
++position_in_parent;
}
result.push_back(position_in_parent);
child = parent;
parent = parent->Parent();
}
return result;
}
blink::WebLocalFrame* RenderFrameImpl::UniqueNameFrameAdapter::GetWebFrame()
const {
return render_frame_->frame_;
}
// static
RenderFrameImpl* RenderFrameImpl::Create(
RenderViewImpl* render_view,
int32_t routing_id,
service_manager::mojom::InterfaceProviderPtr interface_provider,
const base::UnguessableToken& devtools_frame_token) {
DCHECK(routing_id != MSG_ROUTING_NONE);
CreateParams params(render_view, routing_id, std::move(interface_provider),
devtools_frame_token);
if (g_create_render_frame_impl)
return g_create_render_frame_impl(std::move(params));
else
return new RenderFrameImpl(std::move(params));
}
// static
RenderFrame* RenderFrame::FromRoutingID(int routing_id) {
return RenderFrameImpl::FromRoutingID(routing_id);
}
// static
RenderFrameImpl* RenderFrameImpl::FromRoutingID(int routing_id) {
RoutingIDFrameMap::iterator iter =
g_routing_id_frame_map.Get().find(routing_id);
if (iter != g_routing_id_frame_map.Get().end())
return iter->second;
return nullptr;
}
// static
RenderFrameImpl* RenderFrameImpl::CreateMainFrame(
RenderViewImpl* render_view,
int32_t routing_id,
service_manager::mojom::InterfaceProviderPtr interface_provider,
int32_t widget_routing_id,
bool hidden,
const ScreenInfo& screen_info,
CompositorDependencies* compositor_deps,
blink::WebFrame* opener,
const base::UnguessableToken& devtools_frame_token,
const FrameReplicationState& replicated_state,
bool has_committed_real_load) {
// A main frame RenderFrame must have a RenderWidget.
DCHECK_NE(MSG_ROUTING_NONE, widget_routing_id);
RenderFrameImpl* render_frame = RenderFrameImpl::Create(
render_view, routing_id, std::move(interface_provider),
devtools_frame_token);
render_frame->InitializeBlameContext(nullptr);
WebLocalFrame* web_frame = WebLocalFrame::CreateMainFrame(
render_view->webview(), render_frame,
render_frame->blink_interface_registry_.get(), opener,
// This conversion is a little sad, as this often comes from a
// WebString...
WebString::FromUTF8(replicated_state.name),
replicated_state.frame_policy.sandbox_flags);
if (has_committed_real_load)
web_frame->SetCommittedFirstRealLoad();
render_frame->render_widget_ = RenderWidget::CreateForFrame(
widget_routing_id, hidden, screen_info, compositor_deps, web_frame);
// TODO(avi): This DCHECK is to track cleanup for https://crbug.com/545684
DCHECK_EQ(render_view->GetWidget(), render_frame->render_widget_)
<< "Main frame is no longer reusing the RenderView as its widget! "
<< "Does the RenderFrame need to register itself with the RenderWidget?";
render_frame->in_frame_tree_ = true;
return render_frame;
}
// static
void RenderFrameImpl::CreateFrame(
int routing_id,
service_manager::mojom::InterfaceProviderPtr interface_provider,
int proxy_routing_id,
int opener_routing_id,
int parent_routing_id,
int previous_sibling_routing_id,
const base::UnguessableToken& devtools_frame_token,
const FrameReplicationState& replicated_state,
CompositorDependencies* compositor_deps,
const mojom::CreateFrameWidgetParams& widget_params,
const FrameOwnerProperties& frame_owner_properties,
bool has_committed_real_load) {
blink::WebLocalFrame* web_frame;
RenderFrameImpl* render_frame;
if (proxy_routing_id == MSG_ROUTING_NONE) {
// TODO(alexmos): This path is currently used only:
// 1) When recreating a RenderFrame after a crash.
// 2) In tests that issue this IPC directly.
// These two cases should be cleaned up to also pass a proxy_routing_id,
// which would allow removing this branch altogether. See
// https://crbug.com/756790.
RenderFrameProxy* parent_proxy =
RenderFrameProxy::FromRoutingID(parent_routing_id);
// If the browser is sending a valid parent routing id, it should already
// be created and registered.
CHECK(parent_proxy);
blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
blink::WebFrame* previous_sibling_web_frame = nullptr;
RenderFrameProxy* previous_sibling_proxy =
RenderFrameProxy::FromRoutingID(previous_sibling_routing_id);
if (previous_sibling_proxy)
previous_sibling_web_frame = previous_sibling_proxy->web_frame();
// Create the RenderFrame and WebLocalFrame, linking the two.
render_frame = RenderFrameImpl::Create(
parent_proxy->render_view(), routing_id, std::move(interface_provider),
devtools_frame_token);
render_frame->InitializeBlameContext(FromRoutingID(parent_routing_id));
render_frame->unique_name_helper_.set_propagated_name(
replicated_state.unique_name);
web_frame = parent_web_frame->CreateLocalChild(
replicated_state.scope, WebString::FromUTF8(replicated_state.name),
replicated_state.frame_policy.sandbox_flags, render_frame,
render_frame->blink_interface_registry_.get(),
previous_sibling_web_frame,
replicated_state.frame_policy.container_policy,
ConvertFrameOwnerPropertiesToWebFrameOwnerProperties(
frame_owner_properties),
ResolveOpener(opener_routing_id));
// The RenderFrame is created and inserted into the frame tree in the above
// call to createLocalChild.
render_frame->in_frame_tree_ = true;
} else {
RenderFrameProxy* proxy =
RenderFrameProxy::FromRoutingID(proxy_routing_id);
// The remote frame could've been detached while the remote-to-local
// navigation was being initiated in the browser process. Drop the
// navigation and don't create the frame in that case. See
// https://crbug.com/526304.
if (!proxy)
return;
render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id,
std::move(interface_provider),
devtools_frame_token);
render_frame->InitializeBlameContext(nullptr);
render_frame->proxy_routing_id_ = proxy_routing_id;
proxy->set_provisional_frame_routing_id(routing_id);
web_frame = blink::WebLocalFrame::CreateProvisional(
render_frame, render_frame->blink_interface_registry_.get(),
proxy->web_frame(), replicated_state.frame_policy.sandbox_flags,
replicated_state.frame_policy.container_policy);
}
CHECK(parent_routing_id != MSG_ROUTING_NONE || !web_frame->Parent());
if (widget_params.routing_id != MSG_ROUTING_NONE) {
render_frame->render_widget_ = RenderWidget::CreateForFrame(
widget_params.routing_id, widget_params.hidden,
render_frame->render_view_->screen_info(), compositor_deps, web_frame);
}
if (has_committed_real_load)
web_frame->SetCommittedFirstRealLoad();
render_frame->Initialize();
}
// static
RenderFrame* RenderFrame::FromWebFrame(blink::WebLocalFrame* web_frame) {
return RenderFrameImpl::FromWebFrame(web_frame);
}
// static
void RenderFrame::ForEach(RenderFrameVisitor* visitor) {
FrameMap* frames = g_frame_map.Pointer();
for (FrameMap::iterator it = frames->begin(); it != frames->end(); ++it) {
if (!visitor->Visit(it->second))
return;
}
}
// static
int RenderFrame::GetRoutingIdForWebFrame(blink::WebFrame* web_frame) {
if (!web_frame)
return MSG_ROUTING_NONE;
if (web_frame->IsWebRemoteFrame()) {
return RenderFrameProxy::FromWebFrame(web_frame->ToWebRemoteFrame())
->routing_id();
}
return RenderFrameImpl::FromWebFrame(web_frame)->GetRoutingID();
}
// static
RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
if (iter != g_frame_map.Get().end())
return iter->second;
return nullptr;
}
// static
void RenderFrameImpl::InstallCreateHook(
CreateRenderFrameImplFunction create_render_frame_impl) {
CHECK(!g_create_render_frame_impl);
g_create_render_frame_impl = create_render_frame_impl;
}
// static
blink::WebFrame* RenderFrameImpl::ResolveOpener(int opener_frame_routing_id) {
if (opener_frame_routing_id == MSG_ROUTING_NONE)
return nullptr;
// Opener routing ID could refer to either a RenderFrameProxy or a
// RenderFrame, so need to check both.
RenderFrameProxy* opener_proxy =
RenderFrameProxy::FromRoutingID(opener_frame_routing_id);
if (opener_proxy)
return opener_proxy->web_frame();
RenderFrameImpl* opener_frame =
RenderFrameImpl::FromRoutingID(opener_frame_routing_id);
if (opener_frame)
return opener_frame->GetWebFrame();
return nullptr;
}
blink::WebURL RenderFrameImpl::OverrideFlashEmbedWithHTML(
const blink::WebURL& url) {
return GetContentClient()->renderer()->OverrideFlashEmbedWithHTML(url);
}
// RenderFrameImpl::CreateParams --------------------------------------------
RenderFrameImpl::CreateParams::CreateParams(
RenderViewImpl* render_view,
int32_t routing_id,
service_manager::mojom::InterfaceProviderPtr interface_provider,
const base::UnguessableToken& devtools_frame_token)
: render_view(render_view),
routing_id(routing_id),
interface_provider(std::move(interface_provider)),
devtools_frame_token(devtools_frame_token) {}
RenderFrameImpl::CreateParams::~CreateParams() = default;
RenderFrameImpl::CreateParams::CreateParams(CreateParams&&) = default;
RenderFrameImpl::CreateParams& RenderFrameImpl::CreateParams::operator=(
CreateParams&&) = default;
// RenderFrameImpl ----------------------------------------------------------
RenderFrameImpl::RenderFrameImpl(CreateParams params)
: frame_(nullptr),
is_main_frame_(true),
unique_name_frame_adapter_(this),
unique_name_helper_(&unique_name_frame_adapter_),
in_browser_initiated_detach_(false),
in_frame_tree_(false),
render_view_(params.render_view),
routing_id_(params.routing_id),
proxy_routing_id_(MSG_ROUTING_NONE),
#if BUILDFLAG(ENABLE_PLUGINS)
plugin_power_saver_helper_(nullptr),
plugin_find_handler_(nullptr),
#endif
cookie_jar_(this),
selection_text_offset_(0),
selection_range_(gfx::Range::InvalidRange()),
handling_select_range_(false),
web_user_media_client_(nullptr),
presentation_dispatcher_(nullptr),
push_messaging_client_(nullptr),
screen_orientation_dispatcher_(nullptr),
render_accessibility_(nullptr),
previews_state_(PREVIEWS_UNSPECIFIED),
effective_connection_type_(
blink::WebEffectiveConnectionType::kTypeUnknown),
is_pasting_(false),
suppress_further_dialogs_(false),
blame_context_(nullptr),
#if BUILDFLAG(ENABLE_PLUGINS)
focused_pepper_plugin_(nullptr),
pepper_last_mouse_event_target_(nullptr),
#endif
engagement_binding_(this),
media_engagement_binding_(this),
frame_binding_(this),
host_zoom_binding_(this),
frame_bindings_control_binding_(this),
frame_navigation_control_binding_(this),
fullscreen_binding_(this),
has_accessed_initial_document_(false),
media_factory_(this,
base::Bind(&RenderFrameImpl::RequestOverlayRoutingToken,
base::Unretained(this))),
input_target_client_impl_(this),
devtools_frame_token_(
blink::WebString::FromUTF8(params.devtools_frame_token.ToString())),
weak_factory_(this) {
// The InterfaceProvider to access Mojo services exposed by the RFHI must be
// provided at construction time. See: https://crbug.com/729021/.
CHECK(params.interface_provider.is_bound());
remote_interfaces_.Bind(std::move(params.interface_provider));
blink_interface_registry_.reset(new BlinkInterfaceRegistryImpl(
registry_.GetWeakPtr(), associated_interfaces_.GetWeakPtr()));
// Must call after binding our own remote interfaces.
media_factory_.SetupMojo();
std::pair<RoutingIDFrameMap::iterator, bool> result =
g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
CHECK(result.second) << "Inserting a duplicate item.";
RenderThread::Get()->AddRoute(routing_id_, this);
// Everything below subclasses RenderFrameObserver and is automatically
// deleted when the RenderFrame gets deleted.
#if defined(OS_ANDROID)
new GinJavaBridgeDispatcher(this);
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
// Manages its own lifetime.
plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
#endif
manifest_manager_ = std::make_unique<ManifestManager>(this);
if (IsMainFrame()) {
// Manages its own lifetime.
new ManifestChangeNotifier(this);
}
memset(&peak_memory_metrics_, 0,
sizeof(RenderThreadImpl::RendererMemoryMetrics));
}
mojom::FrameHost* RenderFrameImpl::GetFrameHost() {
if (!frame_host_ptr_.is_bound())
GetRemoteAssociatedInterfaces()->GetInterface(&frame_host_ptr_);
return frame_host_ptr_.get();
}
RenderFrameImpl::~RenderFrameImpl() {
// If file chooser is still waiting for answer, dispatch empty answer.
while (!file_chooser_completions_.empty()) {
if (file_chooser_completions_.front()->completion) {
file_chooser_completions_.front()->completion->DidChooseFile(
WebVector<WebString>());
}
file_chooser_completions_.pop_front();
}
for (auto& observer : observers_)
observer.RenderFrameGone();
for (auto& observer : observers_)
observer.OnDestruct();
base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
// Unregister from InputHandlerManager. render_thread may be NULL in tests.
RenderThreadImpl* render_thread = RenderThreadImpl::current();
InputHandlerManager* input_handler_manager =
render_thread ? render_thread->input_handler_manager() : nullptr;
if (input_handler_manager)
input_handler_manager->UnregisterRoutingID(GetRoutingID());
if (auto* factory = AudioOutputIPCFactory::get())
factory->MaybeDeregisterRemoteFactory(GetRoutingID());
if (is_main_frame_) {
// Ensure the RenderView doesn't point to this object, once it is destroyed.
// TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
// is |this|, once the object is no longer leaked.
// See https://crbug.com/464764.
render_view_->main_render_frame_ = nullptr;
}
g_routing_id_frame_map.Get().erase(routing_id_);
RenderThread::Get()->RemoveRoute(routing_id_);
}
void RenderFrameImpl::Initialize() {
is_main_frame_ = !frame_->Parent();
GetRenderWidget()->RegisterRenderFrame(this);
RenderFrameImpl* parent_frame =
RenderFrameImpl::FromWebFrame(frame_->Parent());
if (parent_frame) {
previews_state_ = parent_frame->GetPreviewsState();
effective_connection_type_ = parent_frame->GetEffectiveConnectionType();
}
bool is_tracing_rail = false;
bool is_tracing_navigation = false;
TRACE_EVENT_CATEGORY_GROUP_ENABLED("navigation", &is_tracing_navigation);
TRACE_EVENT_CATEGORY_GROUP_ENABLED("rail", &is_tracing_rail);
if (is_tracing_rail || is_tracing_navigation) {
int parent_id = RenderFrame::GetRoutingIdForWebFrame(frame_->Parent());
TRACE_EVENT2("navigation,rail", "RenderFrameImpl::Initialize",
"id", routing_id_,
"parent", parent_id);
}
#if BUILDFLAG(ENABLE_PLUGINS)
new PepperBrowserConnection(this);
#endif
shared_worker_repository_ =
std::make_unique<SharedWorkerRepository>(GetInterfaceProvider());
GetWebFrame()->SetSharedWorkerRepositoryClient(
shared_worker_repository_.get());
RegisterMojoInterfaces();
// We delay calling this until we have the WebFrame so that any observer or
// embedder can call GetWebFrame on any RenderFrame.
GetContentClient()->renderer()->RenderFrameCreated(this);
RenderThreadImpl* render_thread = RenderThreadImpl::current();
// render_thread may be NULL in tests.
InputHandlerManager* input_handler_manager =
render_thread ? render_thread->input_handler_manager() : nullptr;
if (input_handler_manager) {
DCHECK(render_view_->HasAddedInputHandler());
input_handler_manager->RegisterAssociatedRenderFrameRoutingID(
GetRoutingID(), render_view_->GetRoutingID());
}
// AudioOutputIPCFactory may be null in tests.
if (auto* factory = AudioOutputIPCFactory::get())
factory->MaybeRegisterRemoteFactory(GetRoutingID(), GetRemoteInterfaces());
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kDomAutomationController))
enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
if (command_line.HasSwitch(switches::kStatsCollectionController))
enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
}
void RenderFrameImpl::InitializeBlameContext(RenderFrameImpl* parent_frame) {
DCHECK(!blame_context_);
blame_context_ = std::make_unique<FrameBlameContext>(this, parent_frame);
blame_context_->Initialize();
}
void RenderFrameImpl::GetInterface(
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) {
if (registry_.TryBindInterface(interface_name, &interface_pipe))
return;
for (auto& observer : observers_) {
observer.OnInterfaceRequestForFrame(interface_name, &interface_pipe);
if (!interface_pipe.is_valid())
return;
}
}
RenderWidget* RenderFrameImpl::GetRenderWidget() {
return GetLocalRoot()->render_widget_.get();
}
#if BUILDFLAG(ENABLE_PLUGINS)
void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
for (auto& observer : observers_)
observer.DidCreatePepperPlugin(host);
}
void RenderFrameImpl::PepperDidChangeCursor(
PepperPluginInstanceImpl* instance,
const blink::WebCursorInfo& cursor) {
// Update the cursor appearance immediately if the requesting plugin is the
// one which receives the last mouse event. Otherwise, the new cursor won't be
// picked up until the plugin gets the next input event. That is bad if, e.g.,
// the plugin would like to set an invisible cursor when there isn't any user
// input for a while.
if (instance == pepper_last_mouse_event_target_)
GetRenderWidget()->DidChangeCursor(cursor);
}
void RenderFrameImpl::PepperDidReceiveMouseEvent(
PepperPluginInstanceImpl* instance) {
set_pepper_last_mouse_event_target(instance);
}
void RenderFrameImpl::PepperTextInputTypeChanged(
PepperPluginInstanceImpl* instance) {
if (instance != focused_pepper_plugin_)
return;
GetRenderWidget()->UpdateTextInputState();
FocusedNodeChangedForAccessibility(WebNode());
}
void RenderFrameImpl::PepperCaretPositionChanged(
PepperPluginInstanceImpl* instance) {
if (instance != focused_pepper_plugin_)
return;
GetRenderWidget()->UpdateSelectionBounds();
}
void RenderFrameImpl::PepperCancelComposition(
PepperPluginInstanceImpl* instance) {
if (instance != focused_pepper_plugin_)
return;
Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));
#if defined(OS_MACOSX) || defined(USE_AURA)
GetRenderWidget()->UpdateCompositionInfo(
false /* not an immediate request */);
#endif
}
void RenderFrameImpl::PepperSelectionChanged(
PepperPluginInstanceImpl* instance) {
if (instance != focused_pepper_plugin_)
return;
SyncSelectionIfRequired();
}
RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
PepperPluginInstanceImpl* plugin) {
GURL active_url;
if (render_view()->webview())
active_url = render_view()->GetURLForGraphicsContext3D();
mojom::WidgetPtr widget_channel;
mojom::WidgetRequest widget_channel_request =
mojo::MakeRequest(&widget_channel);
// Synchronous IPC to obtain a routing id for the fullscreen widget.
int32_t fullscreen_widget_routing_id = MSG_ROUTING_NONE;
if (!RenderThreadImpl::current_render_message_filter()
->CreateFullscreenWidget(render_view()->routing_id(),
std::move(widget_channel),
&fullscreen_widget_routing_id)) {
return nullptr;
}
RenderWidget::ShowCallback show_callback =
base::Bind(&RenderViewImpl::ShowCreatedFullscreenWidget,
render_view()->GetWeakPtr());
RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
fullscreen_widget_routing_id, show_callback,
GetRenderWidget()->compositor_deps(), plugin, active_url,
GetRenderWidget()->screen_info(), std::move(widget_channel_request));
// TODO(nick): The show() handshake seems like unnecessary complexity here,
// since there's no real delay between CreateFullscreenWidget and
// ShowCreatedFullscreenWidget. Would it be simpler to have the
// CreateFullscreenWidget mojo method implicitly show the window, and skip the
// subsequent step?
widget->Show(blink::kWebNavigationPolicyIgnore);
return widget;
}
bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
if (!focused_pepper_plugin_)
return false;
return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
}
void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
// TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
// routing_id_ as a result.
Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
}
void RenderFrameImpl::SimulateImeSetComposition(
const base::string16& text,
const std::vector<blink::WebImeTextSpan>& ime_text_spans,
int selection_start,
int selection_end) {
render_view_->OnImeSetComposition(text, ime_text_spans,
gfx::Range::InvalidRange(), selection_start,
selection_end);
}
void RenderFrameImpl::SimulateImeCommitText(
const base::string16& text,
const std::vector<blink::WebImeTextSpan>& ime_text_spans,
const gfx::Range& replacement_range) {
render_view_->OnImeCommitText(text, ime_text_spans, replacement_range, 0);
}
void RenderFrameImpl::SimulateImeFinishComposingText(bool keep_selection) {
render_view_->OnImeFinishComposingText(keep_selection);
}
void RenderFrameImpl::OnImeSetComposition(
const base::string16& text,
const std::vector<blink::WebImeTextSpan>& ime_text_spans,
int selection_start,
int selection_end) {
// When a PPAPI plugin has focus, we bypass WebKit.
if (!IsPepperAcceptingCompositionEvents()) {
pepper_composition_text_ = text;
} else {
// TODO(kinaba) currently all composition events are sent directly to
// plugins. Use DOM event mechanism after WebKit is made aware about
// plugins that support composition.
// The code below mimics the behavior of WebCore::Editor::setComposition.
// Empty -> nonempty: composition started.
if (pepper_composition_text_.empty() && !text.empty()) {
focused_pepper_plugin_->HandleCompositionStart(base::string16());
}
// Nonempty -> empty: composition canceled.
if (!pepper_composition_text_.empty() && text.empty()) {
focused_pepper_plugin_->HandleCompositionEnd(base::string16());
}
pepper_composition_text_ = text;
// Nonempty: composition is ongoing.
if (!pepper_composition_text_.empty()) {
focused_pepper_plugin_->HandleCompositionUpdate(
pepper_composition_text_, ime_text_spans, selection_start,
selection_end);
}
}
}
void RenderFrameImpl::OnImeCommitText(const base::string16& text,
const gfx::Range& replacement_range,
int relative_cursor_pos) {
HandlePepperImeCommit(text);
}
void RenderFrameImpl::OnImeFinishComposingText(bool keep_selection) {
const base::string16& text = pepper_composition_text_;
HandlePepperImeCommit(text);
}
#endif // BUILDFLAG(ENABLE_PLUGINS)
MediaStreamDeviceObserver* RenderFrameImpl::GetMediaStreamDeviceObserver() {
if (!web_user_media_client_)
InitializeUserMediaClient();
return web_user_media_client_
? web_user_media_client_->media_stream_device_observer()
: nullptr;
}
void RenderFrameImpl::ScriptedPrint(bool user_initiated) {
SCOPED_UMA_HISTOGRAM_TIMER("RenderFrameObservers.ScriptedPrint");
for (auto& observer : observers_)
observer.ScriptedPrint(user_initiated);
}
bool RenderFrameImpl::Send(IPC::Message* message) {
return RenderThread::Get()->Send(message);
}
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
void RenderFrameImpl::DidHideExternalPopupMenu() {
// We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
// is called. Otherwise, createExternalPopupMenu() for new popup will fail.
external_popup_menu_.reset();
}
#endif
bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
// Forward Page IPCs to the RenderView.
if ((IPC_MESSAGE_CLASS(msg) == PageMsgStart)) {
if (render_view())
return render_view()->OnMessageReceived(msg);
return false;
}
// We may get here while detaching, when the WebFrame has been deleted. Do
// not process any messages in this state.
if (!frame_)
return false;
DCHECK(!frame_->GetDocument().IsNull());
GetContentClient()->SetActiveURL(
frame_->GetDocument().Url(),
frame_->Top()->GetSecurityOrigin().ToString().Utf8());
{
SCOPED_UMA_HISTOGRAM_TIMER("RenderFrameObservers.OnMessageReceived");
for (auto& observer : observers_) {
if (observer.OnMessageReceived(msg))
return true;
}
}
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
IPC_MESSAGE_HANDLER(FrameMsg_SwapIn, OnSwapIn)
IPC_MESSAGE_HANDLER(FrameMsg_Delete, OnDeleteFrame)
IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
IPC_MESSAGE_HANDLER(FrameMsg_DroppedNavigation, OnDroppedNavigation)
IPC_MESSAGE_HANDLER(FrameMsg_Collapse, OnCollapse)
IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
OnCustomContextMenuAction)
#if BUILDFLAG(ENABLE_PLUGINS)
IPC_MESSAGE_HANDLER(FrameMsg_SetPepperVolume, OnSetPepperVolume)
#endif
IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset,
OnAdjustSelectionByCharacterOffset)
IPC_MESSAGE_HANDLER(InputMsg_CollapseSelection, OnCollapseSelection)
IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
OnMoveRangeSelectionExtent)
IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
OnScrollFocusedEditableNodeIntoRect)
IPC_MESSAGE_HANDLER(FrameMsg_CopyImageAt, OnCopyImageAt)
IPC_MESSAGE_HANDLER(FrameMsg_SaveImageAt, OnSaveImageAt)
IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
OnExtendSelectionAndDelete)
IPC_MESSAGE_HANDLER(InputMsg_DeleteSurroundingText, OnDeleteSurroundingText)
IPC_MESSAGE_HANDLER(InputMsg_DeleteSurroundingTextInCodePoints,
OnDeleteSurroundingTextInCodePoints)
IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
OnSetCompositionFromExistingText)
IPC_MESSAGE_HANDLER(InputMsg_SetEditableSelectionOffsets,
OnSetEditableSelectionOffsets)
IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand,
OnExecuteNoValueEditCommand)
IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole, OnAddMessageToConsole)
IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
OnJavaScriptExecuteRequest)
IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
OnJavaScriptExecuteRequestForTests)
IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld,
OnJavaScriptExecuteRequestInIsolatedWorld)
IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest,
OnVisualStateRequest)
IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
IPC_MESSAGE_HANDLER(FrameMsg_ReloadLoFiImages, OnReloadLoFiImages)
IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
OnTextSurroundingSelectionRequest)
IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
OnSetAccessibilityMode)
IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree,
OnSnapshotAccessibilityTree)
IPC_MESSAGE_HANDLER(FrameMsg_UpdateOpener, OnUpdateOpener)
IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateFramePolicy, OnDidUpdateFramePolicy)
IPC_MESSAGE_HANDLER(FrameMsg_SetFrameOwnerProperties,
OnSetFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameMsg_AdvanceFocus, OnAdvanceFocus)
IPC_MESSAGE_HANDLER(FrameMsg_AdvanceFocusInForm, OnAdvanceFocusInForm)
IPC_MESSAGE_HANDLER(FrameMsg_SetFocusedFrame, OnSetFocusedFrame)
IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings,
OnTextTrackSettingsChanged)
IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent, OnPostMessageEvent)
IPC_MESSAGE_HANDLER(FrameMsg_ReportContentSecurityPolicyViolation,
OnReportContentSecurityPolicyViolation)
IPC_MESSAGE_HANDLER(FrameMsg_GetSavableResourceLinks,
OnGetSavableResourceLinks)
IPC_MESSAGE_HANDLER(FrameMsg_GetSerializedHtmlWithLocalLinks,
OnGetSerializedHtmlWithLocalLinks)
IPC_MESSAGE_HANDLER(FrameMsg_SerializeAsMHTML, OnSerializeAsMHTML)
IPC_MESSAGE_HANDLER(FrameMsg_Find, OnFind)
IPC_MESSAGE_HANDLER(FrameMsg_ClearActiveFindMatch, OnClearActiveFindMatch)
IPC_MESSAGE_HANDLER(FrameMsg_StopFinding, OnStopFinding)
IPC_MESSAGE_HANDLER(FrameMsg_EnableViewSourceMode, OnEnableViewSourceMode)
IPC_MESSAGE_HANDLER(FrameMsg_SuppressFurtherDialogs,
OnSuppressFurtherDialogs)
IPC_MESSAGE_HANDLER(FrameMsg_RunFileChooserResponse, OnFileChooserResponse)
IPC_MESSAGE_HANDLER(FrameMsg_ClearFocusedElement, OnClearFocusedElement)
IPC_MESSAGE_HANDLER(FrameMsg_BlinkFeatureUsageReport,
OnBlinkFeatureUsageReport)
IPC_MESSAGE_HANDLER(FrameMsg_MixedContentFound, OnMixedContentFound)
IPC_MESSAGE_HANDLER(FrameMsg_SetOverlayRoutingToken,
OnSetOverlayRoutingToken)
#if defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(FrameMsg_ActivateNearestFindResult,
OnActivateNearestFindResult)
IPC_MESSAGE_HANDLER(FrameMsg_GetNearestFindResult,
OnGetNearestFindResult)
IPC_MESSAGE_HANDLER(FrameMsg_FindMatchRects, OnFindMatchRects)
#endif
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
#else
IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
#endif
#endif
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
#endif
IPC_END_MESSAGE_MAP()
return handled;
}
void RenderFrameImpl::OnAssociatedInterfaceRequest(
const std::string& interface_name,
mojo::ScopedInterfaceEndpointHandle handle) {
associated_interfaces_.BindRequest(interface_name, std::move(handle));
}
void RenderFrameImpl::BindEngagement(
blink::mojom::EngagementClientAssociatedRequest request) {
engagement_binding_.Bind(std::move(request));
}
void RenderFrameImpl::BindFullscreen(
mojom::FullscreenVideoElementHandlerAssociatedRequest request) {
fullscreen_binding_.Bind(std::move(request));
}
void RenderFrameImpl::BindMediaEngagement(
blink::mojom::MediaEngagementClientAssociatedRequest request) {
media_engagement_binding_.Bind(std::move(request));
}
void RenderFrameImpl::BindFrame(
const service_manager::BindSourceInfo& browser_info,
mojom::FrameRequest request) {
browser_info_ = browser_info;
frame_binding_.Bind(std::move(request));
}
void RenderFrameImpl::BindFrameBindingsControl(
mojom::FrameBindingsControlAssociatedRequest request) {
frame_bindings_control_binding_.Bind(std::move(request));
}
void RenderFrameImpl::BindFrameNavigationControl(
mojom::FrameNavigationControlAssociatedRequest request) {
frame_navigation_control_binding_.Bind(std::move(request));
}
blink::mojom::ManifestManager& RenderFrameImpl::GetManifestManager() {
return *manifest_manager_;
}
void RenderFrameImpl::SetPendingNavigationParams(
std::unique_ptr<NavigationParams> navigation_params) {
pending_navigation_params_ = std::move(navigation_params);
}
void RenderFrameImpl::OnBeforeUnload(bool is_reload) {
TRACE_EVENT1("navigation,rail", "RenderFrameImpl::OnBeforeUnload",
"id", routing_id_);
// Save the routing_id, as the RenderFrameImpl can be deleted in
// dispatchBeforeUnloadEvent. See https://crbug.com/666714 for details.
int routing_id = routing_id_;
base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
// TODO(clamy): Ensure BeforeUnload is dispatched to all subframes, even when
// --site-per-process is enabled. |dispatchBeforeUnloadEvent| will only
// execute the BeforeUnload event in this frame and local child frames. It
// should also be dispatched to out-of-process child frames.
bool proceed = frame_->DispatchBeforeUnloadEvent(is_reload);
base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
RenderThread::Get()->Send(new FrameHostMsg_BeforeUnload_ACK(
routing_id, proceed, before_unload_start_time, before_unload_end_time));
}
void RenderFrameImpl::OnSwapOut(
int proxy_routing_id,
bool is_loading,
const FrameReplicationState& replicated_frame_state) {
TRACE_EVENT1("navigation,rail", "RenderFrameImpl::OnSwapOut",
"id", routing_id_);
RenderFrameProxy* proxy = nullptr;
// Swap this RenderFrame out so the frame can navigate to a page rendered by
// a different process. This involves running the unload handler and
// clearing the page. We also allow this process to exit if there are no
// other active RenderFrames in it.
// Send an UpdateState message before we get deleted.
SendUpdateState();
// There should always be a proxy to replace this RenderFrame. Create it now
// so its routing id is registered for receiving IPC messages.
CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
this, proxy_routing_id, replicated_frame_state.scope);
// Synchronously run the unload handler before sending the ACK.
// TODO(creis): Call dispatchUnloadEvent unconditionally here to support
// unload on subframes as well.
if (is_main_frame_)
frame_->DispatchUnloadEvent();
// Swap out and stop sending any IPC messages that are not ACKs.
if (is_main_frame_)
render_view_->SetSwappedOut(true);
RenderViewImpl* render_view = render_view_;
bool is_main_frame = is_main_frame_;
int routing_id = GetRoutingID();
// Now that all of the cleanup is complete and the browser side is notified,
// start using the RenderFrameProxy.
//
// The swap call deletes this RenderFrame via frameDetached. Do not access
// any members after this call.
//
// TODO(creis): WebFrame::swap() can return false. Most of those cases
// should be due to the frame being detached during unload (in which case
// the necessary cleanup has happened anyway), but it might be possible for
// it to return false without detaching. Catch any cases that the
// RenderView's main_render_frame_ isn't cleared below (whether swap returns
// false or not).
bool success = frame_->Swap(proxy->web_frame());
// For main frames, the swap should have cleared the RenderView's pointer to
// this frame.
if (is_main_frame)
CHECK(!render_view->main_render_frame_);
if (!success) {
// The swap can fail when the frame is detached during swap (this can
// happen while running the unload handlers). When that happens, delete
// the proxy.
proxy->FrameDetached(blink::WebRemoteFrameClient::DetachType::kSwap);
return;
}
if (is_loading)
proxy->OnDidStartLoading();
// Initialize the WebRemoteFrame with the replication state passed by the
// process that is now rendering the frame.
proxy->SetReplicatedState(replicated_frame_state);
// Safe to exit if no one else is using the process.
// TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
// the process based on the lifetime of this RenderFrameImpl object.
if (is_main_frame)
render_view->WasSwappedOut();
// Notify the browser that this frame was swapped. Use the RenderThread
// directly because |this| is deleted.
RenderThread::Get()->Send(new FrameHostMsg_SwapOut_ACK(routing_id));
}
void RenderFrameImpl::OnSwapIn() {
SwapIn();
}
void RenderFrameImpl::OnDeleteFrame() {
// TODO(nasko): If this message is received right after a commit has
// swapped a RenderFrameProxy with this RenderFrame, the proxy needs to be
// recreated in addition to the RenderFrame being deleted.
// See https://crbug.com/569683 for details.
in_browser_initiated_detach_ = true;
// This will result in a call to RenderFrameImpl::frameDetached, which
// deletes the object. Do not access |this| after detach.
frame_->Detach();
}
void RenderFrameImpl::OnContextMenuClosed(
const CustomContextMenuContext& custom_context) {
if (custom_context.request_id) {
// External request, should be in our map.
ContextMenuClient* client =
pending_context_menus_.Lookup(custom_context.request_id);
if (client) {
client->OnMenuClosed(custom_context.request_id);
pending_context_menus_.Remove(custom_context.request_id);
}
} else {
if (custom_context.link_followed.is_valid())
frame_->SendPings(custom_context.link_followed);
}
render_view()->webview()->DidCloseContextMenu();
}
void RenderFrameImpl::OnCustomContextMenuAction(
const CustomContextMenuContext& custom_context,
unsigned action) {
if (custom_context.request_id) {
// External context menu request, look in our map.
ContextMenuClient* client =
pending_context_menus_.Lookup(custom_context.request_id);
if (client)
client->OnMenuAction(custom_context.request_id, action);
} else {
// Internal request, forward to WebKit.
render_view_->webview()->PerformCustomContextMenuAction(action);
}
}
void RenderFrameImpl::OnMoveCaret(const gfx::Point& point) {
Send(new InputHostMsg_MoveCaret_ACK(render_view_->GetRoutingID()));
frame_->MoveCaretSelection(render_view_->ConvertWindowPointToViewport(point));
}
void RenderFrameImpl::OnScrollFocusedEditableNodeIntoRect(
const gfx::Rect& rect) {
ScrollFocusedEditableElementIntoRect(rect);
}
void RenderFrameImpl::OnUndo() {
frame_->ExecuteCommand(WebString::FromUTF8("Undo"));
}
void RenderFrameImpl::OnRedo() {
frame_->ExecuteCommand(WebString::FromUTF8("Redo"));
}
void RenderFrameImpl::OnCut() {
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
frame_->ExecuteCommand(WebString::FromUTF8("Cut"));
}
void RenderFrameImpl::OnCopy() {
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
frame_->ExecuteCommand(WebString::FromUTF8("Copy"));
}
void RenderFrameImpl::OnPaste() {
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
AutoResetMember<bool> handling_paste(this, &RenderFrameImpl::is_pasting_,
true);
frame_->ExecuteCommand(WebString::FromUTF8("Paste"));
}
void RenderFrameImpl::OnPasteAndMatchStyle() {
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
frame_->ExecuteCommand(WebString::FromUTF8("PasteAndMatchStyle"));
}
#if defined(OS_MACOSX)
void RenderFrameImpl::OnCopyToFindPboard() {
// Since the find pasteboard supports only plain text, this can be simpler
// than the |OnCopy()| case.
if (frame_->HasSelection()) {
if (!clipboard_host_) {
auto* platform = RenderThreadImpl::current_blink_platform_impl();
platform->GetConnector()->BindInterface(platform->GetBrowserServiceName(),
&clipboard_host_);
}
base::string16 selection = frame_->SelectionAsText().Utf16();
clipboard_host_->WriteStringToFindPboard(selection);
}
}
#endif
void RenderFrameImpl::OnDelete() {
frame_->ExecuteCommand(WebString::FromUTF8("Delete"));
}
void RenderFrameImpl::OnSelectAll() {
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
frame_->ExecuteCommand(WebString::FromUTF8("SelectAll"));
}
void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
const gfx::Point& extent) {
// This IPC is dispatched by RenderWidgetHost, so use its routing id.
Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
frame_->SelectRange(render_view_->ConvertWindowPointToViewport(base),
render_view_->ConvertWindowPointToViewport(extent));
}
void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(
int start_adjust,
int end_adjust,
bool show_selection_menu) {
WebRange range = frame_->GetInputMethodController()->GetSelectionOffsets();
if (range.IsNull())
return;
// Sanity checks to disallow empty and out of range selections.
if (start_adjust - end_adjust > range.length() ||
range.StartOffset() + start_adjust < 0)
return;
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
// A negative adjust amount moves the selection towards the beginning of
// the document, a positive amount moves the selection towards the end of
// the document.
frame_->SelectRange(WebRange(range.StartOffset() + start_adjust,
range.length() + end_adjust - start_adjust),
WebLocalFrame::kPreserveHandleVisibility,
show_selection_menu ? SelectionMenuBehavior::kShow
: SelectionMenuBehavior::kHide);
}
void RenderFrameImpl::OnCollapseSelection() {
const WebRange& range =
frame_->GetInputMethodController()->GetSelectionOffsets();
if (range.IsNull())
return;
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
frame_->SelectRange(WebRange(range.EndOffset(), 0),
WebLocalFrame::kHideSelectionHandle,
SelectionMenuBehavior::kHide);
}
void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
// This IPC is dispatched by RenderWidgetHost, so use its routing id.
Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
GetRenderWidget()->routing_id()));
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
frame_->MoveRangeSelectionExtent(
render_view_->ConvertWindowPointToViewport(point));
}
void RenderFrameImpl::OnReplace(const base::string16& text) {
if (!frame_->HasSelection())
frame_->SelectWordAroundCaret();
frame_->ReplaceSelection(WebString::FromUTF16(text));
SyncSelectionIfRequired();
}
void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
if (!frame_->HasSelection())
return;
frame_->ReplaceMisspelledRange(WebString::FromUTF16(text));
}
void RenderFrameImpl::OnCopyImageAt(int x, int y) {
blink::WebFloatRect viewport_position(x, y, 0, 0);
GetRenderWidget()->ConvertWindowToViewport(&viewport_position);
frame_->CopyImageAt(WebPoint(viewport_position.x, viewport_position.y));
}
void RenderFrameImpl::OnSaveImageAt(int x, int y) {
blink::WebFloatRect viewport_position(x, y, 0, 0);
GetRenderWidget()->ConvertWindowToViewport(&viewport_position);
frame_->SaveImageAt(WebPoint(viewport_position.x, viewport_position.y));
}
void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level,
const std::string& message) {
AddMessageToConsole(level, message);
}
void RenderFrameImpl::OnJavaScriptExecuteRequest(
const base::string16& jscript,
int id,
bool notify_result) {
TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
TRACE_EVENT_SCOPE_THREAD);
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::Local<v8::Value> result = frame_->ExecuteScriptAndReturnValue(
WebScriptSource(WebString::FromUTF16(jscript)));
HandleJavascriptExecutionResult(jscript, id, notify_result, result);
}
void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
const base::string16& jscript,
int id,
bool notify_result,
bool has_user_gesture) {
TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
TRACE_EVENT_SCOPE_THREAD);
// A bunch of tests expect to run code in the context of a user gesture, which
// can grant additional privileges (e.g. the ability to create popups).
std::unique_ptr<blink::WebScopedUserGesture> gesture(
has_user_gesture ? new blink::WebScopedUserGesture(frame_) : nullptr);
v8::HandleScope handle_scope(blink::MainThreadIsolate());
v8::Local<v8::Value> result = frame_->ExecuteScriptAndReturnValue(
WebScriptSource(WebString::FromUTF16(jscript)));
HandleJavascriptExecutionResult(jscript, id, notify_result, result);
}
void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
const base::string16& jscript,
int id,
bool notify_result,
int world_id) {
TRACE_EVENT_INSTANT0("test_tracing",
"OnJavaScriptExecuteRequestInIsolatedWorld",
TRACE_EVENT_SCOPE_THREAD);
if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
world_id > ISOLATED_WORLD_ID_MAX) {
// Return if the world_id is not valid. world_id is passed as a plain int
// over IPC and needs to be verified here, in the IPC endpoint.
NOTREACHED();
return;
}
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
WebScriptSource script = WebScriptSource(WebString::FromUTF16(jscript));
JavaScriptIsolatedWorldRequest* request = new JavaScriptIsolatedWorldRequest(
id, notify_result, routing_id_, weak_factory_.GetWeakPtr());
frame_->RequestExecuteScriptInIsolatedWorld(
world_id, &script, 1, false, WebLocalFrame::kSynchronous, request);
}
RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
int id,
bool notify_result,
int routing_id,
base::WeakPtr<RenderFrameImpl> render_frame_impl)
: id_(id),
notify_result_(notify_result),
routing_id_(routing_id),
render_frame_impl_(render_frame_impl) {
}
RenderFrameImpl::JavaScriptIsolatedWorldRequest::
~JavaScriptIsolatedWorldRequest() {
}
void RenderFrameImpl::JavaScriptIsolatedWorldRequest::Completed(
const blink::WebVector<v8::Local<v8::Value>>& result) {
if (!render_frame_impl_.get()) {
return;
}
if (notify_result_) {
base::ListValue list;
if (!result.IsEmpty()) {
// It's safe to always use the main world context when converting
// here. V8ValueConverterImpl shouldn't actually care about the
// context scope, and it switches to v8::Object's creation context
// when encountered. (from extensions/renderer/script_injection.cc)
v8::Local<v8::Context> context =
render_frame_impl_.get()->frame_->MainWorldScriptContext();
v8::Context::Scope context_scope(context);
V8ValueConverterImpl converter;
converter.SetDateAllowed(true);
converter.SetRegExpAllowed(true);
for (const auto& value : result) {
std::unique_ptr<base::Value> result_value(
converter.FromV8Value(value, context));
list.Append(result_value ? std::move(result_value)
: std::make_unique<base::Value>());
}
} else {
list.Set(0, std::make_unique<base::Value>());
}
render_frame_impl_.get()->Send(
new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id_, list));
}
delete this;
}
void RenderFrameImpl::HandleJavascriptExecutionResult(
const base::string16& jscript,
int id,
bool notify_result,
v8::Local<v8::Value> result) {
if (notify_result) {
base::ListValue list;
if (!result.IsEmpty()) {
v8::Local<v8::Context> context = frame_->MainWorldScriptContext();
v8::Context::Scope context_scope(context);
V8ValueConverterImpl converter;
converter.SetDateAllowed(true);
converter.SetRegExpAllowed(true);
std::unique_ptr<base::Value> result_value(
converter.FromV8Value(result, context));
list.Set(0, result_value ? std::move(result_value)
: std::make_unique<base::Value>());
} else {
list.Set(0, std::make_unique<base::Value>());
}
Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
}
}
void RenderFrameImpl::OnVisualStateRequest(uint64_t id) {
GetRenderWidget()->QueueMessage(
new FrameHostMsg_VisualStateResponse(routing_id_, id),
MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
}
void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
AutoResetMember<bool> handling_select_range(
this, &RenderFrameImpl::handling_select_range_, true);
ImeEventGuard guard(GetRenderWidget());
frame_->SetEditableSelectionOffsets(start, end);
}
void RenderFrameImpl::OnSetCompositionFromExistingText(
int start,
int end,
const std::vector<blink::WebImeTextSpan>& ime_text_spans) {
ImeEventGuard guard(GetRenderWidget());
frame_->SetCompositionFromExistingText(start, end, ime_text_spans);
}
void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string& name) {
frame_->ExecuteCommand(WebString::FromUTF8(name));
}
void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
ImeEventGuard guard(GetRenderWidget());
frame_->ExtendSelectionAndDelete(before, after);
}
void RenderFrameImpl::OnDeleteSurroundingText(int before, int after) {
ImeEventGuard guard(GetRenderWidget());
frame_->DeleteSurroundingText(before, after);
}
void RenderFrameImpl::OnDeleteSurroundingTextInCodePoints(int before,
int after) {
ImeEventGuard guard(GetRenderWidget());
frame_->DeleteSurroundingTextInCodePoints(before, after);
}
void RenderFrameImpl::OnSetAccessibilityMode(ui::AXMode new_mode) {
if (accessibility_mode_ == new_mode)
return;
ui::AXMode old_mode = accessibility_mode_;
accessibility_mode_ = new_mode;
if (new_mode.has_mode(ui::AXMode::kWebContents) &&
!old_mode.has_mode(ui::AXMode::kWebContents)) {
render_accessibility_ = new RenderAccessibilityImpl(this, new_mode);
} else if (!new_mode.has_mode(ui::AXMode::kWebContents) &&
old_mode.has_mode(ui::AXMode::kWebContents)) {
// Note: this isn't called automatically by the destructor because
// there'd be no point in calling it in frame teardown, only if there's
// an accessibility mode change but the frame is persisting.
render_accessibility_->DisableAccessibility();
delete render_accessibility_;
render_accessibility_ = nullptr;
}
for (auto& observer : observers_)
observer.AccessibilityModeChanged();
}
void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id) {
AXContentTreeUpdate response;
RenderAccessibilityImpl::SnapshotAccessibilityTree(this, &response);
Send(new AccessibilityHostMsg_SnapshotResponse(
routing_id_, callback_id, response));
}
void RenderFrameImpl::ExtractSmartClipData(
const gfx::Rect& rect,
ExtractSmartClipDataCallback callback) {
#if defined(OS_ANDROID)
blink::WebString clip_text;
blink::WebString clip_html;
GetWebFrame()->ExtractSmartClipData(rect, clip_text, clip_html);
std::move(callback).Run(clip_text.Utf16(), clip_html.Utf16());
#endif // defined(OS_ANDROID)
}
void RenderFrameImpl::OnUpdateOpener(int opener_routing_id) {
WebFrame* opener = ResolveOpener(opener_routing_id);
frame_->SetOpener(opener);
}
void RenderFrameImpl::OnDidUpdateFramePolicy(
const blink::FramePolicy& frame_policy) {
frame_->SetFrameOwnerPolicy(frame_policy.sandbox_flags,
frame_policy.container_policy);
}
void RenderFrameImpl::OnSetFrameOwnerProperties(
const FrameOwnerProperties& frame_owner_properties) {
DCHECK(frame_);
frame_->SetFrameOwnerProperties(
ConvertFrameOwnerPropertiesToWebFrameOwnerProperties(
frame_owner_properties));
}
void RenderFrameImpl::OnAdvanceFocus(blink::WebFocusType type,
int32_t source_routing_id) {
RenderFrameProxy* source_frame =
RenderFrameProxy::FromRoutingID(source_routing_id);
if (!source_frame) {
render_view_->webview()->SetInitialFocus(type ==
blink::kWebFocusTypeBackward);
return;
}
render_view_->webview()->AdvanceFocusAcrossFrames(
type, source_frame->web_frame(), frame_);
}
void RenderFrameImpl::OnAdvanceFocusInForm(blink::WebFocusType focus_type) {
if (render_view_->webview()->FocusedFrame() != frame_)
return;
frame_->AdvanceFocusInForm(focus_type);
}
void RenderFrameImpl::OnSetFocusedFrame() {
// This uses focusDocumentView rather than setFocusedFrame so that focus/blur
// events are properly dispatched on any currently focused elements.
render_view_->webview()->FocusDocumentView(frame_);
}
void RenderFrameImpl::OnTextTrackSettingsChanged(
const FrameMsg_TextTrackSettings_Params& params) {
DCHECK(!frame_->Parent());
if (!render_view_->webview())
return;
if (params.text_tracks_enabled) {
render_view_->webview()->GetSettings()->SetTextTrackKindUserPreference(
WebSettings::TextTrackKindUserPreference::kCaptions);
} else {
render_view_->webview()->GetSettings()->SetTextTrackKindUserPreference(
WebSettings::TextTrackKindUserPreference::kDefault);
}
render_view_->webview()->GetSettings()->SetTextTrackBackgroundColor(
WebString::FromUTF8(params.text_track_background_color));
render_view_->webview()->GetSettings()->SetTextTrackFontFamily(
WebString::FromUTF8(params.text_track_font_family));
render_view_->webview()->GetSettings()->SetTextTrackFontStyle(
WebString::FromUTF8(params.text_track_font_style));
render_view_->webview()->GetSettings()->SetTextTrackFontVariant(
WebString::FromUTF8(params.text_track_font_variant));
render_view_->webview()->GetSettings()->SetTextTrackTextColor(
WebString::FromUTF8(params.text_track_text_color));
render_view_->webview()->GetSettings()->SetTextTrackTextShadow(
WebString::FromUTF8(params.text_track_text_shadow));
render_view_->webview()->GetSettings()->SetTextTrackTextSize(
WebString::FromUTF8(params.text_track_text_size));
}
void RenderFrameImpl::OnPostMessageEvent(
const FrameMsg_PostMessage_Params& params) {
// Find the source frame if it exists.
WebFrame* source_frame = nullptr;
if (params.source_routing_id != MSG_ROUTING_NONE) {
RenderFrameProxy* source_proxy =
RenderFrameProxy::FromRoutingID(params.source_routing_id);
if (source_proxy)
source_frame = source_proxy->web_frame();
}
WebSerializedScriptValue serialized_script_value;
if (params.is_data_raw_string) {
v8::Isolate* isolate = blink::MainThreadIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = frame_->MainWorldScriptContext();
v8::Context::Scope context_scope(context);
V8ValueConverterImpl converter;
converter.SetDateAllowed(true);
converter.SetRegExpAllowed(true);
std::unique_ptr<base::Value> value(new base::Value(params.data));
v8::Local<v8::Value> result_value = converter.ToV8Value(value.get(),
context);
serialized_script_value =
WebSerializedScriptValue::Serialize(isolate, result_value);
} else {
serialized_script_value =
WebSerializedScriptValue::FromString(WebString::FromUTF16(params.data));
}
// We must pass in the target_origin to do the security check on this side,
// since it may have changed since the original postMessage call was made.
WebSecurityOrigin target_origin;
if (!params.target_origin.empty()) {
target_origin = WebSecurityOrigin::CreateFromString(
WebString::FromUTF16(params.target_origin));
}
WebDOMMessageEvent msg_event(
serialized_script_value, WebString::FromUTF16(params.source_origin),
source_frame, frame_->GetDocument(), std::move(params.message_ports));
frame_->DispatchMessageEventWithOriginCheck(target_origin, msg_event);
}
void RenderFrameImpl::OnReload(bool bypass_cache) {
frame_->Reload(bypass_cache ? WebFrameLoadType::kReloadBypassingCache
: WebFrameLoadType::kReload);
}
void RenderFrameImpl::OnReloadLoFiImages() {
previews_state_ = PREVIEWS_NO_TRANSFORM;
GetWebFrame()->ReloadLoFiImages();
}
void RenderFrameImpl::OnTextSurroundingSelectionRequest(uint32_t max_length) {
blink::WebSurroundingText surrounding_text(frame_, max_length);
if (surrounding_text.IsEmpty()) {
// |surrounding_text| might not be correctly initialized, for example if
// |frame_->SelectionRange().IsNull()|, in other words, if there was no
// selection.
Send(new FrameHostMsg_TextSurroundingSelectionResponse(
routing_id_, base::string16(), 0, 0));
return;
}
Send(new FrameHostMsg_TextSurroundingSelectionResponse(
routing_id_, surrounding_text.TextContent().Utf16(),
surrounding_text.StartOffsetInTextContent(),
surrounding_text.EndOffsetInTextContent()));
}
bool RenderFrameImpl::RunJavaScriptDialog(JavaScriptDialogType type,
const base::string16& message,
const base::string16& default_value,
const GURL& frame_url,
base::string16* result) {
// Don't allow further dialogs if we are waiting to swap out, since the
// ScopedPageLoadDeferrer in our stack prevents it.
if (suppress_further_dialogs_)
return false;
int32_t message_length = static_cast<int32_t>(message.length());
if (WebUserGestureIndicator::ProcessedUserGestureSinceLoad(frame_)) {
UMA_HISTOGRAM_COUNTS("JSDialogs.CharacterCount.UserGestureSinceLoad",
message_length);
} else {
UMA_HISTOGRAM_COUNTS("JSDialogs.CharacterCount.NoUserGestureSinceLoad",
message_length);
}
bool success = false;
base::string16 result_temp;
if (!result)
result = &result_temp;
Send(new FrameHostMsg_RunJavaScriptDialog(routing_id_, message, default_value,
frame_url, type, &success, result));
return success;
}
bool RenderFrameImpl::ScheduleFileChooser(
const FileChooserParams& params,
blink::WebFileChooserCompletion* completion) {
static const size_t kMaximumPendingFileChooseRequests = 4;
// Do not open the file dialog in a hidden RenderFrame.
if (IsHidden())
return false;
if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
// This sanity check prevents too many file choose requests from getting
// queued which could DoS the user. Getting these is most likely a
// programming error (there are many ways to DoS the user so it's not
// considered a "real" security check), either in JS requesting many file
// choosers to pop up, or in a plugin.
//
// TODO(brettw): We might possibly want to require a user gesture to open
// a file picker, which will address this issue in a better way.
return false;
}
file_chooser_completions_.push_back(
std::make_unique<PendingFileChooser>(params, completion));
if (file_chooser_completions_.size() == 1) {
// Actually show the browse dialog when this is the first request.
Send(new FrameHostMsg_RunFileChooser(routing_id_, params));
}
return true;
}
void RenderFrameImpl::DidFailProvisionalLoadInternal(
const WebURLError& error,
blink::WebHistoryCommitType commit_type,
const base::Optional<std::string>& error_page_content) {
TRACE_EVENT1("navigation,benchmark,rail",
"RenderFrameImpl::didFailProvisionalLoad", "id", routing_id_);
// Note: It is important this notification occur before DidStopLoading so the
// SSL manager can react to the provisional load failure before being
// notified the load stopped.
//
for (auto& observer : render_view_->observers())
observer.DidFailProvisionalLoad(frame_, error);
{
SCOPED_UMA_HISTOGRAM_TIMER("RenderFrameObservers.DidFailProvisionalLoad");
for (auto& observer : observers_)
observer.DidFailProvisionalLoad(error);
}
WebDocumentLoader* document_loader = frame_->GetProvisionalDocumentLoader();
if (!document_loader)
return;
const WebURLRequest& failed_request = document_loader->GetRequest();
// Notify the browser that we failed a provisional load with an error.
SendFailedProvisionalLoad(failed_request, error, frame_);
if (!ShouldDisplayErrorPageForFailedLoad(error.reason(), error.url()))
return;
// Make sure we never show errors in view source mode.
frame_->EnableViewSourceMode(false);
DocumentState* document_state =
DocumentState::FromDocumentLoader(document_loader);
NavigationStateImpl* navigation_state =
static_cast<NavigationStateImpl*>(document_state->navigation_state());
// If this is a failed back/forward/reload navigation, then we need to do a
// 'replace' load. This is necessary to avoid messing up session history.
// Otherwise, we do a normal load, which simulates a 'go' navigation as far
// as session history is concerned.
bool replace = commit_type != blink::kWebStandardCommit;
// If we failed on a browser initiated request, then make sure that our error
// page load is regarded as the same browser initiated request.
if (!navigation_state->IsContentInitiated()) {
pending_navigation_params_.reset(new NavigationParams(
navigation_state->common_params(), navigation_state->request_params()));
}
// Load an error page.
LoadNavigationErrorPage(failed_request, error, replace, nullptr,