-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathJscEngine.cc
More file actions
380 lines (314 loc) · 13.5 KB
/
JscEngine.cc
File metadata and controls
380 lines (314 loc) · 13.5 KB
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
/*
* Tencent is pleased to support the open source community by making ScriptX available.
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "JscEngine.h"
#include "../../src/Native.hpp"
#include "JscEngine.hpp"
#include "JscHelper.h"
#include "../../src/utils/Helper.hpp"
namespace script::jsc_backend {
static std::once_flag globalClassRefFlag{};
JSClassRef JscEngine::globalClass_{};
JSClassRef JscEngine::externalClass_{};
// When we link against high-version library
// but run with a low-version one, macOS/iOS linker just set the undefined symbols to nullptr.
// cast to void* to suppress g++ -Werror=address
bool JscEngine::hasByteBufferAPI_ = reinterpret_cast<void*>(&JSValueGetTypedArrayType) != nullptr;
JscEngine::JscEngine(std::shared_ptr<utils::MessageQueue> mq)
: messageQueue_(mq ? std::move(mq) : std::make_shared<utils::MessageQueue>()) {
std::call_once(globalClassRefFlag, []() {
JSClassDefinition global = kJSClassDefinitionEmpty;
global.className = "JscEngine";
globalClass_ = JSClassCreate(&global);
JSClassDefinition external = kJSClassDefinitionEmpty;
external.className = "JscExternal";
externalClass_ = JSClassCreate(&external);
});
virtualMachine_ = JSContextGroupCreate();
context_ = JSGlobalContextCreateInGroup(virtualMachine_, globalClass_);
JSObjectSetPrivate(JSContextGetGlobalObject(context_), this);
initInternalSymbols();
}
JscEngine::~JscEngine() = default;
// NOLINTNEXTLINE(bugprone-exception-escape)
void JscEngine::destroy() noexcept {
ScriptEngine::destroyUserData();
{
EngineScope scope(this);
// clear class registry
for (auto& r : classRegistry_) {
auto clazz = r.second.instanceClass;
if (clazz) JSClassRelease(clazz);
}
classRegistry_.clear();
keptReference_.clear();
internalStorageSymbol_.reset();
constructorMarkSymbol_.reset();
getInternalStorageBySymbolFunction_.reset();
isByteBuffer_.reset();
globalWeakBookkeeping_.clear();
}
isDestroying_ = true;
messageQueue_->removeMessageByTag(this);
JSGlobalContextRelease(context_);
JSContextGroupRelease(virtualMachine_);
delete this;
}
void JscEngine::initInternalSymbols() {
EngineScope scope(this);
// JSValueMakeSymbol isn't available on older version of JSCore (iOS < 13, macOS < 15),
// meanwhile JSCore don't export version marco nor runtime method to check version,
// and we don't want to add hard dependencies on macOS, iOS SDK to check version at runtime.
// So we just use script API to do this all the time, ignoring what JSCore we are
// compile against/running with.
try {
auto symbol = getGlobal().get("Symbol");
if (symbol.isFunction()) {
auto symbolFunc = symbol.asFunction();
internalStorageSymbol_ = symbolFunc.call({}, "InternalStorageSymbol");
constructorMarkSymbol_ = symbolFunc.call({}, "ConstructorMarkSymbol");
} else {
// on really old version of JSC, Symbol is not implemented, use String instead
internalStorageSymbol_ = String::newString("__ScriptX_InternalStorageSymbol__");
constructorMarkSymbol_ = String::newString("__ScriptX_ConstructorMarkSymbol__");
}
// same problem applies to JSObjectGetPropertyForKey & JSObjectSetPropertyForKey
getInternalStorageBySymbolFunction_ = static_cast<ScriptEngine*>(this)
->eval(R"(
(function () {
return function getOrCreateInternalStorage(obj, symbol) {
var ret = obj[symbol];
if (!Array.isArray(ret)) {
ret = [];
obj[symbol] = ret;
}
return ret;
}
})();
)")
.asFunction();
if (!hasByteBufferAPI_) {
isByteBuffer_ = eval(R"(
(function() {
return function isByteBuffer(val) {
return val instanceof ArrayBuffer ||
ArrayBuffer.isView(val);
};
})();
)")
.asFunction();
}
} catch (const Exception& e) {
// won't happen, if it does, crash the program.
throw std::runtime_error(e.message());
}
}
bool JscEngine::isConstructorMarkSymbol(JSValueRef value) {
return JSValueIsStrictEqual(context_, value, toJsc(context_, constructorMarkSymbol_.get()));
}
Local<Object> JscEngine::getGlobal() { return Local<Object>(JSContextGetGlobalObject(context_)); }
script::Local<script::Value> JscEngine::get(const script::Local<script::String>& key) {
return getGlobal().get(key);
}
void JscEngine::set(const script::Local<script::String>& key,
const script::Local<script::Value>& value) {
getGlobal().set(key, value);
}
script::Local<script::Value> JscEngine::eval(const script::Local<script::String>& script,
const Local<Value>& sourceFile) {
Tracer trace(this, "JscEngine::eval");
auto scriptString = script.val_.getString(context_);
auto sourceFileString = sourceFile.isString()
? sourceFile.asString().val_.getSharedStringRef(context_)
: jsc_backend::StringLocalRef::SharedStringRef{nullptr};
JSValueRef jscException = nullptr;
Local<Value> ret(JSEvaluateScript(context_, scriptString, JSContextGetGlobalObject(context_),
sourceFileString.get(), 0, &jscException));
jsc_backend::JscEngine::checkException(jscException);
return ret;
}
script::Local<script::Value> JscEngine::eval(const script::Local<script::String>& script,
const Local<String>& sourceFile) {
return eval(script, sourceFile.asValue());
}
script::Local<script::Value> JscEngine::eval(const script::Local<script::String>& script) {
return eval(script, {});
}
Local<Value> JscEngine::loadFile(const Local<String>& scriptFile) {
if(scriptFile.toString().empty())
throw Exception("script file no found");
Local<Value> content = internal::readAllFileContent(scriptFile);
if(content.isNull())
throw Exception("can't load script file");
std::string sourceFilePath = scriptFile.toString();
std::size_t pathSymbol = sourceFilePath.rfind("/");
if(pathSymbol != -1)
sourceFilePath = sourceFilePath.substr(pathSymbol + 1);
else
{
pathSymbol = sourceFilePath.rfind("\\");
if(pathSymbol != -1)
sourceFilePath = sourceFilePath.substr(pathSymbol + 1);
}
Local<String> sourceFileName = String::newString(sourceFilePath);
return eval(content.asString(), sourceFileName);
}
std::shared_ptr<utils::MessageQueue> JscEngine::messageQueue() { return messageQueue_; }
void JscEngine::gc() {
if (isDestroying()) return;
EngineScope engineScope(this);
JSGarbageCollect(context_);
}
void JscEngine::adjustAssociatedMemory(int64_t /*count*/) {
if (isDestroying()) return;
// JSC have implemented this method
// but not exported to public header...
}
size_t JscEngine::keepReference(const Local<Value>& ref) {
auto id = keepId_++;
keptReference_.emplace(id, ref);
return id;
}
void JscEngine::removeKeptReference(size_t id) {
EngineScope scope(this);
keptReference_.erase(id);
}
Arguments JscEngine::newArguments(JscEngine* engine, JSObjectRef thisObject,
const JSValueRef* arguments, size_t size) {
ArgumentsData data{engine, thisObject, arguments, size};
return Arguments(data);
}
void JscEngine::registerStaticDefine(const internal::StaticDefine& staticDefine,
const Local<Object>& object) {
for (auto& func : staticDefine.functions) {
StackFrameScope stack;
Local<Function> jsFunc = newStaticFunction(func);
object.set(func.name, jsFunc);
}
if (!staticDefine.properties.empty()) {
auto Object = getGlobal().get("Object").asObject();
auto def = Object.get("defineProperty").asFunction();
auto get = String::newString("get");
auto set = String::newString("set");
for (auto& prop : staticDefine.properties) {
Local<Value> getter = newStaticGetter(prop);
Local<Value> setter = newStaticSetter(prop);
auto desc = Object::newObject();
if (!getter.isNull()) desc.set(get, getter);
if (!setter.isNull()) desc.set(set, setter);
def.call(Object, {object, String::newString(prop.name), desc});
}
}
}
Local<Value> JscEngine::newStaticSetter(const internal::StaticDefine::PropertyDefine& prop) {
// setter may null
if (prop.setter == nullptr) return {};
using S = typename internal::StaticDefine::PropertyDefine;
using ContextData = std::pair<S*, JscEngine*>;
JSClassDefinition jsFunc = kJSClassDefinitionEmpty;
jsFunc.className = "setter";
jsFunc.callAsFunction = [](JSContextRef /*ctx*/, JSObjectRef function, JSObjectRef thisObject,
size_t argumentCount,
// NOLINTNEXTLINE (cppcoreguidelines-avoid-c-arrays)
const JSValueRef arguments[], JSValueRef* exception) {
auto contextData = static_cast<ContextData*>(JSObjectGetPrivate(function));
auto setter = contextData->first;
auto engine = contextData->second;
Tracer trace(engine, setter->traceName);
auto args = newArguments(engine, thisObject, arguments, argumentCount);
if (args.size() > 0) {
try {
(setter->setter)(args[0]);
} catch (Exception& e) {
*exception = jsc_backend::JscEngine::toJsc(engine->context_, e.exception());
}
}
return JSValueMakeUndefined(engine->context_);
};
jsFunc.finalize = [](JSObjectRef function) {
delete static_cast<ContextData*>(JSObjectGetPrivate(function));
};
auto funcClazz = JSClassCreate(&jsFunc);
Local<Function> ret(
JSObjectMake(context_, funcClazz, new ContextData(const_cast<S*>(&prop), this)));
JSClassRelease(funcClazz);
return ret;
}
Local<Value> JscEngine::newStaticGetter(const internal::StaticDefine::PropertyDefine& prop) {
if (prop.getter == nullptr) return {};
using G = typename internal::StaticDefine::PropertyDefine;
using ContextData = std::pair<G*, JscEngine*>;
JSClassDefinition jsFunc = kJSClassDefinitionEmpty;
jsFunc.className = "getter";
jsFunc.callAsFunction = [](JSContextRef /*ctx*/, JSObjectRef function, JSObjectRef thisObject,
size_t argumentCount,
// NOLINTNEXTLINE (cppcoreguidelines-avoid-c-arrays)
const JSValueRef arguments[], JSValueRef* exception) {
auto contextData = static_cast<ContextData*>(JSObjectGetPrivate(function));
auto getter = contextData->first;
auto engine = contextData->second;
Tracer trace(engine, getter->traceName);
auto args = newArguments(engine, thisObject, arguments, argumentCount);
try {
auto value = (getter->getter)();
return toJsc(engine->context_, value);
} catch (Exception& e) {
*exception = jsc_backend::JscEngine::toJsc(engine->context_, e.exception());
return JSValueMakeUndefined(currentEngineContextChecked());
}
};
jsFunc.finalize = [](JSObjectRef function) {
delete static_cast<ContextData*>(JSObjectGetPrivate(function));
};
auto funcClazz = JSClassCreate(&jsFunc);
Local<Function> ret(JSObjectMake(currentEngineContextChecked(), funcClazz,
new ContextData(const_cast<G*>(&prop), this)));
JSClassRelease(funcClazz);
return ret;
}
Local<Function> JscEngine::newStaticFunction(const internal::StaticDefine::FunctionDefine& func) {
using ContextData = std::pair<internal::StaticDefine::FunctionDefine*, JscEngine*>;
JSClassDefinition jsFunc = kJSClassDefinitionEmpty;
jsFunc.className = "anonymous";
jsFunc.callAsFunction = [](JSContextRef /*ctx*/, JSObjectRef function, JSObjectRef thisObject,
// NOLINTNEXTLINE (cppcoreguidelines-avoid-c-arrays)
size_t argumentCount, const JSValueRef arguments[],
JSValueRef* exception) {
auto funcPtr = static_cast<ContextData*>(JSObjectGetPrivate(function));
auto engine = funcPtr->second;
Tracer trace(engine, funcPtr->first->traceName);
auto args = newArguments(engine, thisObject, arguments, argumentCount);
try {
auto returnVal = (funcPtr->first->callback)(args);
return toJsc(engine->context_, returnVal);
} catch (Exception& e) {
*exception = jsc_backend::JscEngine::toJsc(engine->context_, e.exception());
return JSValueMakeUndefined(engine->context_);
}
};
jsFunc.finalize = [](JSObjectRef function) {
delete static_cast<ContextData*>(JSObjectGetPrivate(function));
};
auto funcClazz = JSClassCreate(&jsFunc);
Local<Function> funcObj(JSObjectMake(
currentEngineContextChecked(), funcClazz,
new ContextData(const_cast<internal::StaticDefine::FunctionDefine*>(&func), this)));
JSClassRelease(funcClazz);
return funcObj;
}
script::ScriptLanguage JscEngine::getLanguageType() { return ScriptLanguage::kJavaScript; }
std::string JscEngine::getEngineVersion() { return "JavaScriptCore v-unknown"; }
} // namespace script::jsc_backend