Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / renderer / pepper / message_channel.cc
blob4e373ac2eabfc3d8c0c3de4fc7da8a428f0cb21d
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 "content/renderer/pepper/message_channel.h"
7 #include <cstdlib>
8 #include <string>
10 #include "base/bind.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "content/renderer/pepper/host_array_buffer_var.h"
14 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
15 #include "content/renderer/pepper/pepper_try_catch.h"
16 #include "content/renderer/pepper/plugin_module.h"
17 #include "content/renderer/pepper/plugin_object.h"
18 #include "gin/arguments.h"
19 #include "gin/converter.h"
20 #include "gin/function_template.h"
21 #include "gin/object_template_builder.h"
22 #include "gin/public/gin_embedders.h"
23 #include "ppapi/shared_impl/ppapi_globals.h"
24 #include "ppapi/shared_impl/scoped_pp_var.h"
25 #include "ppapi/shared_impl/var.h"
26 #include "ppapi/shared_impl/var_tracker.h"
27 #include "third_party/WebKit/public/web/WebBindings.h"
28 #include "third_party/WebKit/public/web/WebDocument.h"
29 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
30 #include "third_party/WebKit/public/web/WebElement.h"
31 #include "third_party/WebKit/public/web/WebLocalFrame.h"
32 #include "third_party/WebKit/public/web/WebNode.h"
33 #include "third_party/WebKit/public/web/WebPluginContainer.h"
34 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
35 #include "v8/include/v8.h"
37 using ppapi::ArrayBufferVar;
38 using ppapi::PpapiGlobals;
39 using ppapi::ScopedPPVar;
40 using ppapi::StringVar;
41 using blink::WebBindings;
42 using blink::WebElement;
43 using blink::WebDOMEvent;
44 using blink::WebDOMMessageEvent;
45 using blink::WebPluginContainer;
46 using blink::WebSerializedScriptValue;
48 namespace content {
50 namespace {
52 const char kPostMessage[] = "postMessage";
53 const char kPostMessageAndAwaitResponse[] = "postMessageAndAwaitResponse";
54 const char kV8ToVarConversionError[] =
55 "Failed to convert a PostMessage "
56 "argument from a JavaScript value to a PP_Var. It may have cycles or be of "
57 "an unsupported type.";
58 const char kVarToV8ConversionError[] =
59 "Failed to convert a PostMessage "
60 "argument from a PP_Var to a Javascript value. It may have cycles or be of "
61 "an unsupported type.";
63 } // namespace
65 // MessageChannel --------------------------------------------------------------
66 struct MessageChannel::VarConversionResult {
67 VarConversionResult() : success_(false), conversion_completed_(false) {}
68 void ConversionCompleted(const ScopedPPVar& var,
69 bool success) {
70 conversion_completed_ = true;
71 var_ = var;
72 success_ = success;
74 const ScopedPPVar& var() const { return var_; }
75 bool success() const { return success_; }
76 bool conversion_completed() const { return conversion_completed_; }
78 private:
79 ScopedPPVar var_;
80 bool success_;
81 bool conversion_completed_;
84 // static
85 gin::WrapperInfo MessageChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
87 // static
88 MessageChannel* MessageChannel::Create(PepperPluginInstanceImpl* instance,
89 v8::Persistent<v8::Object>* result) {
90 MessageChannel* message_channel = new MessageChannel(instance);
91 v8::HandleScope handle_scope(instance->GetIsolate());
92 v8::Context::Scope context_scope(instance->GetMainWorldContext());
93 gin::Handle<MessageChannel> handle =
94 gin::CreateHandle(instance->GetIsolate(), message_channel);
95 result->Reset(instance->GetIsolate(),
96 handle.ToV8()->ToObject(instance->GetIsolate()));
97 return message_channel;
100 MessageChannel::~MessageChannel() {
101 UnregisterSyncMessageStatusObserver();
103 passthrough_object_.Reset();
104 if (instance_)
105 instance_->MessageChannelDestroyed();
108 void MessageChannel::InstanceDeleted() {
109 UnregisterSyncMessageStatusObserver();
110 instance_ = NULL;
113 void MessageChannel::PostMessageToJavaScript(PP_Var message_data) {
114 v8::HandleScope scope(v8::Isolate::GetCurrent());
116 // Because V8 is probably not on the stack for Native->JS calls, we need to
117 // enter the appropriate context for the plugin.
118 v8::Local<v8::Context> context = instance_->GetMainWorldContext();
119 if (context.IsEmpty())
120 return;
122 v8::Context::Scope context_scope(context);
124 v8::Handle<v8::Value> v8_val;
125 if (!var_converter_.ToV8Value(message_data, context, &v8_val)) {
126 PpapiGlobals::Get()->LogWithSource(instance_->pp_instance(),
127 PP_LOGLEVEL_ERROR,
128 std::string(),
129 kVarToV8ConversionError);
130 return;
133 WebSerializedScriptValue serialized_val =
134 WebSerializedScriptValue::serialize(v8_val);
136 if (js_message_queue_state_ != SEND_DIRECTLY) {
137 // We can't just PostTask here; the messages would arrive out of
138 // order. Instead, we queue them up until we're ready to post
139 // them.
140 js_message_queue_.push_back(serialized_val);
141 } else {
142 // The proxy sent an asynchronous message, so the plugin is already
143 // unblocked. Therefore, there's no need to PostTask.
144 DCHECK(js_message_queue_.empty());
145 PostMessageToJavaScriptImpl(serialized_val);
149 void MessageChannel::Start() {
150 DCHECK_EQ(WAITING_TO_START, js_message_queue_state_);
151 DCHECK_EQ(WAITING_TO_START, plugin_message_queue_state_);
153 ppapi::proxy::HostDispatcher* dispatcher =
154 ppapi::proxy::HostDispatcher::GetForInstance(instance_->pp_instance());
155 // The dispatcher is NULL for in-process.
156 if (dispatcher) {
157 unregister_observer_callback_ =
158 dispatcher->AddSyncMessageStatusObserver(this);
161 // We can't drain the JS message queue directly since we haven't finished
162 // initializing the PepperWebPluginImpl yet, so the plugin isn't available in
163 // the DOM.
164 DrainJSMessageQueueSoon();
166 plugin_message_queue_state_ = SEND_DIRECTLY;
167 DrainCompletedPluginMessages();
170 void MessageChannel::SetPassthroughObject(v8::Handle<v8::Object> passthrough) {
171 passthrough_object_.Reset(instance_->GetIsolate(), passthrough);
174 void MessageChannel::SetReadOnlyProperty(PP_Var key, PP_Var value) {
175 StringVar* key_string = StringVar::FromPPVar(key);
176 if (key_string) {
177 internal_named_properties_[key_string->value()] = ScopedPPVar(value);
178 } else {
179 NOTREACHED();
183 MessageChannel::MessageChannel(PepperPluginInstanceImpl* instance)
184 : gin::NamedPropertyInterceptor(instance->GetIsolate(), this),
185 instance_(instance),
186 js_message_queue_state_(WAITING_TO_START),
187 blocking_message_depth_(0),
188 plugin_message_queue_state_(WAITING_TO_START),
189 var_converter_(instance->pp_instance(),
190 V8VarConverter::kDisallowObjectVars),
191 template_cache_(instance->GetIsolate()),
192 weak_ptr_factory_(this) {
195 gin::ObjectTemplateBuilder MessageChannel::GetObjectTemplateBuilder(
196 v8::Isolate* isolate) {
197 return Wrappable<MessageChannel>::GetObjectTemplateBuilder(isolate)
198 .AddNamedPropertyInterceptor();
201 void MessageChannel::BeginBlockOnSyncMessage() {
202 js_message_queue_state_ = QUEUE_MESSAGES;
203 ++blocking_message_depth_;
206 void MessageChannel::EndBlockOnSyncMessage() {
207 DCHECK_GT(blocking_message_depth_, 0);
208 --blocking_message_depth_;
209 if (!blocking_message_depth_)
210 DrainJSMessageQueueSoon();
213 v8::Local<v8::Value> MessageChannel::GetNamedProperty(
214 v8::Isolate* isolate,
215 const std::string& identifier) {
216 if (!instance_)
217 return v8::Local<v8::Value>();
219 PepperTryCatchV8 try_catch(instance_, &var_converter_, isolate);
220 if (identifier == kPostMessage) {
221 return GetFunctionTemplate(isolate, identifier,
222 &MessageChannel::PostMessageToNative)
223 ->GetFunction();
224 } else if (identifier == kPostMessageAndAwaitResponse) {
225 return GetFunctionTemplate(isolate, identifier,
226 &MessageChannel::PostBlockingMessageToNative)
227 ->GetFunction();
230 std::map<std::string, ScopedPPVar>::const_iterator it =
231 internal_named_properties_.find(identifier);
232 if (it != internal_named_properties_.end()) {
233 v8::Handle<v8::Value> result = try_catch.ToV8(it->second.get());
234 if (try_catch.ThrowException())
235 return v8::Local<v8::Value>();
236 return result;
239 PluginObject* plugin_object = GetPluginObject(isolate);
240 if (plugin_object)
241 return plugin_object->GetNamedProperty(isolate, identifier);
242 return v8::Local<v8::Value>();
245 bool MessageChannel::SetNamedProperty(v8::Isolate* isolate,
246 const std::string& identifier,
247 v8::Local<v8::Value> value) {
248 if (!instance_)
249 return false;
250 PepperTryCatchV8 try_catch(instance_, &var_converter_, isolate);
251 if (identifier == kPostMessage ||
252 identifier == kPostMessageAndAwaitResponse) {
253 try_catch.ThrowException("Cannot set properties with the name postMessage"
254 "or postMessageAndAwaitResponse");
255 return true;
258 // TODO(raymes): This is only used by the gTalk plugin which is deprecated.
259 // Remove passthrough of SetProperty calls as soon as it is removed.
260 PluginObject* plugin_object = GetPluginObject(isolate);
261 if (plugin_object)
262 return plugin_object->SetNamedProperty(isolate, identifier, value);
264 return false;
267 std::vector<std::string> MessageChannel::EnumerateNamedProperties(
268 v8::Isolate* isolate) {
269 std::vector<std::string> result;
270 PluginObject* plugin_object = GetPluginObject(isolate);
271 if (plugin_object)
272 result = plugin_object->EnumerateNamedProperties(isolate);
273 result.push_back(kPostMessage);
274 result.push_back(kPostMessageAndAwaitResponse);
275 return result;
278 void MessageChannel::PostMessageToNative(gin::Arguments* args) {
279 if (!instance_)
280 return;
281 if (args->Length() != 1) {
282 // TODO(raymes): Consider throwing an exception here. We don't now for
283 // backward compatibility.
284 return;
287 v8::Handle<v8::Value> message_data;
288 if (!args->GetNext(&message_data)) {
289 NOTREACHED();
292 EnqueuePluginMessage(message_data);
293 DrainCompletedPluginMessages();
296 void MessageChannel::PostBlockingMessageToNative(gin::Arguments* args) {
297 if (!instance_)
298 return;
299 PepperTryCatchV8 try_catch(instance_, &var_converter_, args->isolate());
300 if (args->Length() != 1) {
301 try_catch.ThrowException(
302 "postMessageAndAwaitResponse requires one argument");
303 return;
306 v8::Handle<v8::Value> message_data;
307 if (!args->GetNext(&message_data)) {
308 NOTREACHED();
311 if (plugin_message_queue_state_ == WAITING_TO_START) {
312 try_catch.ThrowException(
313 "Attempted to call a synchronous method on a plugin that was not "
314 "yet loaded.");
315 return;
318 // If the queue of messages to the plugin is non-empty, we're still waiting on
319 // pending Var conversions. This means at some point in the past, JavaScript
320 // called postMessage (the async one) and passed us something with a browser-
321 // side host (e.g., FileSystem) and we haven't gotten a response from the
322 // browser yet. We can't currently support sending a sync message if the
323 // plugin does this, because it will break the ordering of the messages
324 // arriving at the plugin.
325 // TODO(dmichael): Fix this.
326 // See https://code.google.com/p/chromium/issues/detail?id=367896#c4
327 if (!plugin_message_queue_.empty()) {
328 try_catch.ThrowException(
329 "Failed to convert parameter synchronously, because a prior "
330 "call to postMessage contained a type which required asynchronous "
331 "transfer which has not completed. Not all types are supported yet by "
332 "postMessageAndAwaitResponse. See crbug.com/367896.");
333 return;
335 ScopedPPVar param = try_catch.FromV8(message_data);
336 if (try_catch.ThrowException())
337 return;
339 ScopedPPVar pp_result;
340 bool was_handled = instance_->HandleBlockingMessage(param, &pp_result);
341 if (!was_handled) {
342 try_catch.ThrowException(
343 "The plugin has not registered a handler for synchronous messages. "
344 "See the documentation for PPB_Messaging::RegisterMessageHandler "
345 "and PPP_MessageHandler.");
346 return;
348 v8::Handle<v8::Value> v8_result = try_catch.ToV8(pp_result.get());
349 if (try_catch.ThrowException())
350 return;
352 args->Return(v8_result);
355 void MessageChannel::PostMessageToJavaScriptImpl(
356 const WebSerializedScriptValue& message_data) {
357 DCHECK(instance_);
359 WebPluginContainer* container = instance_->container();
360 // It's possible that container() is NULL if the plugin has been removed from
361 // the DOM (but the PluginInstance is not destroyed yet).
362 if (!container)
363 return;
365 WebDOMEvent event =
366 container->element().document().createEvent("MessageEvent");
367 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
368 msg_event.initMessageEvent("message", // type
369 false, // canBubble
370 false, // cancelable
371 message_data, // data
372 "", // origin [*]
373 NULL, // source [*]
374 ""); // lastEventId
375 // [*] Note that the |origin| is only specified for cross-document and server-
376 // sent messages, while |source| is only specified for cross-document
377 // messages:
378 // http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
379 // This currently behaves like Web Workers. On Firefox, Chrome, and Safari
380 // at least, postMessage on Workers does not provide the origin or source.
381 // TODO(dmichael): Add origin if we change to a more iframe-like origin
382 // policy (see crbug.com/81537)
383 container->element().dispatchEvent(msg_event);
386 PluginObject* MessageChannel::GetPluginObject(v8::Isolate* isolate) {
387 return PluginObject::FromV8Object(isolate,
388 v8::Local<v8::Object>::New(isolate, passthrough_object_));
391 void MessageChannel::EnqueuePluginMessage(v8::Handle<v8::Value> v8_value) {
392 plugin_message_queue_.push_back(VarConversionResult());
393 // Convert the v8 value in to an appropriate PP_Var like Dictionary,
394 // Array, etc. (We explicitly don't want an "Object" PP_Var, which we don't
395 // support for Messaging.)
396 // TODO(raymes): Possibly change this to use TryCatch to do the conversion and
397 // throw an exception if necessary.
398 V8VarConverter::VarResult conversion_result =
399 var_converter_.FromV8Value(
400 v8_value,
401 v8::Isolate::GetCurrent()->GetCurrentContext(),
402 base::Bind(&MessageChannel::FromV8ValueComplete,
403 weak_ptr_factory_.GetWeakPtr(),
404 &plugin_message_queue_.back()));
405 if (conversion_result.completed_synchronously) {
406 plugin_message_queue_.back().ConversionCompleted(
407 conversion_result.var,
408 conversion_result.success);
412 void MessageChannel::FromV8ValueComplete(VarConversionResult* result_holder,
413 const ScopedPPVar& result,
414 bool success) {
415 if (!instance_)
416 return;
417 result_holder->ConversionCompleted(result, success);
418 DrainCompletedPluginMessages();
421 void MessageChannel::DrainCompletedPluginMessages() {
422 DCHECK(instance_);
423 if (plugin_message_queue_state_ == WAITING_TO_START)
424 return;
426 while (!plugin_message_queue_.empty() &&
427 plugin_message_queue_.front().conversion_completed()) {
428 const VarConversionResult& front = plugin_message_queue_.front();
429 if (front.success()) {
430 instance_->HandleMessage(front.var());
431 } else {
432 PpapiGlobals::Get()->LogWithSource(instance()->pp_instance(),
433 PP_LOGLEVEL_ERROR,
434 std::string(),
435 kV8ToVarConversionError);
437 plugin_message_queue_.pop_front();
441 void MessageChannel::DrainJSMessageQueue() {
442 if (!instance_)
443 return;
444 if (js_message_queue_state_ == SEND_DIRECTLY)
445 return;
447 // Take a reference on the PluginInstance. This is because JavaScript code
448 // may delete the plugin, which would destroy the PluginInstance and its
449 // corresponding MessageChannel.
450 scoped_refptr<PepperPluginInstanceImpl> instance_ref(instance_);
451 while (!js_message_queue_.empty()) {
452 PostMessageToJavaScriptImpl(js_message_queue_.front());
453 js_message_queue_.pop_front();
455 js_message_queue_state_ = SEND_DIRECTLY;
458 void MessageChannel::DrainJSMessageQueueSoon() {
459 base::MessageLoop::current()->PostTask(
460 FROM_HERE,
461 base::Bind(&MessageChannel::DrainJSMessageQueue,
462 weak_ptr_factory_.GetWeakPtr()));
465 void MessageChannel::UnregisterSyncMessageStatusObserver() {
466 if (!unregister_observer_callback_.is_null()) {
467 unregister_observer_callback_.Run();
468 unregister_observer_callback_.Reset();
472 v8::Local<v8::FunctionTemplate> MessageChannel::GetFunctionTemplate(
473 v8::Isolate* isolate,
474 const std::string& name,
475 void (MessageChannel::*memberFuncPtr)(gin::Arguments* args)) {
476 v8::Local<v8::FunctionTemplate> function_template = template_cache_.Get(name);
477 if (!function_template.IsEmpty())
478 return function_template;
479 function_template = gin::CreateFunctionTemplate(
480 isolate, base::Bind(memberFuncPtr, weak_ptr_factory_.GetWeakPtr()));
481 template_cache_.Set(name, function_template);
482 return function_template;
485 } // namespace content