1 // Copyright 2014 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 "ppapi/proxy/plugin_main_irt.h"
11 #include "build/build_config.h"
12 // Need to include this before most other files because it defines
13 // IPC_MESSAGE_LOG_ENABLED. We need to use it to define
14 // IPC_MESSAGE_MACROS_LOG_ENABLED so ppapi_messages.h will generate the
15 // ViewMsgLog et al. functions.
17 #include "base/command_line.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/synchronization/waitable_event.h"
22 #include "base/threading/thread.h"
23 #include "components/tracing/child_trace_message_filter.h"
24 #include "ipc/ipc_channel_handle.h"
25 #include "ipc/ipc_logging.h"
26 #include "ipc/ipc_message.h"
27 #include "ppapi/c/ppp.h"
28 #include "ppapi/c/ppp_instance.h"
29 #include "ppapi/proxy/plugin_dispatcher.h"
30 #include "ppapi/proxy/plugin_globals.h"
31 #include "ppapi/proxy/plugin_message_filter.h"
32 #include "ppapi/proxy/plugin_proxy_delegate.h"
33 #include "ppapi/proxy/resource_reply_thread_registrar.h"
34 #include "ppapi/shared_impl/ppb_audio_shared.h"
36 #if defined(__native_client__)
37 #include "base/at_exit.h"
38 #include "native_client/src/public/chrome_main.h"
39 #include "native_client/src/shared/srpc/nacl_srpc.h"
42 #if defined(IPC_MESSAGE_LOG_ENABLED)
43 #include "base/containers/hash_tables.h"
45 LogFunctionMap g_log_function_mapping;
47 #define IPC_MESSAGE_MACROS_LOG_ENABLED
48 #define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \
49 g_log_function_mapping[msg_id] = logger
52 #include "ppapi/proxy/ppapi_messages.h"
54 using ppapi::proxy::PluginDispatcher;
55 using ppapi::proxy::PluginGlobals;
56 using ppapi::proxy::PluginProxyDelegate;
57 using ppapi::proxy::ProxyChannel;
58 using ppapi::proxy::SerializedHandle;
62 #if defined(__native_client__)
63 // In SFI mode, the FDs of IPC channels are NACL_CHROME_DESC_BASE and its
64 // successor, which is set in nacl_listener.cc.
65 int g_nacl_ipc_browser_fd = NACL_CHROME_DESC_BASE;
66 int g_nacl_ipc_renderer_fd = NACL_CHROME_DESC_BASE + 1;
68 // In non-SFI mode, the FDs of IPC channels are different from the hard coded
69 // ones. These values will be set by SetIPCFileDescriptors() below.
70 // At first, both are initialized to invalid FD number (-1).
71 int g_nacl_ipc_browser_fd = -1;
72 int g_nacl_ipc_renderer_fd = -1;
75 // This class manages communication between the plugin and the browser, and
76 // manages the PluginDispatcher instances for communication between the plugin
78 class PpapiDispatcher : public PluginDispatcher::PluginDelegate,
79 public PluginProxyDelegate,
83 explicit PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop);
85 // PluginDispatcher::PluginDelegate implementation.
86 virtual base::MessageLoopProxy* GetIPCMessageLoop() OVERRIDE;
87 virtual base::WaitableEvent* GetShutdownEvent() OVERRIDE;
88 virtual IPC::PlatformFileForTransit ShareHandleWithRemote(
89 base::PlatformFile handle,
90 base::ProcessId peer_pid,
91 bool should_close_source) OVERRIDE;
92 virtual std::set<PP_Instance>* GetGloballySeenInstanceIDSet() OVERRIDE;
93 virtual uint32 Register(PluginDispatcher* plugin_dispatcher) OVERRIDE;
94 virtual void Unregister(uint32 plugin_dispatcher_id) OVERRIDE;
96 // PluginProxyDelegate implementation.
97 virtual IPC::Sender* GetBrowserSender() OVERRIDE;
98 virtual std::string GetUILanguage() OVERRIDE;
99 virtual void PreCacheFont(const void* logfontw) OVERRIDE;
100 virtual void SetActiveURL(const std::string& url) OVERRIDE;
101 virtual PP_Resource CreateBrowserFont(
102 ppapi::proxy::Connection connection,
103 PP_Instance instance,
104 const PP_BrowserFont_Trusted_Description& desc,
105 const ppapi::Preferences& prefs) OVERRIDE;
107 // IPC::Listener implementation.
108 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
109 virtual void OnChannelError() OVERRIDE;
111 // IPC::Sender implementation
112 virtual bool Send(IPC::Message* message) OVERRIDE;
115 void OnMsgInitializeNaClDispatcher(const ppapi::PpapiNaClPluginArgs& args);
116 void OnPluginDispatcherMessageReceived(const IPC::Message& msg);
118 std::set<PP_Instance> instances_;
119 std::map<uint32, PluginDispatcher*> plugin_dispatchers_;
120 uint32 next_plugin_dispatcher_id_;
121 scoped_refptr<base::MessageLoopProxy> message_loop_;
122 base::WaitableEvent shutdown_event_;
123 scoped_ptr<IPC::SyncChannel> channel_;
126 PpapiDispatcher::PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop)
127 : next_plugin_dispatcher_id_(0),
128 message_loop_(io_loop),
129 shutdown_event_(true, false) {
130 DCHECK_NE(g_nacl_ipc_browser_fd, -1)
131 << "g_nacl_ipc_browser_fd must be initialized before the plugin starts";
132 IPC::ChannelHandle channel_handle(
133 "NaCl IPC", base::FileDescriptor(g_nacl_ipc_browser_fd, false));
135 // Delay initializing the SyncChannel until after we add filters. This
136 // ensures that the filters won't miss any messages received by
138 channel_.reset(new IPC::SyncChannel(
139 this, GetIPCMessageLoop(), GetShutdownEvent()));
140 channel_->AddFilter(new ppapi::proxy::PluginMessageFilter(
141 NULL, PluginGlobals::Get()->resource_reply_thread_registrar()));
143 new tracing::ChildTraceMessageFilter(message_loop_.get()));
144 channel_->Init(channel_handle, IPC::Channel::MODE_SERVER, true);
147 base::MessageLoopProxy* PpapiDispatcher::GetIPCMessageLoop() {
148 return message_loop_.get();
151 base::WaitableEvent* PpapiDispatcher::GetShutdownEvent() {
152 return &shutdown_event_;
155 IPC::PlatformFileForTransit PpapiDispatcher::ShareHandleWithRemote(
156 base::PlatformFile handle,
157 base::ProcessId peer_pid,
158 bool should_close_source) {
159 return IPC::InvalidPlatformFileForTransit();
162 std::set<PP_Instance>* PpapiDispatcher::GetGloballySeenInstanceIDSet() {
166 uint32 PpapiDispatcher::Register(PluginDispatcher* plugin_dispatcher) {
167 if (!plugin_dispatcher ||
168 plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) {
174 // Although it is unlikely, make sure that we won't cause any trouble
175 // when the counter overflows.
176 id = next_plugin_dispatcher_id_++;
178 plugin_dispatchers_.find(id) != plugin_dispatchers_.end());
179 plugin_dispatchers_[id] = plugin_dispatcher;
183 void PpapiDispatcher::Unregister(uint32 plugin_dispatcher_id) {
184 plugin_dispatchers_.erase(plugin_dispatcher_id);
187 IPC::Sender* PpapiDispatcher::GetBrowserSender() {
191 std::string PpapiDispatcher::GetUILanguage() {
193 return std::string();
196 void PpapiDispatcher::PreCacheFont(const void* logfontw) {
200 void PpapiDispatcher::SetActiveURL(const std::string& url) {
204 PP_Resource PpapiDispatcher::CreateBrowserFont(
205 ppapi::proxy::Connection connection,
206 PP_Instance instance,
207 const PP_BrowserFont_Trusted_Description& desc,
208 const ppapi::Preferences& prefs) {
213 bool PpapiDispatcher::OnMessageReceived(const IPC::Message& msg) {
214 IPC_BEGIN_MESSAGE_MAP(PpapiDispatcher, msg)
215 IPC_MESSAGE_HANDLER(PpapiMsg_InitializeNaClDispatcher,
216 OnMsgInitializeNaClDispatcher)
217 // All other messages are simply forwarded to a PluginDispatcher.
218 IPC_MESSAGE_UNHANDLED(OnPluginDispatcherMessageReceived(msg))
219 IPC_END_MESSAGE_MAP()
223 void PpapiDispatcher::OnChannelError() {
227 bool PpapiDispatcher::Send(IPC::Message* msg) {
228 return channel_->Send(msg);
231 void PpapiDispatcher::OnMsgInitializeNaClDispatcher(
232 const ppapi::PpapiNaClPluginArgs& args) {
233 static bool command_line_and_logging_initialized = false;
234 if (command_line_and_logging_initialized) {
235 LOG(FATAL) << "InitializeNaClDispatcher must be called once per plugin.";
239 command_line_and_logging_initialized = true;
240 CommandLine::Init(0, NULL);
241 for (size_t i = 0; i < args.switch_names.size(); ++i) {
242 DCHECK(i < args.switch_values.size());
243 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
244 args.switch_names[i], args.switch_values[i]);
246 logging::LoggingSettings settings;
247 settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
248 logging::InitLogging(settings);
250 ppapi::proxy::PluginGlobals::Get()
251 ->set_keepalive_throttle_interval_milliseconds(
252 args.keepalive_throttle_interval_milliseconds);
254 // Tell the process-global GetInterface which interfaces it can return to the
256 ppapi::proxy::InterfaceList::SetProcessGlobalPermissions(
259 int32_t error = ::PPP_InitializeModule(
261 &ppapi::proxy::PluginDispatcher::GetBrowserInterface);
265 PluginDispatcher* dispatcher =
266 new PluginDispatcher(::PPP_GetInterface, args.permissions,
267 args.off_the_record);
268 // The channel handle's true name is not revealed here.
269 DCHECK_NE(g_nacl_ipc_renderer_fd, -1)
270 << "g_nacl_ipc_renderer_fd must be initialized before the plugin starts";
271 IPC::ChannelHandle channel_handle(
272 "nacl", base::FileDescriptor(g_nacl_ipc_renderer_fd, false));
273 if (!dispatcher->InitPluginWithChannel(this, base::kNullProcessId,
274 channel_handle, false)) {
278 // From here, the dispatcher will manage its own lifetime according to the
279 // lifetime of the attached channel.
282 void PpapiDispatcher::OnPluginDispatcherMessageReceived(
283 const IPC::Message& msg) {
284 // The first parameter should be a plugin dispatcher ID.
285 PickleIterator iter(msg);
287 if (!msg.ReadUInt32(&iter, &id)) {
291 std::map<uint32, ppapi::proxy::PluginDispatcher*>::iterator dispatcher =
292 plugin_dispatchers_.find(id);
293 if (dispatcher != plugin_dispatchers_.end())
294 dispatcher->second->OnMessageReceived(msg);
299 void SetIPCFileDescriptors(int ipc_browser_fd, int ipc_renderer_fd) {
300 g_nacl_ipc_browser_fd = ipc_browser_fd;
301 g_nacl_ipc_renderer_fd = ipc_renderer_fd;
304 void PpapiPluginRegisterThreadCreator(
305 const struct PP_ThreadFunctions* thread_functions) {
306 #if defined(__native_client__)
307 // TODO(hidehiko): The thread creation for the PPB_Audio is not yet
308 // implemented on non-SFI mode. Support this. Now, this function invocation
311 // Initialize all classes that need to create threads that call back into
313 ppapi::PPB_Audio_Shared::SetThreadFunctions(thread_functions);
317 int PpapiPluginMain() {
318 // For non-SFI mode, the manager is already instantiated in nacl_helper,
319 // so we do not need to instantiate it here.
320 #if defined(__native_client__)
321 // Though it isn't referenced here, we must instantiate an AtExitManager.
322 base::AtExitManager exit_manager;
324 base::MessageLoop loop;
325 #if defined(IPC_MESSAGE_LOG_ENABLED)
326 IPC::Logging::set_log_function_map(&g_log_function_mapping);
328 ppapi::proxy::PluginGlobals plugin_globals;
329 base::Thread io_thread("Chrome_NaClIOThread");
330 base::Thread::Options options;
331 options.message_loop_type = base::MessageLoop::TYPE_IO;
332 io_thread.StartWithOptions(options);
334 #if defined(__native_client__)
335 // Currently on non-SFI mode, we don't use SRPC server on plugin.
336 // TODO(hidehiko): Make sure this SRPC is actually used on SFI-mode.
338 // Start up the SRPC server on another thread. Otherwise, when it blocks
339 // on an RPC, the PPAPI proxy will hang. Do this before we initialize the
340 // module and start the PPAPI proxy so that the NaCl plugin can continue
342 static struct NaClSrpcHandlerDesc srpc_methods[] = { { NULL, NULL } };
343 if (!NaClSrpcAcceptClientOnThread(srpc_methods)) {
348 PpapiDispatcher ppapi_dispatcher(io_thread.message_loop_proxy());
349 plugin_globals.set_plugin_proxy_delegate(&ppapi_dispatcher);