- add sources.
[platform/framework/web/crosswalk.git] / src / content / renderer / pepper / plugin_module.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/renderer/pepper/plugin_module.h"
6
7 #include <set>
8
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/message_loop/message_loop_proxy.h"
15 #include "base/time/time.h"
16 #include "build/build_config.h"
17 #include "content/common/view_messages.h"
18 #include "content/public/renderer/content_renderer_client.h"
19 #include "content/renderer/pepper/common.h"
20 #include "content/renderer/pepper/host_dispatcher_wrapper.h"
21 #include "content/renderer/pepper/host_globals.h"
22 #include "content/renderer/pepper/pepper_hung_plugin_filter.h"
23 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
24 #include "content/renderer/pepper/pepper_plugin_registry.h"
25 #include "content/renderer/pepper/ppb_image_data_impl.h"
26 #include "content/renderer/pepper/ppb_proxy_impl.h"
27 #include "content/renderer/pepper/ppb_scrollbar_impl.h"
28 #include "content/renderer/pepper/ppb_uma_private_impl.h"
29 #include "content/renderer/pepper/ppb_var_deprecated_impl.h"
30 #include "content/renderer/pepper/ppb_video_decoder_impl.h"
31 #include "content/renderer/pepper/renderer_ppapi_host_impl.h"
32 #include "content/renderer/render_view_impl.h"
33 #include "ppapi/c/dev/ppb_audio_input_dev.h"
34 #include "ppapi/c/dev/ppb_buffer_dev.h"
35 #include "ppapi/c/dev/ppb_char_set_dev.h"
36 #include "ppapi/c/dev/ppb_crypto_dev.h"
37 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
38 #include "ppapi/c/dev/ppb_device_ref_dev.h"
39 #include "ppapi/c/dev/ppb_file_chooser_dev.h"
40 #include "ppapi/c/dev/ppb_find_dev.h"
41 #include "ppapi/c/dev/ppb_font_dev.h"
42 #include "ppapi/c/dev/ppb_gles_chromium_texture_mapping_dev.h"
43 #include "ppapi/c/dev/ppb_graphics_2d_dev.h"
44 #include "ppapi/c/dev/ppb_memory_dev.h"
45 #include "ppapi/c/dev/ppb_opengles2ext_dev.h"
46 #include "ppapi/c/dev/ppb_printing_dev.h"
47 #include "ppapi/c/dev/ppb_resource_array_dev.h"
48 #include "ppapi/c/dev/ppb_scrollbar_dev.h"
49 #include "ppapi/c/dev/ppb_testing_dev.h"
50 #include "ppapi/c/dev/ppb_text_input_dev.h"
51 #include "ppapi/c/dev/ppb_trace_event_dev.h"
52 #include "ppapi/c/dev/ppb_truetype_font_dev.h"
53 #include "ppapi/c/dev/ppb_url_util_dev.h"
54 #include "ppapi/c/dev/ppb_var_deprecated.h"
55 #include "ppapi/c/dev/ppb_var_resource_dev.h"
56 #include "ppapi/c/dev/ppb_video_capture_dev.h"
57 #include "ppapi/c/dev/ppb_video_decoder_dev.h"
58 #include "ppapi/c/dev/ppb_view_dev.h"
59 #include "ppapi/c/dev/ppb_widget_dev.h"
60 #include "ppapi/c/dev/ppb_zoom_dev.h"
61 #include "ppapi/c/extensions/dev/ppb_ext_alarms_dev.h"
62 #include "ppapi/c/extensions/dev/ppb_ext_socket_dev.h"
63 #include "ppapi/c/pp_module.h"
64 #include "ppapi/c/pp_resource.h"
65 #include "ppapi/c/pp_var.h"
66 #include "ppapi/c/ppb_audio.h"
67 #include "ppapi/c/ppb_audio_config.h"
68 #include "ppapi/c/ppb_console.h"
69 #include "ppapi/c/ppb_core.h"
70 #include "ppapi/c/ppb_file_io.h"
71 #include "ppapi/c/ppb_file_ref.h"
72 #include "ppapi/c/ppb_file_system.h"
73 #include "ppapi/c/ppb_fullscreen.h"
74 #include "ppapi/c/ppb_graphics_2d.h"
75 #include "ppapi/c/ppb_graphics_3d.h"
76 #include "ppapi/c/ppb_host_resolver.h"
77 #include "ppapi/c/ppb_image_data.h"
78 #include "ppapi/c/ppb_instance.h"
79 #include "ppapi/c/ppb_messaging.h"
80 #include "ppapi/c/ppb_mouse_cursor.h"
81 #include "ppapi/c/ppb_mouse_lock.h"
82 #include "ppapi/c/ppb_net_address.h"
83 #include "ppapi/c/ppb_network_list.h"
84 #include "ppapi/c/ppb_network_monitor.h"
85 #include "ppapi/c/ppb_network_proxy.h"
86 #include "ppapi/c/ppb_opengles2.h"
87 #include "ppapi/c/ppb_tcp_socket.h"
88 #include "ppapi/c/ppb_text_input_controller.h"
89 #include "ppapi/c/ppb_udp_socket.h"
90 #include "ppapi/c/ppb_url_loader.h"
91 #include "ppapi/c/ppb_url_request_info.h"
92 #include "ppapi/c/ppb_url_response_info.h"
93 #include "ppapi/c/ppb_var.h"
94 #include "ppapi/c/ppb_var_array.h"
95 #include "ppapi/c/ppb_var_array_buffer.h"
96 #include "ppapi/c/ppb_var_dictionary.h"
97 #include "ppapi/c/ppb_view.h"
98 #include "ppapi/c/ppp.h"
99 #include "ppapi/c/ppp_instance.h"
100 #include "ppapi/c/private/ppb_ext_crx_file_system_private.h"
101 #include "ppapi/c/private/ppb_file_io_private.h"
102 #include "ppapi/c/private/ppb_file_ref_private.h"
103 #include "ppapi/c/private/ppb_flash.h"
104 #include "ppapi/c/private/ppb_flash_clipboard.h"
105 #include "ppapi/c/private/ppb_flash_device_id.h"
106 #include "ppapi/c/private/ppb_flash_drm.h"
107 #include "ppapi/c/private/ppb_flash_file.h"
108 #include "ppapi/c/private/ppb_flash_font_file.h"
109 #include "ppapi/c/private/ppb_flash_fullscreen.h"
110 #include "ppapi/c/private/ppb_flash_menu.h"
111 #include "ppapi/c/private/ppb_flash_message_loop.h"
112 #include "ppapi/c/private/ppb_flash_print.h"
113 #include "ppapi/c/private/ppb_host_resolver_private.h"
114 #include "ppapi/c/private/ppb_instance_private.h"
115 #include "ppapi/c/private/ppb_output_protection_private.h"
116 #include "ppapi/c/private/ppb_pdf.h"
117 #include "ppapi/c/private/ppb_proxy_private.h"
118 #include "ppapi/c/private/ppb_talk_private.h"
119 #include "ppapi/c/private/ppb_tcp_server_socket_private.h"
120 #include "ppapi/c/private/ppb_tcp_socket_private.h"
121 #include "ppapi/c/private/ppb_udp_socket_private.h"
122 #include "ppapi/c/private/ppb_uma_private.h"
123 #include "ppapi/c/private/ppb_video_destination_private.h"
124 #include "ppapi/c/private/ppb_video_source_private.h"
125 #include "ppapi/c/private/ppb_x509_certificate_private.h"
126 #include "ppapi/c/trusted/ppb_broker_trusted.h"
127 #include "ppapi/c/trusted/ppb_browser_font_trusted.h"
128 #include "ppapi/c/trusted/ppb_char_set_trusted.h"
129 #include "ppapi/c/trusted/ppb_file_chooser_trusted.h"
130 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
131 #include "ppapi/shared_impl/callback_tracker.h"
132 #include "ppapi/shared_impl/ppapi_preferences.h"
133 #include "ppapi/shared_impl/ppapi_switches.h"
134 #include "ppapi/shared_impl/ppb_input_event_shared.h"
135 #include "ppapi/shared_impl/ppb_opengles2_shared.h"
136 #include "ppapi/shared_impl/ppb_var_shared.h"
137 #include "ppapi/shared_impl/time_conversion.h"
138 #include "ppapi/thunk/enter.h"
139 #include "ppapi/thunk/ppb_graphics_2d_api.h"
140 #include "ppapi/thunk/thunk.h"
141
142 #if defined(OS_CHROMEOS)
143 #include "ppapi/c/private/ppb_platform_verification_private.h"
144 #endif
145
146 using ppapi::InputEventData;
147 using ppapi::PpapiGlobals;
148 using ppapi::TimeTicksToPPTimeTicks;
149 using ppapi::TimeToPPTime;
150 using ppapi::thunk::EnterResource;
151 using ppapi::thunk::PPB_Graphics2D_API;
152 using ppapi::thunk::PPB_InputEvent_API;
153
154 namespace content {
155
156 namespace {
157
158 // Global tracking info for PPAPI plugins. This is lazily created before the
159 // first plugin is allocated, and leaked on shutdown.
160 //
161 // Note that we don't want a Singleton here since destroying this object will
162 // try to free some stuff that requires WebKit, and Singletons are destroyed
163 // after WebKit.
164 // TODO(raymes): I'm not sure if it is completely necessary to leak the
165 // HostGlobals. Figure out the shutdown sequence and find a way to do this
166 // more elegantly.
167 HostGlobals* host_globals = NULL;
168
169 // Maintains all currently loaded plugin libs for validating PP_Module
170 // identifiers.
171 typedef std::set<PluginModule*> PluginModuleSet;
172
173 PluginModuleSet* GetLivePluginSet() {
174   CR_DEFINE_STATIC_LOCAL(PluginModuleSet, live_plugin_libs, ());
175   return &live_plugin_libs;
176 }
177
178 // PPB_Core --------------------------------------------------------------------
179
180 void AddRefResource(PP_Resource resource) {
181   PpapiGlobals::Get()->GetResourceTracker()->AddRefResource(resource);
182 }
183
184 void ReleaseResource(PP_Resource resource) {
185   PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(resource);
186 }
187
188 PP_Time GetTime() {
189   return TimeToPPTime(base::Time::Now());
190 }
191
192 PP_TimeTicks GetTickTime() {
193   return TimeTicksToPPTimeTicks(base::TimeTicks::Now());
194 }
195
196 void CallOnMainThread(int delay_in_msec,
197                       PP_CompletionCallback callback,
198                       int32_t result) {
199   if (callback.func) {
200     PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostDelayedTask(
201         FROM_HERE,
202         base::Bind(callback.func, callback.user_data, result),
203         base::TimeDelta::FromMilliseconds(delay_in_msec));
204   }
205 }
206
207 PP_Bool IsMainThread() {
208   return BoolToPPBool(PpapiGlobals::Get()->
209       GetMainThreadMessageLoop()->BelongsToCurrentThread());
210 }
211
212 const PPB_Core core_interface = {
213   &AddRefResource,
214   &ReleaseResource,
215   &GetTime,
216   &GetTickTime,
217   &CallOnMainThread,
218   &IsMainThread
219 };
220
221 // PPB_Testing -----------------------------------------------------------------
222
223 PP_Bool ReadImageData(PP_Resource device_context_2d,
224                       PP_Resource image,
225                       const PP_Point* top_left) {
226   EnterResource<PPB_Graphics2D_API> enter(device_context_2d, true);
227   if (enter.failed())
228     return PP_FALSE;
229   return BoolToPPBool(enter.object()->ReadImageData(image, top_left));
230 }
231
232 void RunMessageLoop(PP_Instance instance) {
233   base::MessageLoop::ScopedNestableTaskAllower allow(
234       base::MessageLoop::current());
235   base::MessageLoop::current()->Run();
236 }
237
238 void QuitMessageLoop(PP_Instance instance) {
239   base::MessageLoop::current()->QuitNow();
240 }
241
242 uint32_t GetLiveObjectsForInstance(PP_Instance instance_id) {
243   return HostGlobals::Get()->GetResourceTracker()->GetLiveObjectsForInstance(
244       instance_id);
245 }
246
247 PP_Bool IsOutOfProcess() {
248   return PP_FALSE;
249 }
250
251 void SimulateInputEvent(PP_Instance instance, PP_Resource input_event) {
252   PepperPluginInstanceImpl* plugin_instance =
253       host_globals->GetInstance(instance);
254   if (!plugin_instance)
255     return;
256
257   EnterResource<PPB_InputEvent_API> enter(input_event, false);
258   if (enter.failed())
259     return;
260
261   const InputEventData& input_event_data = enter.object()->GetInputEventData();
262   plugin_instance->SimulateInputEvent(input_event_data);
263 }
264
265 PP_Var GetDocumentURL(PP_Instance instance, PP_URLComponents_Dev* components) {
266   PepperPluginInstanceImpl* plugin_instance =
267       host_globals->GetInstance(instance);
268   if (!plugin_instance)
269     return PP_MakeUndefined();
270   return plugin_instance->GetDocumentURL(instance, components);
271 }
272
273 uint32_t GetLiveVars(PP_Var live_vars[], uint32_t array_size) {
274   std::vector<PP_Var> vars =
275       PpapiGlobals::Get()->GetVarTracker()->GetLiveVars();
276   for (size_t i = 0u;
277        i < std::min(static_cast<size_t>(array_size), vars.size());
278        ++i)
279     live_vars[i] = vars[i];
280   return vars.size();
281 }
282
283 void SetMinimumArrayBufferSizeForShmem(PP_Instance /*instance*/,
284                                        uint32_t /*threshold*/) {
285   // Does nothing. Not needed in-process.
286 }
287
288 const PPB_Testing_Dev testing_interface = {
289   &ReadImageData,
290   &RunMessageLoop,
291   &QuitMessageLoop,
292   &GetLiveObjectsForInstance,
293   &IsOutOfProcess,
294   &SimulateInputEvent,
295   &GetDocumentURL,
296   &GetLiveVars,
297   &SetMinimumArrayBufferSizeForShmem
298 };
299
300 // GetInterface ----------------------------------------------------------------
301
302 const void* InternalGetInterface(const char* name) {
303   // Allow custom interface factories first stab at the GetInterface call.
304   const void* custom_interface =
305       GetContentClient()->renderer()->CreatePPAPIInterface(name);
306   if (custom_interface)
307     return custom_interface;
308
309   // TODO(brettw) put these in a hash map for better performance.
310   #define UNPROXIED_IFACE(api_name, iface_str, iface_struct) \
311       if (strcmp(name, iface_str) == 0) \
312         return ppapi::thunk::Get##iface_struct##_Thunk();
313   #define PROXIED_IFACE(api_name, iface_str, iface_struct) \
314       UNPROXIED_IFACE(api_name, iface_str, iface_struct)
315
316   #include "ppapi/thunk/interfaces_ppb_public_stable.h"
317   #include "ppapi/thunk/interfaces_ppb_public_dev.h"
318   #include "ppapi/thunk/interfaces_ppb_private.h"
319   #include "ppapi/thunk/interfaces_ppb_private_no_permissions.h"
320   #include "ppapi/thunk/interfaces_ppb_private_flash.h"
321
322   #undef UNPROXIED_API
323   #undef PROXIED_IFACE
324
325   #define LEGACY_IFACE(iface_str, function_name) \
326       if (strcmp(name, iface_str) == 0) \
327         return function_name;
328
329   #include "ppapi/thunk/interfaces_legacy.h"
330
331   #undef LEGACY_IFACE
332
333   // Only support the testing interface when the command line switch is
334   // specified. This allows us to prevent people from (ab)using this interface
335   // in production code.
336   if (CommandLine::ForCurrentProcess()->HasSwitch(
337           switches::kEnablePepperTesting)) {
338     if (strcmp(name, PPB_TESTING_DEV_INTERFACE) == 0 ||
339         strcmp(name, PPB_TESTING_DEV_INTERFACE_0_9) == 0) {
340       return &testing_interface;
341     }
342   }
343   return NULL;
344 }
345
346 const void* GetInterface(const char* name) {
347   // All interfaces should be used on the main thread.
348   CHECK(IsMainThread());
349
350   return InternalGetInterface(name);
351 }
352
353 // Gets the PPAPI entry points from the given library and places them into the
354 // given structure. Returns true on success.
355 bool LoadEntryPointsFromLibrary(
356     const base::NativeLibrary& library,
357     PepperPluginInfo::EntryPoints* entry_points) {
358   entry_points->get_interface =
359       reinterpret_cast<PepperPluginInfo::GetInterfaceFunc>(
360           base::GetFunctionPointerFromNativeLibrary(library,
361                                                     "PPP_GetInterface"));
362   if (!entry_points->get_interface) {
363     LOG(WARNING) << "No PPP_GetInterface in plugin library";
364     return false;
365   }
366
367   entry_points->initialize_module =
368       reinterpret_cast<PepperPluginInfo::PPP_InitializeModuleFunc>(
369           base::GetFunctionPointerFromNativeLibrary(library,
370                                                     "PPP_InitializeModule"));
371   if (!entry_points->initialize_module) {
372     LOG(WARNING) << "No PPP_InitializeModule in plugin library";
373     return false;
374   }
375
376   // It's okay for PPP_ShutdownModule to not be defined and shutdown_module to
377   // be NULL.
378   entry_points->shutdown_module =
379       reinterpret_cast<PepperPluginInfo::PPP_ShutdownModuleFunc>(
380           base::GetFunctionPointerFromNativeLibrary(library,
381                                                     "PPP_ShutdownModule"));
382
383   return true;
384 }
385
386 void CreateHostForInProcessModule(RenderViewImpl* render_view,
387                                   PluginModule* module,
388                                   const WebPluginInfo& webplugin_info) {
389   // First time an in-process plugin was used, make a host for it.
390   const PepperPluginInfo* info =
391       PepperPluginRegistry::GetInstance()->GetInfoForPlugin(webplugin_info);
392   DCHECK(!info->is_out_of_process);
393
394   ppapi::PpapiPermissions perms(
395       PepperPluginRegistry::GetInstance()->GetInfoForPlugin(
396           webplugin_info)->permissions);
397   RendererPpapiHostImpl* host_impl =
398       RendererPpapiHostImpl::CreateOnModuleForInProcess(
399           module, perms);
400   render_view->PepperPluginCreated(host_impl);
401 }
402
403 }  // namespace
404
405 // PluginModule ----------------------------------------------------------------
406
407 PluginModule::PluginModule(const std::string& name,
408                            const base::FilePath& path,
409                            const ppapi::PpapiPermissions& perms)
410     : callback_tracker_(new ppapi::CallbackTracker),
411       is_in_destructor_(false),
412       is_crashed_(false),
413       broker_(NULL),
414       library_(NULL),
415       name_(name),
416       path_(path),
417       permissions_(perms),
418       reserve_instance_id_(NULL) {
419   // Ensure the globals object is created.
420   if (!host_globals)
421     host_globals = new HostGlobals;
422
423   memset(&entry_points_, 0, sizeof(entry_points_));
424   pp_module_ = HostGlobals::Get()->AddModule(this);
425   GetLivePluginSet()->insert(this);
426 }
427
428 PluginModule::~PluginModule() {
429   // In the past there have been crashes reentering the plugin module
430   // destructor. Catch if that happens again earlier.
431   CHECK(!is_in_destructor_);
432   is_in_destructor_ = true;
433
434   // When the module is being deleted, there should be no more instances still
435   // holding a reference to us.
436   DCHECK(instances_.empty());
437
438   // Some resources and other stuff are hung off of the embedder state, which
439   // should be torn down before the routing stuff below.
440   renderer_ppapi_host_.reset();
441
442   GetLivePluginSet()->erase(this);
443
444   callback_tracker_->AbortAll();
445
446   if (entry_points_.shutdown_module)
447     entry_points_.shutdown_module();
448
449   if (library_)
450     base::UnloadNativeLibrary(library_);
451
452   // Notifications that we've been deleted should be last.
453   HostGlobals::Get()->ModuleDeleted(pp_module_);
454   if (!is_crashed_) {
455     // When the plugin crashes, we immediately tell the lifetime delegate that
456     // we're gone, so we don't want to tell it again.
457     PepperPluginRegistry::GetInstance()->PluginModuleDead(this);
458   }
459
460   // Don't add stuff here, the two notifications that the module object has
461   // been deleted should be last. This allows, for example,
462   // PPB_Proxy.IsInModuleDestructor to map PP_Module to this class during the
463   // previous parts of the destructor.
464 }
465
466 void PluginModule::SetRendererPpapiHost(
467     scoped_ptr<RendererPpapiHostImpl> host) {
468   renderer_ppapi_host_ = host.Pass();
469 }
470
471 bool PluginModule::InitAsInternalPlugin(
472     const PepperPluginInfo::EntryPoints& entry_points) {
473   if (InitializeModule(entry_points)) {
474     entry_points_ = entry_points;
475     return true;
476   }
477   return false;
478 }
479
480 bool PluginModule::InitAsLibrary(const base::FilePath& path) {
481   base::NativeLibrary library = base::LoadNativeLibrary(path, NULL);
482   if (!library)
483     return false;
484
485   PepperPluginInfo::EntryPoints entry_points;
486
487   if (!LoadEntryPointsFromLibrary(library, &entry_points) ||
488       !InitializeModule(entry_points)) {
489     base::UnloadNativeLibrary(library);
490     return false;
491   }
492   entry_points_ = entry_points;
493   library_ = library;
494   return true;
495 }
496
497 void PluginModule::InitAsProxied(
498     HostDispatcherWrapper* host_dispatcher_wrapper) {
499   DCHECK(!host_dispatcher_wrapper_.get());
500   host_dispatcher_wrapper_.reset(host_dispatcher_wrapper);
501 }
502
503 scoped_refptr<PluginModule>
504     PluginModule::CreateModuleForExternalPluginInstance() {
505   // Create a new module, but don't set the lifetime delegate. This isn't a
506   // plugin in the usual sense, so it isn't tracked by the browser.
507   scoped_refptr<PluginModule> external_plugin_module(
508       new PluginModule(name_,
509                        path_,
510                        permissions_));
511   return external_plugin_module;
512 }
513
514 PP_ExternalPluginResult PluginModule::InitAsProxiedExternalPlugin(
515     PepperPluginInstanceImpl* instance) {
516   DCHECK(host_dispatcher_wrapper_.get());
517   // InitAsProxied (for the trusted/out-of-process case) initializes only the
518   // module, and one or more instances are added later. In this case, the
519   // PluginInstance was already created as in-process, so we missed the proxy
520   // AddInstance step and must do it now.
521   host_dispatcher_wrapper_->AddInstance(instance->pp_instance());
522   // For external plugins, we need to tell the instance to reset itself as
523   // proxied. This will clear cached interface pointers and send DidCreate (etc)
524   // to the plugin side of the proxy.
525   return instance->ResetAsProxied(this);
526 }
527
528 bool PluginModule::IsProxied() const {
529   return !!host_dispatcher_wrapper_;
530 }
531
532 base::ProcessId PluginModule::GetPeerProcessId() {
533   if (host_dispatcher_wrapper_)
534     return host_dispatcher_wrapper_->peer_pid();
535   return base::kNullProcessId;
536 }
537
538 int PluginModule::GetPluginChildId() {
539   if (host_dispatcher_wrapper_)
540     return host_dispatcher_wrapper_->plugin_child_id();
541   return 0;
542 }
543
544 // static
545 const PPB_Core* PluginModule::GetCore() {
546   return &core_interface;
547 }
548
549 // static
550 bool PluginModule::SupportsInterface(const char* name) {
551   return !!InternalGetInterface(name);
552 }
553
554 PepperPluginInstanceImpl* PluginModule::CreateInstance(
555     RenderViewImpl* render_view,
556     WebKit::WebPluginContainer* container,
557     const GURL& plugin_url) {
558   PepperPluginInstanceImpl* instance = PepperPluginInstanceImpl::Create(
559       render_view, this, container, plugin_url);
560   if (!instance) {
561     LOG(WARNING) << "Plugin doesn't support instance interface, failing.";
562     return NULL;
563   }
564   if (host_dispatcher_wrapper_)
565     host_dispatcher_wrapper_->AddInstance(instance->pp_instance());
566   return instance;
567 }
568
569 PepperPluginInstanceImpl* PluginModule::GetSomeInstance() const {
570   // This will generally crash later if there is not actually any instance to
571   // return, so we force a crash now to make bugs easier to track down.
572   CHECK(!instances_.empty());
573   return *instances_.begin();
574 }
575
576 const void* PluginModule::GetPluginInterface(const char* name) const {
577   if (host_dispatcher_wrapper_)
578     return host_dispatcher_wrapper_->GetProxiedInterface(name);
579
580   // In-process plugins.
581   if (!entry_points_.get_interface)
582     return NULL;
583   return entry_points_.get_interface(name);
584 }
585
586 void PluginModule::InstanceCreated(PepperPluginInstanceImpl* instance) {
587   instances_.insert(instance);
588 }
589
590 void PluginModule::InstanceDeleted(PepperPluginInstanceImpl* instance) {
591   if (host_dispatcher_wrapper_)
592     host_dispatcher_wrapper_->RemoveInstance(instance->pp_instance());
593   instances_.erase(instance);
594 }
595
596 scoped_refptr<ppapi::CallbackTracker> PluginModule::GetCallbackTracker() {
597   return callback_tracker_;
598 }
599
600 void PluginModule::PluginCrashed() {
601   DCHECK(!is_crashed_);  // Should only get one notification.
602   is_crashed_ = true;
603
604   // Notify all instances that they crashed.
605   for (PluginInstanceSet::iterator i = instances_.begin();
606        i != instances_.end(); ++i)
607     (*i)->InstanceCrashed();
608
609   PepperPluginRegistry::GetInstance()->PluginModuleDead(this);
610 }
611
612 void PluginModule::SetReserveInstanceIDCallback(
613     PP_Bool (*reserve)(PP_Module, PP_Instance)) {
614   DCHECK(!reserve_instance_id_) << "Only expect one set.";
615   reserve_instance_id_ = reserve;
616 }
617
618 bool PluginModule::ReserveInstanceID(PP_Instance instance) {
619   if (reserve_instance_id_)
620     return PPBoolToBool(reserve_instance_id_(pp_module_, instance));
621   return true;  // Instance ID is usable.
622 }
623
624 void PluginModule::SetBroker(PepperBroker* broker) {
625   DCHECK(!broker_ || !broker);
626   broker_ = broker;
627 }
628
629 PepperBroker* PluginModule::GetBroker() {
630   return broker_;
631 }
632
633 RendererPpapiHostImpl* PluginModule::CreateOutOfProcessModule(
634     RenderViewImpl* render_view,
635     const base::FilePath& path,
636     ppapi::PpapiPermissions permissions,
637     const IPC::ChannelHandle& channel_handle,
638     base::ProcessId peer_pid,
639     int plugin_child_id,
640     bool is_external) {
641   scoped_refptr<PepperHungPluginFilter> hung_filter(new PepperHungPluginFilter(
642       path, render_view->GetRoutingID(), plugin_child_id));
643   scoped_ptr<HostDispatcherWrapper> dispatcher(
644       new HostDispatcherWrapper(this,
645                                 peer_pid,
646                                 plugin_child_id,
647                                 permissions,
648                                 is_external));
649   if (!dispatcher->Init(
650           channel_handle,
651           &GetInterface,
652           ppapi::Preferences(render_view->webkit_preferences()),
653           hung_filter.get()))
654     return NULL;
655
656   RendererPpapiHostImpl* host_impl =
657       RendererPpapiHostImpl::CreateOnModuleForOutOfProcess(
658           this, dispatcher->dispatcher(), permissions);
659   render_view->PepperPluginCreated(host_impl);
660
661   InitAsProxied(dispatcher.release());
662   return host_impl;
663 }
664
665 // static
666 void PluginModule::ResetHostGlobalsForTest() {
667   delete host_globals;
668   host_globals = NULL;
669 }
670
671 bool PluginModule::InitializeModule(
672     const PepperPluginInfo::EntryPoints& entry_points) {
673   DCHECK(!host_dispatcher_wrapper_.get()) << "Don't call for proxied modules.";
674   DCHECK(entry_points.initialize_module != NULL);
675   int retval = entry_points.initialize_module(pp_module(), &GetInterface);
676   if (retval != 0) {
677     LOG(WARNING) << "PPP_InitializeModule returned failure " << retval;
678     return false;
679   }
680   return true;
681 }
682
683 scoped_refptr<PluginModule> PluginModule::Create(
684     RenderViewImpl* render_view,
685     const WebPluginInfo& webplugin_info,
686     bool* pepper_plugin_was_registered) {
687   *pepper_plugin_was_registered = true;
688
689   // See if a module has already been loaded for this plugin.
690   base::FilePath path(webplugin_info.path);
691   scoped_refptr<PluginModule> module =
692       PepperPluginRegistry::GetInstance()->GetLiveModule(path);
693   if (module.get()) {
694     if (!module->renderer_ppapi_host()) {
695       // If the module exists and no embedder state was associated with it,
696       // then the module was one of the ones preloaded and is an in-process
697       // plugin. We need to associate our host state with it.
698       CreateHostForInProcessModule(render_view, module.get(), webplugin_info);
699     }
700     return module;
701   }
702
703   // In-process plugins will have always been created up-front to avoid the
704   // sandbox restrictions. So getting here implies it doesn't exist or should
705   // be out of process.
706   const PepperPluginInfo* info =
707       PepperPluginRegistry::GetInstance()->GetInfoForPlugin(webplugin_info);
708   if (!info) {
709     *pepper_plugin_was_registered = false;
710     return scoped_refptr<PluginModule>();
711   } else if (!info->is_out_of_process) {
712     // In-process plugin not preloaded, it probably couldn't be initialized.
713     return scoped_refptr<PluginModule>();
714   }
715
716   ppapi::PpapiPermissions permissions =
717       ppapi::PpapiPermissions::GetForCommandLine(info->permissions);
718
719   // Out of process: have the browser start the plugin process for us.
720   IPC::ChannelHandle channel_handle;
721   base::ProcessId peer_pid;
722   int plugin_child_id = 0;
723   render_view->Send(new ViewHostMsg_OpenChannelToPepperPlugin(
724       path, &channel_handle, &peer_pid, &plugin_child_id));
725   if (channel_handle.name.empty()) {
726     // Couldn't be initialized.
727     return scoped_refptr<PluginModule>();
728   }
729
730   // AddLiveModule must be called before any early returns since the
731   // module's destructor will remove itself.
732   module = new PluginModule(info->name, path, permissions);
733   PepperPluginRegistry::GetInstance()->AddLiveModule(path, module.get());
734
735   if (!module->CreateOutOfProcessModule(render_view,
736                                         path,
737                                         permissions,
738                                         channel_handle,
739                                         peer_pid,
740                                         plugin_child_id,
741                                         false))  // is_external = false
742     return scoped_refptr<PluginModule>();
743
744   return module;
745 }
746
747 }  // namespace content