forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPITest.cpp
More file actions
382 lines (322 loc) · 12.3 KB
/
Copy pathAPITest.cpp
File metadata and controls
382 lines (322 loc) · 12.3 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
381
382
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include <hermes/CompileJS.h>
#include <hermes/hermes.h>
using namespace facebook::jsi;
using namespace facebook::hermes;
struct HermesTestHelper {
static size_t rootsListLength(const HermesRuntime &rt) {
return rt.rootsListLength();
}
static int64_t calculateRootsListChange(
const HermesRuntime &rt,
std::function<void(void)> f) {
auto before = rootsListLength(rt);
f();
return rootsListLength(rt) - before;
}
};
namespace {
class HermesRuntimeTest : public ::testing::Test {
public:
HermesRuntimeTest() : rt(makeHermesRuntime()) {}
protected:
Value eval(const char *code) {
return rt->global().getPropertyAsFunction(*rt, "eval").call(*rt, code);
}
std::shared_ptr<HermesRuntime> rt;
};
using HermesRuntimeDeathTest = HermesRuntimeTest;
// In JSC there's a bug where host functions are always ran with a this in
// nonstrict mode so this must be a hermes only test. See
// https://es5.github.io/#x10.4.3 for more info.
TEST_F(HermesRuntimeTest, StrictHostFunctionBindTest) {
Function coolify = Function::createFromHostFunction(
*rt,
PropNameID::forAscii(*rt, "coolify"),
0,
[](Runtime &, const Value &thisVal, const Value *args, size_t count) {
EXPECT_TRUE(thisVal.isUndefined());
return thisVal.isUndefined();
});
rt->global().setProperty(*rt, "coolify", coolify);
EXPECT_TRUE(eval("(function() {"
" \"use strict\";"
" return coolify.bind(undefined)();"
"})()")
.getBool());
}
TEST_F(HermesRuntimeTest, ArrayBufferTest) {
eval(
"var buffer = new ArrayBuffer(16);\
var int32View = new Int32Array(buffer);\
int32View[0] = 1234;\
int32View[1] = 5678;");
Object object = rt->global().getPropertyAsObject(*rt, "buffer");
EXPECT_TRUE(object.isArrayBuffer(*rt));
auto arrayBuffer = object.getArrayBuffer(*rt);
EXPECT_EQ(arrayBuffer.size(*rt), 16);
#ifndef HERMESVM_API_TRACE
// Since synthetic benchmarks disallow raw memory access, don't do this test.
int32_t *buffer = reinterpret_cast<int32_t *>(arrayBuffer.data(*rt));
EXPECT_EQ(buffer[0], 1234);
EXPECT_EQ(buffer[1], 5678);
#endif
}
TEST_F(HermesRuntimeTest, BytecodeTest) {
const uint8_t shortBytes[] = {1, 2, 3};
EXPECT_FALSE(HermesRuntime::isHermesBytecode(shortBytes, 0));
EXPECT_FALSE(HermesRuntime::isHermesBytecode(shortBytes, sizeof(shortBytes)));
uint8_t longBytes[1024];
memset(longBytes, 'H', sizeof(longBytes));
EXPECT_FALSE(HermesRuntime::isHermesBytecode(longBytes, sizeof(longBytes)));
std::string bytecode;
ASSERT_TRUE(hermes::compileJS("x = 1", bytecode));
EXPECT_TRUE(HermesRuntime::isHermesBytecode(
reinterpret_cast<const uint8_t *>(bytecode.data()), bytecode.size()));
rt->evaluateJavaScript(
std::unique_ptr<StringBuffer>(new StringBuffer(bytecode)), "");
EXPECT_EQ(rt->global().getProperty(*rt, "x").getNumber(), 1);
}
TEST_F(HermesRuntimeTest, PreparedJavaScriptBytecodeTest) {
eval("var q = 0;");
std::string bytecode;
ASSERT_TRUE(hermes::compileJS("q++", bytecode));
auto prep =
rt->prepareJavaScript(std::make_unique<StringBuffer>(bytecode), "");
EXPECT_EQ(rt->global().getProperty(*rt, "q").getNumber(), 0);
rt->evaluatePreparedJavaScript(prep);
EXPECT_EQ(rt->global().getProperty(*rt, "q").getNumber(), 1);
rt->evaluatePreparedJavaScript(prep);
EXPECT_EQ(rt->global().getProperty(*rt, "q").getNumber(), 2);
}
TEST_F(HermesRuntimeTest, PreparedJavaScriptInvalidSourceThrows) {
const char *badSource = "this is definitely not valid javascript";
bool caught = false;
try {
rt->prepareJavaScript(std::make_unique<StringBuffer>(badSource), "");
} catch (const facebook::jsi::JSIException &err) {
caught = true;
}
EXPECT_TRUE(caught) << "prepareJavaScript should have thrown an exception";
}
TEST_F(HermesRuntimeTest, NoCorruptionOnJSError) {
// If the test crashes or infinite loops, the likely cause is that
// Hermes API library is not built with proper compiler flags
// (-fexception in GCC/CLANG, /EHsc in MSVC)
try {
rt->evaluateJavaScript(std::make_unique<StringBuffer>("foo.bar = 1"), "");
FAIL() << "Expected JSIException";
} catch (const facebook::jsi::JSIException &) {
// expected exception, ignore
}
try {
rt->evaluateJavaScript(std::make_unique<StringBuffer>("foo.baz = 1"), "");
FAIL() << "Expected JSIException";
} catch (const facebook::jsi::JSIException &) {
// expected exception, ignore
}
rt->evaluateJavaScript(std::make_unique<StringBuffer>("gc()"), "");
}
// In JSC we use multiple threads in our implementation of JSI so we can't
// use the ASSERT_DEATH macros when testing that implementation.
// Asserts are compiled out of opt builds
#if !defined(NDEBUG) && defined(ASSERT_DEATH)
TEST_F(HermesRuntimeDeathTest, ValueTest) {
ASSERT_DEATH(eval("'slay'").getNumber(), "Assertion.*isNumber");
ASSERT_DEATH(eval("123").getString(*rt), "Assertion.*isString");
}
#endif
TEST_F(HermesRuntimeTest, DontGrowWhenMoveObjectOutOfValue) {
Value val = Object(*rt);
auto rootsDelta = HermesTestHelper::calculateRootsListChange(*rt, [&]() {
Object obj = std::move(val).getObject(*rt);
(void)obj;
});
EXPECT_EQ(rootsDelta, 0);
}
TEST_F(HermesRuntimeTest, DontGrowWhenCloneObject) {
Value val = Object(*rt);
auto rootsDelta = HermesTestHelper::calculateRootsListChange(*rt, [&]() {
for (int i = 0; i < 1000; i++) {
Object obj = val.getObject(*rt);
(void)obj;
}
});
EXPECT_EQ(rootsDelta, 0);
}
TEST_F(HermesRuntimeTest, ScopeCleansUpObjectReferences) {
Object o1(*rt);
auto rootsDelta = HermesTestHelper::calculateRootsListChange(*rt, [&]() {
Scope s(*rt);
Object o2(*rt);
Object o3(*rt);
});
EXPECT_EQ(rootsDelta, 0);
}
TEST_F(HermesRuntimeTest, ReferencesCanEscapeScope) {
Value v;
auto rootsDelta = HermesTestHelper::calculateRootsListChange(*rt, [&]() {
Scope s(*rt);
Object o1(*rt);
Object o2(*rt);
Object o3(*rt);
v = std::move(o2);
});
EXPECT_EQ(rootsDelta, 1);
}
TEST_F(HermesRuntimeTest, HostObjectWithOwnProperties) {
class HostObjectWithPropertyNames : public HostObject {
std::vector<PropNameID> getPropertyNames(Runtime &rt) override {
return PropNameID::names(rt, "prop1", "1", "2", "prop2", "3");
}
Value get(Runtime &runtime, const PropNameID &name) override {
if (PropNameID::compare(
runtime, name, PropNameID::forAscii(runtime, "prop1")))
return 10;
return Value();
}
};
Object ho = Object::createFromHostObject(
*rt, std::make_shared<HostObjectWithPropertyNames>());
rt->global().setProperty(*rt, "ho", ho);
EXPECT_TRUE(eval("\"prop1\" in ho").getBool());
EXPECT_TRUE(eval("1 in ho").getBool());
EXPECT_TRUE(eval("2 in ho").getBool());
EXPECT_TRUE(eval("\"prop2\" in ho").getBool());
EXPECT_TRUE(eval("3 in ho").getBool());
// HostObjects say they own any property, even if it's not in their property
// names list.
// This is an explicit design choice, to avoid the runtime and API costs of
// handling checking for property existence.
EXPECT_TRUE(eval("\"foo\" in ho").getBool());
EXPECT_TRUE(eval("var properties = Object.getOwnPropertyNames(ho);"
"properties[0] === '1' && "
"properties[1] === '2' && "
"properties[2] === '3' && "
"properties[3] === 'prop1' && "
"properties[4] === 'prop2' && "
"properties.length === 5")
.getBool());
EXPECT_TRUE(eval("ho[2] === undefined").getBool());
EXPECT_TRUE(eval("ho.prop2 === undefined").getBool());
eval("Object.defineProperty(ho, '0', {value: 'hi there'})");
eval("Object.defineProperty(ho, '2', {value: 'hi there'})");
eval("Object.defineProperty(ho, '4', {value: 'hi there'})");
eval("Object.defineProperty(ho, 'prop2', {value: 'hi there'})");
EXPECT_TRUE(eval("var properties = Object.getOwnPropertyNames(ho);"
"properties[0] === '0' && "
"properties[1] === '1' && "
"properties[2] === '2' && "
"properties[3] === '3' && "
"properties[4] === '4' && "
"properties[5] === 'prop2' && "
"properties[6] === 'prop1' && "
"properties.length === 7")
.getBool());
EXPECT_TRUE(eval("ho[2] === 'hi there'").getBool());
EXPECT_TRUE(eval("ho.prop2 === 'hi there'").getBool());
// hasOwnProperty() always succeeds on HostObject
EXPECT_TRUE(
eval("Object.prototype.hasOwnProperty.call(ho, 'prop1')").getBool());
EXPECT_TRUE(
eval("Object.prototype.hasOwnProperty.call(ho, 'any-string')").getBool());
// getOwnPropertyDescriptor() always succeeds on HostObject
EXPECT_TRUE(eval("var d = Object.getOwnPropertyDescriptor(ho, 'prop1');"
"d != undefined && "
"d.value == 10 && "
"d.enumerable && "
"d.writable ")
.getBool());
EXPECT_TRUE(eval("var d = Object.getOwnPropertyDescriptor(ho, 'any-string');"
"d != undefined && "
"d.value == undefined && "
"d.enumerable && "
"d.writable")
.getBool());
}
// TODO mhorowitz: move this to jsi/testlib.cpp once we have impls for all VMs
TEST_F(HermesRuntimeTest, WeakReferences) {
Object o = eval("({one: 1})").getObject(*rt);
WeakObject wo = WeakObject(*rt, o);
rt->global().setProperty(*rt, "obj", o);
eval("gc()");
Value v = wo.lock(*rt);
// At this point, the object has three strong refs (C++ o, v; JS global.obj).
EXPECT_TRUE(v.isObject());
EXPECT_EQ(v.getObject(*rt).getProperty(*rt, "one").asNumber(), 1);
// Now start removing references.
v = nullptr;
// Two left
eval("gc()");
EXPECT_EQ(wo.lock(*rt).getObject(*rt).getProperty(*rt, "one").asNumber(), 1);
o = Object(*rt);
// Now one, only JS
eval("gc()");
EXPECT_EQ(wo.lock(*rt).getObject(*rt).getProperty(*rt, "one").asNumber(), 1);
eval("obj = null");
// Now none.
eval("gc()");
EXPECT_TRUE(wo.lock(*rt).isUndefined());
// test where the last ref is C++
o = eval("({two: 2})").getObject(*rt);
wo = WeakObject(*rt, o);
v = Value(*rt, o);
eval("gc()");
EXPECT_EQ(wo.lock(*rt).getObject(*rt).getProperty(*rt, "two").asNumber(), 2);
v = nullptr;
eval("gc()");
EXPECT_EQ(wo.lock(*rt).getObject(*rt).getProperty(*rt, "two").asNumber(), 2);
o = Object(*rt);
eval("gc()");
EXPECT_TRUE(wo.lock(*rt).isUndefined());
}
TEST_F(HermesRuntimeTest, SourceURLAppearsInBacktraceTest) {
std::string sourceURL = "//SourceURLAppearsInBacktraceTest/Test/URL";
std::string sourceCode = R"(
function thrower() { throw new Error('Test Error Message')}
function throws1() { thrower(); }
throws1();
)";
std::string bytecode;
bool compiled = hermes::compileJS(sourceCode, sourceURL.c_str(), bytecode);
ASSERT_TRUE(compiled) << "JS source should have compiled";
for (const std::string &code : {sourceCode, bytecode}) {
bool caught = false;
try {
rt->evaluateJavaScript(std::make_unique<StringBuffer>(code), sourceURL);
} catch (facebook::jsi::JSError &err) {
caught = true;
EXPECT_TRUE(err.getStack().find(sourceURL) != std::string::npos)
<< "Backtrace should contain source URL";
}
EXPECT_TRUE(caught) << "JS should have thrown an exception";
}
}
TEST_F(HermesRuntimeTest, HostObjectAsParentTest) {
class HostObjectWithProp : public HostObject {
Value get(Runtime &runtime, const PropNameID &name) override {
if (PropNameID::compare(
runtime, name, PropNameID::forAscii(runtime, "prop1")))
return 10;
return Value();
}
};
Object ho =
Object::createFromHostObject(*rt, std::make_shared<HostObjectWithProp>());
rt->global().setProperty(*rt, "ho", ho);
EXPECT_TRUE(
eval("var subClass = {__proto__: ho}; subClass.prop1 == 10;").getBool());
}
TEST_F(HermesRuntimeTest, GlobalObjectTest) {
rt->global().setProperty(*rt, "a", 5);
eval("f = function(b) { return a + b; }");
eval("gc()");
EXPECT_EQ(eval("f(10)").getNumber(), 15);
}
} // namespace