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/lazy_instance.h"
13 #include "base/logging.h"
14 #include "base/metrics/histogram.h"
15 #include "base/numerics/safe_math.h"
16 #include "base/path_service.h"
17 #include "base/process/process_metrics.h"
18 #include "base/rand_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
21 #include "content/common/child_process_messages.h"
22 #include "content/common/gpu/client/gpu_memory_buffer_impl_shared_memory.h"
23 #include "content/public/common/child_process_host_delegate.h"
24 #include "content/public/common/content_paths.h"
25 #include "content/public/common/content_switches.h"
26 #include "ipc/ipc_channel.h"
27 #include "ipc/ipc_logging.h"
28 #include "ipc/message_filter.h"
31 #include "base/linux_util.h"
33 #include "content/common/font_cache_dispatcher_win.h"
34 #include "ipc/attachment_broker_win.h"
38 base::LazyInstance
<IPC::AttachmentBrokerWin
>::Leaky g_attachment_broker
=
39 LAZY_INSTANCE_INITIALIZER
;
40 #endif // defined(OS_WIN)
44 #if defined(OS_MACOSX)
45 // Given |path| identifying a Mac-style child process executable path, adjusts
46 // it to correspond to |feature|. For a child process path such as
47 // ".../Chromium Helper.app/Contents/MacOS/Chromium Helper", the transformed
48 // path for feature "NP" would be
49 // ".../Chromium Helper NP.app/Contents/MacOS/Chromium Helper NP". The new
51 base::FilePath
TransformPathForFeature(const base::FilePath
& path
,
52 const std::string
& feature
) {
53 std::string basename
= path
.BaseName().value();
55 base::FilePath macos_path
= path
.DirName();
56 const char kMacOSName
[] = "MacOS";
57 DCHECK_EQ(kMacOSName
, macos_path
.BaseName().value());
59 base::FilePath contents_path
= macos_path
.DirName();
60 const char kContentsName
[] = "Contents";
61 DCHECK_EQ(kContentsName
, contents_path
.BaseName().value());
63 base::FilePath helper_app_path
= contents_path
.DirName();
64 const char kAppExtension
[] = ".app";
65 std::string basename_app
= basename
;
66 basename_app
.append(kAppExtension
);
67 DCHECK_EQ(basename_app
, helper_app_path
.BaseName().value());
69 base::FilePath root_path
= helper_app_path
.DirName();
71 std::string new_basename
= basename
;
72 new_basename
.append(1, ' ');
73 new_basename
.append(feature
);
74 std::string new_basename_app
= new_basename
;
75 new_basename_app
.append(kAppExtension
);
77 base::FilePath new_path
= root_path
.Append(new_basename_app
)
78 .Append(kContentsName
)
80 .Append(new_basename
);
86 // Global atomic to generate child process unique IDs.
87 base::StaticAtomicSequenceNumber g_unique_id
;
89 // Global atomic to generate gpu memory buffer unique IDs.
90 base::StaticAtomicSequenceNumber g_next_gpu_memory_buffer_id
;
96 int ChildProcessHost::kInvalidUniqueID
= -1;
99 ChildProcessHost
* ChildProcessHost::Create(ChildProcessHostDelegate
* delegate
) {
100 return new ChildProcessHostImpl(delegate
);
104 base::FilePath
ChildProcessHost::GetChildPath(int flags
) {
105 base::FilePath child_path
;
107 child_path
= base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
108 switches::kBrowserSubprocessPath
);
110 #if defined(OS_LINUX)
111 // Use /proc/self/exe rather than our known binary path so updates
112 // can't swap out the binary from underneath us.
113 // When running under Valgrind, forking /proc/self/exe ends up forking the
114 // Valgrind executable, which then crashes. However, it's almost safe to
115 // assume that the updates won't happen while testing with Valgrind tools.
116 if (child_path
.empty() && flags
& CHILD_ALLOW_SELF
&& !RunningOnValgrind())
117 child_path
= base::FilePath(base::kProcSelfExe
);
120 // On most platforms, the child executable is the same as the current
122 if (child_path
.empty())
123 PathService::Get(CHILD_PROCESS_EXE
, &child_path
);
125 #if defined(OS_MACOSX)
126 DCHECK(!(flags
& CHILD_NO_PIE
&& flags
& CHILD_ALLOW_HEAP_EXECUTION
));
128 // If needed, choose an executable with special flags set that inform the
129 // kernel to enable or disable specific optional process-wide features.
130 if (flags
& CHILD_NO_PIE
) {
131 // "NP" is "No PIE". This results in Chromium Helper NP.app or
132 // Google Chrome Helper NP.app.
133 child_path
= TransformPathForFeature(child_path
, "NP");
134 } else if (flags
& CHILD_ALLOW_HEAP_EXECUTION
) {
135 // "EH" is "Executable Heap". A non-executable heap is only available to
136 // 32-bit processes on Mac OS X 10.7. Most code can and should run with a
137 // non-executable heap, but the "EH" feature is provided to allow code
138 // intolerant of a non-executable heap to work properly on 10.7. This
139 // results in Chromium Helper EH.app or Google Chrome Helper EH.app.
140 child_path
= TransformPathForFeature(child_path
, "EH");
148 IPC::AttachmentBroker
* ChildProcessHost::GetAttachmentBroker() {
150 return &g_attachment_broker
.Get();
153 #endif // defined(OS_WIN)
156 ChildProcessHostImpl::ChildProcessHostImpl(ChildProcessHostDelegate
* delegate
)
157 : delegate_(delegate
),
158 opening_channel_(false) {
160 AddFilter(new FontCacheDispatcher());
164 ChildProcessHostImpl::~ChildProcessHostImpl() {
165 for (size_t i
= 0; i
< filters_
.size(); ++i
) {
166 filters_
[i
]->OnChannelClosing();
167 filters_
[i
]->OnFilterRemoved();
171 void ChildProcessHostImpl::AddFilter(IPC::MessageFilter
* filter
) {
172 filters_
.push_back(filter
);
175 filter
->OnFilterAdded(channel_
.get());
178 void ChildProcessHostImpl::ForceShutdown() {
179 Send(new ChildProcessMsg_Shutdown());
182 std::string
ChildProcessHostImpl::CreateChannel() {
183 channel_id_
= IPC::Channel::GenerateVerifiedChannelID(std::string());
185 IPC::Channel::CreateServer(channel_id_
, this, GetAttachmentBroker());
186 if (!channel_
->Connect())
187 return std::string();
189 for (size_t i
= 0; i
< filters_
.size(); ++i
)
190 filters_
[i
]->OnFilterAdded(channel_
.get());
192 // Make sure these messages get sent first.
193 #if defined(IPC_MESSAGE_LOG_ENABLED)
194 bool enabled
= IPC::Logging::GetInstance()->Enabled();
195 Send(new ChildProcessMsg_SetIPCLoggingEnabled(enabled
));
198 opening_channel_
= true;
203 bool ChildProcessHostImpl::IsChannelOpening() {
204 return opening_channel_
;
207 #if defined(OS_POSIX)
208 base::ScopedFD
ChildProcessHostImpl::TakeClientFileDescriptor() {
209 return channel_
->TakeClientFileDescriptor();
213 bool ChildProcessHostImpl::Send(IPC::Message
* message
) {
218 return channel_
->Send(message
);
221 void ChildProcessHostImpl::AllocateSharedMemory(
222 size_t buffer_size
, base::ProcessHandle child_process_handle
,
223 base::SharedMemoryHandle
* shared_memory_handle
) {
224 base::SharedMemory shared_buf
;
225 if (!shared_buf
.CreateAnonymous(buffer_size
)) {
226 *shared_memory_handle
= base::SharedMemory::NULLHandle();
227 NOTREACHED() << "Cannot create shared memory buffer";
230 shared_buf
.GiveToProcess(child_process_handle
, shared_memory_handle
);
233 int ChildProcessHostImpl::GenerateChildProcessUniqueId() {
234 // This function must be threadsafe.
236 // Historically, this function returned ids started with 1, so in several
237 // places in the code a value of 0 (rather than kInvalidUniqueID) was used as
238 // an invalid value. So we retain those semantics.
239 int id
= g_unique_id
.GetNext() + 1;
242 CHECK_NE(kInvalidUniqueID
, id
);
247 bool ChildProcessHostImpl::OnMessageReceived(const IPC::Message
& msg
) {
248 #ifdef IPC_MESSAGE_LOG_ENABLED
249 IPC::Logging
* logger
= IPC::Logging::GetInstance();
250 if (msg
.type() == IPC_LOGGING_ID
) {
251 logger
->OnReceivedLoggingMessage(msg
);
255 if (logger
->Enabled())
256 logger
->OnPreDispatchMessage(msg
);
259 bool handled
= false;
260 for (size_t i
= 0; i
< filters_
.size(); ++i
) {
261 if (filters_
[i
]->OnMessageReceived(msg
)) {
269 IPC_BEGIN_MESSAGE_MAP(ChildProcessHostImpl
, msg
)
270 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest
,
272 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateSharedMemory
,
273 OnAllocateSharedMemory
)
274 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer
,
275 OnAllocateGpuMemoryBuffer
)
276 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer
,
277 OnDeletedGpuMemoryBuffer
)
278 IPC_MESSAGE_UNHANDLED(handled
= false)
279 IPC_END_MESSAGE_MAP()
282 handled
= delegate_
->OnMessageReceived(msg
);
285 #ifdef IPC_MESSAGE_LOG_ENABLED
286 if (logger
->Enabled())
287 logger
->OnPostDispatchMessage(msg
, channel_id_
);
292 void ChildProcessHostImpl::OnChannelConnected(int32 peer_pid
) {
293 if (!peer_process_
.IsValid()) {
294 peer_process_
= base::Process::OpenWithExtraPrivileges(peer_pid
);
295 if (!peer_process_
.IsValid())
296 peer_process_
= delegate_
->GetProcess().Duplicate();
297 DCHECK(peer_process_
.IsValid());
299 opening_channel_
= false;
300 delegate_
->OnChannelConnected(peer_pid
);
301 for (size_t i
= 0; i
< filters_
.size(); ++i
)
302 filters_
[i
]->OnChannelConnected(peer_pid
);
305 void ChildProcessHostImpl::OnChannelError() {
306 opening_channel_
= false;
307 delegate_
->OnChannelError();
309 for (size_t i
= 0; i
< filters_
.size(); ++i
)
310 filters_
[i
]->OnChannelError();
312 // This will delete host_, which will also destroy this!
313 delegate_
->OnChildDisconnected();
316 void ChildProcessHostImpl::OnBadMessageReceived(const IPC::Message
& message
) {
317 delegate_
->OnBadMessageReceived(message
);
320 void ChildProcessHostImpl::OnAllocateSharedMemory(
322 base::SharedMemoryHandle
* handle
) {
323 AllocateSharedMemory(buffer_size
, peer_process_
.Handle(), handle
);
326 void ChildProcessHostImpl::OnShutdownRequest() {
327 if (delegate_
->CanShutdown())
328 Send(new ChildProcessMsg_Shutdown());
331 void ChildProcessHostImpl::OnAllocateGpuMemoryBuffer(
334 gfx::GpuMemoryBuffer::Format format
,
335 gfx::GpuMemoryBuffer::Usage usage
,
336 gfx::GpuMemoryBufferHandle
* handle
) {
337 // TODO(reveman): Add support for other types of GpuMemoryBuffers.
339 // AllocateForChildProcess() will check if |width| and |height| are valid
340 // and handle failure in a controlled way when not. We just need to make
341 // sure |format| and |usage| are supported here.
342 if (GpuMemoryBufferImplSharedMemory::IsFormatSupported(format
) &&
343 GpuMemoryBufferImplSharedMemory::IsUsageSupported(usage
)) {
344 *handle
= GpuMemoryBufferImplSharedMemory::AllocateForChildProcess(
345 g_next_gpu_memory_buffer_id
.GetNext(), gfx::Size(width
, height
), format
,
346 peer_process_
.Handle());
350 void ChildProcessHostImpl::OnDeletedGpuMemoryBuffer(
351 gfx::GpuMemoryBufferId id
,
353 // Note: Nothing to do here as ownership of shared memory backed
354 // GpuMemoryBuffers is passed with IPC.
357 } // namespace content