Roll src/third_party/WebKit a3b4a2e:7441784 (svn 202551:202552)
[chromium-blink-merge.git] / content / common / child_process_host_impl.cc
blob071d96d207d0c424f5a0976a885a1dc3f96e7a4e
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/synchronization/lock.h"
22 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
23 #include "content/common/child_process_messages.h"
24 #include "content/common/gpu/client/gpu_memory_buffer_impl_shared_memory.h"
25 #include "content/public/common/child_process_host_delegate.h"
26 #include "content/public/common/content_paths.h"
27 #include "content/public/common/content_switches.h"
28 #include "ipc/ipc_channel.h"
29 #include "ipc/ipc_logging.h"
30 #include "ipc/message_filter.h"
32 #if defined(OS_LINUX)
33 #include "base/linux_util.h"
34 #elif defined(OS_WIN)
35 #include "content/common/font_cache_dispatcher_win.h"
36 #include "ipc/attachment_broker_privileged_win.h"
37 #endif // OS_LINUX
39 namespace {
41 #if USE_ATTACHMENT_BROKER
42 // This class is wrapped in a singleton to ensure that its constructor is only
43 // called once. The constructor creates an attachment broker and
44 // sets it as the global broker.
45 class AttachmentBrokerWrapper {
46 public:
47 AttachmentBrokerWrapper() {
48 IPC::AttachmentBroker::SetGlobal(&attachment_broker_);
51 IPC::AttachmentBrokerPrivileged* GetAttachmentBroker() {
52 return &attachment_broker_;
55 private:
56 IPC::AttachmentBrokerPrivilegedWin attachment_broker_;
59 base::LazyInstance<AttachmentBrokerWrapper>::Leaky
60 g_attachment_broker_wrapper = LAZY_INSTANCE_INITIALIZER;
62 IPC::AttachmentBrokerPrivileged* GetAttachmentBroker() {
63 return g_attachment_broker_wrapper.Get().GetAttachmentBroker();
65 #endif // USE_ATTACHMENT_BROKER
67 // Global atomic to generate child process unique IDs.
68 base::StaticAtomicSequenceNumber g_unique_id;
70 } // namespace
72 namespace content {
74 int ChildProcessHost::kInvalidUniqueID = -1;
76 uint64 ChildProcessHost::kBrowserTracingProcessId =
77 std::numeric_limits<uint64>::max();
79 // static
80 ChildProcessHost* ChildProcessHost::Create(ChildProcessHostDelegate* delegate) {
81 return new ChildProcessHostImpl(delegate);
84 // static
85 base::FilePath ChildProcessHost::GetChildPath(int flags) {
86 base::FilePath child_path;
88 child_path = base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
89 switches::kBrowserSubprocessPath);
91 #if defined(OS_LINUX)
92 // Use /proc/self/exe rather than our known binary path so updates
93 // can't swap out the binary from underneath us.
94 // When running under Valgrind, forking /proc/self/exe ends up forking the
95 // Valgrind executable, which then crashes. However, it's almost safe to
96 // assume that the updates won't happen while testing with Valgrind tools.
97 if (child_path.empty() && flags & CHILD_ALLOW_SELF && !RunningOnValgrind())
98 child_path = base::FilePath(base::kProcSelfExe);
99 #endif
101 // On most platforms, the child executable is the same as the current
102 // executable.
103 if (child_path.empty())
104 PathService::Get(CHILD_PROCESS_EXE, &child_path);
105 return child_path;
108 ChildProcessHostImpl::ChildProcessHostImpl(ChildProcessHostDelegate* delegate)
109 : delegate_(delegate),
110 opening_channel_(false) {
111 #if defined(OS_WIN)
112 AddFilter(new FontCacheDispatcher());
113 #endif
116 ChildProcessHostImpl::~ChildProcessHostImpl() {
117 #if USE_ATTACHMENT_BROKER
118 GetAttachmentBroker()->DeregisterCommunicationChannel(channel_.get());
119 #endif
120 for (size_t i = 0; i < filters_.size(); ++i) {
121 filters_[i]->OnChannelClosing();
122 filters_[i]->OnFilterRemoved();
126 void ChildProcessHostImpl::AddFilter(IPC::MessageFilter* filter) {
127 filters_.push_back(filter);
129 if (channel_)
130 filter->OnFilterAdded(channel_.get());
133 void ChildProcessHostImpl::ForceShutdown() {
134 Send(new ChildProcessMsg_Shutdown());
137 std::string ChildProcessHostImpl::CreateChannel() {
138 channel_id_ = IPC::Channel::GenerateVerifiedChannelID(std::string());
139 channel_ = IPC::Channel::CreateServer(channel_id_, this);
140 if (!channel_->Connect())
141 return std::string();
142 #if USE_ATTACHMENT_BROKER
143 GetAttachmentBroker()->RegisterCommunicationChannel(channel_.get());
144 #endif
146 for (size_t i = 0; i < filters_.size(); ++i)
147 filters_[i]->OnFilterAdded(channel_.get());
149 // Make sure these messages get sent first.
150 #if defined(IPC_MESSAGE_LOG_ENABLED)
151 bool enabled = IPC::Logging::GetInstance()->Enabled();
152 Send(new ChildProcessMsg_SetIPCLoggingEnabled(enabled));
153 #endif
155 opening_channel_ = true;
157 return channel_id_;
160 bool ChildProcessHostImpl::IsChannelOpening() {
161 return opening_channel_;
164 #if defined(OS_POSIX)
165 base::ScopedFD ChildProcessHostImpl::TakeClientFileDescriptor() {
166 return channel_->TakeClientFileDescriptor();
168 #endif
170 bool ChildProcessHostImpl::Send(IPC::Message* message) {
171 if (!channel_) {
172 delete message;
173 return false;
175 return channel_->Send(message);
178 void ChildProcessHostImpl::AllocateSharedMemory(
179 size_t buffer_size, base::ProcessHandle child_process_handle,
180 base::SharedMemoryHandle* shared_memory_handle) {
181 base::SharedMemory shared_buf;
182 if (!shared_buf.CreateAnonymous(buffer_size)) {
183 *shared_memory_handle = base::SharedMemory::NULLHandle();
184 NOTREACHED() << "Cannot create shared memory buffer";
185 return;
187 shared_buf.GiveToProcess(child_process_handle, shared_memory_handle);
190 int ChildProcessHostImpl::GenerateChildProcessUniqueId() {
191 // This function must be threadsafe.
193 // Historically, this function returned ids started with 1, so in several
194 // places in the code a value of 0 (rather than kInvalidUniqueID) was used as
195 // an invalid value. So we retain those semantics.
196 int id = g_unique_id.GetNext() + 1;
198 CHECK_NE(0, id);
199 CHECK_NE(kInvalidUniqueID, id);
201 return id;
204 uint64 ChildProcessHostImpl::ChildProcessUniqueIdToTracingProcessId(
205 int child_process_id) {
206 // In single process mode, all the children are hosted in the same process,
207 // therefore the generated memory dump guids should not be conditioned by the
208 // child process id. The clients need not be aware of SPM and the conversion
209 // takes care of the SPM special case while translating child process ids to
210 // tracing process ids.
211 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
212 switches::kSingleProcess))
213 return ChildProcessHost::kBrowserTracingProcessId;
215 // The hash value is incremented so that the tracing id is never equal to
216 // MemoryDumpManager::kInvalidTracingProcessId.
217 return static_cast<uint64>(
218 base::Hash(reinterpret_cast<const char*>(&child_process_id),
219 sizeof(child_process_id))) +
223 bool ChildProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
224 #ifdef IPC_MESSAGE_LOG_ENABLED
225 IPC::Logging* logger = IPC::Logging::GetInstance();
226 if (msg.type() == IPC_LOGGING_ID) {
227 logger->OnReceivedLoggingMessage(msg);
228 return true;
231 if (logger->Enabled())
232 logger->OnPreDispatchMessage(msg);
233 #endif
235 bool handled = false;
236 for (size_t i = 0; i < filters_.size(); ++i) {
237 if (filters_[i]->OnMessageReceived(msg)) {
238 handled = true;
239 break;
243 if (!handled) {
244 handled = true;
245 IPC_BEGIN_MESSAGE_MAP(ChildProcessHostImpl, msg)
246 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
247 OnShutdownRequest)
248 // NB: The SyncAllocateSharedMemory, SyncAllocateGpuMemoryBuffer, and
249 // DeletedGpuMemoryBuffer IPCs are handled here for non-renderer child
250 // processes. For renderer processes, they are handled in
251 // RenderMessageFilter.
252 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateSharedMemory,
253 OnAllocateSharedMemory)
254 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer,
255 OnAllocateGpuMemoryBuffer)
256 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer,
257 OnDeletedGpuMemoryBuffer)
258 IPC_MESSAGE_UNHANDLED(handled = false)
259 IPC_END_MESSAGE_MAP()
261 if (!handled)
262 handled = delegate_->OnMessageReceived(msg);
265 #ifdef IPC_MESSAGE_LOG_ENABLED
266 if (logger->Enabled())
267 logger->OnPostDispatchMessage(msg, channel_id_);
268 #endif
269 return handled;
272 void ChildProcessHostImpl::OnChannelConnected(int32 peer_pid) {
273 if (!peer_process_.IsValid()) {
274 peer_process_ = base::Process::OpenWithExtraPrivileges(peer_pid);
275 if (!peer_process_.IsValid())
276 peer_process_ = delegate_->GetProcess().Duplicate();
277 DCHECK(peer_process_.IsValid());
279 opening_channel_ = false;
280 delegate_->OnChannelConnected(peer_pid);
281 for (size_t i = 0; i < filters_.size(); ++i)
282 filters_[i]->OnChannelConnected(peer_pid);
285 void ChildProcessHostImpl::OnChannelError() {
286 opening_channel_ = false;
287 delegate_->OnChannelError();
289 for (size_t i = 0; i < filters_.size(); ++i)
290 filters_[i]->OnChannelError();
292 // This will delete host_, which will also destroy this!
293 delegate_->OnChildDisconnected();
296 void ChildProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
297 delegate_->OnBadMessageReceived(message);
300 void ChildProcessHostImpl::OnAllocateSharedMemory(
301 uint32 buffer_size,
302 base::SharedMemoryHandle* handle) {
303 AllocateSharedMemory(buffer_size, peer_process_.Handle(), handle);
306 void ChildProcessHostImpl::OnShutdownRequest() {
307 if (delegate_->CanShutdown())
308 Send(new ChildProcessMsg_Shutdown());
311 void ChildProcessHostImpl::OnAllocateGpuMemoryBuffer(
312 gfx::GpuMemoryBufferId id,
313 uint32 width,
314 uint32 height,
315 gfx::BufferFormat format,
316 gfx::BufferUsage usage,
317 gfx::GpuMemoryBufferHandle* handle) {
318 // TODO(reveman): Add support for other types of GpuMemoryBuffers.
320 // AllocateForChildProcess() will check if |width| and |height| are valid
321 // and handle failure in a controlled way when not. We just need to make
322 // sure |format| and |usage| are supported here.
323 if (GpuMemoryBufferImplSharedMemory::IsFormatSupported(format) &&
324 GpuMemoryBufferImplSharedMemory::IsUsageSupported(usage)) {
325 *handle = GpuMemoryBufferImplSharedMemory::AllocateForChildProcess(
326 id, gfx::Size(width, height), format, peer_process_.Handle());
330 void ChildProcessHostImpl::OnDeletedGpuMemoryBuffer(
331 gfx::GpuMemoryBufferId id,
332 uint32 sync_point) {
333 // Note: Nothing to do here as ownership of shared memory backed
334 // GpuMemoryBuffers is passed with IPC.
337 } // namespace content