forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsoleHost.cpp
More file actions
462 lines (405 loc) · 14.6 KB
/
ConsoleHost.cpp
File metadata and controls
462 lines (405 loc) · 14.6 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
/*
* 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 "hermes/ConsoleHost/ConsoleHost.h"
#include "hermes/CompilerDriver/CompilerDriver.h"
#include "hermes/Support/MemoryBuffer.h"
#include "hermes/Support/UTF8.h"
#include "hermes/VM/Callable.h"
#include "hermes/VM/Domain.h"
#include "hermes/VM/JSObject.h"
#include "hermes/VM/MockedEnvironment.h"
#include "hermes/VM/NativeArgs.h"
#include "hermes/VM/Profiler/SamplingProfiler.h"
#include "hermes/VM/Runtime.h"
#include "hermes/VM/StringPrimitive.h"
#include "hermes/VM/StringView.h"
#include "hermes/VM/TimeLimitMonitor.h"
#include "hermes/VM/instrumentation/PerfEvents.h"
namespace hermes {
/// Raises an uncatchable quit exception.
static vm::CallResult<vm::HermesValue>
quit(void *, vm::Runtime *runtime, vm::NativeArgs) {
return runtime->raiseQuitError();
}
static void printStats(vm::Runtime *runtime, llvh::raw_ostream &os) {
std::string stats;
{
llvh::raw_string_ostream tmp{stats};
runtime->printHeapStats(tmp);
}
vm::instrumentation::PerfEvents::endAndInsertStats(stats);
os << stats;
}
static vm::CallResult<vm::HermesValue>
createHeapSnapshot(void *, vm::Runtime *runtime, vm::NativeArgs args) {
using namespace vm;
std::string fileName;
if (args.getArgCount() >= 1 && !args.getArg(0).isUndefined()) {
if (!args.getArg(0).isString()) {
return runtime->raiseTypeError("Filename argument must be a string");
}
auto str = Handle<StringPrimitive>::vmcast(args.getArgHandle(0));
auto jsFileName = StringPrimitive::createStringView(runtime, str);
llvh::SmallVector<char16_t, 16> buf;
convertUTF16ToUTF8WithReplacements(fileName, jsFileName.getUTF16Ref(buf));
}
if (fileName.empty()) {
// "-" is recognized as stdout.
fileName = "-";
} else if (!llvh::StringRef{fileName}.endswith(".heapsnapshot")) {
return runtime->raiseTypeError("Filename must end in .heapsnapshot");
}
if (auto err = runtime->getHeap().createSnapshotToFile(fileName)) {
// This isn't a TypeError, but no other built-in can express file errors,
// so this will have to do.
return runtime->raiseTypeError(
TwineChar16("Could not write out to the file located at \"") +
llvh::StringRef(fileName) +
"\". System error: " + llvh::StringRef(err.message()));
}
return HermesValue::encodeUndefinedValue();
}
static vm::CallResult<vm::HermesValue>
loadSegment(void *ctx, vm::Runtime *runtime, vm::NativeArgs args) {
using namespace hermes::vm;
const auto *baseFilename = reinterpret_cast<std::string *>(ctx);
auto requireContext = args.dyncastArg<RequireContext>(0);
if (!requireContext) {
return runtime->raiseTypeError(
"First argument to loadSegment must be context");
}
auto segmentRes = toUInt32_RJS(runtime, args.getArgHandle(1));
if (LLVM_UNLIKELY(segmentRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
uint32_t segment = segmentRes->getNumberAs<uint32_t>();
auto fileBufRes =
llvh::MemoryBuffer::getFile(Twine(*baseFilename) + "." + Twine(segment));
if (!fileBufRes) {
return runtime->raiseTypeError(
TwineChar16("Failed to open segment: ") + segment);
}
auto ret = hbc::BCProviderFromBuffer::createBCProviderFromBuffer(
llvh::make_unique<OwnedMemoryBuffer>(std::move(*fileBufRes)));
if (!ret.first) {
return runtime->raiseTypeError("Error deserializing bytecode");
}
if (LLVM_UNLIKELY(
runtime->loadSegment(std::move(ret.first), requireContext) ==
ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return HermesValue::encodeUndefinedValue();
}
#ifdef HERMESVM_SERIALIZE
static std::vector<void *> getNativeFunctionPtrs();
/// serializeVM(funciton() {/*resumed*/}, [filename]) will serialize the VM
/// state to a file. When deserialize from the file, we will continue to execute
/// the closure funciton provided. Serialize filename is specified by
/// -serializevm-path when provided, otherwise we will use the second argument.
static vm::CallResult<vm::HermesValue>
serializeVM(void *ctx, vm::Runtime *runtime, vm::NativeArgs args) {
using namespace vm;
if (!args.getArg(0).isObject()) {
return runtime->raiseTypeError("Invalid/Missing function argument");
}
std::unique_ptr<llvh::raw_ostream> serializeStream = nullptr;
if (ctx) {
const auto *fileName = reinterpret_cast<std::string *>(ctx);
std::error_code EC;
serializeStream =
llvh::make_unique<llvh::raw_fd_ostream>(llvh::StringRef(*fileName), EC);
if (EC) {
return runtime->raiseTypeError(
TwineChar16("Could not write to file located at ") +
llvh::StringRef(*fileName));
}
} else {
// See if filename is provided as an argument.
if (!args.getArg(1).isString()) {
return runtime->raiseTypeError(
"Missing filename argument or filename argument not a string");
}
std::string fileName;
// In the rare events where we have a UTF16 string, convert it to ASCII.
auto str = Handle<StringPrimitive>::vmcast(args.getArgHandle(1));
auto jsFileName = StringPrimitive::createStringView(runtime, str);
llvh::SmallVector<char16_t, 16> buf;
convertUTF16ToUTF8WithReplacements(fileName, jsFileName.getUTF16Ref(buf));
if (fileName.empty()) {
return runtime->raiseTypeError("Filename must not be empty");
}
std::error_code EC;
serializeStream =
llvh::make_unique<llvh::raw_fd_ostream>(llvh::StringRef(fileName), EC);
if (EC) {
return runtime->raiseTypeError(
TwineChar16("Could not write to file located at ") +
llvh::StringRef(fileName));
}
}
auto closureFunction = Handle<JSFunction>::vmcast(args.getArgHandle(0));
Serializer s(*serializeStream, runtime, getNativeFunctionPtrs);
runtime->setSerializeClosure(closureFunction);
runtime->serialize(s);
return HermesValue::encodeUndefinedValue();
}
/// Gather function pointers of native functions and put them in \p vec.
static std::vector<void *> getNativeFunctionPtrs() {
std::vector<void *> res;
res.push_back((void *)quit);
res.push_back((void *)createHeapSnapshot);
res.push_back((void *)serializeVM);
res.push_back((void *)loadSegment);
return res;
}
#endif
void installConsoleBindings(
vm::Runtime *runtime,
vm::StatSamplingThread *statSampler,
#ifdef HERMESVM_SERIALIZE
const std::string *serializePath,
#endif
const std::string *filename) {
vm::DefinePropertyFlags normalDPF =
vm::DefinePropertyFlags::getNewNonEnumerableFlags();
#if defined HERMESVM_SERIALIZE && !defined NDEBUG
// Verify that all native pointers can be captured by getNativeFunctionPtrs.
std::vector<void *> pointers = getNativeFunctionPtrs();
#endif
auto defineGlobalFunc = [&](vm::SymbolID name,
vm::NativeFunctionPtr functionPtr,
void *context,
unsigned paramCount) -> void {
vm::GCScopeMarkerRAII marker{runtime};
#ifdef HERMESVM_SERIALIZE
assert(
(std::find(pointers.begin(), pointers.end(), (void *)functionPtr) !=
pointers.end()) &&
"All function pointers must be added in getNativeFunctionPtrs");
#endif
auto func = vm::NativeFunction::createWithoutPrototype(
runtime, context, functionPtr, name, paramCount);
auto res = vm::JSObject::defineOwnProperty(
runtime->getGlobal(), runtime, name, normalDPF, func);
(void)res;
assert(
res != vm::ExecutionStatus::EXCEPTION && *res &&
"global.defineOwnProperty() failed");
};
// Define the 'quit' function.
defineGlobalFunc(
vm::Predefined::getSymbolID(vm::Predefined::quit), quit, nullptr, 0);
defineGlobalFunc(
vm::Predefined::getSymbolID(vm::Predefined::createHeapSnapshot),
createHeapSnapshot,
nullptr,
1);
#ifdef HERMESVM_SERIALIZE
defineGlobalFunc(
runtime
->ignoreAllocationFailure(
runtime->getIdentifierTable().getSymbolHandle(
runtime, llvh::createASCIIRef("serializeVM")))
.get(),
serializeVM,
reinterpret_cast<void *>(const_cast<std::string *>(serializePath)),
1);
#endif
// Define the 'loadSegment' function.
defineGlobalFunc(
runtime
->ignoreAllocationFailure(
runtime->getIdentifierTable().getSymbolHandle(
runtime, llvh::createASCIIRef("loadSegment")))
.get(),
loadSegment,
reinterpret_cast<void *>(const_cast<std::string *>(filename)),
2);
}
// If a function body might throw C++ exceptions other than
// jsi::JSError from Hermes, it should be wrapped in this form:
//
// return maybeCatchException([&] { body })
//
// This will execute body; if exceptions are enabled, this execution
// will be wrapped in a try/catch that catches those exceptions, report it then
// exit.
namespace {
template <typename F>
auto maybeCatchException(const F &f) -> decltype(f()) {
#if defined(HERMESVM_EXCEPTION_ON_OOM)
try {
return f();
} catch (const std::exception &ex) {
// Report thrown exception and exit the process with failure code.
llvh::errs() << ex.what();
exit(1);
}
#else // HERMESVM_EXCEPTION_ON_OOM
return f();
#endif
}
bool executeHBCBytecodeImpl(
std::shared_ptr<hbc::BCProvider> &&bytecode,
const ExecuteOptions &options,
const std::string *filename) {
bool shouldRecordGCStats =
options.runtimeConfig.getGCConfig().getShouldRecordStats();
if (shouldRecordGCStats) {
vm::instrumentation::PerfEvents::begin();
}
#ifdef HERMESVM_SERIALIZE
// Handle Serialization/Deserialization options
std::shared_ptr<llvh::raw_ostream> serializeFile = nullptr;
std::shared_ptr<llvh::MemoryBuffer> deserializeFile = nullptr;
if (!options.SerializeAfterInitFile.empty()) {
if (!options.DeserializeFile.empty()) {
llvh::errs()
<< "Cannot serialize and deserialize in the same execution\n";
return false;
}
std::error_code EC;
serializeFile = std::make_shared<llvh::raw_fd_ostream>(
llvh::StringRef(options.SerializeAfterInitFile), EC);
if (EC) {
llvh::errs() << "Failed to read Serialize file: "
<< options.SerializeAfterInitFile << "\n";
return false;
}
}
if (options.DeserializeFile != "") {
auto inputFileOrErr = llvh::MemoryBuffer::getFile(options.DeserializeFile);
if (!inputFileOrErr) {
llvh::errs() << "Failed to read Deserialize file: "
<< options.DeserializeFile << '\n';
return false;
}
deserializeFile = std::move(*inputFileOrErr);
}
#endif
std::unique_ptr<vm::StatSamplingThread> statSampler;
#ifdef HERMESVM_SERIALIZE
auto runtime = vm::Runtime::create(
options.runtimeConfig.rebuild()
.withSerializeAfterInitFile(serializeFile)
.withDeserializeFile(deserializeFile)
.withExternalPointersVectorCallBack(getNativeFunctionPtrs)
.build());
#else
auto runtime = vm::Runtime::create(options.runtimeConfig);
#endif
runtime->getJITContext().setDumpJITCode(options.dumpJITCode);
runtime->getJITContext().setCrashOnError(options.jitCrashOnError);
if (options.stabilizeInstructionCount) {
// Try to limit features that can introduce unpredictable CPU instruction
// behavior. Date is a potential cause, but is not handled currently.
vm::MockedEnvironment env;
env.mathRandomSeed = 0;
env.stabilizeInstructionCount = true;
runtime->setMockedEnvironment(env);
}
if (options.timeLimit > 0) {
vm::TimeLimitMonitor::getInstance().watchRuntime(
runtime.get(), options.timeLimit);
}
if (shouldRecordGCStats) {
statSampler = llvh::make_unique<vm::StatSamplingThread>(
std::chrono::milliseconds(100));
}
vm::GCScope scope(runtime.get());
installConsoleBindings(
runtime.get(),
statSampler.get(),
#ifdef HERMESVM_SERIALIZE
options.SerializeVMPath.empty() ? nullptr : &options.SerializeVMPath,
#endif
filename);
vm::RuntimeModuleFlags flags;
flags.persistent = true;
if (options.stopAfterInit) {
vm::Handle<vm::Domain> domain =
runtime->makeHandle(vm::Domain::create(runtime.get()));
if (LLVM_UNLIKELY(
vm::RuntimeModule::create(
runtime.get(),
domain,
facebook::hermes::debugger::kInvalidLocation,
std::move(bytecode),
flags) == vm::ExecutionStatus::EXCEPTION)) {
llvh::errs() << "Failed to initialize main RuntimeModule\n";
return false;
}
return true;
}
if (options.runtimeConfig.getEnableSampleProfiling()) {
vm::SamplingProfiler::getInstance()->enable();
}
llvh::StringRef sourceURL{};
vm::CallResult<vm::HermesValue> status = runtime->runBytecode(
std::move(bytecode),
flags,
sourceURL,
vm::Runtime::makeNullHandle<vm::Environment>());
if (options.runtimeConfig.getEnableSampleProfiling()) {
auto profiler = vm::SamplingProfiler::getInstance();
profiler->dumpChromeTrace(llvh::errs());
profiler->disable();
}
bool threwException = status == vm::ExecutionStatus::EXCEPTION;
if (threwException) {
// Make sure stdout catches up to stderr.
llvh::outs().flush();
runtime->printException(
llvh::errs(), runtime->makeHandle(runtime->getThrownValue()));
}
if (options.timeLimit > 0) {
vm::TimeLimitMonitor::getInstance().unwatchRuntime(runtime.get());
}
#ifdef HERMESVM_PROFILER_OPCODE
runtime->dumpOpcodeStats(llvh::outs());
#endif
#ifdef HERMESVM_PROFILER_JSFUNCTION
runtime->dumpJSFunctionStats();
#endif
#ifdef HERMESVM_PROFILER_EXTERN
if (options.patchProfilerSymbols) {
patchProfilerSymbols(runtime.get());
} else {
dumpProfilerSymbolMap(runtime.get(), options.profilerSymbolsFile);
}
#endif
#ifdef HERMESVM_PROFILER_NATIVECALL
runtime->dumpNativeCallStats(llvh::outs());
#endif
if (shouldRecordGCStats) {
llvh::errs() << "Process stats:\n";
statSampler->stop().printJSON(llvh::errs());
if (options.forceGCBeforeStats) {
runtime->collect("forced for stats");
}
printStats(runtime.get(), llvh::errs());
}
#ifdef HERMESVM_PROFILER_BB
if (options.basicBlockProfiling) {
runtime->getBasicBlockExecutionInfo().dump(llvh::errs());
}
#endif
return !threwException;
}
} // namespace
/// Executes the HBC bytecode provided in HermesVM.
/// \return true on success, false on error.
bool executeHBCBytecode(
std::shared_ptr<hbc::BCProvider> &&bytecode,
const ExecuteOptions &options,
const std::string *filename) {
return maybeCatchException([&] {
return executeHBCBytecodeImpl(std::move(bytecode), options, filename);
});
}
} // namespace hermes