gpu: Add memory tracing of GPU transfer buffers.
[chromium-blink-merge.git] / content / common / child_process_host_impl.cc
blob3aad503d6c424ca50db5096ffe8a2fad90ae7ec4
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/common/child_process_host_impl.h"
7 #include <limits>
9 #include "base/atomic_sequence_num.h"
10 #include "base/command_line.h"
11 #include "base/files/file_path.h"
12 #include "base/hash.h"
13 #include "base/lazy_instance.h"
14 #include "base/logging.h"
15 #include "base/metrics/histogram.h"
16 #include "base/numerics/safe_math.h"
17 #include "base/path_service.h"
18 #include "base/process/process_metrics.h"
19 #include "base/rand_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
22 #include "content/common/child_process_messages.h"
23 #include "content/common/gpu/client/gpu_memory_buffer_impl_shared_memory.h"
24 #include "content/public/common/child_process_host_delegate.h"
25 #include "content/public/common/content_paths.h"
26 #include "content/public/common/content_switches.h"
27 #include "ipc/ipc_channel.h"
28 #include "ipc/ipc_logging.h"
29 #include "ipc/message_filter.h"
31 #if defined(OS_LINUX)
32 #include "base/linux_util.h"
33 #elif defined(OS_WIN)
34 #include "content/common/font_cache_dispatcher_win.h"
35 #include "ipc/attachment_broker_privileged_win.h"
36 #endif // OS_LINUX
38 #if defined(OS_WIN)
39 base::LazyInstance<IPC::AttachmentBrokerPrivilegedWin>::Leaky
40 g_attachment_broker = LAZY_INSTANCE_INITIALIZER;
41 #endif // defined(OS_WIN)
43 namespace {
45 #if defined(OS_MACOSX)
46 // Given |path| identifying a Mac-style child process executable path, adjusts
47 // it to correspond to |feature|. For a child process path such as
48 // ".../Chromium Helper.app/Contents/MacOS/Chromium Helper", the transformed
49 // path for feature "NP" would be
50 // ".../Chromium Helper NP.app/Contents/MacOS/Chromium Helper NP". The new
51 // path is returned.
52 base::FilePath TransformPathForFeature(const base::FilePath& path,
53 const std::string& feature) {
54 std::string basename = path.BaseName().value();
56 base::FilePath macos_path = path.DirName();
57 const char kMacOSName[] = "MacOS";
58 DCHECK_EQ(kMacOSName, macos_path.BaseName().value());
60 base::FilePath contents_path = macos_path.DirName();
61 const char kContentsName[] = "Contents";
62 DCHECK_EQ(kContentsName, contents_path.BaseName().value());
64 base::FilePath helper_app_path = contents_path.DirName();
65 const char kAppExtension[] = ".app";
66 std::string basename_app = basename;
67 basename_app.append(kAppExtension);
68 DCHECK_EQ(basename_app, helper_app_path.BaseName().value());
70 base::FilePath root_path = helper_app_path.DirName();
72 std::string new_basename = basename;
73 new_basename.append(1, ' ');
74 new_basename.append(feature);
75 std::string new_basename_app = new_basename;
76 new_basename_app.append(kAppExtension);
78 base::FilePath new_path = root_path.Append(new_basename_app)
79 .Append(kContentsName)
80 .Append(kMacOSName)
81 .Append(new_basename);
83 return new_path;
85 #endif // OS_MACOSX
87 // Global atomic to generate child process unique IDs.
88 base::StaticAtomicSequenceNumber g_unique_id;
90 } // namespace
92 namespace content {
94 int ChildProcessHost::kInvalidUniqueID = -1;
96 uint64 ChildProcessHost::kBrowserTracingProcessId =
97 std::numeric_limits<uint64>::max();
99 // static
100 ChildProcessHost* ChildProcessHost::Create(ChildProcessHostDelegate* delegate) {
101 return new ChildProcessHostImpl(delegate);
104 // static
105 base::FilePath ChildProcessHost::GetChildPath(int flags) {
106 base::FilePath child_path;
108 child_path = base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
109 switches::kBrowserSubprocessPath);
111 #if defined(OS_LINUX)
112 // Use /proc/self/exe rather than our known binary path so updates
113 // can't swap out the binary from underneath us.
114 // When running under Valgrind, forking /proc/self/exe ends up forking the
115 // Valgrind executable, which then crashes. However, it's almost safe to
116 // assume that the updates won't happen while testing with Valgrind tools.
117 if (child_path.empty() && flags & CHILD_ALLOW_SELF && !RunningOnValgrind())
118 child_path = base::FilePath(base::kProcSelfExe);
119 #endif
121 // On most platforms, the child executable is the same as the current
122 // executable.
123 if (child_path.empty())
124 PathService::Get(CHILD_PROCESS_EXE, &child_path);
126 #if defined(OS_MACOSX)
127 DCHECK(!(flags & CHILD_NO_PIE && flags & CHILD_ALLOW_HEAP_EXECUTION));
129 // If needed, choose an executable with special flags set that inform the
130 // kernel to enable or disable specific optional process-wide features.
131 if (flags & CHILD_NO_PIE) {
132 // "NP" is "No PIE". This results in Chromium Helper NP.app or
133 // Google Chrome Helper NP.app.
134 child_path = TransformPathForFeature(child_path, "NP");
135 } else if (flags & CHILD_ALLOW_HEAP_EXECUTION) {
136 // "EH" is "Executable Heap". A non-executable heap is only available to
137 // 32-bit processes on Mac OS X 10.7. Most code can and should run with a
138 // non-executable heap, but the "EH" feature is provided to allow code
139 // intolerant of a non-executable heap to work properly on 10.7. This
140 // results in Chromium Helper EH.app or Google Chrome Helper EH.app.
141 child_path = TransformPathForFeature(child_path, "EH");
143 #endif
145 return child_path;
148 // static
149 IPC::AttachmentBrokerPrivileged* ChildProcessHost::GetAttachmentBroker() {
150 #if USE_ATTACHMENT_BROKER
151 return &g_attachment_broker.Get();
152 #else
153 return nullptr;
154 #endif // USE_ATTACHMENT_BROKER
157 ChildProcessHostImpl::ChildProcessHostImpl(ChildProcessHostDelegate* delegate)
158 : delegate_(delegate),
159 opening_channel_(false) {
160 #if defined(OS_WIN)
161 AddFilter(new FontCacheDispatcher());
162 #endif
165 ChildProcessHostImpl::~ChildProcessHostImpl() {
166 #if USE_ATTACHMENT_BROKER
167 g_attachment_broker.Get().DeregisterCommunicationChannel(channel_.get());
168 #endif
169 for (size_t i = 0; i < filters_.size(); ++i) {
170 filters_[i]->OnChannelClosing();
171 filters_[i]->OnFilterRemoved();
175 void ChildProcessHostImpl::AddFilter(IPC::MessageFilter* filter) {
176 filters_.push_back(filter);
178 if (channel_)
179 filter->OnFilterAdded(channel_.get());
182 void ChildProcessHostImpl::ForceShutdown() {
183 Send(new ChildProcessMsg_Shutdown());
186 std::string ChildProcessHostImpl::CreateChannel() {
187 channel_id_ = IPC::Channel::GenerateVerifiedChannelID(std::string());
188 channel_ =
189 IPC::Channel::CreateServer(channel_id_, this, GetAttachmentBroker());
190 if (!channel_->Connect())
191 return std::string();
192 #if USE_ATTACHMENT_BROKER
193 g_attachment_broker.Get().RegisterCommunicationChannel(channel_.get());
194 #endif
196 for (size_t i = 0; i < filters_.size(); ++i)
197 filters_[i]->OnFilterAdded(channel_.get());
199 // Make sure these messages get sent first.
200 #if defined(IPC_MESSAGE_LOG_ENABLED)
201 bool enabled = IPC::Logging::GetInstance()->Enabled();
202 Send(new ChildProcessMsg_SetIPCLoggingEnabled(enabled));
203 #endif
205 opening_channel_ = true;
207 return channel_id_;
210 bool ChildProcessHostImpl::IsChannelOpening() {
211 return opening_channel_;
214 #if defined(OS_POSIX)
215 base::ScopedFD ChildProcessHostImpl::TakeClientFileDescriptor() {
216 return channel_->TakeClientFileDescriptor();
218 #endif
220 bool ChildProcessHostImpl::Send(IPC::Message* message) {
221 if (!channel_) {
222 delete message;
223 return false;
225 return channel_->Send(message);
228 void ChildProcessHostImpl::AllocateSharedMemory(
229 size_t buffer_size, base::ProcessHandle child_process_handle,
230 base::SharedMemoryHandle* shared_memory_handle) {
231 base::SharedMemory shared_buf;
232 if (!shared_buf.CreateAnonymous(buffer_size)) {
233 *shared_memory_handle = base::SharedMemory::NULLHandle();
234 NOTREACHED() << "Cannot create shared memory buffer";
235 return;
237 shared_buf.GiveToProcess(child_process_handle, shared_memory_handle);
240 int ChildProcessHostImpl::GenerateChildProcessUniqueId() {
241 // This function must be threadsafe.
243 // Historically, this function returned ids started with 1, so in several
244 // places in the code a value of 0 (rather than kInvalidUniqueID) was used as
245 // an invalid value. So we retain those semantics.
246 int id = g_unique_id.GetNext() + 1;
248 CHECK_NE(0, id);
249 CHECK_NE(kInvalidUniqueID, id);
251 return id;
254 uint64 ChildProcessHostImpl::ChildProcessUniqueIdToTracingProcessId(
255 int child_process_id) {
256 // In single process mode, all the children are hosted in the same process,
257 // therefore the generated memory dump guids should not be conditioned by the
258 // child process id. The clients need not be aware of SPM and the conversion
259 // takes care of the SPM special case while translating child process ids to
260 // tracing process ids.
261 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
262 switches::kSingleProcess))
263 return ChildProcessHost::kBrowserTracingProcessId;
265 // The hash value is incremented so that the tracing id is never equal to
266 // MemoryDumpManager::kInvalidTracingProcessId.
267 return static_cast<uint64>(
268 base::Hash(reinterpret_cast<const char*>(&child_process_id),
269 sizeof(child_process_id))) +
273 bool ChildProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
274 #ifdef IPC_MESSAGE_LOG_ENABLED
275 IPC::Logging* logger = IPC::Logging::GetInstance();
276 if (msg.type() == IPC_LOGGING_ID) {
277 logger->OnReceivedLoggingMessage(msg);
278 return true;
281 if (logger->Enabled())
282 logger->OnPreDispatchMessage(msg);
283 #endif
285 bool handled = false;
286 for (size_t i = 0; i < filters_.size(); ++i) {
287 if (filters_[i]->OnMessageReceived(msg)) {
288 handled = true;
289 break;
293 if (!handled) {
294 handled = true;
295 IPC_BEGIN_MESSAGE_MAP(ChildProcessHostImpl, msg)
296 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
297 OnShutdownRequest)
298 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateSharedMemory,
299 OnAllocateSharedMemory)
300 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer,
301 OnAllocateGpuMemoryBuffer)
302 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer,
303 OnDeletedGpuMemoryBuffer)
304 IPC_MESSAGE_UNHANDLED(handled = false)
305 IPC_END_MESSAGE_MAP()
307 if (!handled)
308 handled = delegate_->OnMessageReceived(msg);
311 #ifdef IPC_MESSAGE_LOG_ENABLED
312 if (logger->Enabled())
313 logger->OnPostDispatchMessage(msg, channel_id_);
314 #endif
315 return handled;
318 void ChildProcessHostImpl::OnChannelConnected(int32 peer_pid) {
319 if (!peer_process_.IsValid()) {
320 peer_process_ = base::Process::OpenWithExtraPrivileges(peer_pid);
321 if (!peer_process_.IsValid())
322 peer_process_ = delegate_->GetProcess().Duplicate();
323 DCHECK(peer_process_.IsValid());
325 opening_channel_ = false;
326 delegate_->OnChannelConnected(peer_pid);
327 for (size_t i = 0; i < filters_.size(); ++i)
328 filters_[i]->OnChannelConnected(peer_pid);
331 void ChildProcessHostImpl::OnChannelError() {
332 opening_channel_ = false;
333 delegate_->OnChannelError();
335 for (size_t i = 0; i < filters_.size(); ++i)
336 filters_[i]->OnChannelError();
338 // This will delete host_, which will also destroy this!
339 delegate_->OnChildDisconnected();
342 void ChildProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
343 delegate_->OnBadMessageReceived(message);
346 void ChildProcessHostImpl::OnAllocateSharedMemory(
347 uint32 buffer_size,
348 base::SharedMemoryHandle* handle) {
349 AllocateSharedMemory(buffer_size, peer_process_.Handle(), handle);
352 void ChildProcessHostImpl::OnShutdownRequest() {
353 if (delegate_->CanShutdown())
354 Send(new ChildProcessMsg_Shutdown());
357 void ChildProcessHostImpl::OnAllocateGpuMemoryBuffer(
358 gfx::GpuMemoryBufferId id,
359 uint32 width,
360 uint32 height,
361 gfx::BufferFormat format,
362 gfx::BufferUsage usage,
363 gfx::GpuMemoryBufferHandle* handle) {
364 // TODO(reveman): Add support for other types of GpuMemoryBuffers.
366 // AllocateForChildProcess() will check if |width| and |height| are valid
367 // and handle failure in a controlled way when not. We just need to make
368 // sure |format| and |usage| are supported here.
369 if (GpuMemoryBufferImplSharedMemory::IsFormatSupported(format) &&
370 GpuMemoryBufferImplSharedMemory::IsUsageSupported(usage)) {
371 *handle = GpuMemoryBufferImplSharedMemory::AllocateForChildProcess(
372 id, gfx::Size(width, height), format, peer_process_.Handle());
376 void ChildProcessHostImpl::OnDeletedGpuMemoryBuffer(
377 gfx::GpuMemoryBufferId id,
378 uint32 sync_point) {
379 // Note: Nothing to do here as ownership of shared memory backed
380 // GpuMemoryBuffers is passed with IPC.
383 } // namespace content