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