Update V8 to version 4.7.42.
[chromium-blink-merge.git] / content / common / child_process_host_impl.cc
blob2341db13083705eb14995038787566d4bf9e5c02
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 // Global atomic to generate child process unique IDs.
46 base::StaticAtomicSequenceNumber g_unique_id;
48 } // namespace
50 namespace content {
52 int ChildProcessHost::kInvalidUniqueID = -1;
54 uint64 ChildProcessHost::kBrowserTracingProcessId =
55 std::numeric_limits<uint64>::max();
57 // static
58 ChildProcessHost* ChildProcessHost::Create(ChildProcessHostDelegate* delegate) {
59 return new ChildProcessHostImpl(delegate);
62 // static
63 base::FilePath ChildProcessHost::GetChildPath(int flags) {
64 base::FilePath child_path;
66 child_path = base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
67 switches::kBrowserSubprocessPath);
69 #if defined(OS_LINUX)
70 // Use /proc/self/exe rather than our known binary path so updates
71 // can't swap out the binary from underneath us.
72 // When running under Valgrind, forking /proc/self/exe ends up forking the
73 // Valgrind executable, which then crashes. However, it's almost safe to
74 // assume that the updates won't happen while testing with Valgrind tools.
75 if (child_path.empty() && flags & CHILD_ALLOW_SELF && !RunningOnValgrind())
76 child_path = base::FilePath(base::kProcSelfExe);
77 #endif
79 // On most platforms, the child executable is the same as the current
80 // executable.
81 if (child_path.empty())
82 PathService::Get(CHILD_PROCESS_EXE, &child_path);
83 return child_path;
86 // static
87 IPC::AttachmentBrokerPrivileged* ChildProcessHost::GetAttachmentBroker() {
88 #if USE_ATTACHMENT_BROKER
89 return &g_attachment_broker.Get();
90 #else
91 return nullptr;
92 #endif // USE_ATTACHMENT_BROKER
95 ChildProcessHostImpl::ChildProcessHostImpl(ChildProcessHostDelegate* delegate)
96 : delegate_(delegate),
97 opening_channel_(false) {
98 #if defined(OS_WIN)
99 AddFilter(new FontCacheDispatcher());
100 #endif
103 ChildProcessHostImpl::~ChildProcessHostImpl() {
104 #if USE_ATTACHMENT_BROKER
105 g_attachment_broker.Get().DeregisterCommunicationChannel(channel_.get());
106 #endif
107 for (size_t i = 0; i < filters_.size(); ++i) {
108 filters_[i]->OnChannelClosing();
109 filters_[i]->OnFilterRemoved();
113 void ChildProcessHostImpl::AddFilter(IPC::MessageFilter* filter) {
114 filters_.push_back(filter);
116 if (channel_)
117 filter->OnFilterAdded(channel_.get());
120 void ChildProcessHostImpl::ForceShutdown() {
121 Send(new ChildProcessMsg_Shutdown());
124 std::string ChildProcessHostImpl::CreateChannel() {
125 channel_id_ = IPC::Channel::GenerateVerifiedChannelID(std::string());
126 channel_ =
127 IPC::Channel::CreateServer(channel_id_, this, GetAttachmentBroker());
128 if (!channel_->Connect())
129 return std::string();
130 #if USE_ATTACHMENT_BROKER
131 g_attachment_broker.Get().RegisterCommunicationChannel(channel_.get());
132 #endif
134 for (size_t i = 0; i < filters_.size(); ++i)
135 filters_[i]->OnFilterAdded(channel_.get());
137 // Make sure these messages get sent first.
138 #if defined(IPC_MESSAGE_LOG_ENABLED)
139 bool enabled = IPC::Logging::GetInstance()->Enabled();
140 Send(new ChildProcessMsg_SetIPCLoggingEnabled(enabled));
141 #endif
143 opening_channel_ = true;
145 return channel_id_;
148 bool ChildProcessHostImpl::IsChannelOpening() {
149 return opening_channel_;
152 #if defined(OS_POSIX)
153 base::ScopedFD ChildProcessHostImpl::TakeClientFileDescriptor() {
154 return channel_->TakeClientFileDescriptor();
156 #endif
158 bool ChildProcessHostImpl::Send(IPC::Message* message) {
159 if (!channel_) {
160 delete message;
161 return false;
163 return channel_->Send(message);
166 void ChildProcessHostImpl::AllocateSharedMemory(
167 size_t buffer_size, base::ProcessHandle child_process_handle,
168 base::SharedMemoryHandle* shared_memory_handle) {
169 base::SharedMemory shared_buf;
170 if (!shared_buf.CreateAnonymous(buffer_size)) {
171 *shared_memory_handle = base::SharedMemory::NULLHandle();
172 NOTREACHED() << "Cannot create shared memory buffer";
173 return;
175 shared_buf.GiveToProcess(child_process_handle, shared_memory_handle);
178 int ChildProcessHostImpl::GenerateChildProcessUniqueId() {
179 // This function must be threadsafe.
181 // Historically, this function returned ids started with 1, so in several
182 // places in the code a value of 0 (rather than kInvalidUniqueID) was used as
183 // an invalid value. So we retain those semantics.
184 int id = g_unique_id.GetNext() + 1;
186 CHECK_NE(0, id);
187 CHECK_NE(kInvalidUniqueID, id);
189 return id;
192 uint64 ChildProcessHostImpl::ChildProcessUniqueIdToTracingProcessId(
193 int child_process_id) {
194 // In single process mode, all the children are hosted in the same process,
195 // therefore the generated memory dump guids should not be conditioned by the
196 // child process id. The clients need not be aware of SPM and the conversion
197 // takes care of the SPM special case while translating child process ids to
198 // tracing process ids.
199 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
200 switches::kSingleProcess))
201 return ChildProcessHost::kBrowserTracingProcessId;
203 // The hash value is incremented so that the tracing id is never equal to
204 // MemoryDumpManager::kInvalidTracingProcessId.
205 return static_cast<uint64>(
206 base::Hash(reinterpret_cast<const char*>(&child_process_id),
207 sizeof(child_process_id))) +
211 bool ChildProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
212 #ifdef IPC_MESSAGE_LOG_ENABLED
213 IPC::Logging* logger = IPC::Logging::GetInstance();
214 if (msg.type() == IPC_LOGGING_ID) {
215 logger->OnReceivedLoggingMessage(msg);
216 return true;
219 if (logger->Enabled())
220 logger->OnPreDispatchMessage(msg);
221 #endif
223 bool handled = false;
224 for (size_t i = 0; i < filters_.size(); ++i) {
225 if (filters_[i]->OnMessageReceived(msg)) {
226 handled = true;
227 break;
231 if (!handled) {
232 handled = true;
233 IPC_BEGIN_MESSAGE_MAP(ChildProcessHostImpl, msg)
234 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
235 OnShutdownRequest)
236 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateSharedMemory,
237 OnAllocateSharedMemory)
238 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer,
239 OnAllocateGpuMemoryBuffer)
240 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer,
241 OnDeletedGpuMemoryBuffer)
242 IPC_MESSAGE_UNHANDLED(handled = false)
243 IPC_END_MESSAGE_MAP()
245 if (!handled)
246 handled = delegate_->OnMessageReceived(msg);
249 #ifdef IPC_MESSAGE_LOG_ENABLED
250 if (logger->Enabled())
251 logger->OnPostDispatchMessage(msg, channel_id_);
252 #endif
253 return handled;
256 void ChildProcessHostImpl::OnChannelConnected(int32 peer_pid) {
257 if (!peer_process_.IsValid()) {
258 peer_process_ = base::Process::OpenWithExtraPrivileges(peer_pid);
259 if (!peer_process_.IsValid())
260 peer_process_ = delegate_->GetProcess().Duplicate();
261 DCHECK(peer_process_.IsValid());
263 opening_channel_ = false;
264 delegate_->OnChannelConnected(peer_pid);
265 for (size_t i = 0; i < filters_.size(); ++i)
266 filters_[i]->OnChannelConnected(peer_pid);
269 void ChildProcessHostImpl::OnChannelError() {
270 opening_channel_ = false;
271 delegate_->OnChannelError();
273 for (size_t i = 0; i < filters_.size(); ++i)
274 filters_[i]->OnChannelError();
276 // This will delete host_, which will also destroy this!
277 delegate_->OnChildDisconnected();
280 void ChildProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
281 delegate_->OnBadMessageReceived(message);
284 void ChildProcessHostImpl::OnAllocateSharedMemory(
285 uint32 buffer_size,
286 base::SharedMemoryHandle* handle) {
287 AllocateSharedMemory(buffer_size, peer_process_.Handle(), handle);
290 void ChildProcessHostImpl::OnShutdownRequest() {
291 if (delegate_->CanShutdown())
292 Send(new ChildProcessMsg_Shutdown());
295 void ChildProcessHostImpl::OnAllocateGpuMemoryBuffer(
296 gfx::GpuMemoryBufferId id,
297 uint32 width,
298 uint32 height,
299 gfx::BufferFormat format,
300 gfx::BufferUsage usage,
301 gfx::GpuMemoryBufferHandle* handle) {
302 // TODO(reveman): Add support for other types of GpuMemoryBuffers.
304 // AllocateForChildProcess() will check if |width| and |height| are valid
305 // and handle failure in a controlled way when not. We just need to make
306 // sure |format| and |usage| are supported here.
307 if (GpuMemoryBufferImplSharedMemory::IsFormatSupported(format) &&
308 GpuMemoryBufferImplSharedMemory::IsUsageSupported(usage)) {
309 *handle = GpuMemoryBufferImplSharedMemory::AllocateForChildProcess(
310 id, gfx::Size(width, height), format, peer_process_.Handle());
314 void ChildProcessHostImpl::OnDeletedGpuMemoryBuffer(
315 gfx::GpuMemoryBufferId id,
316 uint32 sync_point) {
317 // Note: Nothing to do here as ownership of shared memory backed
318 // GpuMemoryBuffers is passed with IPC.
321 } // namespace content