Roll leveldb from r73 to r75.
[chromium-blink-merge.git] / ppapi / proxy / plugin_main_nacl.cc
blob770ebd209df3925564b32dd2487e4e143dd72eba
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 <map>
6 #include <set>
8 #include "build/build_config.h"
9 // Need to include this before most other files because it defines
10 // IPC_MESSAGE_LOG_ENABLED. We need to use it to define
11 // IPC_MESSAGE_MACROS_LOG_ENABLED so ppapi_messages.h will generate the
12 // ViewMsgLog et al. functions.
14 #include "base/command_line.h"
15 #include "base/message_loop.h"
16 #include "base/synchronization/waitable_event.h"
17 #include "base/threading/thread.h"
18 #include "components/tracing/child_trace_message_filter.h"
19 #include "ipc/ipc_channel_handle.h"
20 #include "ipc/ipc_logging.h"
21 #include "ipc/ipc_message.h"
22 #include "native_client/src/shared/ppapi_proxy/ppruntime.h"
23 #include "native_client/src/shared/srpc/nacl_srpc.h"
24 #include "native_client/src/untrusted/irt/irt_ppapi.h"
25 #include "ppapi/c/ppp.h"
26 #include "ppapi/c/ppp_instance.h"
27 #include "ppapi/proxy/plugin_dispatcher.h"
28 #include "ppapi/proxy/plugin_globals.h"
29 #include "ppapi/proxy/plugin_proxy_delegate.h"
30 #include "ppapi/shared_impl/ppb_audio_shared.h"
32 #if defined(IPC_MESSAGE_LOG_ENABLED)
33 #include "base/containers/hash_tables.h"
35 LogFunctionMap g_log_function_mapping;
37 #define IPC_MESSAGE_MACROS_LOG_ENABLED
38 #define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \
39 g_log_function_mapping[msg_id] = logger
41 #endif
42 #include "ppapi/proxy/ppapi_messages.h"
44 // This must match up with NACL_CHROME_INITIAL_IPC_DESC,
45 // defined in sel_main_chrome.h
46 #define NACL_IPC_FD 6
48 using ppapi::proxy::PluginDispatcher;
49 using ppapi::proxy::PluginGlobals;
50 using ppapi::proxy::PluginProxyDelegate;
51 using ppapi::proxy::ProxyChannel;
52 using ppapi::proxy::SerializedHandle;
54 namespace {
56 // This class manages communication between the plugin and the browser, and
57 // manages the PluginDispatcher instances for communication between the plugin
58 // and the renderer.
59 class PpapiDispatcher : public ProxyChannel,
60 public PluginDispatcher::PluginDelegate,
61 public PluginProxyDelegate {
62 public:
63 explicit PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop);
65 // PluginDispatcher::PluginDelegate implementation.
66 virtual base::MessageLoopProxy* GetIPCMessageLoop() OVERRIDE;
67 virtual base::WaitableEvent* GetShutdownEvent() OVERRIDE;
68 virtual IPC::PlatformFileForTransit ShareHandleWithRemote(
69 base::PlatformFile handle,
70 base::ProcessId peer_pid,
71 bool should_close_source) OVERRIDE;
72 virtual std::set<PP_Instance>* GetGloballySeenInstanceIDSet() OVERRIDE;
73 virtual uint32 Register(PluginDispatcher* plugin_dispatcher) OVERRIDE;
74 virtual void Unregister(uint32 plugin_dispatcher_id) OVERRIDE;
76 // PluginProxyDelegate implementation.
77 virtual IPC::Sender* GetBrowserSender() OVERRIDE;
78 virtual std::string GetUILanguage() OVERRIDE;
79 virtual void PreCacheFont(const void* logfontw) OVERRIDE;
80 virtual void SetActiveURL(const std::string& url) OVERRIDE;
82 // IPC::Listener implementation.
83 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
85 private:
86 void OnMsgCreateNaClChannel(int renderer_id,
87 const ppapi::PpapiNaClChannelArgs& args,
88 SerializedHandle handle);
89 void OnMsgResourceReply(
90 const ppapi::proxy::ResourceMessageReplyParams& reply_params,
91 const IPC::Message& nested_msg);
92 void OnPluginDispatcherMessageReceived(const IPC::Message& msg);
94 std::set<PP_Instance> instances_;
95 std::map<uint32, PluginDispatcher*> plugin_dispatchers_;
96 uint32 next_plugin_dispatcher_id_;
97 scoped_refptr<base::MessageLoopProxy> message_loop_;
98 base::WaitableEvent shutdown_event_;
101 PpapiDispatcher::PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop)
102 : next_plugin_dispatcher_id_(0),
103 message_loop_(io_loop),
104 shutdown_event_(true, false) {
105 IPC::ChannelHandle channel_handle(
106 "NaCl IPC", base::FileDescriptor(NACL_IPC_FD, false));
107 // We don't have/need a PID since handle sharing happens outside of the
108 // NaCl sandbox.
109 InitWithChannel(this, base::kNullProcessId, channel_handle,
110 false); // Channel is server.
111 channel()->AddFilter(new tracing::ChildTraceMessageFilter(message_loop_));
114 base::MessageLoopProxy* PpapiDispatcher::GetIPCMessageLoop() {
115 return message_loop_.get();
118 base::WaitableEvent* PpapiDispatcher::GetShutdownEvent() {
119 return &shutdown_event_;
122 IPC::PlatformFileForTransit PpapiDispatcher::ShareHandleWithRemote(
123 base::PlatformFile handle,
124 base::ProcessId peer_pid,
125 bool should_close_source) {
126 return IPC::InvalidPlatformFileForTransit();
129 std::set<PP_Instance>* PpapiDispatcher::GetGloballySeenInstanceIDSet() {
130 return &instances_;
133 uint32 PpapiDispatcher::Register(PluginDispatcher* plugin_dispatcher) {
134 if (!plugin_dispatcher ||
135 plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) {
136 return 0;
139 uint32 id = 0;
140 do {
141 // Although it is unlikely, make sure that we won't cause any trouble
142 // when the counter overflows.
143 id = next_plugin_dispatcher_id_++;
144 } while (id == 0 ||
145 plugin_dispatchers_.find(id) != plugin_dispatchers_.end());
146 plugin_dispatchers_[id] = plugin_dispatcher;
147 return id;
150 void PpapiDispatcher::Unregister(uint32 plugin_dispatcher_id) {
151 plugin_dispatchers_.erase(plugin_dispatcher_id);
154 IPC::Sender* PpapiDispatcher::GetBrowserSender() {
155 return this;
158 std::string PpapiDispatcher::GetUILanguage() {
159 NOTIMPLEMENTED();
160 return std::string();
163 void PpapiDispatcher::PreCacheFont(const void* logfontw) {
164 NOTIMPLEMENTED();
167 void PpapiDispatcher::SetActiveURL(const std::string& url) {
168 NOTIMPLEMENTED();
171 bool PpapiDispatcher::OnMessageReceived(const IPC::Message& msg) {
172 IPC_BEGIN_MESSAGE_MAP(PpapiDispatcher, msg)
173 IPC_MESSAGE_HANDLER(PpapiMsg_CreateNaClChannel, OnMsgCreateNaClChannel)
174 IPC_MESSAGE_HANDLER(PpapiPluginMsg_ResourceReply, OnMsgResourceReply)
175 // All other messages are simply forwarded to a PluginDispatcher.
176 IPC_MESSAGE_UNHANDLED(OnPluginDispatcherMessageReceived(msg))
177 IPC_END_MESSAGE_MAP()
178 return true;
181 void PpapiDispatcher::OnMsgCreateNaClChannel(
182 int renderer_id,
183 const ppapi::PpapiNaClChannelArgs& args,
184 SerializedHandle handle) {
185 static bool command_line_and_logging_initialized = false;
186 if (!command_line_and_logging_initialized) {
187 CommandLine::Init(0, NULL);
188 for (size_t i = 0; i < args.switch_names.size(); ++i) {
189 DCHECK(i < args.switch_values.size());
190 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
191 args.switch_names[i], args.switch_values[i]);
193 logging::InitLogging(
194 NULL,
195 logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
196 logging::DONT_LOCK_LOG_FILE,
197 logging::DELETE_OLD_LOG_FILE,
198 logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
199 command_line_and_logging_initialized = true;
201 // Tell the process-global GetInterface which interfaces it can return to the
202 // plugin.
203 ppapi::proxy::InterfaceList::SetProcessGlobalPermissions(
204 args.permissions);
206 PluginDispatcher* dispatcher =
207 new PluginDispatcher(::PPP_GetInterface, args.permissions,
208 args.off_the_record);
209 // The channel handle's true name is not revealed here.
210 IPC::ChannelHandle channel_handle("nacl", handle.descriptor());
211 if (!dispatcher->InitPluginWithChannel(this, base::kNullProcessId,
212 channel_handle, false)) {
213 delete dispatcher;
214 return;
216 // From here, the dispatcher will manage its own lifetime according to the
217 // lifetime of the attached channel.
220 void PpapiDispatcher::OnMsgResourceReply(
221 const ppapi::proxy::ResourceMessageReplyParams& reply_params,
222 const IPC::Message& nested_msg) {
223 ppapi::proxy::PluginDispatcher::DispatchResourceReply(reply_params,
224 nested_msg);
227 void PpapiDispatcher::OnPluginDispatcherMessageReceived(
228 const IPC::Message& msg) {
229 // The first parameter should be a plugin dispatcher ID.
230 PickleIterator iter(msg);
231 uint32 id = 0;
232 if (!msg.ReadUInt32(&iter, &id)) {
233 NOTREACHED();
234 return;
236 std::map<uint32, ppapi::proxy::PluginDispatcher*>::iterator dispatcher =
237 plugin_dispatchers_.find(id);
238 if (dispatcher != plugin_dispatchers_.end())
239 dispatcher->second->OnMessageReceived(msg);
242 } // namespace
244 void PpapiPluginRegisterThreadCreator(
245 const struct PP_ThreadFunctions* thread_functions) {
246 // Initialize all classes that need to create threads that call back into
247 // user code.
248 ppapi::PPB_Audio_Shared::SetThreadFunctions(thread_functions);
251 int IrtInit() {
252 static int initialized = 0;
253 if (initialized) {
254 return 0;
256 if (!NaClSrpcModuleInit()) {
257 return 1;
259 initialized = 1;
260 return 0;
263 int PpapiPluginMain() {
264 IrtInit();
266 // Though it isn't referenced here, we must instantiate an AtExitManager.
267 base::AtExitManager exit_manager;
268 base::MessageLoop loop;
269 IPC::Logging::set_log_function_map(&g_log_function_mapping);
270 ppapi::proxy::PluginGlobals plugin_globals;
271 base::Thread io_thread("Chrome_NaClIOThread");
272 base::Thread::Options options;
273 options.message_loop_type = base::MessageLoop::TYPE_IO;
274 io_thread.StartWithOptions(options);
276 // Start up the SRPC server on another thread. Otherwise, when it blocks
277 // on an RPC, the PPAPI proxy will hang. Do this before we initialize the
278 // module and start the PPAPI proxy so that the NaCl plugin can continue
279 // loading the app.
280 static struct NaClSrpcHandlerDesc srpc_methods[] = { { NULL, NULL } };
281 if (!NaClSrpcAcceptClientOnThread(srpc_methods)) {
282 return 1;
285 int32_t error = ::PPP_InitializeModule(
286 0 /* module */,
287 &ppapi::proxy::PluginDispatcher::GetBrowserInterface);
288 // TODO(dmichael): Handle other error conditions, like failure to connect?
289 if (error)
290 return error;
292 PpapiDispatcher ppapi_dispatcher(io_thread.message_loop_proxy());
293 plugin_globals.set_plugin_proxy_delegate(&ppapi_dispatcher);
295 loop.Run();
297 NaClSrpcModuleFini();
299 return 0;