Add long running gmail memory benchmark for background tab.
[chromium-blink-merge.git] / content / browser / loader / async_resource_handler.cc
blobf0268e71d5f1a6457e8e1b07103a08774e4588c3
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/loader/async_resource_handler.h"
7 #include <algorithm>
8 #include <vector>
10 #include "base/command_line.h"
11 #include "base/containers/hash_tables.h"
12 #include "base/debug/alias.h"
13 #include "base/logging.h"
14 #include "base/memory/shared_memory.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/time/time.h"
18 #include "content/browser/devtools/devtools_netlog_observer.h"
19 #include "content/browser/host_zoom_map_impl.h"
20 #include "content/browser/loader/resource_buffer.h"
21 #include "content/browser/loader/resource_dispatcher_host_impl.h"
22 #include "content/browser/loader/resource_message_filter.h"
23 #include "content/browser/loader/resource_request_info_impl.h"
24 #include "content/browser/resource_context_impl.h"
25 #include "content/common/resource_messages.h"
26 #include "content/common/view_messages.h"
27 #include "content/public/browser/resource_dispatcher_host_delegate.h"
28 #include "content/public/common/resource_response.h"
29 #include "net/base/io_buffer.h"
30 #include "net/base/load_flags.h"
31 #include "net/base/net_util.h"
32 #include "net/log/net_log.h"
33 #include "net/url_request/redirect_info.h"
35 using base::TimeTicks;
37 namespace content {
38 namespace {
40 static int kBufferSize = 1024 * 512;
41 static int kMinAllocationSize = 1024 * 4;
42 static int kMaxAllocationSize = 1024 * 32;
44 void GetNumericArg(const std::string& name, int* result) {
45 const std::string& value =
46 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(name);
47 if (!value.empty())
48 base::StringToInt(value, result);
51 void InitializeResourceBufferConstants() {
52 static bool did_init = false;
53 if (did_init)
54 return;
55 did_init = true;
57 GetNumericArg("resource-buffer-size", &kBufferSize);
58 GetNumericArg("resource-buffer-min-allocation-size", &kMinAllocationSize);
59 GetNumericArg("resource-buffer-max-allocation-size", &kMaxAllocationSize);
62 } // namespace
64 class DependentIOBuffer : public net::WrappedIOBuffer {
65 public:
66 DependentIOBuffer(ResourceBuffer* backing, char* memory)
67 : net::WrappedIOBuffer(memory),
68 backing_(backing) {
70 private:
71 ~DependentIOBuffer() override {}
72 scoped_refptr<ResourceBuffer> backing_;
75 AsyncResourceHandler::AsyncResourceHandler(
76 net::URLRequest* request,
77 ResourceDispatcherHostImpl* rdh)
78 : ResourceHandler(request),
79 ResourceMessageDelegate(request),
80 rdh_(rdh),
81 pending_data_count_(0),
82 allocation_size_(0),
83 did_defer_(false),
84 has_checked_for_sufficient_resources_(false),
85 sent_received_response_msg_(false),
86 sent_first_data_msg_(false),
87 reported_transfer_size_(0) {
88 InitializeResourceBufferConstants();
91 AsyncResourceHandler::~AsyncResourceHandler() {
92 if (has_checked_for_sufficient_resources_)
93 rdh_->FinishedWithResourcesForRequest(request());
96 bool AsyncResourceHandler::OnMessageReceived(const IPC::Message& message) {
97 bool handled = true;
98 IPC_BEGIN_MESSAGE_MAP(AsyncResourceHandler, message)
99 IPC_MESSAGE_HANDLER(ResourceHostMsg_FollowRedirect, OnFollowRedirect)
100 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataReceived_ACK, OnDataReceivedACK)
101 IPC_MESSAGE_UNHANDLED(handled = false)
102 IPC_END_MESSAGE_MAP()
103 return handled;
106 void AsyncResourceHandler::OnFollowRedirect(int request_id) {
107 if (!request()->status().is_success()) {
108 DVLOG(1) << "OnFollowRedirect for invalid request";
109 return;
112 ResumeIfDeferred();
115 void AsyncResourceHandler::OnDataReceivedACK(int request_id) {
116 if (pending_data_count_) {
117 --pending_data_count_;
119 buffer_->RecycleLeastRecentlyAllocated();
120 if (buffer_->CanAllocate())
121 ResumeIfDeferred();
125 bool AsyncResourceHandler::OnUploadProgress(uint64 position,
126 uint64 size) {
127 ResourceMessageFilter* filter = GetFilter();
128 if (!filter)
129 return false;
130 return filter->Send(
131 new ResourceMsg_UploadProgress(GetRequestID(), position, size));
134 bool AsyncResourceHandler::OnRequestRedirected(
135 const net::RedirectInfo& redirect_info,
136 ResourceResponse* response,
137 bool* defer) {
138 const ResourceRequestInfoImpl* info = GetRequestInfo();
139 if (!info->filter())
140 return false;
142 *defer = did_defer_ = true;
143 OnDefer();
145 if (rdh_->delegate()) {
146 rdh_->delegate()->OnRequestRedirected(
147 redirect_info.new_url, request(), info->GetContext(), response);
150 DevToolsNetLogObserver::PopulateResponseInfo(request(), response);
151 response->head.encoded_data_length = request()->GetTotalReceivedBytes();
152 reported_transfer_size_ = 0;
153 response->head.request_start = request()->creation_time();
154 response->head.response_start = TimeTicks::Now();
155 // TODO(davidben): Is it necessary to pass the new first party URL for
156 // cookies? The only case where it can change is top-level navigation requests
157 // and hopefully those will eventually all be owned by the browser. It's
158 // possible this is still needed while renderer-owned ones exist.
159 return info->filter()->Send(new ResourceMsg_ReceivedRedirect(
160 GetRequestID(), redirect_info, response->head));
163 bool AsyncResourceHandler::OnResponseStarted(ResourceResponse* response,
164 bool* defer) {
165 // For changes to the main frame, inform the renderer of the new URL's
166 // per-host settings before the request actually commits. This way the
167 // renderer will be able to set these precisely at the time the
168 // request commits, avoiding the possibility of e.g. zooming the old content
169 // or of having to layout the new content twice.
171 const ResourceRequestInfoImpl* info = GetRequestInfo();
172 if (!info->filter())
173 return false;
175 if (rdh_->delegate()) {
176 rdh_->delegate()->OnResponseStarted(
177 request(), info->GetContext(), response, info->filter());
180 DevToolsNetLogObserver::PopulateResponseInfo(request(), response);
182 const HostZoomMapImpl* host_zoom_map =
183 static_cast<const HostZoomMapImpl*>(info->filter()->GetHostZoomMap());
185 if (info->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME && host_zoom_map) {
186 const GURL& request_url = request()->url();
187 int render_process_id = info->GetChildID();
188 int render_view_id = info->GetRouteID();
190 double zoom_level = host_zoom_map->GetZoomLevelForView(
191 request_url, render_process_id, render_view_id);
193 info->filter()->Send(new ViewMsg_SetZoomLevelForLoadingURL(
194 render_view_id, request_url, zoom_level));
197 // If the parent handler downloaded the resource to a file, grant the child
198 // read permissions on it.
199 if (!response->head.download_file_path.empty()) {
200 rdh_->RegisterDownloadedTempFile(
201 info->GetChildID(), info->GetRequestID(),
202 response->head.download_file_path);
205 response->head.request_start = request()->creation_time();
206 response->head.response_start = TimeTicks::Now();
207 info->filter()->Send(new ResourceMsg_ReceivedResponse(GetRequestID(),
208 response->head));
209 sent_received_response_msg_ = true;
211 if (request()->response_info().metadata.get()) {
212 std::vector<char> copy(request()->response_info().metadata->data(),
213 request()->response_info().metadata->data() +
214 request()->response_info().metadata->size());
215 info->filter()->Send(new ResourceMsg_ReceivedCachedMetadata(GetRequestID(),
216 copy));
219 return true;
222 bool AsyncResourceHandler::OnWillStart(const GURL& url, bool* defer) {
223 return true;
226 bool AsyncResourceHandler::OnBeforeNetworkStart(const GURL& url, bool* defer) {
227 return true;
230 bool AsyncResourceHandler::OnWillRead(scoped_refptr<net::IOBuffer>* buf,
231 int* buf_size,
232 int min_size) {
233 DCHECK_EQ(-1, min_size);
235 if (!EnsureResourceBufferIsInitialized())
236 return false;
238 DCHECK(buffer_->CanAllocate());
239 char* memory = buffer_->Allocate(&allocation_size_);
240 CHECK(memory);
242 *buf = new DependentIOBuffer(buffer_.get(), memory);
243 *buf_size = allocation_size_;
245 return true;
248 bool AsyncResourceHandler::OnReadCompleted(int bytes_read, bool* defer) {
249 DCHECK_GE(bytes_read, 0);
251 if (!bytes_read)
252 return true;
254 ResourceMessageFilter* filter = GetFilter();
255 if (!filter)
256 return false;
258 buffer_->ShrinkLastAllocation(bytes_read);
260 if (!sent_first_data_msg_) {
261 base::SharedMemoryHandle handle;
262 int size;
263 if (!buffer_->ShareToProcess(filter->PeerHandle(), &handle, &size))
264 return false;
265 filter->Send(new ResourceMsg_SetDataBuffer(
266 GetRequestID(), handle, size, filter->peer_pid()));
267 sent_first_data_msg_ = true;
270 int data_offset = buffer_->GetLastAllocationOffset();
272 int64_t current_transfer_size = request()->GetTotalReceivedBytes();
273 int encoded_data_length = current_transfer_size - reported_transfer_size_;
274 reported_transfer_size_ = current_transfer_size;
276 filter->Send(new ResourceMsg_DataReceived(
277 GetRequestID(), data_offset, bytes_read, encoded_data_length));
278 ++pending_data_count_;
280 if (!buffer_->CanAllocate()) {
281 *defer = did_defer_ = true;
282 OnDefer();
285 return true;
288 void AsyncResourceHandler::OnDataDownloaded(int bytes_downloaded) {
289 int64_t current_transfer_size = request()->GetTotalReceivedBytes();
290 int encoded_data_length = current_transfer_size - reported_transfer_size_;
291 reported_transfer_size_ = current_transfer_size;
293 ResourceMessageFilter* filter = GetFilter();
294 if (filter) {
295 filter->Send(new ResourceMsg_DataDownloaded(
296 GetRequestID(), bytes_downloaded, encoded_data_length));
300 void AsyncResourceHandler::OnResponseCompleted(
301 const net::URLRequestStatus& status,
302 const std::string& security_info,
303 bool* defer) {
304 const ResourceRequestInfoImpl* info = GetRequestInfo();
305 if (!info->filter())
306 return;
308 // If we crash here, figure out what URL the renderer was requesting.
309 // http://crbug.com/107692
310 char url_buf[128];
311 base::strlcpy(url_buf, request()->url().spec().c_str(), arraysize(url_buf));
312 base::debug::Alias(url_buf);
314 // TODO(gavinp): Remove this CHECK when we figure out the cause of
315 // http://crbug.com/124680 . This check mirrors closely check in
316 // WebURLLoaderImpl::OnCompletedRequest that routes this message to a WebCore
317 // ResourceHandleInternal which asserts on its state and crashes. By crashing
318 // when the message is sent, we should get better crash reports.
319 CHECK(status.status() != net::URLRequestStatus::SUCCESS ||
320 sent_received_response_msg_);
322 int error_code = status.error();
323 bool was_ignored_by_handler = info->WasIgnoredByHandler();
325 DCHECK(status.status() != net::URLRequestStatus::IO_PENDING);
326 // If this check fails, then we're in an inconsistent state because all
327 // requests ignored by the handler should be canceled (which should result in
328 // the ERR_ABORTED error code).
329 DCHECK(!was_ignored_by_handler || error_code == net::ERR_ABORTED);
331 // TODO(mkosiba): Fix up cases where we create a URLRequestStatus
332 // with a status() != SUCCESS and an error_code() == net::OK.
333 if (status.status() == net::URLRequestStatus::CANCELED &&
334 error_code == net::OK) {
335 error_code = net::ERR_ABORTED;
336 } else if (status.status() == net::URLRequestStatus::FAILED &&
337 error_code == net::OK) {
338 error_code = net::ERR_FAILED;
341 ResourceMsg_RequestCompleteData request_complete_data;
342 request_complete_data.error_code = error_code;
343 request_complete_data.was_ignored_by_handler = was_ignored_by_handler;
344 request_complete_data.exists_in_cache = request()->response_info().was_cached;
345 request_complete_data.security_info = security_info;
346 request_complete_data.completion_time = TimeTicks::Now();
347 request_complete_data.encoded_data_length =
348 request()->GetTotalReceivedBytes();
349 info->filter()->Send(
350 new ResourceMsg_RequestComplete(GetRequestID(), request_complete_data));
353 bool AsyncResourceHandler::EnsureResourceBufferIsInitialized() {
354 if (buffer_.get() && buffer_->IsInitialized())
355 return true;
357 if (!has_checked_for_sufficient_resources_) {
358 has_checked_for_sufficient_resources_ = true;
359 if (!rdh_->HasSufficientResourcesForRequest(request())) {
360 controller()->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
361 return false;
365 buffer_ = new ResourceBuffer();
366 return buffer_->Initialize(kBufferSize,
367 kMinAllocationSize,
368 kMaxAllocationSize);
371 void AsyncResourceHandler::ResumeIfDeferred() {
372 if (did_defer_) {
373 did_defer_ = false;
374 request()->LogUnblocked();
375 controller()->Resume();
379 void AsyncResourceHandler::OnDefer() {
380 request()->LogBlockedBy("AsyncResourceHandler");
383 } // namespace content