1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "gin/shell_runner.h"
9 #include "gin/converter.h"
10 #include "gin/per_context_data.h"
11 #include "gin/public/context_holder.h"
12 #include "gin/try_catch.h"
13 #include "v8/include/v8-script.h"
16 using v8::HandleScope;
19 using v8::ObjectTemplate;
24 ShellRunnerDelegate::ShellRunnerDelegate() = default;
26 ShellRunnerDelegate::~ShellRunnerDelegate() = default;
28 v8::Local<ObjectTemplate> ShellRunnerDelegate::GetGlobalTemplate(
30 v8::Isolate* isolate) {
31 return v8::Local<ObjectTemplate>();
34 void ShellRunnerDelegate::DidCreateContext(ShellRunner* runner) {
37 void ShellRunnerDelegate::WillRunScript(ShellRunner* runner) {
40 void ShellRunnerDelegate::DidRunScript(ShellRunner* runner) {
43 void ShellRunnerDelegate::UnhandledException(ShellRunner* runner,
44 TryCatch& try_catch) {
45 CHECK(false) << try_catch.GetStackTrace();
48 ShellRunner::ShellRunner(ShellRunnerDelegate* delegate, Isolate* isolate)
49 : delegate_(delegate) {
50 v8::Isolate::Scope isolate_scope(isolate);
51 HandleScope handle_scope(isolate);
52 v8::Local<v8::Context> context =
53 Context::New(isolate, NULL, delegate_->GetGlobalTemplate(this, isolate));
55 context_holder_ = std::make_unique<ContextHolder>(isolate);
56 context_holder_->SetContext(context);
57 PerContextData::From(context)->set_runner(this);
59 v8::Context::Scope scope(context);
60 delegate_->DidCreateContext(this);
63 ShellRunner::~ShellRunner() = default;
65 v8::MaybeLocal<v8::Value> ShellRunner::Run(const std::string& source,
66 const std::string& resource_name) {
67 v8::Isolate* isolate = GetContextHolder()->isolate();
68 TryCatch try_catch(isolate);
69 v8::ScriptOrigin origin(isolate, StringToV8(isolate, resource_name));
70 auto maybe_script = Script::Compile(GetContextHolder()->context(),
71 StringToV8(isolate, source), &origin);
72 v8::Local<Script> script;
73 if (!maybe_script.ToLocal(&script)) {
74 delegate_->UnhandledException(this, try_catch);
75 return v8::MaybeLocal<v8::Value>();
81 ContextHolder* ShellRunner::GetContextHolder() {
82 return context_holder_.get();
85 v8::MaybeLocal<v8::Value> ShellRunner::Run(v8::Local<Script> script) {
86 TryCatch try_catch(GetContextHolder()->isolate());
87 delegate_->WillRunScript(this);
89 auto maybe = script->Run(GetContextHolder()->context());
91 delegate_->DidRunScript(this);
92 if (maybe.IsEmpty()) {
93 delegate_->UnhandledException(this, try_catch);