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"
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"
32 #include "base/linux_util.h"
34 #include "content/common/font_cache_dispatcher_win.h"
35 #include "ipc/attachment_broker_privileged_win.h"
39 base::LazyInstance
<IPC::AttachmentBrokerPrivilegedWin
>::Leaky
40 g_attachment_broker
= LAZY_INSTANCE_INITIALIZER
;
41 #endif // defined(OS_WIN)
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
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
)
81 .Append(new_basename
);
87 // Global atomic to generate child process unique IDs.
88 base::StaticAtomicSequenceNumber g_unique_id
;
90 // Global atomic to generate gpu memory buffer unique IDs.
91 base::StaticAtomicSequenceNumber g_next_gpu_memory_buffer_id
;
97 int ChildProcessHost::kInvalidUniqueID
= -1;
99 uint64
ChildProcessHost::kBrowserTracingProcessId
=
100 std::numeric_limits
<uint64
>::max();
103 ChildProcessHost
* ChildProcessHost::Create(ChildProcessHostDelegate
* delegate
) {
104 return new ChildProcessHostImpl(delegate
);
108 base::FilePath
ChildProcessHost::GetChildPath(int flags
) {
109 base::FilePath child_path
;
111 child_path
= base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
112 switches::kBrowserSubprocessPath
);
114 #if defined(OS_LINUX)
115 // Use /proc/self/exe rather than our known binary path so updates
116 // can't swap out the binary from underneath us.
117 // When running under Valgrind, forking /proc/self/exe ends up forking the
118 // Valgrind executable, which then crashes. However, it's almost safe to
119 // assume that the updates won't happen while testing with Valgrind tools.
120 if (child_path
.empty() && flags
& CHILD_ALLOW_SELF
&& !RunningOnValgrind())
121 child_path
= base::FilePath(base::kProcSelfExe
);
124 // On most platforms, the child executable is the same as the current
126 if (child_path
.empty())
127 PathService::Get(CHILD_PROCESS_EXE
, &child_path
);
129 #if defined(OS_MACOSX)
130 DCHECK(!(flags
& CHILD_NO_PIE
&& flags
& CHILD_ALLOW_HEAP_EXECUTION
));
132 // If needed, choose an executable with special flags set that inform the
133 // kernel to enable or disable specific optional process-wide features.
134 if (flags
& CHILD_NO_PIE
) {
135 // "NP" is "No PIE". This results in Chromium Helper NP.app or
136 // Google Chrome Helper NP.app.
137 child_path
= TransformPathForFeature(child_path
, "NP");
138 } else if (flags
& CHILD_ALLOW_HEAP_EXECUTION
) {
139 // "EH" is "Executable Heap". A non-executable heap is only available to
140 // 32-bit processes on Mac OS X 10.7. Most code can and should run with a
141 // non-executable heap, but the "EH" feature is provided to allow code
142 // intolerant of a non-executable heap to work properly on 10.7. This
143 // results in Chromium Helper EH.app or Google Chrome Helper EH.app.
144 child_path
= TransformPathForFeature(child_path
, "EH");
152 IPC::AttachmentBrokerPrivileged
* ChildProcessHost::GetAttachmentBroker() {
153 #if USE_ATTACHMENT_BROKER
154 return &g_attachment_broker
.Get();
157 #endif // USE_ATTACHMENT_BROKER
160 ChildProcessHostImpl::ChildProcessHostImpl(ChildProcessHostDelegate
* delegate
)
161 : delegate_(delegate
),
162 opening_channel_(false) {
164 AddFilter(new FontCacheDispatcher());
168 ChildProcessHostImpl::~ChildProcessHostImpl() {
169 #if USE_ATTACHMENT_BROKER
170 g_attachment_broker
.Get().DeregisterCommunicationChannel(channel_
.get());
172 for (size_t i
= 0; i
< filters_
.size(); ++i
) {
173 filters_
[i
]->OnChannelClosing();
174 filters_
[i
]->OnFilterRemoved();
178 void ChildProcessHostImpl::AddFilter(IPC::MessageFilter
* filter
) {
179 filters_
.push_back(filter
);
182 filter
->OnFilterAdded(channel_
.get());
185 void ChildProcessHostImpl::ForceShutdown() {
186 Send(new ChildProcessMsg_Shutdown());
189 std::string
ChildProcessHostImpl::CreateChannel() {
190 channel_id_
= IPC::Channel::GenerateVerifiedChannelID(std::string());
192 IPC::Channel::CreateServer(channel_id_
, this, GetAttachmentBroker());
193 if (!channel_
->Connect())
194 return std::string();
195 #if USE_ATTACHMENT_BROKER
196 g_attachment_broker
.Get().RegisterCommunicationChannel(channel_
.get());
199 for (size_t i
= 0; i
< filters_
.size(); ++i
)
200 filters_
[i
]->OnFilterAdded(channel_
.get());
202 // Make sure these messages get sent first.
203 #if defined(IPC_MESSAGE_LOG_ENABLED)
204 bool enabled
= IPC::Logging::GetInstance()->Enabled();
205 Send(new ChildProcessMsg_SetIPCLoggingEnabled(enabled
));
208 opening_channel_
= true;
213 bool ChildProcessHostImpl::IsChannelOpening() {
214 return opening_channel_
;
217 #if defined(OS_POSIX)
218 base::ScopedFD
ChildProcessHostImpl::TakeClientFileDescriptor() {
219 return channel_
->TakeClientFileDescriptor();
223 bool ChildProcessHostImpl::Send(IPC::Message
* message
) {
228 return channel_
->Send(message
);
231 void ChildProcessHostImpl::AllocateSharedMemory(
232 size_t buffer_size
, base::ProcessHandle child_process_handle
,
233 base::SharedMemoryHandle
* shared_memory_handle
) {
234 base::SharedMemory shared_buf
;
235 if (!shared_buf
.CreateAnonymous(buffer_size
)) {
236 *shared_memory_handle
= base::SharedMemory::NULLHandle();
237 NOTREACHED() << "Cannot create shared memory buffer";
240 shared_buf
.GiveToProcess(child_process_handle
, shared_memory_handle
);
243 int ChildProcessHostImpl::GenerateChildProcessUniqueId() {
244 // This function must be threadsafe.
246 // Historically, this function returned ids started with 1, so in several
247 // places in the code a value of 0 (rather than kInvalidUniqueID) was used as
248 // an invalid value. So we retain those semantics.
249 int id
= g_unique_id
.GetNext() + 1;
252 CHECK_NE(kInvalidUniqueID
, id
);
257 uint64
ChildProcessHostImpl::ChildProcessUniqueIdToTracingProcessId(
258 int child_process_id
) {
259 // In single process mode, all the children are hosted in the same process,
260 // therefore the generated memory dump guids should not be conditioned by the
261 // child process id. The clients need not be aware of SPM and the conversion
262 // takes care of the SPM special case while translating child process ids to
263 // tracing process ids.
264 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
265 switches::kSingleProcess
))
266 return ChildProcessHost::kBrowserTracingProcessId
;
268 // The hash value is incremented so that the tracing id is never equal to
269 // MemoryDumpManager::kInvalidTracingProcessId.
270 return static_cast<uint64
>(
271 base::Hash(reinterpret_cast<const char*>(&child_process_id
),
272 sizeof(child_process_id
))) +
276 bool ChildProcessHostImpl::OnMessageReceived(const IPC::Message
& msg
) {
277 #ifdef IPC_MESSAGE_LOG_ENABLED
278 IPC::Logging
* logger
= IPC::Logging::GetInstance();
279 if (msg
.type() == IPC_LOGGING_ID
) {
280 logger
->OnReceivedLoggingMessage(msg
);
284 if (logger
->Enabled())
285 logger
->OnPreDispatchMessage(msg
);
288 bool handled
= false;
289 for (size_t i
= 0; i
< filters_
.size(); ++i
) {
290 if (filters_
[i
]->OnMessageReceived(msg
)) {
298 IPC_BEGIN_MESSAGE_MAP(ChildProcessHostImpl
, msg
)
299 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest
,
301 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateSharedMemory
,
302 OnAllocateSharedMemory
)
303 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer
,
304 OnAllocateGpuMemoryBuffer
)
305 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer
,
306 OnDeletedGpuMemoryBuffer
)
307 IPC_MESSAGE_UNHANDLED(handled
= false)
308 IPC_END_MESSAGE_MAP()
311 handled
= delegate_
->OnMessageReceived(msg
);
314 #ifdef IPC_MESSAGE_LOG_ENABLED
315 if (logger
->Enabled())
316 logger
->OnPostDispatchMessage(msg
, channel_id_
);
321 void ChildProcessHostImpl::OnChannelConnected(int32 peer_pid
) {
322 if (!peer_process_
.IsValid()) {
323 peer_process_
= base::Process::OpenWithExtraPrivileges(peer_pid
);
324 if (!peer_process_
.IsValid())
325 peer_process_
= delegate_
->GetProcess().Duplicate();
326 DCHECK(peer_process_
.IsValid());
328 opening_channel_
= false;
329 delegate_
->OnChannelConnected(peer_pid
);
330 for (size_t i
= 0; i
< filters_
.size(); ++i
)
331 filters_
[i
]->OnChannelConnected(peer_pid
);
334 void ChildProcessHostImpl::OnChannelError() {
335 opening_channel_
= false;
336 delegate_
->OnChannelError();
338 for (size_t i
= 0; i
< filters_
.size(); ++i
)
339 filters_
[i
]->OnChannelError();
341 // This will delete host_, which will also destroy this!
342 delegate_
->OnChildDisconnected();
345 void ChildProcessHostImpl::OnBadMessageReceived(const IPC::Message
& message
) {
346 delegate_
->OnBadMessageReceived(message
);
349 void ChildProcessHostImpl::OnAllocateSharedMemory(
351 base::SharedMemoryHandle
* handle
) {
352 AllocateSharedMemory(buffer_size
, peer_process_
.Handle(), handle
);
355 void ChildProcessHostImpl::OnShutdownRequest() {
356 if (delegate_
->CanShutdown())
357 Send(new ChildProcessMsg_Shutdown());
360 void ChildProcessHostImpl::OnAllocateGpuMemoryBuffer(
363 gfx::BufferFormat format
,
364 gfx::BufferUsage usage
,
365 gfx::GpuMemoryBufferHandle
* handle
) {
366 // TODO(reveman): Add support for other types of GpuMemoryBuffers.
368 // AllocateForChildProcess() will check if |width| and |height| are valid
369 // and handle failure in a controlled way when not. We just need to make
370 // sure |format| and |usage| are supported here.
371 if (GpuMemoryBufferImplSharedMemory::IsFormatSupported(format
) &&
372 GpuMemoryBufferImplSharedMemory::IsUsageSupported(usage
)) {
373 *handle
= GpuMemoryBufferImplSharedMemory::AllocateForChildProcess(
374 g_next_gpu_memory_buffer_id
.GetNext(), gfx::Size(width
, height
), format
,
375 peer_process_
.Handle());
379 void ChildProcessHostImpl::OnDeletedGpuMemoryBuffer(
380 gfx::GpuMemoryBufferId id
,
382 // Note: Nothing to do here as ownership of shared memory backed
383 // GpuMemoryBuffers is passed with IPC.
386 } // namespace content