Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(885)

Side by Side Diff: extensions/renderer/event_bindings.cc

Issue 1227093008: Clear an extension's filtered events when a context is destroyed. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: comments, rebase Created 5 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "extensions/renderer/event_bindings.h" 5 #include "extensions/renderer/event_bindings.h"
6 6
7 #include <map> 7 #include <map>
8 #include <utility>
8 9
9 #include "base/basictypes.h" 10 #include "base/basictypes.h"
10 #include "base/bind.h" 11 #include "base/bind.h"
12 #include "base/containers/scoped_ptr_map.h"
11 #include "base/lazy_instance.h" 13 #include "base/lazy_instance.h"
12 #include "base/memory/scoped_ptr.h" 14 #include "base/memory/scoped_ptr.h"
13 #include "components/crx_file/id_util.h" 15 #include "components/crx_file/id_util.h"
14 #include "content/public/child/v8_value_converter.h" 16 #include "content/public/child/v8_value_converter.h"
15 #include "content/public/renderer/render_frame.h" 17 #include "content/public/renderer/render_frame.h"
16 #include "content/public/renderer/render_thread.h" 18 #include "content/public/renderer/render_thread.h"
17 #include "content/public/renderer/render_view.h" 19 #include "content/public/renderer/render_view.h"
18 #include "extensions/common/event_filter.h" 20 #include "extensions/common/event_filter.h"
19 #include "extensions/common/extension.h" 21 #include "extensions/common/extension.h"
20 #include "extensions/common/extension_messages.h" 22 #include "extensions/common/extension_messages.h"
21 #include "extensions/common/value_counter.h" 23 #include "extensions/common/value_counter.h"
22 #include "extensions/renderer/extension_frame_helper.h" 24 #include "extensions/renderer/extension_frame_helper.h"
23 #include "extensions/renderer/script_context.h" 25 #include "extensions/renderer/script_context.h"
24 #include "url/gurl.h" 26 #include "url/gurl.h"
25 27
26 namespace extensions { 28 namespace extensions {
27 29
28 namespace { 30 namespace {
29 31
30 // A map of event names to the number of contexts listening to that event. 32 // A map of event names to the number of contexts listening to that event.
31 // We notify the browser about event listeners when we transition between 0 33 // We notify the browser about event listeners when we transition between 0
32 // and 1. 34 // and 1.
33 typedef std::map<std::string, int> EventListenerCounts; 35 typedef std::map<std::string, int> EventListenerCounts;
34 36
35 // A map of extension IDs to listener counts for that extension. 37 // A map of extension IDs to listener counts for that extension.
36 base::LazyInstance<std::map<std::string, EventListenerCounts> > 38 base::LazyInstance<std::map<std::string, EventListenerCounts>>
37 g_listener_counts = LAZY_INSTANCE_INITIALIZER; 39 g_listener_counts = LAZY_INSTANCE_INITIALIZER;
38 40
39 // A map of event names to a (filter -> count) map. The map is used to keep 41 // A map of (extension ID, event name) pairs to the filtered listener counts
40 // track of which filters are in effect for which events. 42 // for that pair. The map is used to keep track of which filters are in effect
41 // We notify the browser about filtered event listeners when we transition 43 // for which events. We notify the browser about filtered event listeners when
42 // between 0 and 1. 44 // we transition between 0 and 1.
43 typedef std::map<std::string, linked_ptr<ValueCounter> > 45 using FilteredEventListenerKey = std::pair<std::string, std::string>;
44 FilteredEventListenerCounts; 46 using FilteredEventListenerCounts =
45 47 base::ScopedPtrMap<FilteredEventListenerKey, scoped_ptr<ValueCounter>>;
46 // A map of extension IDs to filtered listener counts for that extension. 48 base::LazyInstance<FilteredEventListenerCounts> g_filtered_listener_counts =
47 base::LazyInstance<std::map<std::string, FilteredEventListenerCounts> > 49 LAZY_INSTANCE_INITIALIZER;
48 g_filtered_listener_counts = LAZY_INSTANCE_INITIALIZER;
49 50
50 base::LazyInstance<EventFilter> g_event_filter = LAZY_INSTANCE_INITIALIZER; 51 base::LazyInstance<EventFilter> g_event_filter = LAZY_INSTANCE_INITIALIZER;
51 52
53 // Gets a unique string key identifier for a ScriptContext.
54 // TODO(kalman): Just use pointer equality...?
52 std::string GetKeyForScriptContext(ScriptContext* script_context) { 55 std::string GetKeyForScriptContext(ScriptContext* script_context) {
53 const std::string& extension_id = script_context->GetExtensionID(); 56 const std::string& extension_id = script_context->GetExtensionID();
54 CHECK(crx_file::id_util::IdIsValid(extension_id) || 57 CHECK(crx_file::id_util::IdIsValid(extension_id) ||
55 script_context->GetURL().is_valid()); 58 script_context->GetURL().is_valid());
56 return crx_file::id_util::IdIsValid(extension_id) 59 return crx_file::id_util::IdIsValid(extension_id)
57 ? extension_id 60 ? extension_id
58 : script_context->GetURL().spec(); 61 : script_context->GetURL().spec();
59 } 62 }
60 63
61 // Increments the number of event-listeners for the given |event_name| and 64 // Increments the number of event-listeners for the given |event_name| and
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
94 v8::Local<v8::Value> service_type_value(object->Get(service_type)); 97 v8::Local<v8::Value> service_type_value(object->Get(service_type));
95 info.SetServiceType(*v8::String::Utf8Value(service_type_value)); 98 info.SetServiceType(*v8::String::Utf8Value(service_type_value));
96 } 99 }
97 return info; 100 return info;
98 } 101 }
99 102
100 // Add a filter to |event_name| in |extension_id|, returning true if it 103 // Add a filter to |event_name| in |extension_id|, returning true if it
101 // was the first filter for that event in that extension. 104 // was the first filter for that event in that extension.
102 bool AddFilter(const std::string& event_name, 105 bool AddFilter(const std::string& event_name,
103 const std::string& extension_id, 106 const std::string& extension_id,
104 base::DictionaryValue* filter) { 107 const base::DictionaryValue& filter) {
105 FilteredEventListenerCounts& counts = 108 FilteredEventListenerKey key(extension_id, event_name);
106 g_filtered_listener_counts.Get()[extension_id]; 109 FilteredEventListenerCounts& all_counts = g_filtered_listener_counts.Get();
107 FilteredEventListenerCounts::iterator it = counts.find(event_name); 110 FilteredEventListenerCounts::const_iterator counts = all_counts.find(key);
108 if (it == counts.end()) 111 if (counts == all_counts.end()) {
109 counts[event_name].reset(new ValueCounter); 112 counts = all_counts.insert(key, make_scoped_ptr(new ValueCounter())).first;
110 113 }
111 int result = counts[event_name]->Add(*filter); 114 return counts->second->Add(filter) == 1;
112 return 1 == result;
113 } 115 }
114 116
115 // Remove a filter from |event_name| in |extension_id|, returning true if it 117 // Remove a filter from |event_name| in |extension_id|, returning true if it
116 // was the last filter for that event in that extension. 118 // was the last filter for that event in that extension.
117 bool RemoveFilter(const std::string& event_name, 119 bool RemoveFilter(const std::string& event_name,
118 const std::string& extension_id, 120 const std::string& extension_id,
119 base::DictionaryValue* filter) { 121 base::DictionaryValue* filter) {
120 FilteredEventListenerCounts& counts = 122 FilteredEventListenerKey key(extension_id, event_name);
121 g_filtered_listener_counts.Get()[extension_id]; 123 FilteredEventListenerCounts& all_counts = g_filtered_listener_counts.Get();
122 FilteredEventListenerCounts::iterator it = counts.find(event_name); 124 FilteredEventListenerCounts::const_iterator counts = all_counts.find(key);
123 if (it == counts.end()) 125 if (counts == all_counts.end())
124 return false; 126 return false;
125 return 0 == it->second->Remove(*filter); 127 if (counts->second->Remove(*filter) == 0) {
128 all_counts.erase(counts);
129 return true;
130 }
131 return false;
126 } 132 }
127 133
128 } // namespace 134 } // namespace
129 135
130 EventBindings::EventBindings(ScriptContext* context) 136 EventBindings::EventBindings(ScriptContext* context)
131 : ObjectBackedNativeHandler(context) { 137 : ObjectBackedNativeHandler(context) {
132 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler, 138 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler,
133 base::Unretained(this))); 139 base::Unretained(this)));
134 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler, 140 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler,
135 base::Unretained(this))); 141 base::Unretained(this)));
136 RouteFunction( 142 RouteFunction(
137 "AttachFilteredEvent", 143 "AttachFilteredEvent",
138 base::Bind(&EventBindings::AttachFilteredEvent, base::Unretained(this))); 144 base::Bind(&EventBindings::AttachFilteredEvent, base::Unretained(this)));
139 RouteFunction( 145 RouteFunction("DetachFilteredEvent",
140 "DetachFilteredEvent", 146 base::Bind(&EventBindings::DetachFilteredEventHandler,
141 base::Bind(&EventBindings::DetachFilteredEvent, base::Unretained(this))); 147 base::Unretained(this)));
142 RouteFunction("MatchAgainstEventFilter", 148 RouteFunction("MatchAgainstEventFilter",
143 base::Bind(&EventBindings::MatchAgainstEventFilter, 149 base::Bind(&EventBindings::MatchAgainstEventFilter,
144 base::Unretained(this))); 150 base::Unretained(this)));
145 151
146 // It's safe to use base::Unretained here because |context| will always 152 // It's safe to use base::Unretained here because |context| will always
147 // outlive us. 153 // outlive us.
148 context->AddInvalidationObserver( 154 context->AddInvalidationObserver(
149 base::Bind(&EventBindings::OnInvalidated, base::Unretained(this))); 155 base::Bind(&EventBindings::OnInvalidated, base::Unretained(this)));
150 } 156 }
151 157
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
223 void EventBindings::AttachFilteredEvent( 229 void EventBindings::AttachFilteredEvent(
224 const v8::FunctionCallbackInfo<v8::Value>& args) { 230 const v8::FunctionCallbackInfo<v8::Value>& args) {
225 CHECK_EQ(2, args.Length()); 231 CHECK_EQ(2, args.Length());
226 CHECK(args[0]->IsString()); 232 CHECK(args[0]->IsString());
227 CHECK(args[1]->IsObject()); 233 CHECK(args[1]->IsObject());
228 234
229 std::string event_name = *v8::String::Utf8Value(args[0]); 235 std::string event_name = *v8::String::Utf8Value(args[0]);
230 if (!context()->HasAccessOrThrowError(event_name)) 236 if (!context()->HasAccessOrThrowError(event_name))
231 return; 237 return;
232 238
233 std::string extension_id = context()->GetExtensionID();
234
235 scoped_ptr<base::DictionaryValue> filter; 239 scoped_ptr<base::DictionaryValue> filter;
236 scoped_ptr<content::V8ValueConverter> converter( 240 {
237 content::V8ValueConverter::create()); 241 scoped_ptr<content::V8ValueConverter> converter(
238 242 content::V8ValueConverter::create());
239 base::DictionaryValue* filter_dict = NULL; 243 scoped_ptr<base::Value> filter_value(converter->FromV8Value(
240 base::Value* filter_value = converter->FromV8Value( 244 v8::Local<v8::Object>::Cast(args[1]), context()->v8_context()));
241 v8::Local<v8::Object>::Cast(args[1]), context()->v8_context()); 245 if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) {
242 if (!filter_value) { 246 args.GetReturnValue().Set(static_cast<int32_t>(-1));
243 args.GetReturnValue().Set(static_cast<int32_t>(-1)); 247 return;
244 return; 248 }
245 } 249 filter.reset(static_cast<base::DictionaryValue*>(filter_value.release()));
246 if (!filter_value->GetAsDictionary(&filter_dict)) {
247 delete filter_value;
248 args.GetReturnValue().Set(static_cast<int32_t>(-1));
249 return;
250 } 250 }
251 251
252 filter.reset(filter_dict); 252 // Hold onto a weak reference to |filter| so that it can be used after passing
253 EventFilter& event_filter = g_event_filter.Get(); 253 // ownership to |event_filter|.
254 int id = 254 base::DictionaryValue* filter_weak = filter.get();
255 event_filter.AddEventMatcher(event_name, ParseEventMatcher(filter.get())); 255 int id = g_event_filter.Get().AddEventMatcher(
256 event_name, ParseEventMatcher(filter.Pass()));
257 attached_matcher_ids_.insert(id);
256 258
257 // Only send IPCs the first time a filter gets added. 259 // Only send IPCs the first time a filter gets added.
258 if (AddFilter(event_name, extension_id, filter.get())) { 260 std::string extension_id = context()->GetExtensionID();
261 if (AddFilter(event_name, extension_id, *filter_weak)) {
259 bool lazy = ExtensionFrameHelper::IsContextForEventPage(context()); 262 bool lazy = ExtensionFrameHelper::IsContextForEventPage(context());
260 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener( 263 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
261 extension_id, event_name, *filter, lazy)); 264 extension_id, event_name, *filter_weak, lazy));
262 } 265 }
263 266
264 args.GetReturnValue().Set(static_cast<int32_t>(id)); 267 args.GetReturnValue().Set(static_cast<int32_t>(id));
265 } 268 }
266 269
267 void EventBindings::DetachFilteredEvent( 270 void EventBindings::DetachFilteredEventHandler(
268 const v8::FunctionCallbackInfo<v8::Value>& args) { 271 const v8::FunctionCallbackInfo<v8::Value>& args) {
269 CHECK_EQ(2, args.Length()); 272 CHECK_EQ(2, args.Length());
270 CHECK(args[0]->IsInt32()); 273 CHECK(args[0]->IsInt32());
271 CHECK(args[1]->IsBoolean()); 274 CHECK(args[1]->IsBoolean());
272 bool is_manual = args[1]->BooleanValue(); 275 DetachFilteredEvent(args[0]->Int32Value(), args[1]->BooleanValue());
276 }
273 277
274 std::string extension_id = context()->GetExtensionID(); 278 void EventBindings::DetachFilteredEvent(int matcher_id, bool is_manual) {
275
276 int matcher_id = args[0]->Int32Value();
277 EventFilter& event_filter = g_event_filter.Get(); 279 EventFilter& event_filter = g_event_filter.Get();
278 EventMatcher* event_matcher = event_filter.GetEventMatcher(matcher_id); 280 EventMatcher* event_matcher = event_filter.GetEventMatcher(matcher_id);
279 281
280 const std::string& event_name = event_filter.GetEventName(matcher_id); 282 const std::string& event_name = event_filter.GetEventName(matcher_id);
281 283
282 // Only send IPCs the last time a filter gets removed. 284 // Only send IPCs the last time a filter gets removed.
285 std::string extension_id = context()->GetExtensionID();
283 if (RemoveFilter(event_name, extension_id, event_matcher->value())) { 286 if (RemoveFilter(event_name, extension_id, event_matcher->value())) {
284 bool remove_lazy = 287 bool remove_lazy =
285 is_manual && ExtensionFrameHelper::IsContextForEventPage(context()); 288 is_manual && ExtensionFrameHelper::IsContextForEventPage(context());
286 content::RenderThread::Get()->Send( 289 content::RenderThread::Get()->Send(
287 new ExtensionHostMsg_RemoveFilteredListener( 290 new ExtensionHostMsg_RemoveFilteredListener(
288 extension_id, event_name, *event_matcher->value(), remove_lazy)); 291 extension_id, event_name, *event_matcher->value(), remove_lazy));
289 } 292 }
290 293
291 event_filter.RemoveEventMatcher(matcher_id); 294 event_filter.RemoveEventMatcher(matcher_id);
295 attached_matcher_ids_.erase(matcher_id);
292 } 296 }
293 297
294 void EventBindings::MatchAgainstEventFilter( 298 void EventBindings::MatchAgainstEventFilter(
295 const v8::FunctionCallbackInfo<v8::Value>& args) { 299 const v8::FunctionCallbackInfo<v8::Value>& args) {
296 v8::Isolate* isolate = args.GetIsolate(); 300 v8::Isolate* isolate = args.GetIsolate();
297 typedef std::set<EventFilter::MatcherID> MatcherIDs; 301 typedef std::set<EventFilter::MatcherID> MatcherIDs;
298 EventFilter& event_filter = g_event_filter.Get(); 302 EventFilter& event_filter = g_event_filter.Get();
299 std::string event_name = *v8::String::Utf8Value(args[0]); 303 std::string event_name = *v8::String::Utf8Value(args[0]);
300 EventFilteringInfo info = 304 EventFilteringInfo info =
301 ParseFromObject(args[1]->ToObject(isolate), isolate); 305 ParseFromObject(args[1]->ToObject(isolate), isolate);
302 // Only match events routed to this context's RenderFrame or ones that don't 306 // Only match events routed to this context's RenderFrame or ones that don't
303 // have a routingId in their filter. 307 // have a routingId in their filter.
304 MatcherIDs matched_event_filters = event_filter.MatchEvent( 308 MatcherIDs matched_event_filters = event_filter.MatchEvent(
305 event_name, info, context()->GetRenderFrame()->GetRoutingID()); 309 event_name, info, context()->GetRenderFrame()->GetRoutingID());
306 v8::Local<v8::Array> array( 310 v8::Local<v8::Array> array(
307 v8::Array::New(isolate, matched_event_filters.size())); 311 v8::Array::New(isolate, matched_event_filters.size()));
308 int i = 0; 312 int i = 0;
309 for (MatcherIDs::iterator it = matched_event_filters.begin(); 313 for (MatcherIDs::iterator it = matched_event_filters.begin();
310 it != matched_event_filters.end(); 314 it != matched_event_filters.end();
311 ++it) { 315 ++it) {
312 array->Set(v8::Integer::New(isolate, i++), v8::Integer::New(isolate, *it)); 316 array->Set(v8::Integer::New(isolate, i++), v8::Integer::New(isolate, *it));
313 } 317 }
314 args.GetReturnValue().Set(array); 318 args.GetReturnValue().Set(array);
315 } 319 }
316 320
317 scoped_ptr<EventMatcher> EventBindings::ParseEventMatcher( 321 scoped_ptr<EventMatcher> EventBindings::ParseEventMatcher(
318 base::DictionaryValue* filter_dict) { 322 scoped_ptr<base::DictionaryValue> filter) {
319 return scoped_ptr<EventMatcher>(new EventMatcher( 323 return make_scoped_ptr(new EventMatcher(
320 scoped_ptr<base::DictionaryValue>(filter_dict->DeepCopy()), 324 filter.Pass(), context()->GetRenderFrame()->GetRoutingID()));
321 context()->GetRenderFrame()->GetRoutingID()));
322 } 325 }
323 326
324 void EventBindings::OnInvalidated() { 327 void EventBindings::OnInvalidated() {
325 // Detach all attached events that weren't attached. Iterate over a copy 328 // Detach all attached events that weren't attached. Iterate over a copy
326 // because it will be mutated. 329 // because it will be mutated.
327 std::set<std::string> attached_event_names_safe = attached_event_names_; 330 std::set<std::string> attached_event_names_safe = attached_event_names_;
328 for (const std::string& event_name : attached_event_names_safe) { 331 for (const std::string& event_name : attached_event_names_safe) {
329 DetachEvent(event_name, false /* is_manual */); 332 DetachEvent(event_name, false /* is_manual */);
330 } 333 }
331 DCHECK(attached_event_names_.empty()) 334 DCHECK(attached_event_names_.empty())
332 << "Events cannot be attached during invalidation"; 335 << "Events cannot be attached during invalidation";
336
337 // Same for filtered events.
338 std::set<int> attached_matcher_ids_safe = attached_matcher_ids_;
339 for (int matcher_id : attached_matcher_ids_safe) {
340 DetachFilteredEvent(matcher_id, false /* is_manual */);
341 }
342 DCHECK(attached_matcher_ids_.empty())
343 << "Filtered events cannot be attached during invalidation";
333 } 344 }
334 345
335 } // namespace extensions 346 } // namespace extensions
OLDNEW
« extensions/renderer/event_bindings.h ('K') | « extensions/renderer/event_bindings.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698