Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / browser / android / java / gin_java_bridge_dispatcher_host.cc
blob07430757a2af20ef0c97a49592e8788cc9d69ea8
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 "content/browser/android/java/gin_java_bridge_dispatcher_host.h"
7 #include "base/android/java_handler_thread.h"
8 #include "base/android/jni_android.h"
9 #include "base/android/scoped_java_ref.h"
10 #include "base/atomic_sequence_num.h"
11 #include "base/lazy_instance.h"
12 #include "base/pickle.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/task_runner_util.h"
16 #include "content/browser/android/java/gin_java_bound_object_delegate.h"
17 #include "content/browser/android/java/jni_helper.h"
18 #include "content/common/android/gin_java_bridge_value.h"
19 #include "content/common/android/hash_set.h"
20 #include "content/common/gin_java_bridge_messages.h"
21 #include "content/public/browser/browser_thread.h"
22 #include "content/public/browser/render_frame_host.h"
23 #include "content/public/browser/render_process_host.h"
24 #include "content/public/browser/web_contents.h"
25 #include "ipc/ipc_message_utils.h"
27 #if !defined(OS_ANDROID)
28 #error "JavaBridge only supports OS_ANDROID"
29 #endif
31 namespace content {
33 namespace {
34 // The JavaBridge needs to use a Java thread so the callback
35 // will happen on a thread with a prepared Looper.
36 class JavaBridgeThread : public base::android::JavaHandlerThread {
37 public:
38 JavaBridgeThread() : base::android::JavaHandlerThread("JavaBridge") {
39 Start();
41 ~JavaBridgeThread() override { Stop(); }
42 static bool CurrentlyOn();
45 base::LazyInstance<JavaBridgeThread> g_background_thread =
46 LAZY_INSTANCE_INITIALIZER;
48 // static
49 bool JavaBridgeThread::CurrentlyOn() {
50 return base::MessageLoop::current() ==
51 g_background_thread.Get().message_loop();
54 // Object IDs are globally unique, so we can figure out the right
55 // GinJavaBridgeDispatcherHost when dispatching messages on the background
56 // thread.
57 base::StaticAtomicSequenceNumber g_next_object_id;
59 } // namespace
61 GinJavaBridgeDispatcherHost::GinJavaBridgeDispatcherHost(
62 WebContents* web_contents,
63 jobject retained_object_set)
64 : WebContentsObserver(web_contents),
65 BrowserMessageFilter(GinJavaBridgeMsgStart),
66 browser_filter_added_(false),
67 retained_object_set_(base::android::AttachCurrentThread(),
68 retained_object_set),
69 allow_object_contents_inspection_(true),
70 current_routing_id_(MSG_ROUTING_NONE) {
71 DCHECK(retained_object_set);
74 GinJavaBridgeDispatcherHost::~GinJavaBridgeDispatcherHost() {
77 // GinJavaBridgeDispatcherHost gets created earlier than RenderProcessHost
78 // is initialized. So we postpone installing the message filter until we know
79 // that the RPH is in a good shape. Currently this means that we are calling
80 // this function from any UI thread function that is about to communicate
81 // with the renderer.
82 // TODO(mnaganov): Redesign, so we only have a single filter for all hosts.
83 void GinJavaBridgeDispatcherHost::AddBrowserFilterIfNeeded() {
84 DCHECK_CURRENTLY_ON(BrowserThread::UI);
85 // Transient objects can only appear after named objects were added. Thus,
86 // we can wait until we have one, to avoid installing unnecessary filters.
87 if (!browser_filter_added_ &&
88 web_contents()->GetRenderProcessHost()->GetChannel() &&
89 !named_objects_.empty()) {
90 web_contents()->GetRenderProcessHost()->AddFilter(this);
91 browser_filter_added_ = true;
95 void GinJavaBridgeDispatcherHost::RenderFrameCreated(
96 RenderFrameHost* render_frame_host) {
97 DCHECK_CURRENTLY_ON(BrowserThread::UI);
98 AddBrowserFilterIfNeeded();
99 for (NamedObjectMap::const_iterator iter = named_objects_.begin();
100 iter != named_objects_.end();
101 ++iter) {
102 render_frame_host->Send(new GinJavaBridgeMsg_AddNamedObject(
103 render_frame_host->GetRoutingID(), iter->first, iter->second));
107 void GinJavaBridgeDispatcherHost::RenderFrameDeleted(
108 RenderFrameHost* render_frame_host) {
109 DCHECK_CURRENTLY_ON(BrowserThread::UI);
110 AddBrowserFilterIfNeeded();
111 // Do not release any objects, as RenderFrames do not actually hold
112 // objects, it is object wrappers' job. See http://crbug.com/486245.
115 GinJavaBoundObject::ObjectID GinJavaBridgeDispatcherHost::AddObject(
116 const base::android::JavaRef<jobject>& object,
117 const base::android::JavaRef<jclass>& safe_annotation_clazz,
118 bool is_named,
119 int32 holder) {
120 // Can be called on any thread. Calls come from the UI thread via
121 // AddNamedObject, and from the background thread, when injected Java
122 // object's method returns a Java object.
123 DCHECK(is_named || holder);
124 JNIEnv* env = base::android::AttachCurrentThread();
125 JavaObjectWeakGlobalRef ref(env, object.obj());
126 scoped_refptr<GinJavaBoundObject> new_object =
127 is_named ? GinJavaBoundObject::CreateNamed(ref, safe_annotation_clazz)
128 : GinJavaBoundObject::CreateTransient(ref, safe_annotation_clazz,
129 holder);
130 // Note that we are abusing the fact that StaticAtomicSequenceNumber
131 // uses Atomic32 as a counter, so it is guaranteed that it will not
132 // overflow our int32 IDs. IDs start from 1.
133 GinJavaBoundObject::ObjectID object_id = g_next_object_id.GetNext() + 1;
135 base::AutoLock locker(objects_lock_);
136 objects_[object_id] = new_object;
138 #if DCHECK_IS_ON()
140 GinJavaBoundObject::ObjectID added_object_id;
141 DCHECK(FindObjectId(object, &added_object_id));
142 DCHECK_EQ(object_id, added_object_id);
144 #endif // DCHECK_IS_ON()
145 base::android::ScopedJavaLocalRef<jobject> retained_object_set =
146 retained_object_set_.get(env);
147 if (!retained_object_set.is_null()) {
148 base::AutoLock locker(objects_lock_);
149 JNI_Java_HashSet_add(env, retained_object_set, object);
151 return object_id;
154 bool GinJavaBridgeDispatcherHost::FindObjectId(
155 const base::android::JavaRef<jobject>& object,
156 GinJavaBoundObject::ObjectID* object_id) {
157 // Can be called on any thread.
158 JNIEnv* env = base::android::AttachCurrentThread();
159 base::AutoLock locker(objects_lock_);
160 for (const auto& pair : objects_) {
161 if (env->IsSameObject(
162 object.obj(),
163 pair.second->GetLocalRef(env).obj())) {
164 *object_id = pair.first;
165 return true;
168 return false;
171 JavaObjectWeakGlobalRef GinJavaBridgeDispatcherHost::GetObjectWeakRef(
172 GinJavaBoundObject::ObjectID object_id) {
173 scoped_refptr<GinJavaBoundObject> object = FindObject(object_id);
174 if (object.get())
175 return object->GetWeakRef();
176 else
177 return JavaObjectWeakGlobalRef();
180 JavaObjectWeakGlobalRef
181 GinJavaBridgeDispatcherHost::RemoveHolderAndAdvanceLocked(
182 int32 holder,
183 ObjectMap::iterator* iter_ptr) {
184 objects_lock_.AssertAcquired();
185 JavaObjectWeakGlobalRef result;
186 scoped_refptr<GinJavaBoundObject> object((*iter_ptr)->second);
187 bool object_erased = false;
188 if (!object->IsNamed()) {
189 object->RemoveHolder(holder);
190 if (!object->HasHolders()) {
191 result = object->GetWeakRef();
192 objects_.erase((*iter_ptr)++);
193 object_erased = true;
196 if (!object_erased) {
197 ++(*iter_ptr);
199 return result;
202 void GinJavaBridgeDispatcherHost::RemoveFromRetainedObjectSetLocked(
203 const JavaObjectWeakGlobalRef& ref) {
204 objects_lock_.AssertAcquired();
205 JNIEnv* env = base::android::AttachCurrentThread();
206 base::android::ScopedJavaLocalRef<jobject> retained_object_set =
207 retained_object_set_.get(env);
208 if (!retained_object_set.is_null()) {
209 JNI_Java_HashSet_remove(env, retained_object_set, ref.get(env));
213 void GinJavaBridgeDispatcherHost::AddNamedObject(
214 const std::string& name,
215 const base::android::JavaRef<jobject>& object,
216 const base::android::JavaRef<jclass>& safe_annotation_clazz) {
217 DCHECK_CURRENTLY_ON(BrowserThread::UI);
218 GinJavaBoundObject::ObjectID object_id;
219 NamedObjectMap::iterator iter = named_objects_.find(name);
220 bool existing_object = FindObjectId(object, &object_id);
221 if (existing_object && iter != named_objects_.end() &&
222 iter->second == object_id) {
223 // Nothing to do.
224 return;
226 if (iter != named_objects_.end()) {
227 RemoveNamedObject(iter->first);
229 if (existing_object) {
230 base::AutoLock locker(objects_lock_);
231 objects_[object_id]->AddName();
232 } else {
233 object_id = AddObject(object, safe_annotation_clazz, true, 0);
235 named_objects_[name] = object_id;
237 AddBrowserFilterIfNeeded();
238 web_contents()->SendToAllFrames(
239 new GinJavaBridgeMsg_AddNamedObject(MSG_ROUTING_NONE, name, object_id));
242 void GinJavaBridgeDispatcherHost::RemoveNamedObject(
243 const std::string& name) {
244 DCHECK_CURRENTLY_ON(BrowserThread::UI);
245 NamedObjectMap::iterator iter = named_objects_.find(name);
246 if (iter == named_objects_.end())
247 return;
249 // |name| may come from |named_objects_|. Make a copy of name so that if
250 // |name| is from |named_objects_| it'll be valid after the remove below.
251 const std::string copied_name(name);
254 base::AutoLock locker(objects_lock_);
255 objects_[iter->second]->RemoveName();
257 named_objects_.erase(iter);
259 // As the object isn't going to be removed from the JavaScript side until the
260 // next page reload, calls to it must still work, thus we should continue to
261 // hold it. All the transient objects and removed named objects will be purged
262 // during the cleansing caused by DocumentAvailableInMainFrame event.
264 web_contents()->SendToAllFrames(
265 new GinJavaBridgeMsg_RemoveNamedObject(MSG_ROUTING_NONE, copied_name));
268 void GinJavaBridgeDispatcherHost::SetAllowObjectContentsInspection(bool allow) {
269 if (!JavaBridgeThread::CurrentlyOn()) {
270 g_background_thread.Get().message_loop()->task_runner()->PostTask(
271 FROM_HERE,
272 base::Bind(
273 &GinJavaBridgeDispatcherHost::SetAllowObjectContentsInspection,
274 this, allow));
275 return;
277 allow_object_contents_inspection_ = allow;
280 void GinJavaBridgeDispatcherHost::DocumentAvailableInMainFrame() {
281 DCHECK_CURRENTLY_ON(BrowserThread::UI);
282 // Called when the window object has been cleared in the main frame.
283 // That means, all sub-frames have also been cleared, so only named
284 // objects survived.
285 AddBrowserFilterIfNeeded();
286 JNIEnv* env = base::android::AttachCurrentThread();
287 base::android::ScopedJavaLocalRef<jobject> retained_object_set =
288 retained_object_set_.get(env);
289 base::AutoLock locker(objects_lock_);
290 if (!retained_object_set.is_null()) {
291 JNI_Java_HashSet_clear(env, retained_object_set);
293 auto iter = objects_.begin();
294 while (iter != objects_.end()) {
295 if (iter->second->IsNamed()) {
296 if (!retained_object_set.is_null()) {
297 JNI_Java_HashSet_add(
298 env, retained_object_set, iter->second->GetLocalRef(env));
300 ++iter;
301 } else {
302 objects_.erase(iter++);
307 base::TaskRunner* GinJavaBridgeDispatcherHost::OverrideTaskRunnerForMessage(
308 const IPC::Message& message) {
309 GinJavaBoundObject::ObjectID object_id = 0;
310 // TODO(mnaganov): It's very sad that we have a BrowserMessageFilter per
311 // WebView instance. We should redesign to have a filter per RPH.
312 // Check, if the object ID in the message is known to this host. If not,
313 // this is a message for some other host. As all our IPC messages from the
314 // renderer start with object ID, we just fetch it directly from the
315 // message, considering sync and async messages separately.
316 switch (message.type()) {
317 case GinJavaBridgeHostMsg_GetMethods::ID:
318 case GinJavaBridgeHostMsg_HasMethod::ID:
319 case GinJavaBridgeHostMsg_InvokeMethod::ID: {
320 DCHECK(message.is_sync());
321 base::PickleIterator message_reader =
322 IPC::SyncMessage::GetDataIterator(&message);
323 if (!IPC::ReadParam(&message, &message_reader, &object_id))
324 return NULL;
325 break;
327 case GinJavaBridgeHostMsg_ObjectWrapperDeleted::ID: {
328 DCHECK(!message.is_sync());
329 base::PickleIterator message_reader(message);
330 if (!IPC::ReadParam(&message, &message_reader, &object_id))
331 return NULL;
332 break;
334 default:
335 NOTREACHED();
336 return NULL;
339 base::AutoLock locker(objects_lock_);
340 if (objects_.find(object_id) != objects_.end()) {
341 return g_background_thread.Get().message_loop()->task_runner().get();
344 return NULL;
347 bool GinJavaBridgeDispatcherHost::OnMessageReceived(
348 const IPC::Message& message) {
349 // We can get here As WebContentsObserver also has OnMessageReceived,
350 // or because we have not provided a task runner in
351 // OverrideTaskRunnerForMessage. In either case, just bail out.
352 if (!JavaBridgeThread::CurrentlyOn())
353 return false;
354 SetCurrentRoutingID(message.routing_id());
355 bool handled = true;
356 IPC_BEGIN_MESSAGE_MAP(GinJavaBridgeDispatcherHost, message)
357 IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_GetMethods, OnGetMethods)
358 IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_HasMethod, OnHasMethod)
359 IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_InvokeMethod, OnInvokeMethod)
360 IPC_MESSAGE_HANDLER(GinJavaBridgeHostMsg_ObjectWrapperDeleted,
361 OnObjectWrapperDeleted)
362 IPC_MESSAGE_UNHANDLED(handled = false)
363 IPC_END_MESSAGE_MAP()
364 SetCurrentRoutingID(MSG_ROUTING_NONE);
365 return handled;
368 void GinJavaBridgeDispatcherHost::OnDestruct() const {
369 if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
370 delete this;
371 } else {
372 BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, this);
376 int GinJavaBridgeDispatcherHost::GetCurrentRoutingID() const {
377 DCHECK(JavaBridgeThread::CurrentlyOn());
378 return current_routing_id_;
381 void GinJavaBridgeDispatcherHost::SetCurrentRoutingID(int32 routing_id) {
382 DCHECK(JavaBridgeThread::CurrentlyOn());
383 current_routing_id_ = routing_id;
386 scoped_refptr<GinJavaBoundObject> GinJavaBridgeDispatcherHost::FindObject(
387 GinJavaBoundObject::ObjectID object_id) {
388 // Can be called on any thread.
389 base::AutoLock locker(objects_lock_);
390 auto iter = objects_.find(object_id);
391 if (iter != objects_.end())
392 return iter->second;
393 return NULL;
396 void GinJavaBridgeDispatcherHost::OnGetMethods(
397 GinJavaBoundObject::ObjectID object_id,
398 std::set<std::string>* returned_method_names) {
399 DCHECK(JavaBridgeThread::CurrentlyOn());
400 if (!allow_object_contents_inspection_)
401 return;
402 scoped_refptr<GinJavaBoundObject> object = FindObject(object_id);
403 if (object.get()) {
404 *returned_method_names = object->GetMethodNames();
405 } else {
406 LOG(ERROR) << "WebView: Unknown object: " << object_id;
410 void GinJavaBridgeDispatcherHost::OnHasMethod(
411 GinJavaBoundObject::ObjectID object_id,
412 const std::string& method_name,
413 bool* result) {
414 DCHECK(JavaBridgeThread::CurrentlyOn());
415 scoped_refptr<GinJavaBoundObject> object = FindObject(object_id);
416 if (object.get()) {
417 *result = object->HasMethod(method_name);
418 } else {
419 LOG(ERROR) << "WebView: Unknown object: " << object_id;
423 void GinJavaBridgeDispatcherHost::OnInvokeMethod(
424 GinJavaBoundObject::ObjectID object_id,
425 const std::string& method_name,
426 const base::ListValue& arguments,
427 base::ListValue* wrapped_result,
428 content::GinJavaBridgeError* error_code) {
429 DCHECK(JavaBridgeThread::CurrentlyOn());
430 DCHECK(GetCurrentRoutingID() != MSG_ROUTING_NONE);
431 scoped_refptr<GinJavaBoundObject> object = FindObject(object_id);
432 if (!object.get()) {
433 LOG(ERROR) << "WebView: Unknown object: " << object_id;
434 wrapped_result->Append(base::Value::CreateNullValue());
435 *error_code = kGinJavaBridgeUnknownObjectId;
436 return;
438 scoped_refptr<GinJavaMethodInvocationHelper> result =
439 new GinJavaMethodInvocationHelper(
440 make_scoped_ptr(new GinJavaBoundObjectDelegate(object)),
441 method_name,
442 arguments);
443 result->Init(this);
444 result->Invoke();
445 *error_code = result->GetInvocationError();
446 if (result->HoldsPrimitiveResult()) {
447 scoped_ptr<base::ListValue> result_copy(
448 result->GetPrimitiveResult().DeepCopy());
449 wrapped_result->Swap(result_copy.get());
450 } else if (!result->GetObjectResult().is_null()) {
451 GinJavaBoundObject::ObjectID returned_object_id;
452 if (FindObjectId(result->GetObjectResult(), &returned_object_id)) {
453 base::AutoLock locker(objects_lock_);
454 objects_[returned_object_id]->AddHolder(GetCurrentRoutingID());
455 } else {
456 returned_object_id = AddObject(result->GetObjectResult(),
457 result->GetSafeAnnotationClass(),
458 false,
459 GetCurrentRoutingID());
461 wrapped_result->Append(
462 GinJavaBridgeValue::CreateObjectIDValue(
463 returned_object_id).release());
464 } else {
465 wrapped_result->Append(base::Value::CreateNullValue());
469 void GinJavaBridgeDispatcherHost::OnObjectWrapperDeleted(
470 GinJavaBoundObject::ObjectID object_id) {
471 DCHECK(JavaBridgeThread::CurrentlyOn());
472 DCHECK(GetCurrentRoutingID() != MSG_ROUTING_NONE);
473 base::AutoLock locker(objects_lock_);
474 auto iter = objects_.find(object_id);
475 if (iter == objects_.end())
476 return;
477 JavaObjectWeakGlobalRef ref =
478 RemoveHolderAndAdvanceLocked(GetCurrentRoutingID(), &iter);
479 if (!ref.is_empty()) {
480 RemoveFromRetainedObjectSetLocked(ref);
484 } // namespace content