Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / content / common / child_process_host_impl.cc
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.
4
5 #include "content/common/child_process_host_impl.h"
6
7 #include <limits>
8
9 #include "base/atomic_sequence_num.h"
10 #include "base/command_line.h"
11 #include "base/files/file_path.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/numerics/safe_math.h"
15 #include "base/path_service.h"
16 #include "base/process/process_metrics.h"
17 #include "base/rand_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
20 #include "content/common/child_process_messages.h"
21 #include "content/common/gpu/client/gpu_memory_buffer_impl_shared_memory.h"
22 #include "content/public/common/child_process_host_delegate.h"
23 #include "content/public/common/content_paths.h"
24 #include "content/public/common/content_switches.h"
25 #include "ipc/ipc_channel.h"
26 #include "ipc/ipc_logging.h"
27 #include "ipc/message_filter.h"
28
29 #if defined(OS_LINUX)
30 #include "base/linux_util.h"
31 #elif defined(OS_WIN)
32 #include "content/common/font_cache_dispatcher_win.h"
33 #endif  // OS_LINUX
34
35 namespace {
36
37 #if defined(OS_MACOSX)
38 // Given |path| identifying a Mac-style child process executable path, adjusts
39 // it to correspond to |feature|. For a child process path such as
40 // ".../Chromium Helper.app/Contents/MacOS/Chromium Helper", the transformed
41 // path for feature "NP" would be
42 // ".../Chromium Helper NP.app/Contents/MacOS/Chromium Helper NP". The new
43 // path is returned.
44 base::FilePath TransformPathForFeature(const base::FilePath& path,
45                                  const std::string& feature) {
46   std::string basename = path.BaseName().value();
47
48   base::FilePath macos_path = path.DirName();
49   const char kMacOSName[] = "MacOS";
50   DCHECK_EQ(kMacOSName, macos_path.BaseName().value());
51
52   base::FilePath contents_path = macos_path.DirName();
53   const char kContentsName[] = "Contents";
54   DCHECK_EQ(kContentsName, contents_path.BaseName().value());
55
56   base::FilePath helper_app_path = contents_path.DirName();
57   const char kAppExtension[] = ".app";
58   std::string basename_app = basename;
59   basename_app.append(kAppExtension);
60   DCHECK_EQ(basename_app, helper_app_path.BaseName().value());
61
62   base::FilePath root_path = helper_app_path.DirName();
63
64   std::string new_basename = basename;
65   new_basename.append(1, ' ');
66   new_basename.append(feature);
67   std::string new_basename_app = new_basename;
68   new_basename_app.append(kAppExtension);
69
70   base::FilePath new_path = root_path.Append(new_basename_app)
71                                      .Append(kContentsName)
72                                      .Append(kMacOSName)
73                                      .Append(new_basename);
74
75   return new_path;
76 }
77 #endif  // OS_MACOSX
78
79 // Global atomic to generate child process unique IDs.
80 base::StaticAtomicSequenceNumber g_unique_id;
81
82 // Global atomic to generate gpu memory buffer unique IDs.
83 base::StaticAtomicSequenceNumber g_next_gpu_memory_buffer_id;
84
85 }  // namespace
86
87 namespace content {
88
89 int ChildProcessHost::kInvalidUniqueID = -1;
90
91 // static
92 ChildProcessHost* ChildProcessHost::Create(ChildProcessHostDelegate* delegate) {
93   return new ChildProcessHostImpl(delegate);
94 }
95
96 // static
97 base::FilePath ChildProcessHost::GetChildPath(int flags) {
98   base::FilePath child_path;
99
100   child_path = base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
101       switches::kBrowserSubprocessPath);
102
103 #if defined(OS_LINUX)
104   // Use /proc/self/exe rather than our known binary path so updates
105   // can't swap out the binary from underneath us.
106   // When running under Valgrind, forking /proc/self/exe ends up forking the
107   // Valgrind executable, which then crashes. However, it's almost safe to
108   // assume that the updates won't happen while testing with Valgrind tools.
109   if (child_path.empty() && flags & CHILD_ALLOW_SELF && !RunningOnValgrind())
110     child_path = base::FilePath(base::kProcSelfExe);
111 #endif
112
113   // On most platforms, the child executable is the same as the current
114   // executable.
115   if (child_path.empty())
116     PathService::Get(CHILD_PROCESS_EXE, &child_path);
117
118 #if defined(OS_MACOSX)
119   DCHECK(!(flags & CHILD_NO_PIE && flags & CHILD_ALLOW_HEAP_EXECUTION));
120
121   // If needed, choose an executable with special flags set that inform the
122   // kernel to enable or disable specific optional process-wide features.
123   if (flags & CHILD_NO_PIE) {
124     // "NP" is "No PIE". This results in Chromium Helper NP.app or
125     // Google Chrome Helper NP.app.
126     child_path = TransformPathForFeature(child_path, "NP");
127   } else if (flags & CHILD_ALLOW_HEAP_EXECUTION) {
128     // "EH" is "Executable Heap". A non-executable heap is only available to
129     // 32-bit processes on Mac OS X 10.7. Most code can and should run with a
130     // non-executable heap, but the "EH" feature is provided to allow code
131     // intolerant of a non-executable heap to work properly on 10.7. This
132     // results in Chromium Helper EH.app or Google Chrome Helper EH.app.
133     child_path = TransformPathForFeature(child_path, "EH");
134   }
135 #endif
136
137   return child_path;
138 }
139
140 ChildProcessHostImpl::ChildProcessHostImpl(ChildProcessHostDelegate* delegate)
141     : delegate_(delegate),
142       peer_handle_(base::kNullProcessHandle),
143       opening_channel_(false) {
144 #if defined(OS_WIN)
145   AddFilter(new FontCacheDispatcher());
146 #endif
147 }
148
149 ChildProcessHostImpl::~ChildProcessHostImpl() {
150   for (size_t i = 0; i < filters_.size(); ++i) {
151     filters_[i]->OnChannelClosing();
152     filters_[i]->OnFilterRemoved();
153   }
154
155   base::CloseProcessHandle(peer_handle_);
156 }
157
158 void ChildProcessHostImpl::AddFilter(IPC::MessageFilter* filter) {
159   filters_.push_back(filter);
160
161   if (channel_)
162     filter->OnFilterAdded(channel_.get());
163 }
164
165 void ChildProcessHostImpl::ForceShutdown() {
166   Send(new ChildProcessMsg_Shutdown());
167 }
168
169 std::string ChildProcessHostImpl::CreateChannel() {
170   channel_id_ = IPC::Channel::GenerateVerifiedChannelID(std::string());
171   channel_ = IPC::Channel::CreateServer(channel_id_, this);
172   if (!channel_->Connect())
173     return std::string();
174
175   for (size_t i = 0; i < filters_.size(); ++i)
176     filters_[i]->OnFilterAdded(channel_.get());
177
178   // Make sure these messages get sent first.
179 #if defined(IPC_MESSAGE_LOG_ENABLED)
180   bool enabled = IPC::Logging::GetInstance()->Enabled();
181   Send(new ChildProcessMsg_SetIPCLoggingEnabled(enabled));
182 #endif
183
184   opening_channel_ = true;
185
186   return channel_id_;
187 }
188
189 bool ChildProcessHostImpl::IsChannelOpening() {
190   return opening_channel_;
191 }
192
193 #if defined(OS_POSIX)
194 base::ScopedFD ChildProcessHostImpl::TakeClientFileDescriptor() {
195   return channel_->TakeClientFileDescriptor();
196 }
197 #endif
198
199 bool ChildProcessHostImpl::Send(IPC::Message* message) {
200   if (!channel_) {
201     delete message;
202     return false;
203   }
204   return channel_->Send(message);
205 }
206
207 void ChildProcessHostImpl::AllocateSharedMemory(
208       size_t buffer_size, base::ProcessHandle child_process_handle,
209       base::SharedMemoryHandle* shared_memory_handle) {
210   base::SharedMemory shared_buf;
211   if (!shared_buf.CreateAnonymous(buffer_size)) {
212     *shared_memory_handle = base::SharedMemory::NULLHandle();
213     NOTREACHED() << "Cannot create shared memory buffer";
214     return;
215   }
216   shared_buf.GiveToProcess(child_process_handle, shared_memory_handle);
217 }
218
219 int ChildProcessHostImpl::GenerateChildProcessUniqueId() {
220   // This function must be threadsafe.
221   //
222   // Historically, this function returned ids started with 1, so in several
223   // places in the code a value of 0 (rather than kInvalidUniqueID) was used as
224   // an invalid value. So we retain those semantics.
225   int id = g_unique_id.GetNext() + 1;
226
227   CHECK_NE(0, id);
228   CHECK_NE(kInvalidUniqueID, id);
229
230   return id;
231 }
232
233 bool ChildProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
234 #ifdef IPC_MESSAGE_LOG_ENABLED
235   IPC::Logging* logger = IPC::Logging::GetInstance();
236   if (msg.type() == IPC_LOGGING_ID) {
237     logger->OnReceivedLoggingMessage(msg);
238     return true;
239   }
240
241   if (logger->Enabled())
242     logger->OnPreDispatchMessage(msg);
243 #endif
244
245   bool handled = false;
246   for (size_t i = 0; i < filters_.size(); ++i) {
247     if (filters_[i]->OnMessageReceived(msg)) {
248       handled = true;
249       break;
250     }
251   }
252
253   if (!handled) {
254     handled = true;
255     IPC_BEGIN_MESSAGE_MAP(ChildProcessHostImpl, msg)
256       IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
257                           OnShutdownRequest)
258       IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateSharedMemory,
259                           OnAllocateSharedMemory)
260       IPC_MESSAGE_HANDLER_DELAY_REPLY(
261           ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer,
262           OnAllocateGpuMemoryBuffer)
263       IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer,
264                           OnDeletedGpuMemoryBuffer)
265       IPC_MESSAGE_UNHANDLED(handled = false)
266     IPC_END_MESSAGE_MAP()
267
268     if (!handled)
269       handled = delegate_->OnMessageReceived(msg);
270   }
271
272 #ifdef IPC_MESSAGE_LOG_ENABLED
273   if (logger->Enabled())
274     logger->OnPostDispatchMessage(msg, channel_id_);
275 #endif
276   return handled;
277 }
278
279 void ChildProcessHostImpl::OnChannelConnected(int32 peer_pid) {
280   if (!peer_handle_ &&
281       !base::OpenPrivilegedProcessHandle(peer_pid, &peer_handle_)) {
282     peer_handle_ = delegate_->GetHandle();
283     DCHECK(peer_handle_);
284   }
285   opening_channel_ = false;
286   delegate_->OnChannelConnected(peer_pid);
287   for (size_t i = 0; i < filters_.size(); ++i)
288     filters_[i]->OnChannelConnected(peer_pid);
289 }
290
291 void ChildProcessHostImpl::OnChannelError() {
292   opening_channel_ = false;
293   delegate_->OnChannelError();
294
295   for (size_t i = 0; i < filters_.size(); ++i)
296     filters_[i]->OnChannelError();
297
298   // This will delete host_, which will also destroy this!
299   delegate_->OnChildDisconnected();
300 }
301
302 void ChildProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
303   delegate_->OnBadMessageReceived(message);
304 }
305
306 void ChildProcessHostImpl::OnAllocateSharedMemory(
307     uint32 buffer_size,
308     base::SharedMemoryHandle* handle) {
309   AllocateSharedMemory(buffer_size, peer_handle_, handle);
310 }
311
312 void ChildProcessHostImpl::OnShutdownRequest() {
313   if (delegate_->CanShutdown())
314     Send(new ChildProcessMsg_Shutdown());
315 }
316
317 void ChildProcessHostImpl::OnAllocateGpuMemoryBuffer(
318     uint32 width,
319     uint32 height,
320     gfx::GpuMemoryBuffer::Format format,
321     gfx::GpuMemoryBuffer::Usage usage,
322     IPC::Message* reply) {
323   base::CheckedNumeric<int> size = width;
324   size *= height;
325   if (!size.IsValid()) {
326     GpuMemoryBufferAllocated(reply, gfx::GpuMemoryBufferHandle());
327     return;
328   }
329
330   // TODO(reveman): Add support for other types of GpuMemoryBuffers.
331   if (!GpuMemoryBufferImplSharedMemory::IsConfigurationSupported(
332           gfx::Size(width, height), format, usage)) {
333     GpuMemoryBufferAllocated(reply, gfx::GpuMemoryBufferHandle());
334     return;
335   }
336
337   // Note: It is safe to use base::Unretained here as the shared memory
338   // implementation of AllocateForChildProcess() calls this synchronously.
339   GpuMemoryBufferImplSharedMemory::AllocateForChildProcess(
340       g_next_gpu_memory_buffer_id.GetNext(),
341       gfx::Size(width, height),
342       format,
343       peer_handle_,
344       base::Bind(&ChildProcessHostImpl::GpuMemoryBufferAllocated,
345                  base::Unretained(this),
346                  reply));
347 }
348
349 void ChildProcessHostImpl::OnDeletedGpuMemoryBuffer(
350     gfx::GpuMemoryBufferId id,
351     uint32 sync_point) {
352   // Note: Nothing to do here as ownership of shared memory backed
353   // GpuMemoryBuffers is passed with IPC.
354 }
355
356 void ChildProcessHostImpl::GpuMemoryBufferAllocated(
357     IPC::Message* reply,
358     const gfx::GpuMemoryBufferHandle& handle) {
359   ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer::WriteReplyParams(reply,
360                                                                     handle);
361   Send(reply);
362 }
363
364 }  // namespace content