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
566 lines (489 loc) · 18.7 KB
/
APITest.cpp
File metadata and controls
566 lines (489 loc) · 18.7 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/*
* 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/BCGen/HBC/BytecodeFileFormat.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 HermesRuntimeTestBase : public ::testing::Test {
public:
HermesRuntimeTestBase(::hermes::vm::RuntimeConfig runtimeConfig)
: rt(makeHermesRuntime(runtimeConfig)) {}
protected:
Value eval(const char *code) {
return rt->global().getPropertyAsFunction(*rt, "eval").call(*rt, code);
}
std::shared_ptr<HermesRuntime> rt;
};
class HermesRuntimeTest : public HermesRuntimeTestBase {
public:
HermesRuntimeTest()
: HermesRuntimeTestBase(::hermes::vm::RuntimeConfig::Builder()
.withES6Proxy(true)
.withES6Promise(true)
.build()) {}
};
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, DescriptionTest) {
// Minimally, if the description doesn't include "Hermes", something
// is wrong.
EXPECT_NE(rt->description().find("Hermes"), std::string::npos);
std::shared_ptr<facebook::jsi::Runtime> rt2 = makeHermesRuntime(
::hermes::vm::RuntimeConfig::Builder()
.withGCConfig(
::hermes::vm::GCConfig::Builder().withName("ForTesting").build())
.build());
EXPECT_NE(rt2->description().find("Hermes"), std::string::npos);
}
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);
int32_t *buffer = reinterpret_cast<int32_t *>(arrayBuffer.data(*rt));
EXPECT_EQ(buffer[0], 1234);
EXPECT_EQ(buffer[1], 5678);
}
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);
EXPECT_EQ(HermesRuntime::getBytecodeVersion(), hermes::hbc::BYTECODE_VERSION);
}
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, JumpTableBytecodeTest) {
std::string code = R"xyz(
(function(){
var i = 0;
switch (i) {
case 0:
return 5;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
}
})();
)xyz";
std::string bytecode;
ASSERT_TRUE(hermes::compileJS(code, bytecode));
auto ret =
rt->evaluateJavaScript(std::make_unique<StringBuffer>(bytecode), "");
ASSERT_EQ(ret.asNumber(), 5.0);
}
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, PreparedJavaScriptInvalidSourceBufferPrefix) {
// Construct a 0-terminated buffer that represents an invalid UTF-8 source.
char badSource[32];
memset((void *)badSource, '\xFE', sizeof(badSource));
badSource[31] = 0;
std::string prefix = "fefefefefefefefefefefefefefefefe";
std::string errMsg;
try {
rt->prepareJavaScript(std::make_unique<StringBuffer>(badSource), "");
} catch (const facebook::jsi::JSIException &err) {
errMsg = err.what();
}
// The error msg should include the prefix of buffer in expected formatting.
EXPECT_TRUE(errMsg.find(prefix) != std::string::npos);
}
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(HermesRuntimeCrashManagerTest, CrashGetStackTrace) {
class CrashManagerImpl : public hermes::vm::CrashManager {
public:
void registerMemory(void *, size_t) override {}
void unregisterMemory(void *) override {}
void setCustomData(const char *, const char *) override {}
void removeCustomData(const char *) override {}
void setContextualCustomData(const char *, const char *) override {}
void removeContextualCustomData(const char *) override {}
CallbackKey registerCallback(CallbackFunc cb) override {
auto key = callbacks.size();
callbacks.push_back(std::move(cb));
return key;
}
void unregisterCallback(CallbackKey /*key*/) override {}
void setHeapInfo(const HeapInformation & /*heapInfo*/) override {}
std::vector<CallbackFunc> callbacks;
};
auto cm = std::make_shared<CrashManagerImpl>();
auto rt = makeHermesRuntime(
hermes::vm::RuntimeConfig::Builder().withCrashMgr(cm).build());
Function runCrashCallbacks = Function::createFromHostFunction(
*rt,
PropNameID::forAscii(*rt, "runCrashCallbacks"),
0,
[&](Runtime &rt, const Value &, const Value *, size_t) {
// Create a temporary file to write the crash manager data to.
FILE *f = tmpfile();
for (const auto &cb : cm->callbacks)
cb(fileno(f));
const auto sz = ftell(f);
rewind(f);
// Dump the crash manager data to a std::string.
std::string out;
out.resize(sz);
const auto readsz = fread(&out[0], 1, sz, f);
EXPECT_EQ(readsz, sz);
fclose(f);
return String::createFromUtf8(rt, std::move(out));
});
rt->global().setProperty(
*rt, "runCrashCallbacks", std::move(runCrashCallbacks));
std::string jsCode = R"(
function baz(){ return runCrashCallbacks(); }
function bar(){ return baz(); }
function foo(){ return bar(); }
var out = foo();
// Extract just the source locations of the call stack.
JSON.stringify(JSON.parse(out).callstack.map(x => x.SourceLocation));
)";
auto buf = std::make_shared<StringBuffer>(std::move(jsCode));
std::string callstack =
rt->evaluateJavaScript(buf, "crashCode.js").asString(*rt).utf8(*rt);
const char *expected =
"[\"crashCode.js:2:41\",\"crashCode.js:3:27\",\"crashCode.js:4:27\",\"crashCode.js:5:14\",null]";
EXPECT_EQ(callstack, expected);
}
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, HasComputedTest) {
// The only use of JSObject::hasComputed() is in HermesRuntimeImpl,
// so we test its Proxy support here, instead of from JS.
EXPECT_FALSE(eval("'prop' in new Proxy({}, {})").getBool());
EXPECT_TRUE(eval("'prop' in new Proxy({prop:1}, {})").getBool());
EXPECT_FALSE(
eval("'prop' in new Proxy({}, {has() { return false; }})").getBool());
EXPECT_TRUE(
eval("'prop' in new Proxy({}, {has() { return true; }})").getBool());
// While we're here, test that a HostFunction can be used as a proxy
// trap. This could be very powerful in the right hands.
Function returnTrue = Function::createFromHostFunction(
*rt,
PropNameID::forAscii(*rt, "returnTrue"),
0,
[](Runtime &rt, const Value &, const Value *args, size_t count) {
EXPECT_EQ(count, 2);
EXPECT_EQ(args[1].toString(rt).utf8(rt), "prop");
return true;
});
rt->global().setProperty(*rt, "returnTrue", returnTrue);
EXPECT_TRUE(eval("'prop' in new Proxy({}, {has: returnTrue})").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);
}
class HermesRuntimeTestWithDisableGenerator : public HermesRuntimeTestBase {
public:
HermesRuntimeTestWithDisableGenerator()
: HermesRuntimeTestBase(::hermes::vm::RuntimeConfig::Builder()
.withEnableGenerator(false)
.build()) {}
};
TEST_F(HermesRuntimeTestWithDisableGenerator, WithDisableGenerator) {
try {
rt->evaluateJavaScript(
std::make_unique<StringBuffer>("function* foo() {}"), "");
FAIL() << "Expected JSIException";
} catch (const facebook::jsi::JSIException &err) {
}
try {
rt->evaluateJavaScript(
std::make_unique<StringBuffer>("obj = {*foo() {}}"), "");
FAIL() << "Expected JSIException";
} catch (const facebook::jsi::JSIException &err) {
}
// async function depends on generator.
try {
rt->evaluateJavaScript(
std::make_unique<StringBuffer>("async function foo() {}"), "");
FAIL() << "Expected JSIException";
} catch (const facebook::jsi::JSIException &err) {
}
}
} // namespace