-
Notifications
You must be signed in to change notification settings - Fork 5
/
v8context.cc
404 lines (333 loc) · 12.6 KB
/
v8context.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#include "v8context.h"
#include <cstdlib>
#include <cstring>
#include <sstream>
extern "C" char* _go_v8_callback(unsigned int ctxID, char* name, char* args);
extern "C" PersistentValuePtr _go_v8_callback_raw(
unsigned int ctxID, const char* name, const char* callerFuncname,
const char* callerFilename, int callerLine, int callerColumn, int argc,
PersistentValuePtr* argv);
namespace {
// Calling JSON.stringify on value.
std::string to_json(v8::Isolate* iso, v8::Local<v8::Value> value) {
v8::HandleScope scope(iso);
v8::TryCatch try_catch;
v8::Local<v8::Object> json =
v8::Local<v8::Object>::Cast(iso->GetCurrentContext()->Global()->Get(
v8::String::NewFromUtf8(iso, "JSON")));
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(
json->GetRealNamedProperty(v8::String::NewFromUtf8(iso, "stringify")));
v8::Local<v8::Value> args[1];
args[0] = value;
v8::Local<v8::Value> call_result = func->Call(iso->GetCurrentContext()->Global(), 1, args);
if (call_result.IsEmpty()) {
try_catch.ReThrow();
return "";
}
v8::String::Utf8Value ret(call_result->ToString());
return *ret;
}
// Calling JSON.parse on str.
v8::Local<v8::Value> from_json(v8::Isolate* iso, std::string str) {
v8::HandleScope scope(iso);
v8::TryCatch try_catch;
v8::Local<v8::Object> json =
v8::Local<v8::Object>::Cast(iso->GetCurrentContext()->Global()->Get(
v8::String::NewFromUtf8(iso, "JSON")));
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(
json->GetRealNamedProperty(v8::String::NewFromUtf8(iso, "parse")));
v8::Local<v8::Value> args[1];
args[0] = v8::String::NewFromUtf8(iso, str.c_str());
return func->Call(iso->GetCurrentContext()->Global(), 1, args);
}
// _go_call is a helper function to call Go functions from within v8.
void _go_call(const v8::FunctionCallbackInfo<v8::Value>& args) {
uint32_t id = args[0]->ToUint32()->Value();
v8::String::Utf8Value name(args[1]);
v8::String::Utf8Value argv(args[2]);
v8::Isolate* iso = args.GetIsolate();
v8::HandleScope scope(iso);
v8::ReturnValue<v8::Value> ret = args.GetReturnValue();
char* retv = _go_v8_callback(id, *name, *argv);
if (retv != NULL) {
ret.Set(from_json(iso, retv));
free(retv);
}
}
std::string str(v8::Local<v8::Value> value) {
v8::String::Utf8Value s(value);
if (s.length() == 0) {
return "";
}
return *s;
}
// _go_call_raw is a helper function to call Go functions from within v8.
void _go_call_raw(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* iso = args.GetIsolate();
v8::HandleScope scope(iso);
uint32_t id = args[0]->ToUint32()->Value();
v8::String::Utf8Value name(args[1]);
v8::Local<v8::Array> hargv = v8::Local<v8::Array>::Cast(args[2]);
std::string src_file, src_func;
int line_number = 0, column = 0;
v8::Local<v8::StackTrace> trace(v8::StackTrace::CurrentStackTrace(iso, 2));
if (trace->GetFrameCount() == 2) {
v8::Local<v8::StackFrame> frame(trace->GetFrame(1));
src_file = str(frame->GetScriptName());
src_func = str(frame->GetFunctionName());
line_number = frame->GetLineNumber();
column = frame->GetColumn();
}
int argc = hargv->Length();
PersistentValuePtr argv[argc];
for (int i = 0; i < argc; i++) {
argv[i] = new v8::Persistent<v8::Value>(iso, hargv->Get(i));
}
PersistentValuePtr retv =
_go_v8_callback_raw(id, *name, src_func.c_str(), src_file.c_str(),
line_number, column, argc, argv);
if (retv == NULL) {
args.GetReturnValue().Set(v8::Undefined(iso));
} else {
args.GetReturnValue().Set(*static_cast<v8::Persistent<v8::Value>*>(retv));
}
}
};
class ErrorReporter {
public:
ErrorReporter(v8::Isolate *isolate, v8::TryCatch* try_catch, std::string* error, bool* terminated)
: mIsolate(isolate), mTryCatch(try_catch), mError(error), mTerminated(terminated)
{
mError->clear();
*mTerminated = false;
}
~ErrorReporter() {
*mTerminated = mTryCatch->HasTerminated();
if (mTryCatch->HasCaught()) {
*mError = report_exception(*mTryCatch);
}
}
private:
std::string report_exception(v8::TryCatch& try_catch);
v8::Isolate* mIsolate;
v8::TryCatch* mTryCatch;
std::string *mError;
bool *mTerminated;
};
V8Context::V8Context(v8::Isolate* isolate) : mIsolate(isolate), mTerminated(false) {
v8::Locker lock(mIsolate);
v8::Isolate::Scope isolate_scope(mIsolate);
v8::HandleScope handle_scope(mIsolate);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(true);
v8::Local<v8::ObjectTemplate> globals = v8::ObjectTemplate::New(mIsolate);
globals->Set(v8::String::NewFromUtf8(mIsolate, "_go_call"),
v8::FunctionTemplate::New(mIsolate, _go_call));
globals->Set(v8::String::NewFromUtf8(mIsolate, "_go_call_raw"),
v8::FunctionTemplate::New(mIsolate, _go_call_raw));
mContext.Reset(mIsolate, v8::Context::New(mIsolate, NULL, globals));
};
V8Context::~V8Context() {
v8::Locker lock(mIsolate);
mContext.Reset();
};
char* V8Context::Execute(const char* source, const char* filename) {
v8::Locker locker(mIsolate);
v8::Isolate::Scope isolate_scope(mIsolate);
v8::HandleScope handle_scope(mIsolate);
v8::Context::Scope context_scope(mContext.Get(mIsolate));
v8::TryCatch try_catch;
try_catch.SetVerbose(false);
ErrorReporter er(mIsolate, &try_catch, &mLastError, &mTerminated);
v8::Local<v8::Script> script = v8::Script::Compile(
v8::String::NewFromUtf8(mIsolate, source),
v8::String::NewFromUtf8(mIsolate, filename ? filename : "undefined"));
if (script.IsEmpty()) {
return NULL;
}
v8::Local<v8::Value> result = script->Run();
if (result.IsEmpty()) {
return NULL;
}
if (result->IsFunction() || result->IsUndefined()) {
return strdup("");
} else {
std::string json = to_json(mIsolate, result);
if (json == "") {
return NULL;
}
return strdup(json.c_str());
}
}
PersistentValuePtr V8Context::Eval(const char* source, const char* filename) {
v8::Locker locker(mIsolate);
v8::Isolate::Scope isolate_scope(mIsolate);
v8::HandleScope handle_scope(mIsolate);
v8::Context::Scope context_scope(mContext.Get(mIsolate));
v8::TryCatch try_catch;
try_catch.SetVerbose(false);
ErrorReporter er(mIsolate, &try_catch, &mLastError, &mTerminated);
v8::Local<v8::Script> script = v8::Script::Compile(
v8::String::NewFromUtf8(mIsolate, source),
filename ? v8::String::NewFromUtf8(mIsolate, filename)
: v8::String::NewFromUtf8(mIsolate, "undefined"));
if (script.IsEmpty()) {
return NULL;
}
v8::Local<v8::Value> result = script->Run();
if (result.IsEmpty()) {
return NULL;
}
return new v8::Persistent<v8::Value>(mIsolate, result);
}
PersistentValuePtr V8Context::Apply(PersistentValuePtr func,
PersistentValuePtr self, int argc,
PersistentValuePtr* argv) {
v8::Locker locker(mIsolate);
v8::Isolate::Scope isolate_scope(mIsolate);
v8::HandleScope handle_scope(mIsolate);
v8::Context::Scope context_scope(mContext.Get(mIsolate));
v8::TryCatch try_catch;
try_catch.SetVerbose(false);
ErrorReporter er(mIsolate, &try_catch, &mLastError, &mTerminated);
v8::Local<v8::Value> pfunc =
static_cast<v8::Persistent<v8::Value>*>(func)->Get(mIsolate);
v8::Local<v8::Function> vfunc = v8::Local<v8::Function>::Cast(pfunc);
v8::Local<v8::Value>* vargs = new v8::Local<v8::Value>[argc];
for (int i = 0; i < argc; i++) {
vargs[i] = static_cast<v8::Persistent<v8::Value>*>(argv[i])->Get(mIsolate);
}
// Global scope requested?
v8::Local<v8::Object> vself;
if (self == NULL) {
vself = mContext.Get(mIsolate)->Global();
} else {
v8::Local<v8::Value> pself =
static_cast<v8::Persistent<v8::Value>*>(self)->Get(mIsolate);
vself = v8::Local<v8::Object>::Cast(pself);
}
v8::Local<v8::Value> result = vfunc->Call(vself, argc, vargs);
delete[] vargs;
if (result.IsEmpty()) {
return NULL;
}
return new v8::Persistent<v8::Value>(mIsolate, result);
}
char* V8Context::PersistentToJSON(PersistentValuePtr persistent) {
v8::Locker locker(mIsolate);
v8::Isolate::Scope isolate_scope(mIsolate);
v8::HandleScope handle_scope(mIsolate);
v8::Context::Scope context_scope(mContext.Get(mIsolate));
v8::TryCatch try_catch;
v8::Local<v8::Value> persist =
static_cast<v8::Persistent<v8::Value>*>(persistent)->Get(mIsolate);
ErrorReporter er(mIsolate, &try_catch, &mLastError, &mTerminated);
std::string json_str = to_json(mIsolate, persist);
if (json_str == "") {
return NULL;
}
return strdup(json_str.c_str());
}
void V8Context::ReleasePersistent(PersistentValuePtr persistent) {
v8::Locker locker(mIsolate);
v8::Persistent<v8::Value>* persist =
static_cast<v8::Persistent<v8::Value>*>(persistent);
persist->Reset();
delete persist;
}
const char* V8Context::SetPersistentField(PersistentValuePtr persistent,
const char* field,
PersistentValuePtr value) {
v8::Locker locker(mIsolate);
v8::Isolate::Scope isolate_scope(mIsolate);
v8::HandleScope handle_scope(mIsolate);
v8::Context::Scope context_scope(mContext.Get(mIsolate));
v8::Persistent<v8::Value>* persist =
static_cast<v8::Persistent<v8::Value>*>(persistent);
v8::Local<v8::Value> name(v8::String::NewFromUtf8(mIsolate, field));
// Create the local object now, but reset the persistent one later:
// we could still fail setting the value, and then there is no point
// in re-creating the persistent copy.
v8::Local<v8::Value> maybeObject = persist->Get(mIsolate);
if (!maybeObject->IsObject()) {
return "The supplied receiver is not an object.";
}
// We can safely call `ToLocalChecked`, because
// we've just created the local object above.
v8::Local<v8::Object> object =
maybeObject->ToObject(mContext.Get(mIsolate)).ToLocalChecked();
v8::Persistent<v8::Value>* val =
static_cast<v8::Persistent<v8::Value>*>(value);
v8::Local<v8::Value> local_val = val->Get(mIsolate);
if (!object->Set(name, local_val)) {
return "Cannot set value";
}
// Now it is time to get rid of the previous persistent version,
// and create a new one.
persist->Reset(mIsolate, object);
return NULL;
}
KeyValuePair* V8Context::BurstPersistent(PersistentValuePtr persistent,
int* out_numKeys) {
v8::Locker locker(mIsolate);
v8::Isolate::Scope isolate_scope(mIsolate);
v8::HandleScope handle_scope(mIsolate);
v8::Context::Scope context_scope(mContext.Get(mIsolate));
v8::Persistent<v8::Value>* persist =
static_cast<v8::Persistent<v8::Value>*>(persistent);
mLastError.clear();
v8::Local<v8::Value> maybeObject = persist->Get(mIsolate);
if (!maybeObject->IsObject()) {
return NULL; // Triggers an error creation upstream.
}
// We can safely call `ToLocalChecked`, because
// we've just created the local object above.
v8::Local<v8::Object> object =
maybeObject->ToObject(mContext.Get(mIsolate)).ToLocalChecked();
v8::Local<v8::Array> keys(object->GetPropertyNames());
int num_keys = keys->Length();
*out_numKeys = num_keys;
KeyValuePair* result = new KeyValuePair[num_keys];
for (int i = 0; i < num_keys; i++) {
v8::Local<v8::Value> key = keys->Get(i);
result[i].keyName = strdup(str(key).c_str());
result[i].value = new v8::Persistent<v8::Value>(mIsolate, object->Get(key));
}
return result;
}
std::string ErrorReporter::report_exception(v8::TryCatch& try_catch) {
std::stringstream ss;
ss << "Uncaught exception: ";
std::string exceptionStr = str(try_catch.Exception());
if (exceptionStr == "[object Object]") {
ss << to_json(mIsolate, try_catch.Exception());
} else {
ss << exceptionStr;
}
if (!try_catch.Message().IsEmpty()) {
ss << std::endl
<< "at " << str(try_catch.Message()->GetScriptResourceName()) << ":"
<< try_catch.Message()->GetLineNumber() << ":"
<< try_catch.Message()->GetStartColumn() << ":"
<< str(try_catch.Message()->GetSourceLine());
}
if (!try_catch.StackTrace().IsEmpty()) {
ss << std::endl << "Stack trace: " << str(try_catch.StackTrace());
}
return ss.str();
}
void V8Context::Throw(const char* errmsg) {
v8::Locker locker(mIsolate);
v8::Isolate::Scope isolate_scope(mIsolate);
v8::HandleScope handle_scope(mIsolate);
v8::Context::Scope context_scope(mContext.Get(mIsolate));
v8::Local<v8::Value> err =
v8::Exception::Error(v8::String::NewFromUtf8(mIsolate, errmsg));
mIsolate->ThrowException(err);
}
char* V8Context::Error() {
v8::Locker locker(mIsolate);
return strdup(mLastError.c_str());
}
bool V8Context::HasTerminated() const {
return mTerminated;
}