script_context.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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.
  4. #include "extensions/renderer/script_context.h"
  5. #include "base/command_line.h"
  6. #include "base/containers/flat_set.h"
  7. #include "base/logging.h"
  8. #include "base/no_destructor.h"
  9. #include "base/strings/string_util.h"
  10. #include "base/strings/stringprintf.h"
  11. #include "base/values.h"
  12. #include "content/public/common/content_switches.h"
  13. #include "content/public/common/url_constants.h"
  14. #include "content/public/renderer/render_frame.h"
  15. #include "extensions/common/constants.h"
  16. #include "extensions/common/content_script_injection_url_getter.h"
  17. #include "extensions/common/extension.h"
  18. #include "extensions/common/extension_api.h"
  19. #include "extensions/common/extension_urls.h"
  20. #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
  21. #include "extensions/common/permissions/permissions_data.h"
  22. #include "extensions/renderer/dispatcher.h"
  23. #include "extensions/renderer/renderer_extension_registry.h"
  24. #include "extensions/renderer/v8_helpers.h"
  25. #include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
  26. #include "third_party/blink/public/platform/web_security_origin.h"
  27. #include "third_party/blink/public/web/web_document.h"
  28. #include "third_party/blink/public/web/web_document_loader.h"
  29. #include "third_party/blink/public/web/web_local_frame.h"
  30. #include "v8/include/v8-context.h"
  31. #include "v8/include/v8-debug.h"
  32. #include "v8/include/v8-function.h"
  33. #include "v8/include/v8-isolate.h"
  34. #include "v8/include/v8-microtask-queue.h"
  35. #include "v8/include/v8-primitive.h"
  36. namespace extensions {
  37. namespace {
  38. class WebLocalFrameAdapter
  39. : public ContentScriptInjectionUrlGetter::FrameAdapter {
  40. public:
  41. explicit WebLocalFrameAdapter(const blink::WebLocalFrame* frame)
  42. : frame_(frame) {}
  43. ~WebLocalFrameAdapter() override = default;
  44. std::unique_ptr<FrameAdapter> Clone() const override {
  45. return std::make_unique<WebLocalFrameAdapter>(frame_);
  46. }
  47. std::unique_ptr<FrameAdapter> GetLocalParentOrOpener() const override {
  48. blink::WebFrame* parent_or_opener = nullptr;
  49. if (frame_->Parent())
  50. parent_or_opener = frame_->Parent();
  51. else
  52. parent_or_opener = frame_->Opener();
  53. if (!parent_or_opener || !parent_or_opener->IsWebLocalFrame())
  54. return nullptr;
  55. blink::WebLocalFrame* local_parent_or_opener =
  56. parent_or_opener->ToWebLocalFrame();
  57. if (local_parent_or_opener->GetDocument().IsNull())
  58. return nullptr;
  59. return std::make_unique<WebLocalFrameAdapter>(local_parent_or_opener);
  60. }
  61. GURL GetUrl() const override {
  62. if (frame_->GetDocument().Url().IsEmpty()) {
  63. // It's possible for URL to be empty when `frame_` is on the initial empty
  64. // document. TODO(https://crbug.com/1197308): Consider making `frame_`'s
  65. // document's URL about:blank instead of empty in that case.
  66. return GURL(url::kAboutBlankURL);
  67. }
  68. return frame_->GetDocument().Url();
  69. }
  70. url::Origin GetOrigin() const override { return frame_->GetSecurityOrigin(); }
  71. bool CanAccess(const url::Origin& target) const override {
  72. return frame_->GetSecurityOrigin().CanAccess(target);
  73. }
  74. bool CanAccess(const FrameAdapter& target) const override {
  75. // It is important that below `web_security_origin` wraps the security
  76. // origin of the `target_frame` (rather than a new origin created via
  77. // url::Origin round-trip - such an origin wouldn't be 100% equivalent -
  78. // e.g. `disallowdocumentaccess` information might be lost). FWIW, this
  79. // scenario is execised by ScriptContextTest.GetEffectiveDocumentURL.
  80. const blink::WebLocalFrame* target_frame =
  81. static_cast<const WebLocalFrameAdapter&>(target).frame_;
  82. blink::WebSecurityOrigin web_security_origin =
  83. target_frame->GetDocument().GetSecurityOrigin();
  84. return frame_->GetSecurityOrigin().CanAccess(web_security_origin);
  85. }
  86. uintptr_t GetId() const override {
  87. return reinterpret_cast<uintptr_t>(frame_);
  88. }
  89. private:
  90. const blink::WebLocalFrame* const frame_;
  91. };
  92. GURL GetEffectiveDocumentURL(
  93. blink::WebLocalFrame* frame,
  94. const GURL& document_url,
  95. MatchOriginAsFallbackBehavior match_origin_as_fallback,
  96. bool allow_inaccessible_parents) {
  97. return ContentScriptInjectionUrlGetter::Get(
  98. WebLocalFrameAdapter(frame), document_url, match_origin_as_fallback,
  99. allow_inaccessible_parents);
  100. }
  101. std::string GetContextTypeDescriptionString(Feature::Context context_type) {
  102. switch (context_type) {
  103. case Feature::UNSPECIFIED_CONTEXT:
  104. return "UNSPECIFIED";
  105. case Feature::BLESSED_EXTENSION_CONTEXT:
  106. return "BLESSED_EXTENSION";
  107. case Feature::UNBLESSED_EXTENSION_CONTEXT:
  108. return "UNBLESSED_EXTENSION";
  109. case Feature::CONTENT_SCRIPT_CONTEXT:
  110. return "CONTENT_SCRIPT";
  111. case Feature::WEB_PAGE_CONTEXT:
  112. return "WEB_PAGE";
  113. case Feature::BLESSED_WEB_PAGE_CONTEXT:
  114. return "BLESSED_WEB_PAGE";
  115. case Feature::WEBUI_CONTEXT:
  116. return "WEBUI";
  117. case Feature::WEBUI_UNTRUSTED_CONTEXT:
  118. return "WEBUI_UNTRUSTED";
  119. case Feature::LOCK_SCREEN_EXTENSION_CONTEXT:
  120. return "LOCK_SCREEN_EXTENSION";
  121. case Feature::OFFSCREEN_EXTENSION_CONTEXT:
  122. return "OFFSCREEN_EXTENSION_CONTEXT";
  123. }
  124. NOTREACHED();
  125. return std::string();
  126. }
  127. static std::string ToStringOrDefault(v8::Isolate* isolate,
  128. const v8::Local<v8::String>& v8_string,
  129. const std::string& dflt) {
  130. if (v8_string.IsEmpty())
  131. return dflt;
  132. std::string ascii_value = *v8::String::Utf8Value(isolate, v8_string);
  133. return ascii_value.empty() ? dflt : ascii_value;
  134. }
  135. using FrameToDocumentLoader =
  136. base::flat_map<blink::WebLocalFrame*, blink::WebDocumentLoader*>;
  137. FrameToDocumentLoader& FrameDocumentLoaderMap() {
  138. static base::NoDestructor<FrameToDocumentLoader> map;
  139. return *map;
  140. }
  141. blink::WebDocumentLoader* CurrentDocumentLoader(
  142. const blink::WebLocalFrame* frame) {
  143. auto& map = FrameDocumentLoaderMap();
  144. auto it = map.find(frame);
  145. return it == map.end() ? frame->GetDocumentLoader() : it->second;
  146. }
  147. } // namespace
  148. ScriptContext::ScopedFrameDocumentLoader::ScopedFrameDocumentLoader(
  149. blink::WebLocalFrame* frame,
  150. blink::WebDocumentLoader* document_loader)
  151. : frame_(frame), document_loader_(document_loader) {
  152. auto& map = FrameDocumentLoaderMap();
  153. DCHECK(map.find(frame_) == map.end());
  154. map[frame_] = document_loader_;
  155. }
  156. ScriptContext::ScopedFrameDocumentLoader::~ScopedFrameDocumentLoader() {
  157. auto& map = FrameDocumentLoaderMap();
  158. DCHECK_EQ(document_loader_, map.find(frame_)->second);
  159. map.erase(frame_);
  160. }
  161. ScriptContext::ScriptContext(const v8::Local<v8::Context>& v8_context,
  162. blink::WebLocalFrame* web_frame,
  163. const Extension* extension,
  164. Feature::Context context_type,
  165. const Extension* effective_extension,
  166. Feature::Context effective_context_type)
  167. : is_valid_(true),
  168. v8_context_(v8_context->GetIsolate(), v8_context),
  169. web_frame_(web_frame),
  170. extension_(extension),
  171. context_type_(context_type),
  172. effective_extension_(effective_extension),
  173. effective_context_type_(effective_context_type),
  174. context_id_(base::UnguessableToken::Create()),
  175. safe_builtins_(this),
  176. isolate_(v8_context->GetIsolate()),
  177. service_worker_version_id_(blink::mojom::kInvalidServiceWorkerVersionId) {
  178. VLOG(1) << "Created context:\n" << GetDebugString();
  179. v8_context_.AnnotateStrongRetainer("extensions::ScriptContext::v8_context_");
  180. if (web_frame_)
  181. url_ = GetAccessCheckedFrameURL(web_frame_);
  182. }
  183. ScriptContext::~ScriptContext() {
  184. VLOG(1) << "Destroyed context for extension\n"
  185. << " extension id: " << GetExtensionID() << "\n"
  186. << " effective extension id: "
  187. << (effective_extension_.get() ? effective_extension_->id() : "");
  188. CHECK(!is_valid_) << "ScriptContexts must be invalidated before destruction";
  189. }
  190. // static
  191. bool ScriptContext::IsSandboxedPage(const GURL& url) {
  192. // TODO(kalman): This is checking the wrong thing. See comment in
  193. // HasAccessOrThrowError.
  194. if (url.SchemeIs(kExtensionScheme)) {
  195. const Extension* extension =
  196. RendererExtensionRegistry::Get()->GetByID(url.host());
  197. if (extension) {
  198. return SandboxedPageInfo::IsSandboxedPage(extension, url.path());
  199. }
  200. }
  201. return false;
  202. }
  203. void ScriptContext::SetModuleSystem(
  204. std::unique_ptr<ModuleSystem> module_system) {
  205. module_system_ = std::move(module_system);
  206. module_system_->Initialize();
  207. }
  208. void ScriptContext::Invalidate() {
  209. DCHECK(thread_checker_.CalledOnValidThread());
  210. CHECK(is_valid_);
  211. is_valid_ = false;
  212. // TODO(kalman): Make ModuleSystem use AddInvalidationObserver.
  213. // Ownership graph is a bit weird here.
  214. if (module_system_)
  215. module_system_->Invalidate();
  216. // Swap |invalidate_observers_| to a local variable to clear it, and to make
  217. // sure it's not mutated as we iterate.
  218. std::vector<base::OnceClosure> observers;
  219. observers.swap(invalidate_observers_);
  220. for (base::OnceClosure& observer : observers) {
  221. std::move(observer).Run();
  222. }
  223. DCHECK(invalidate_observers_.empty())
  224. << "Invalidation observers cannot be added during invalidation";
  225. v8_context_.Reset();
  226. }
  227. void ScriptContext::AddInvalidationObserver(base::OnceClosure observer) {
  228. DCHECK(thread_checker_.CalledOnValidThread());
  229. invalidate_observers_.push_back(std::move(observer));
  230. }
  231. const std::string& ScriptContext::GetExtensionID() const {
  232. DCHECK(thread_checker_.CalledOnValidThread());
  233. return extension_.get() ? extension_->id() : base::EmptyString();
  234. }
  235. content::RenderFrame* ScriptContext::GetRenderFrame() const {
  236. DCHECK(thread_checker_.CalledOnValidThread());
  237. if (web_frame_)
  238. return content::RenderFrame::FromWebFrame(web_frame_);
  239. return NULL;
  240. }
  241. void ScriptContext::SafeCallFunction(const v8::Local<v8::Function>& function,
  242. int argc,
  243. v8::Local<v8::Value> argv[]) {
  244. SafeCallFunction(function, argc, argv, blink::WebScriptExecutionCallback());
  245. }
  246. void ScriptContext::SafeCallFunction(
  247. const v8::Local<v8::Function>& function,
  248. int argc,
  249. v8::Local<v8::Value> argv[],
  250. blink::WebScriptExecutionCallback callback) {
  251. DCHECK(thread_checker_.CalledOnValidThread());
  252. v8::HandleScope handle_scope(isolate());
  253. v8::Context::Scope scope(v8_context());
  254. v8::MicrotasksScope microtasks(isolate(),
  255. v8::MicrotasksScope::kDoNotRunMicrotasks);
  256. v8::Local<v8::Object> global = v8_context()->Global();
  257. if (web_frame_) {
  258. web_frame_->RequestExecuteV8Function(v8_context(), function, global, argc,
  259. argv, std::move(callback));
  260. } else {
  261. auto start_time = base::TimeTicks::Now();
  262. v8::MaybeLocal<v8::Value> maybe_result =
  263. function->Call(v8_context(), global, argc, argv);
  264. v8::Local<v8::Value> result;
  265. if (!callback.is_null() && maybe_result.ToLocal(&result)) {
  266. std::vector<v8::Local<v8::Value>> results(1, result);
  267. std::move(callback).Run(results, start_time);
  268. }
  269. }
  270. }
  271. Feature::Availability ScriptContext::GetAvailability(
  272. const std::string& api_name) {
  273. return GetAvailability(api_name, CheckAliasStatus::ALLOWED);
  274. }
  275. Feature::Availability ScriptContext::GetAvailability(
  276. const std::string& api_name,
  277. CheckAliasStatus check_alias) {
  278. DCHECK(thread_checker_.CalledOnValidThread());
  279. if (base::StartsWith(api_name, "test", base::CompareCase::SENSITIVE)) {
  280. bool allowed = base::CommandLine::ForCurrentProcess()->
  281. HasSwitch(::switches::kTestType);
  282. Feature::AvailabilityResult result =
  283. allowed ? Feature::IS_AVAILABLE : Feature::MISSING_COMMAND_LINE_SWITCH;
  284. return Feature::Availability(result,
  285. allowed ? "" : "Only allowed in tests");
  286. }
  287. // Hack: Hosted apps should have the availability of messaging APIs based on
  288. // the URL of the page (which might have access depending on some extension
  289. // with externally_connectable), not whether the app has access to messaging
  290. // (which it won't).
  291. const Extension* extension = extension_.get();
  292. if (extension && extension->is_hosted_app() &&
  293. (api_name == "runtime.connect" || api_name == "runtime.sendMessage")) {
  294. extension = NULL;
  295. }
  296. return ExtensionAPI::GetSharedInstance()->IsAvailable(
  297. api_name, extension, context_type_, url(), check_alias,
  298. kRendererProfileId);
  299. }
  300. std::string ScriptContext::GetContextTypeDescription() const {
  301. DCHECK(thread_checker_.CalledOnValidThread());
  302. return GetContextTypeDescriptionString(context_type_);
  303. }
  304. std::string ScriptContext::GetEffectiveContextTypeDescription() const {
  305. DCHECK(thread_checker_.CalledOnValidThread());
  306. return GetContextTypeDescriptionString(effective_context_type_);
  307. }
  308. const GURL& ScriptContext::service_worker_scope() const {
  309. DCHECK(IsForServiceWorker());
  310. return service_worker_scope_;
  311. }
  312. bool ScriptContext::IsForServiceWorker() const {
  313. return service_worker_version_id_ !=
  314. blink::mojom::kInvalidServiceWorkerVersionId;
  315. }
  316. bool ScriptContext::IsAnyFeatureAvailableToContext(
  317. const Feature& api,
  318. CheckAliasStatus check_alias) {
  319. DCHECK(thread_checker_.CalledOnValidThread());
  320. // TODO(lazyboy): Decide what we should do for service workers, where
  321. // web_frame() is null.
  322. GURL url = web_frame() ? GetDocumentLoaderURLForFrame(web_frame()) : url_;
  323. return ExtensionAPI::GetSharedInstance()->IsAnyFeatureAvailableToContext(
  324. api, extension(), context_type(), url, check_alias, kRendererProfileId);
  325. }
  326. // static
  327. GURL ScriptContext::GetDocumentLoaderURLForFrame(
  328. const blink::WebLocalFrame* frame) {
  329. // Normally we would use frame->document().url() to determine the document's
  330. // URL, but to decide whether to inject a content script, we use the URL from
  331. // the data source. This "quirk" helps prevents content scripts from
  332. // inadvertently adding DOM elements to the compose iframe in Gmail because
  333. // the compose iframe's dataSource URL is about:blank, but the document URL
  334. // changes to match the parent document after Gmail document.writes into
  335. // it to create the editor.
  336. // http://code.google.com/p/chromium/issues/detail?id=86742
  337. blink::WebDocumentLoader* document_loader = CurrentDocumentLoader(frame);
  338. return document_loader ? GURL(document_loader->GetUrl()) : GURL();
  339. }
  340. // static
  341. GURL ScriptContext::GetAccessCheckedFrameURL(
  342. const blink::WebLocalFrame* frame) {
  343. const blink::WebURL& weburl = frame->GetDocument().Url();
  344. if (weburl.IsEmpty()) {
  345. blink::WebDocumentLoader* document_loader = CurrentDocumentLoader(frame);
  346. if (document_loader &&
  347. frame->GetSecurityOrigin().CanAccess(
  348. blink::WebSecurityOrigin::Create(document_loader->GetUrl()))) {
  349. return GURL(document_loader->GetUrl());
  350. }
  351. }
  352. return GURL(weburl);
  353. }
  354. // static
  355. GURL ScriptContext::GetEffectiveDocumentURLForContext(
  356. blink::WebLocalFrame* frame,
  357. const GURL& document_url,
  358. bool match_about_blank) {
  359. // Note: Do not allow matching inaccessible parent frames here; frames like
  360. // sandboxed frames should not inherit the privilege of their parents.
  361. constexpr bool allow_inaccessible_parents = false;
  362. // TODO(devlin): Determine if this could use kAlways instead of
  363. // kMatchForAboutSchemeAndClimbTree.
  364. auto match_origin_as_fallback =
  365. match_about_blank
  366. ? MatchOriginAsFallbackBehavior::kMatchForAboutSchemeAndClimbTree
  367. : MatchOriginAsFallbackBehavior::kNever;
  368. return GetEffectiveDocumentURL(frame, document_url, match_origin_as_fallback,
  369. allow_inaccessible_parents);
  370. }
  371. // static
  372. GURL ScriptContext::GetEffectiveDocumentURLForInjection(
  373. blink::WebLocalFrame* frame,
  374. const GURL& document_url,
  375. MatchOriginAsFallbackBehavior match_origin_as_fallback) {
  376. // We explicitly allow inaccessible parents here. Extensions should still be
  377. // able to inject into a sandboxed iframe if it has access to the embedding
  378. // origin.
  379. constexpr bool allow_inaccessible_parents = true;
  380. return GetEffectiveDocumentURL(frame, document_url, match_origin_as_fallback,
  381. allow_inaccessible_parents);
  382. }
  383. // Grants a set of content capabilities to this context.
  384. bool ScriptContext::HasAPIPermission(mojom::APIPermissionID permission) const {
  385. DCHECK(thread_checker_.CalledOnValidThread());
  386. if (effective_extension_.get()) {
  387. return effective_extension_->permissions_data()->HasAPIPermission(
  388. permission);
  389. }
  390. if (context_type() == Feature::WEB_PAGE_CONTEXT) {
  391. // Only web page contexts may be granted content capabilities. Other
  392. // contexts are either privileged WebUI or extensions with their own set of
  393. // permissions.
  394. if (content_capabilities_.find(permission) != content_capabilities_.end())
  395. return true;
  396. }
  397. return false;
  398. }
  399. bool ScriptContext::HasAccessOrThrowError(const std::string& name) {
  400. DCHECK(thread_checker_.CalledOnValidThread());
  401. // Theoretically[1] we could end up with bindings being injected into
  402. // sandboxed frames, for example content scripts. Don't let them execute API
  403. // functions.
  404. //
  405. // In any case, this check is silly. The frame's document's security origin
  406. // already tells us if it's sandboxed. The only problem is that until
  407. // crbug.com/466373 is fixed, we don't know the security origin up-front and
  408. // may not know it here, either.
  409. //
  410. // [1] citation needed. This ScriptContext should already be in a state that
  411. // doesn't allow this, from ScriptContextSet::ClassifyJavaScriptContext.
  412. if (extension() &&
  413. SandboxedPageInfo::IsSandboxedPage(extension(), url_.path())) {
  414. static const char kMessage[] =
  415. "%s cannot be used within a sandboxed frame.";
  416. std::string error_msg = base::StringPrintf(kMessage, name.c_str());
  417. isolate()->ThrowException(v8::Exception::Error(
  418. v8::String::NewFromUtf8(isolate(), error_msg.c_str(),
  419. v8::NewStringType::kNormal)
  420. .ToLocalChecked()));
  421. return false;
  422. }
  423. Feature::Availability availability = GetAvailability(name);
  424. if (!availability.is_available()) {
  425. isolate()->ThrowException(v8::Exception::Error(
  426. v8::String::NewFromUtf8(isolate(), availability.message().c_str(),
  427. v8::NewStringType::kNormal)
  428. .ToLocalChecked()));
  429. return false;
  430. }
  431. return true;
  432. }
  433. std::string ScriptContext::GetDebugString() const {
  434. DCHECK(thread_checker_.CalledOnValidThread());
  435. return base::StringPrintf(
  436. " extension id: %s\n"
  437. " frame: %p\n"
  438. " URL: %s\n"
  439. " context_type: %s\n"
  440. " effective extension id: %s\n"
  441. " effective context type: %s",
  442. extension_.get() ? extension_->id().c_str() : "(none)", web_frame_,
  443. url_.spec().c_str(), GetContextTypeDescription().c_str(),
  444. effective_extension_.get() ? effective_extension_->id().c_str()
  445. : "(none)",
  446. GetEffectiveContextTypeDescription().c_str());
  447. }
  448. std::string ScriptContext::GetStackTraceAsString() const {
  449. DCHECK(thread_checker_.CalledOnValidThread());
  450. v8::Local<v8::StackTrace> stack_trace =
  451. v8::StackTrace::CurrentStackTrace(isolate(), 10);
  452. if (stack_trace.IsEmpty() || stack_trace->GetFrameCount() <= 0) {
  453. return " <no stack trace>";
  454. }
  455. std::string result;
  456. for (int i = 0; i < stack_trace->GetFrameCount(); ++i) {
  457. v8::Local<v8::StackFrame> frame = stack_trace->GetFrame(isolate(), i);
  458. CHECK(!frame.IsEmpty());
  459. result += base::StringPrintf(
  460. "\n at %s (%s:%d:%d)",
  461. ToStringOrDefault(isolate(), frame->GetFunctionName(), "<anonymous>")
  462. .c_str(),
  463. ToStringOrDefault(isolate(), frame->GetScriptName(), "<anonymous>")
  464. .c_str(),
  465. frame->GetLineNumber(), frame->GetColumn());
  466. }
  467. return result;
  468. }
  469. v8::Local<v8::Value> ScriptContext::RunScript(
  470. v8::Local<v8::String> name,
  471. v8::Local<v8::String> code,
  472. RunScriptExceptionHandler exception_handler,
  473. v8::ScriptCompiler::NoCacheReason no_cache_reason) {
  474. DCHECK(thread_checker_.CalledOnValidThread());
  475. v8::EscapableHandleScope handle_scope(isolate());
  476. v8::Context::Scope context_scope(v8_context());
  477. // Prepend extensions:: to |name| so that internal code can be differentiated
  478. // from external code in stack traces. This has no effect on behaviour.
  479. std::string internal_name = base::StringPrintf(
  480. "extensions::%s", *v8::String::Utf8Value(isolate(), name));
  481. if (internal_name.size() >= v8::String::kMaxLength) {
  482. NOTREACHED() << "internal_name is too long.";
  483. return v8::Undefined(isolate());
  484. }
  485. v8::MicrotasksScope microtasks(
  486. isolate(), v8::MicrotasksScope::kDoNotRunMicrotasks);
  487. v8::TryCatch try_catch(isolate());
  488. try_catch.SetCaptureMessage(true);
  489. v8::ScriptOrigin origin(isolate(), v8_helpers::ToV8StringUnsafe(
  490. isolate(), internal_name.c_str()));
  491. v8::ScriptCompiler::Source script_source(code, origin);
  492. v8::Local<v8::Script> script;
  493. if (!v8::ScriptCompiler::Compile(v8_context(), &script_source,
  494. v8::ScriptCompiler::kNoCompileOptions,
  495. no_cache_reason)
  496. .ToLocal(&script)) {
  497. std::move(exception_handler).Run(try_catch);
  498. return v8::Undefined(isolate());
  499. }
  500. v8::Local<v8::Value> result;
  501. if (!script->Run(v8_context()).ToLocal(&result)) {
  502. std::move(exception_handler).Run(try_catch);
  503. return v8::Undefined(isolate());
  504. }
  505. return handle_scope.Escape(result);
  506. }
  507. } // namespace extensions