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

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: valuecounter 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);
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 // Note: Remove() returns true if it removed the last filter equivalent to
128 // |filter|. If there are more equivalent filters, or if there weren't any in
129 // the first place, it returns false.
130 if (counts->second->Remove(*filter)) {
131 if (counts->second->IsEmpty())
132 all_counts.erase(counts); // Clean up if there are no more filters.
133 return true;
134 }
135 return false;
126 } 136 }
127 137
128 } // namespace 138 } // namespace
129 139
130 EventBindings::EventBindings(ScriptContext* context) 140 EventBindings::EventBindings(ScriptContext* context)
131 : ObjectBackedNativeHandler(context) { 141 : ObjectBackedNativeHandler(context) {
132 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler, 142 RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler,
133 base::Unretained(this))); 143 base::Unretained(this)));
134 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler, 144 RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler,
135 base::Unretained(this))); 145 base::Unretained(this)));
136 RouteFunction( 146 RouteFunction(
137 "AttachFilteredEvent", 147 "AttachFilteredEvent",
138 base::Bind(&EventBindings::AttachFilteredEvent, base::Unretained(this))); 148 base::Bind(&EventBindings::AttachFilteredEvent, base::Unretained(this)));
139 RouteFunction( 149 RouteFunction("DetachFilteredEvent",
140 "DetachFilteredEvent", 150 base::Bind(&EventBindings::DetachFilteredEventHandler,
141 base::Bind(&EventBindings::DetachFilteredEvent, base::Unretained(this))); 151 base::Unretained(this)));
142 RouteFunction("MatchAgainstEventFilter", 152 RouteFunction("MatchAgainstEventFilter",
143 base::Bind(&EventBindings::MatchAgainstEventFilter, 153 base::Bind(&EventBindings::MatchAgainstEventFilter,
144 base::Unretained(this))); 154 base::Unretained(this)));
145 155
146 // It's safe to use base::Unretained here because |context| will always 156 // It's safe to use base::Unretained here because |context| will always
147 // outlive us. 157 // outlive us.
148 context->AddInvalidationObserver( 158 context->AddInvalidationObserver(
149 base::Bind(&EventBindings::OnInvalidated, base::Unretained(this))); 159 base::Bind(&EventBindings::OnInvalidated, base::Unretained(this)));
150 } 160 }
151 161
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
223 void EventBindings::AttachFilteredEvent( 233 void EventBindings::AttachFilteredEvent(
224 const v8::FunctionCallbackInfo<v8::Value>& args) { 234 const v8::FunctionCallbackInfo<v8::Value>& args) {
225 CHECK_EQ(2, args.Length()); 235 CHECK_EQ(2, args.Length());
226 CHECK(args[0]->IsString()); 236 CHECK(args[0]->IsString());
227 CHECK(args[1]->IsObject()); 237 CHECK(args[1]->IsObject());
228 238
229 std::string event_name = *v8::String::Utf8Value(args[0]); 239 std::string event_name = *v8::String::Utf8Value(args[0]);
230 if (!context()->HasAccessOrThrowError(event_name)) 240 if (!context()->HasAccessOrThrowError(event_name))
231 return; 241 return;
232 242
233 std::string extension_id = context()->GetExtensionID();
234
235 scoped_ptr<base::DictionaryValue> filter; 243 scoped_ptr<base::DictionaryValue> filter;
236 scoped_ptr<content::V8ValueConverter> converter( 244 {
237 content::V8ValueConverter::create()); 245 scoped_ptr<content::V8ValueConverter> converter(
238 246 content::V8ValueConverter::create());
239 base::DictionaryValue* filter_dict = NULL; 247 scoped_ptr<base::Value> filter_value(converter->FromV8Value(
240 base::Value* filter_value = converter->FromV8Value( 248 v8::Local<v8::Object>::Cast(args[1]), context()->v8_context()));
241 v8::Local<v8::Object>::Cast(args[1]), context()->v8_context()); 249 if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) {
242 if (!filter_value) { 250 args.GetReturnValue().Set(static_cast<int32_t>(-1));
243 args.GetReturnValue().Set(static_cast<int32_t>(-1)); 251 return;
244 return; 252 }
245 } 253 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 } 254 }
251 255
252 filter.reset(filter_dict); 256 // Hold onto a weak reference to |filter| so that it can be used after passing
253 EventFilter& event_filter = g_event_filter.Get(); 257 // ownership to |event_filter|.
254 int id = 258 base::DictionaryValue* filter_weak = filter.get();
255 event_filter.AddEventMatcher(event_name, ParseEventMatcher(filter.get())); 259 int id = g_event_filter.Get().AddEventMatcher(
260 event_name, ParseEventMatcher(filter.Pass()));
261 attached_matcher_ids_.insert(id);
256 262
257 // Only send IPCs the first time a filter gets added. 263 // Only send IPCs the first time a filter gets added.
258 if (AddFilter(event_name, extension_id, filter.get())) { 264 std::string extension_id = context()->GetExtensionID();
265 if (AddFilter(event_name, extension_id, *filter_weak)) {
259 bool lazy = ExtensionFrameHelper::IsContextForEventPage(context()); 266 bool lazy = ExtensionFrameHelper::IsContextForEventPage(context());
260 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener( 267 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
261 extension_id, event_name, *filter, lazy)); 268 extension_id, event_name, *filter_weak, lazy));
262 } 269 }
263 270
264 args.GetReturnValue().Set(static_cast<int32_t>(id)); 271 args.GetReturnValue().Set(static_cast<int32_t>(id));
265 } 272 }
266 273
267 void EventBindings::DetachFilteredEvent( 274 void EventBindings::DetachFilteredEventHandler(
268 const v8::FunctionCallbackInfo<v8::Value>& args) { 275 const v8::FunctionCallbackInfo<v8::Value>& args) {
269 CHECK_EQ(2, args.Length()); 276 CHECK_EQ(2, args.Length());
270 CHECK(args[0]->IsInt32()); 277 CHECK(args[0]->IsInt32());
271 CHECK(args[1]->IsBoolean()); 278 CHECK(args[1]->IsBoolean());
272 bool is_manual = args[1]->BooleanValue(); 279 DetachFilteredEvent(args[0]->Int32Value(), args[1]->BooleanValue());
280 }
273 281
274 std::string extension_id = context()->GetExtensionID(); 282 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(); 283 EventFilter& event_filter = g_event_filter.Get();
278 EventMatcher* event_matcher = event_filter.GetEventMatcher(matcher_id); 284 EventMatcher* event_matcher = event_filter.GetEventMatcher(matcher_id);
279 285
280 const std::string& event_name = event_filter.GetEventName(matcher_id); 286 const std::string& event_name = event_filter.GetEventName(matcher_id);
281 287
282 // Only send IPCs the last time a filter gets removed. 288 // Only send IPCs the last time a filter gets removed.
289 std::string extension_id = context()->GetExtensionID();
283 if (RemoveFilter(event_name, extension_id, event_matcher->value())) { 290 if (RemoveFilter(event_name, extension_id, event_matcher->value())) {
284 bool remove_lazy = 291 bool remove_lazy =
285 is_manual && ExtensionFrameHelper::IsContextForEventPage(context()); 292 is_manual && ExtensionFrameHelper::IsContextForEventPage(context());
286 content::RenderThread::Get()->Send( 293 content::RenderThread::Get()->Send(
287 new ExtensionHostMsg_RemoveFilteredListener( 294 new ExtensionHostMsg_RemoveFilteredListener(
288 extension_id, event_name, *event_matcher->value(), remove_lazy)); 295 extension_id, event_name, *event_matcher->value(), remove_lazy));
289 } 296 }
290 297
291 event_filter.RemoveEventMatcher(matcher_id); 298 event_filter.RemoveEventMatcher(matcher_id);
299 attached_matcher_ids_.erase(matcher_id);
292 } 300 }
293 301
294 void EventBindings::MatchAgainstEventFilter( 302 void EventBindings::MatchAgainstEventFilter(
295 const v8::FunctionCallbackInfo<v8::Value>& args) { 303 const v8::FunctionCallbackInfo<v8::Value>& args) {
296 v8::Isolate* isolate = args.GetIsolate(); 304 v8::Isolate* isolate = args.GetIsolate();
297 typedef std::set<EventFilter::MatcherID> MatcherIDs; 305 typedef std::set<EventFilter::MatcherID> MatcherIDs;
298 EventFilter& event_filter = g_event_filter.Get(); 306 EventFilter& event_filter = g_event_filter.Get();
299 std::string event_name = *v8::String::Utf8Value(args[0]); 307 std::string event_name = *v8::String::Utf8Value(args[0]);
300 EventFilteringInfo info = 308 EventFilteringInfo info =
301 ParseFromObject(args[1]->ToObject(isolate), isolate); 309 ParseFromObject(args[1]->ToObject(isolate), isolate);
302 // Only match events routed to this context's RenderFrame or ones that don't 310 // Only match events routed to this context's RenderFrame or ones that don't
303 // have a routingId in their filter. 311 // have a routingId in their filter.
304 MatcherIDs matched_event_filters = event_filter.MatchEvent( 312 MatcherIDs matched_event_filters = event_filter.MatchEvent(
305 event_name, info, context()->GetRenderFrame()->GetRoutingID()); 313 event_name, info, context()->GetRenderFrame()->GetRoutingID());
306 v8::Local<v8::Array> array( 314 v8::Local<v8::Array> array(
307 v8::Array::New(isolate, matched_event_filters.size())); 315 v8::Array::New(isolate, matched_event_filters.size()));
308 int i = 0; 316 int i = 0;
309 for (MatcherIDs::iterator it = matched_event_filters.begin(); 317 for (MatcherIDs::iterator it = matched_event_filters.begin();
310 it != matched_event_filters.end(); 318 it != matched_event_filters.end();
311 ++it) { 319 ++it) {
312 array->Set(v8::Integer::New(isolate, i++), v8::Integer::New(isolate, *it)); 320 array->Set(v8::Integer::New(isolate, i++), v8::Integer::New(isolate, *it));
313 } 321 }
314 args.GetReturnValue().Set(array); 322 args.GetReturnValue().Set(array);
315 } 323 }
316 324
317 scoped_ptr<EventMatcher> EventBindings::ParseEventMatcher( 325 scoped_ptr<EventMatcher> EventBindings::ParseEventMatcher(
318 base::DictionaryValue* filter_dict) { 326 scoped_ptr<base::DictionaryValue> filter) {
319 return scoped_ptr<EventMatcher>(new EventMatcher( 327 return make_scoped_ptr(new EventMatcher(
320 scoped_ptr<base::DictionaryValue>(filter_dict->DeepCopy()), 328 filter.Pass(), context()->GetRenderFrame()->GetRoutingID()));
321 context()->GetRenderFrame()->GetRoutingID()));
322 } 329 }
323 330
324 void EventBindings::OnInvalidated() { 331 void EventBindings::OnInvalidated() {
325 // Detach all attached events that weren't attached. Iterate over a copy 332 // Detach all attached events that weren't attached. Iterate over a copy
326 // because it will be mutated. 333 // because it will be mutated.
327 std::set<std::string> attached_event_names_safe = attached_event_names_; 334 std::set<std::string> attached_event_names_safe = attached_event_names_;
328 for (const std::string& event_name : attached_event_names_safe) { 335 for (const std::string& event_name : attached_event_names_safe) {
329 DetachEvent(event_name, false /* is_manual */); 336 DetachEvent(event_name, false /* is_manual */);
330 } 337 }
331 DCHECK(attached_event_names_.empty()) 338 DCHECK(attached_event_names_.empty())
332 << "Events cannot be attached during invalidation"; 339 << "Events cannot be attached during invalidation";
340
341 // Same for filtered events.
342 std::set<int> attached_matcher_ids_safe = attached_matcher_ids_;
343 for (int matcher_id : attached_matcher_ids_safe) {
344 DetachFilteredEvent(matcher_id, false /* is_manual */);
345 }
346 DCHECK(attached_matcher_ids_.empty())
347 << "Filtered events cannot be attached during invalidation";
333 } 348 }
334 349
335 } // namespace extensions 350 } // namespace extensions
OLDNEW
« extensions/common/value_counter.cc ('K') | « extensions/renderer/event_bindings.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698