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

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

Issue 878513005: Extensions: suspend extension's scripts when V8 is paused (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: check added Created 5 years, 10 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/script_injection.h" 5 #include "extensions/renderer/script_injection.h"
6 6
7 #include <map> 7 #include <map>
8 8
9 #include "base/lazy_instance.h" 9 #include "base/lazy_instance.h"
10 #include "base/metrics/histogram.h" 10 #include "base/metrics/histogram.h"
11 #include "base/timer/elapsed_timer.h" 11 #include "base/timer/elapsed_timer.h"
12 #include "base/values.h" 12 #include "base/values.h"
13 #include "content/public/renderer/render_view.h" 13 #include "content/public/renderer/render_view.h"
14 #include "content/public/renderer/v8_value_converter.h" 14 #include "content/public/renderer/v8_value_converter.h"
15 #include "extensions/common/extension.h" 15 #include "extensions/common/extension.h"
16 #include "extensions/common/extension_messages.h" 16 #include "extensions/common/extension_messages.h"
17 #include "extensions/common/feature_switch.h" 17 #include "extensions/common/feature_switch.h"
18 #include "extensions/common/manifest_handlers/csp_info.h" 18 #include "extensions/common/manifest_handlers/csp_info.h"
19 #include "extensions/renderer/dom_activity_logger.h" 19 #include "extensions/renderer/dom_activity_logger.h"
20 #include "extensions/renderer/extension_groups.h" 20 #include "extensions/renderer/extension_groups.h"
21 #include "extensions/renderer/extensions_renderer_client.h" 21 #include "extensions/renderer/extensions_renderer_client.h"
22 #include "extensions/renderer/script_injection_callback.h"
23 #include "extensions/renderer/script_injection_manager.h"
22 #include "third_party/WebKit/public/platform/WebString.h" 24 #include "third_party/WebKit/public/platform/WebString.h"
23 #include "third_party/WebKit/public/web/WebDocument.h" 25 #include "third_party/WebKit/public/web/WebDocument.h"
24 #include "third_party/WebKit/public/web/WebLocalFrame.h" 26 #include "third_party/WebKit/public/web/WebLocalFrame.h"
25 #include "third_party/WebKit/public/web/WebScopedUserGesture.h" 27 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
26 #include "third_party/WebKit/public/web/WebScriptSource.h" 28 #include "third_party/WebKit/public/web/WebScriptSource.h"
27 #include "third_party/WebKit/public/web/WebSecurityOrigin.h" 29 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
28 #include "url/gurl.h" 30 #include "url/gurl.h"
29 31
30 namespace extensions { 32 namespace extensions {
31 33
(...skipping 85 matching lines...) Expand 10 before | Expand all | Expand 10 after
117 blink::WebLocalFrame* web_frame, 119 blink::WebLocalFrame* web_frame,
118 const std::string& extension_id, 120 const std::string& extension_id,
119 UserScript::RunLocation run_location, 121 UserScript::RunLocation run_location,
120 int tab_id) 122 int tab_id)
121 : injector_(injector.Pass()), 123 : injector_(injector.Pass()),
122 web_frame_(web_frame), 124 web_frame_(web_frame),
123 extension_id_(extension_id), 125 extension_id_(extension_id),
124 run_location_(run_location), 126 run_location_(run_location),
125 tab_id_(tab_id), 127 tab_id_(tab_id),
126 request_id_(kInvalidRequestId), 128 request_id_(kInvalidRequestId),
127 complete_(false) { 129 complete_(false),
130 execution_results_(new base::ListValue()),
131 all_injection_started_(false),
132 script_injection_manager_(nullptr) {
128 } 133 }
129 134
130 ScriptInjection::~ScriptInjection() { 135 ScriptInjection::~ScriptInjection() {
131 if (!complete_) 136 if (!complete_)
132 injector_->OnWillNotInject(ScriptInjector::WONT_INJECT); 137 injector_->OnWillNotInject(ScriptInjector::WONT_INJECT);
133 } 138 }
134 139
135 bool ScriptInjection::TryToInject(UserScript::RunLocation current_location, 140 bool ScriptInjection::TryToInject(UserScript::RunLocation current_location,
136 const Extension* extension, 141 const Extension* extension) {
137 ScriptsRunInfo* scripts_run_info) {
138 if (current_location < run_location_) 142 if (current_location < run_location_)
139 return false; // Wait for the right location. 143 return false; // Wait for the right location.
140 144
141 if (request_id_ != kInvalidRequestId) 145 if (request_id_ != kInvalidRequestId)
142 return false; // We're waiting for permission right now, try again later. 146 return false; // We're waiting for permission right now, try again later.
143 147
144 if (!extension) { 148 if (!extension) {
145 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED); 149 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
146 return true; // We're done. 150 return true; // We're done.
147 } 151 }
148 152
149 switch (injector_->CanExecuteOnFrame( 153 switch (injector_->CanExecuteOnFrame(
150 extension, web_frame_, tab_id_, web_frame_->top()->document().url())) { 154 extension, web_frame_, tab_id_, web_frame_->top()->document().url())) {
151 case PermissionsData::ACCESS_DENIED: 155 case PermissionsData::ACCESS_DENIED:
152 NotifyWillNotInject(ScriptInjector::NOT_ALLOWED); 156 NotifyWillNotInject(ScriptInjector::NOT_ALLOWED);
153 return true; // We're done. 157 return true; // We're done.
154 case PermissionsData::ACCESS_WITHHELD: 158 case PermissionsData::ACCESS_WITHHELD:
155 RequestPermission(); 159 RequestPermission();
156 return false; // Wait around for permission. 160 return false; // Wait around for permission.
157 case PermissionsData::ACCESS_ALLOWED: 161 case PermissionsData::ACCESS_ALLOWED:
158 Inject(extension, scripts_run_info); 162 Inject(extension);
159 return true; // We're done! 163 return true; // We're done!
160 } 164 }
161 165
162 // Some compilers don't realize that we always return from the switch() above. 166 // Some compilers don't realize that we always return from the switch() above.
163 // Make them happy. 167 // Make them happy.
164 return false; 168 return false;
165 } 169 }
166 170
167 bool ScriptInjection::OnPermissionGranted(const Extension* extension, 171 bool ScriptInjection::OnPermissionGranted(const Extension* extension) {
168 ScriptsRunInfo* scripts_run_info) {
169 if (!extension) { 172 if (!extension) {
170 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED); 173 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
171 return false; 174 return false;
172 } 175 }
173 176
174 Inject(extension, scripts_run_info); 177 Inject(extension);
175 return true; 178 return true;
176 } 179 }
177 180
178 void ScriptInjection::RequestPermission() { 181 void ScriptInjection::RequestPermission() {
179 content::RenderView* render_view = 182 content::RenderView* render_view =
180 content::RenderView::FromWebView(web_frame()->top()->view()); 183 content::RenderView::FromWebView(web_frame()->top()->view());
181 184
182 // If we are just notifying the browser of the injection, then send an 185 // If we are just notifying the browser of the injection, then send an
183 // invalid request (which is treated like a notification). 186 // invalid request (which is treated like a notification).
184 request_id_ = ShouldNotifyBrowserOfInjections() ? kInvalidRequestId 187 request_id_ = ShouldNotifyBrowserOfInjections() ? kInvalidRequestId
185 : g_next_pending_id++; 188 : g_next_pending_id++;
186 render_view->Send(new ExtensionHostMsg_RequestScriptInjectionPermission( 189 render_view->Send(new ExtensionHostMsg_RequestScriptInjectionPermission(
187 render_view->GetRoutingID(), 190 render_view->GetRoutingID(),
188 extension_id_, 191 extension_id_,
189 injector_->script_type(), 192 injector_->script_type(),
190 request_id_)); 193 request_id_));
191 } 194 }
192 195
193 void ScriptInjection::NotifyWillNotInject( 196 void ScriptInjection::NotifyWillNotInject(
194 ScriptInjector::InjectFailureReason reason) { 197 ScriptInjector::InjectFailureReason reason) {
195 complete_ = true; 198 complete_ = true;
196 injector_->OnWillNotInject(reason); 199 injector_->OnWillNotInject(reason);
197 } 200 }
198 201
199 void ScriptInjection::Inject(const Extension* extension, 202 void ScriptInjection::Inject(const Extension* extension) {
200 ScriptsRunInfo* scripts_run_info) {
201 DCHECK(extension); 203 DCHECK(extension);
202 DCHECK(scripts_run_info);
203 DCHECK(!complete_); 204 DCHECK(!complete_);
204 205
205 if (ShouldNotifyBrowserOfInjections()) 206 if (ShouldNotifyBrowserOfInjections())
206 RequestPermission(); 207 RequestPermission();
207 208
208 std::vector<blink::WebFrame*> frame_vector; 209 std::vector<blink::WebFrame*> frame_vector;
209 frame_vector.push_back(web_frame_); 210 frame_vector.push_back(web_frame_);
210 if (injector_->ShouldExecuteInChildFrames()) 211 if (injector_->ShouldExecuteInChildFrames())
211 AppendAllChildFrames(web_frame_, &frame_vector); 212 AppendAllChildFrames(web_frame_, &frame_vector);
212 213
213 scoped_ptr<blink::WebScopedUserGesture> gesture;
214 if (injector_->IsUserGesture())
215 gesture.reset(new blink::WebScopedUserGesture());
216
217 bool inject_js = injector_->ShouldInjectJs(run_location_); 214 bool inject_js = injector_->ShouldInjectJs(run_location_);
218 bool inject_css = injector_->ShouldInjectCss(run_location_); 215 bool inject_css = injector_->ShouldInjectCss(run_location_);
219 DCHECK(inject_js || inject_css); 216 DCHECK(inject_js || inject_css);
220 217
221 scoped_ptr<base::ListValue> execution_results(new base::ListValue()); 218 scripts_run_info_.reset(new ScriptsRunInfo());
219
222 GURL top_url = web_frame_->top()->document().url(); 220 GURL top_url = web_frame_->top()->document().url();
221 size_t result_index = 0;
223 for (std::vector<blink::WebFrame*>::iterator iter = frame_vector.begin(); 222 for (std::vector<blink::WebFrame*>::iterator iter = frame_vector.begin();
224 iter != frame_vector.end(); 223 iter != frame_vector.end();
225 ++iter) { 224 ++iter) {
226 // TODO(dcheng): Unfortunately, the code as written won't work in an OOPI 225 // TODO(dcheng): Unfortunately, the code as written won't work in an OOPI
227 // world. This is just a temporary hack to make things compile. 226 // world. This is just a temporary hack to make things compile.
228 blink::WebLocalFrame* frame = (*iter)->toWebLocalFrame(); 227 blink::WebLocalFrame* frame = (*iter)->toWebLocalFrame();
229 228
230 // We recheck access here in the renderer for extra safety against races 229 // We recheck access here in the renderer for extra safety against races
231 // with navigation, but different frames can have different URLs, and the 230 // with navigation, but different frames can have different URLs, and the
232 // extension might only have access to a subset of them. 231 // extension might only have access to a subset of them.
233 // For child frames, we just skip ones the extension doesn't have access 232 // For child frames, we just skip ones the extension doesn't have access
234 // to and carry on. 233 // to and carry on.
235 // Note: we don't consider ACCESS_WITHHELD because there is nowhere to 234 // Note: we don't consider ACCESS_WITHHELD because there is nowhere to
236 // surface a request for a child frame. 235 // surface a request for a child frame.
237 // TODO(rdevlin.cronin): We should ask for permission somehow. 236 // TODO(rdevlin.cronin): We should ask for permission somehow.
238 if (injector_->CanExecuteOnFrame(extension, frame, tab_id_, top_url) == 237 if (injector_->CanExecuteOnFrame(extension, frame, tab_id_, top_url) ==
239 PermissionsData::ACCESS_DENIED) { 238 PermissionsData::ACCESS_DENIED) {
240 DCHECK(frame->parent()); 239 DCHECK(frame->parent());
241 continue; 240 continue;
242 } 241 }
243 if (inject_js) 242 if (inject_js) {
244 InjectJs(extension, frame, execution_results.get()); 243 frame_result_index_[frame] = result_index++;
244 InjectJs(extension, frame);
245 }
245 if (inject_css) 246 if (inject_css)
246 InjectCss(frame); 247 InjectCss(frame);
247 } 248 }
248 249
249 complete_ = true; 250 all_injection_started_ = true;
250 injector_->OnInjectionComplete(execution_results.Pass(), 251 TryToFinish();
251 scripts_run_info,
252 run_location_);
253 } 252 }
254 253
255 void ScriptInjection::InjectJs(const Extension* extension, 254 void ScriptInjection::InjectJs(const Extension* extension,
256 blink::WebLocalFrame* frame, 255 blink::WebLocalFrame* frame) {
257 base::ListValue* execution_results) {
258 std::vector<blink::WebScriptSource> sources = 256 std::vector<blink::WebScriptSource> sources =
259 injector_->GetJsSources(run_location_); 257 injector_->GetJsSources(run_location_);
260 bool in_main_world = injector_->ShouldExecuteInMainWorld(); 258 bool in_main_world = injector_->ShouldExecuteInMainWorld();
261 int world_id = in_main_world 259 int world_id = in_main_world
262 ? DOMActivityLogger::kMainWorldId 260 ? DOMActivityLogger::kMainWorldId
263 : GetIsolatedWorldIdForExtension(extension, frame); 261 : GetIsolatedWorldIdForExtension(extension, frame);
264 bool expects_results = injector_->ExpectsResults(); 262 bool is_user_gesture = injector_->IsUserGesture();
263
264 scoped_ptr<blink::WebScriptExecutionCallback> callback(
265 new ScriptInjectionCallback(this, frame));
265 266
266 base::ElapsedTimer exec_timer; 267 base::ElapsedTimer exec_timer;
267 DOMActivityLogger::AttachToWorld(world_id, extension->id()); 268 DOMActivityLogger::AttachToWorld(world_id, extension->id());
268 v8::HandleScope scope(v8::Isolate::GetCurrent()); 269
269 v8::Local<v8::Value> script_value;
270 if (in_main_world) { 270 if (in_main_world) {
271 // We only inject in the main world for javascript: urls. 271 // We only inject in the main world for javascript: urls.
272 DCHECK_EQ(1u, sources.size()); 272 DCHECK_EQ(1u, sources.size());
273 273
274 const blink::WebScriptSource& source = sources.front(); 274 frame->requestExecuteScriptAndReturnValue(sources.front(),
275 if (expects_results) 275 is_user_gesture,
276 script_value = frame->executeScriptAndReturnValue(source); 276 callback.get());
277 else
278 frame->executeScript(source);
279 } else { // in isolated world 277 } else { // in isolated world
280 scoped_ptr<blink::WebVector<v8::Local<v8::Value> > > results; 278 frame->requestExecuteScriptInIsolatedWorld(world_id,
281 if (expects_results) 279 &sources.front(),
282 results.reset(new blink::WebVector<v8::Local<v8::Value> >()); 280 sources.size(),
283 frame->executeScriptInIsolatedWorld(world_id, 281 EXTENSION_GROUP_CONTENT_SCRIPTS,
284 &sources.front(), 282 is_user_gesture,
285 sources.size(), 283 callback.get());
286 EXTENSION_GROUP_CONTENT_SCRIPTS,
287 results.get());
288 if (expects_results && !results->isEmpty())
289 script_value = (*results)[0];
290 } 284 }
291 285
286 callbacks_.push_back(callback.release());
287
292 UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer.Elapsed()); 288 UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer.Elapsed());
289 }
293 290
291 void ScriptInjection::OnJSInjectionCompleted(
292 blink::WebLocalFrame* frame,
293 const blink::WebVector<v8::Local<v8::Value> >& results) {
294 std::map<blink::WebLocalFrame*, size_t>::iterator it =
295 frame_result_index_.find(frame);
Devlin 2015/02/11 17:49:58 If we truly have guarantees of synchronicity with
296 CHECK(it != frame_result_index_.end());
297 size_t idx = it->second;
298 frame_result_index_.erase(it);
299
300 bool expects_results = injector_->ExpectsResults();
294 if (expects_results) { 301 if (expects_results) {
302 v8::Local<v8::Value> script_value;
303 if (!results.isEmpty())
304 script_value = results[0];
295 // Right now, we only support returning single results (per frame). 305 // Right now, we only support returning single results (per frame).
296 scoped_ptr<content::V8ValueConverter> v8_converter( 306 scoped_ptr<content::V8ValueConverter> v8_converter(
297 content::V8ValueConverter::create()); 307 content::V8ValueConverter::create());
298 // It's safe to always use the main world context when converting 308 // It's safe to always use the main world context when converting
299 // here. V8ValueConverterImpl shouldn't actually care about the 309 // here. V8ValueConverterImpl shouldn't actually care about the
300 // context scope, and it switches to v8::Object's creation context 310 // context scope, and it switches to v8::Object's creation context
301 // when encountered. 311 // when encountered.
302 v8::Local<v8::Context> context = frame->mainWorldScriptContext(); 312 v8::Local<v8::Context> context = frame->mainWorldScriptContext();
303 scoped_ptr<base::Value> result( 313 scoped_ptr<base::Value> result(
304 v8_converter->FromV8Value(script_value, context)); 314 v8_converter->FromV8Value(script_value, context));
305 // Always append an execution result (i.e. no result == null result) 315 // Always append an execution result (i.e. no result == null result)
306 // so that |execution_results| lines up with the frames. 316 // so that |execution_results| lines up with the frames.
307 execution_results->Append(result.get() ? result.release() 317 execution_results_->Set(idx, result.get() ? result.release()
308 : base::Value::CreateNullValue()); 318 : base::Value::CreateNullValue());
319 }
320 TryToFinish();
321 }
322
323 void ScriptInjection::SetScriptInjectionManager(
324 ScriptInjectionManager* manager){
325 script_injection_manager_ = manager;
326 }
327
328 void ScriptInjection::TryToFinish() {
329 if (all_injection_started_ && frame_result_index_.size() == 0) {
330 complete_ = true;
331 injector_->OnInjectionComplete(execution_results_.Pass(),
332 scripts_run_info_.get(),
333 run_location_);
334
335 CHECK(script_injection_manager_);
336 // this object can be destroyed after next line
337 script_injection_manager_->OnInjectionFinished(this,
338 scripts_run_info_.get());
309 } 339 }
310 } 340 }
311 341
312 void ScriptInjection::InjectCss(blink::WebLocalFrame* frame) { 342 void ScriptInjection::InjectCss(blink::WebLocalFrame* frame) {
313 std::vector<std::string> css_sources = 343 std::vector<std::string> css_sources =
314 injector_->GetCssSources(run_location_); 344 injector_->GetCssSources(run_location_);
315 for (std::vector<std::string>::const_iterator iter = css_sources.begin(); 345 for (std::vector<std::string>::const_iterator iter = css_sources.begin();
316 iter != css_sources.end(); 346 iter != css_sources.end();
317 ++iter) { 347 ++iter) {
318 frame->document().insertStyleSheet(blink::WebString::fromUTF8(*iter)); 348 frame->document().insertStyleSheet(blink::WebString::fromUTF8(*iter));
319 } 349 }
320 } 350 }
321 351
322 } // namespace extensions 352 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698