forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTracingRuntime.cpp
More file actions
752 lines (681 loc) · 25.1 KB
/
TracingRuntime.cpp
File metadata and controls
752 lines (681 loc) · 25.1 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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
/*
* 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.
*/
#ifdef HERMESVM_API_TRACE
#include "TracingRuntime.h"
#include <hermes/Platform/Logging.h>
#include <hermes/Support/Algorithms.h>
#include <hermes/Support/JSONEmitter.h>
#include <llvh/Support/raw_ostream.h>
#include "llvh/Support/FileSystem.h"
#include "llvh/Support/SHA1.h"
namespace facebook {
namespace hermes {
namespace tracing {
TracingRuntime::TracingRuntime(
std::unique_ptr<jsi::Runtime> runtime,
uint64_t globalID,
const ::hermes::vm::RuntimeConfig &conf,
std::unique_ptr<llvh::raw_ostream> traceStream)
: RuntimeDecorator<jsi::Runtime>(*runtime),
runtime_(std::move(runtime)),
trace_(globalID, conf, std::move(traceStream)) {}
jsi::Value TracingRuntime::evaluateJavaScript(
const std::shared_ptr<const jsi::Buffer> &buffer,
const std::string &sourceURL) {
::hermes::SHA1 sourceHash{};
bool sourceIsBytecode = false;
if (HermesRuntime::isHermesBytecode(buffer->data(), buffer->size())) {
sourceHash = ::hermes::hbc::BCProviderFromBuffer::getSourceHashFromBytecode(
llvh::makeArrayRef(buffer->data(), buffer->size()));
sourceIsBytecode = true;
} else {
sourceHash =
llvh::SHA1::hash(llvh::makeArrayRef(buffer->data(), buffer->size()));
}
trace_.emplace_back<SynthTrace::BeginExecJSRecord>(
getTimeSinceStart(), sourceURL, sourceHash, sourceIsBytecode);
auto res = RD::evaluateJavaScript(buffer, sourceURL);
trace_.emplace_back<SynthTrace::EndExecJSRecord>(
getTimeSinceStart(), toTraceValue(res));
return res;
}
jsi::Object TracingRuntime::createObject() {
auto obj = RD::createObject();
trace_.emplace_back<SynthTrace::CreateObjectRecord>(
getTimeSinceStart(), getUniqueID(obj));
return obj;
}
jsi::Object TracingRuntime::createObject(std::shared_ptr<jsi::HostObject> ho) {
class TracingHostObject : public jsi::DecoratedHostObject {
public:
using jsi::DecoratedHostObject::DecoratedHostObject;
jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &name) override {
TracingRuntime &trt = tracingRuntime();
trt.trace_.emplace_back<SynthTrace::GetPropertyNativeRecord>(
trt.getTimeSinceStart(),
objID_,
trt.getUniqueID(name),
name.utf8(rt));
try {
// Note that this ignores the "rt" argument, passing the
// DHO's cached decoratedRuntime() to the underlying HostObject's get.
// In this case, that will be a TracingRuntime.
auto ret = DecoratedHostObject::get(rt, name);
trt.trace_.emplace_back<SynthTrace::GetPropertyNativeReturnRecord>(
trt.getTimeSinceStart(), trt.toTraceValue(ret));
return ret;
} catch (...) {
// TODO(T28293178): The trace currently has no way to model
// exceptions thrown from C++ code.
::hermes::hermes_fatal(
"Exception happened in native code during trace");
}
}
void set(
jsi::Runtime &rt,
const jsi::PropNameID &name,
const jsi::Value &value) override {
TracingRuntime &trt = tracingRuntime();
trt.trace_.emplace_back<SynthTrace::SetPropertyNativeRecord>(
trt.getTimeSinceStart(),
objID_,
trt.getUniqueID(name),
name.utf8(rt),
trt.toTraceValue(value));
try {
// Note that this ignores the "rt" argument, passing the
// DHO's cached decoratedRuntime() to the underlying HostObject's set.
// In this case, that will be a TracingRuntime.
DecoratedHostObject::set(rt, name, value);
} catch (...) {
// TODO(T28293178): The trace currently has no way to model
// exceptions thrown from C++ code.
::hermes::hermes_fatal(
"Exception happened in native code during trace");
}
trt.trace_.emplace_back<SynthTrace::SetPropertyNativeReturnRecord>(
trt.getTimeSinceStart());
}
std::vector<jsi::PropNameID> getPropertyNames(jsi::Runtime &rt) override {
TracingRuntime &trt = tracingRuntime();
trt.trace_.emplace_back<SynthTrace::GetNativePropertyNamesRecord>(
trt.getTimeSinceStart(), objID_);
std::vector<jsi::PropNameID> props;
try {
// Note that this ignores the "rt" argument, passing the
// DHO's cached decoratedRuntime() to the underlying HostObject's
// getProprtyNames. In this case, that will be a TracingRuntime.
props = DecoratedHostObject::getPropertyNames(rt);
} catch (...) {
// TODO(T28293178): The trace currently has no way to model
// exceptions thrown from C++ code.
::hermes::hermes_fatal(
"Exception happened in native code during trace");
}
std::vector<std::string> names;
names.reserve(props.size());
for (const jsi::PropNameID &prop : props) {
names.emplace_back(prop.utf8(rt));
}
trt.trace_.emplace_back<SynthTrace::GetNativePropertyNamesReturnRecord>(
trt.getTimeSinceStart(), names);
return props;
}
void setObjectID(SynthTrace::ObjectID id) {
objID_ = id;
}
private:
/// The TracingRuntime used when the TracingHostObject was created.
TracingRuntime &tracingRuntime() {
// A TracingHostObject is always created with a TracingRuntime,
// so this cast is safe.
return static_cast<TracingRuntime &>(decoratedRuntime());
}
/// The object id of the host object that this is attached to.
SynthTrace::ObjectID objID_;
};
// These next two lines are very similar to the body of
// RD::createObject:
// return plain_.createObject(
// std::make_shared<DecoratedHostObject>(*this, std::move(ho)));
// but (a) using the TracingHostObject subtype of
// DecoratedHostObject, and (b) using createFromHostObject, because
// createObject is protected, and is thus inaccessible here.
auto tracer = std::make_shared<TracingHostObject>(*this, ho);
auto obj = jsi::Object::createFromHostObject(plain(), tracer);
tracer->setObjectID(getUniqueID(obj));
trace_.emplace_back<SynthTrace::CreateHostObjectRecord>(
getTimeSinceStart(), getUniqueID(obj));
return obj;
}
jsi::String TracingRuntime::createStringFromAscii(
const char *str,
size_t length) {
jsi::String res = RD::createStringFromAscii(str, length);
trace_.emplace_back<SynthTrace::CreateStringRecord>(
getTimeSinceStart(), getUniqueID(res), str, length);
return res;
};
jsi::String TracingRuntime::createStringFromUtf8(
const uint8_t *utf8,
size_t length) {
jsi::String res = RD::createStringFromUtf8(utf8, length);
trace_.emplace_back<SynthTrace::CreateStringRecord>(
getTimeSinceStart(), getUniqueID(res), utf8, length);
return res;
};
jsi::PropNameID TracingRuntime::createPropNameIDFromAscii(
const char *str,
size_t length) {
jsi::PropNameID res = RD::createPropNameIDFromAscii(str, length);
trace_.emplace_back<SynthTrace::CreatePropNameIDRecord>(
getTimeSinceStart(), getUniqueID(res), str, length);
return res;
}
jsi::PropNameID TracingRuntime::createPropNameIDFromUtf8(
const uint8_t *utf8,
size_t length) {
jsi::PropNameID res = RD::createPropNameIDFromUtf8(utf8, length);
trace_.emplace_back<SynthTrace::CreatePropNameIDRecord>(
getTimeSinceStart(), getUniqueID(res), utf8, length);
return res;
}
jsi::PropNameID TracingRuntime::createPropNameIDFromString(
const jsi::String &str) {
std::string s = str.utf8(*this);
jsi::PropNameID res = RD::createPropNameIDFromString(str);
trace_.emplace_back<SynthTrace::CreatePropNameIDRecord>(
getTimeSinceStart(), getUniqueID(res), std::move(s), /* isAscii */ false);
return res;
}
jsi::Value TracingRuntime::getProperty(
const jsi::Object &obj,
const jsi::String &name) {
auto value = RD::getProperty(obj, name);
trace_.emplace_back<SynthTrace::GetPropertyRecord>(
getTimeSinceStart(),
getUniqueID(obj),
getUniqueID(name),
#ifdef HERMESVM_API_TRACE_DEBUG
name.utf8(*this),
#endif
toTraceValue(value));
return value;
}
jsi::Value TracingRuntime::getProperty(
const jsi::Object &obj,
const jsi::PropNameID &name) {
auto value = RD::getProperty(obj, name);
trace_.emplace_back<SynthTrace::GetPropertyRecord>(
getTimeSinceStart(),
getUniqueID(obj),
getUniqueID(name),
#ifdef HERMESVM_API_TRACE_DEBUG
name.utf8(*this),
#endif
toTraceValue(value));
return value;
}
bool TracingRuntime::hasProperty(
const jsi::Object &obj,
const jsi::String &name) {
trace_.emplace_back<SynthTrace::HasPropertyRecord>(
getTimeSinceStart(),
getUniqueID(obj),
getUniqueID(name)
#ifdef HERMESVM_API_TRACE_DEBUG
,
name.utf8(*this)
#endif
);
return RD::hasProperty(obj, name);
}
bool TracingRuntime::hasProperty(
const jsi::Object &obj,
const jsi::PropNameID &name) {
trace_.emplace_back<SynthTrace::HasPropertyRecord>(
getTimeSinceStart(),
getUniqueID(obj),
getUniqueID(name)
#ifdef HERMESVM_API_TRACE_DEBUG
,
name.utf8(*this)
#endif
);
return RD::hasProperty(obj, name);
}
void TracingRuntime::setPropertyValue(
jsi::Object &obj,
const jsi::String &name,
const jsi::Value &value) {
trace_.emplace_back<SynthTrace::SetPropertyRecord>(
getTimeSinceStart(),
getUniqueID(obj),
getUniqueID(name),
#ifdef HERMESVM_API_TRACE_DEBUG
name.utf8(*this),
#endif
toTraceValue(value));
RD::setPropertyValue(obj, name, value);
}
void TracingRuntime::setPropertyValue(
jsi::Object &obj,
const jsi::PropNameID &name,
const jsi::Value &value) {
trace_.emplace_back<SynthTrace::SetPropertyRecord>(
getTimeSinceStart(),
getUniqueID(obj),
getUniqueID(name),
#ifdef HERMESVM_API_TRACE_DEBUG
name.utf8(*this),
#endif
toTraceValue(value));
RD::setPropertyValue(obj, name, value);
}
jsi::Array TracingRuntime::getPropertyNames(const jsi::Object &o) {
jsi::Array arr = RD::getPropertyNames(o);
trace_.emplace_back<SynthTrace::GetPropertyNamesRecord>(
getTimeSinceStart(), getUniqueID(o), getUniqueID(arr));
return arr;
}
jsi::WeakObject TracingRuntime::createWeakObject(const jsi::Object &o) {
// WeakObject is not traced for two reasons:
// It has no effect on the correctness of replay:
// Say an object that is created, then a WeakObject created for
// that object. At some point in the future, lockWeakObject is called. At
// that point, either the original object was dead, and lockWeakObject
// returns an undefined value; else, the original object is still alive, and
// it returns the object reference. For an undefined return, there will be no
// further operations on the object, and the replay will delete it. If that
// returned object is then used for some operation such as getProperty, the
// trace will see that and record that the object was alive for at least that
// long. So it doesn't matter that the WeakObject was created at all, the
// lifetime is unaffected.
// lockWeakObject can have a non-deterministic return value:
// Because the return value of lockWeakObject is non-deterministic, there's
// no guarantee that replaying lockWeakObject will have the same return
// value. The GC may have run at different times on replay then it originally
// did. Making this deterministic would require adding the GC schedule to
// synth traces, which might not even be possible for a concurrent GC. So
// tracing lockWeakObject would not guarantee correct replay of WeakObject
// operations.
return RD::createWeakObject(o);
}
jsi::Value TracingRuntime::lockWeakObject(jsi::WeakObject &wo) {
// See comment in TracingRuntime::createWeakObject for why this function isn't
// traced.
return RD::lockWeakObject(wo);
}
jsi::Array TracingRuntime::createArray(size_t length) {
auto arr = RD::createArray(length);
trace_.emplace_back<SynthTrace::CreateArrayRecord>(
getTimeSinceStart(), getUniqueID(arr), length);
return arr;
}
size_t TracingRuntime::size(const jsi::Array &arr) {
// Array size inquiries read from the length property, which is
// non-configurable and thus cannot have side effects.
return RD::size(arr);
}
size_t TracingRuntime::size(const jsi::ArrayBuffer &buf) {
// ArrayBuffer size inquiries read from the byteLength property, which is
// non-configurable and thus cannot have side effects.
return RD::size(buf);
}
uint8_t *TracingRuntime::data(const jsi::ArrayBuffer &buf) {
throw std::logic_error(
"Cannot write raw bytes into an ArrayBuffer in trace mode");
}
jsi::Value TracingRuntime::getValueAtIndex(const jsi::Array &arr, size_t i) {
auto value = RD::getValueAtIndex(arr, i);
trace_.emplace_back<SynthTrace::ArrayReadRecord>(
getTimeSinceStart(), getUniqueID(arr), i, toTraceValue(value));
return value;
}
void TracingRuntime::setValueAtIndexImpl(
jsi::Array &arr,
size_t i,
const jsi::Value &value) {
trace_.emplace_back<SynthTrace::ArrayWriteRecord>(
getTimeSinceStart(), getUniqueID(arr), i, toTraceValue(value));
return RD::setValueAtIndexImpl(arr, i, value);
}
jsi::Function TracingRuntime::createFunctionFromHostFunction(
const jsi::PropNameID &name,
unsigned int paramCount,
jsi::HostFunctionType func) {
class TracingHostFunction : public jsi::DecoratedHostFunction {
public:
using jsi::DecoratedHostFunction::DecoratedHostFunction;
jsi::Value operator()(
jsi::Runtime &rt,
const jsi::Value &thisVal,
const jsi::Value *args,
size_t count) {
TracingRuntime &trt = static_cast<TracingRuntime &>(rt);
trt.trace_.emplace_back<SynthTrace::CallToNativeRecord>(
trt.getTimeSinceStart(),
functionID_,
// A host function does not have a this.
SynthTrace::encodeUndefined(),
trt.argStringifyer(args, count));
try {
auto ret =
jsi::DecoratedHostFunction::operator()(rt, thisVal, args, count);
trt.trace_.emplace_back<SynthTrace::ReturnFromNativeRecord>(
trt.getTimeSinceStart(), trt.toTraceValue(ret));
return ret;
} catch (...) {
// TODO(T28293178): The trace currently has no way to model
// exceptions thrown from C++ code.
::hermes::hermes_fatal(
"Exception happened in native code during trace");
}
}
void setFunctionID(SynthTrace::ObjectID functionID) {
functionID_ = functionID;
}
private:
/// The object id of the function that this is attached to.
SynthTrace::ObjectID functionID_;
};
auto tracer = TracingHostFunction(*this, func);
auto tfunc =
RD::createFunctionFromHostFunction(name, paramCount, std::move(tracer));
const auto funcID = getUniqueID(tfunc);
RD::getHostFunction(tfunc).target<TracingHostFunction>()->setFunctionID(
funcID);
trace_.emplace_back<SynthTrace::CreateHostFunctionRecord>(
getTimeSinceStart(),
funcID,
getUniqueID(name),
#ifdef HERMESVM_API_TRACE_DEBUG
name.utf8(*this),
#endif
paramCount);
return tfunc;
}
jsi::Value TracingRuntime::call(
const jsi::Function &func,
const jsi::Value &jsThis,
const jsi::Value *args,
size_t count) {
trace_.emplace_back<SynthTrace::CallFromNativeRecord>(
getTimeSinceStart(),
getUniqueID(func),
toTraceValue(jsThis),
argStringifyer(args, count));
auto retval = RD::call(func, jsThis, args, count);
trace_.emplace_back<SynthTrace::ReturnToNativeRecord>(
getTimeSinceStart(), toTraceValue(retval));
return retval;
}
jsi::Value TracingRuntime::callAsConstructor(
const jsi::Function &func,
const jsi::Value *args,
size_t count) {
trace_.emplace_back<SynthTrace::ConstructFromNativeRecord>(
getTimeSinceStart(),
getUniqueID(func),
// A construct call always has an undefined this.
// The ReturnToNativeRecord will contain the object that was either
// created by the new keyword, or the objec that's returned from the
// function.
SynthTrace::encodeUndefined(),
argStringifyer(args, count));
auto retval = RD::callAsConstructor(func, args, count);
trace_.emplace_back<SynthTrace::ReturnToNativeRecord>(
getTimeSinceStart(), toTraceValue(retval));
return retval;
}
void TracingRuntime::addMarker(const std::string &marker) {
trace_.emplace_back<SynthTrace::MarkerRecord>(getTimeSinceStart(), marker);
}
std::vector<SynthTrace::TraceValue> TracingRuntime::argStringifyer(
const jsi::Value *args,
size_t count) {
std::vector<SynthTrace::TraceValue> stringifiedArgs;
stringifiedArgs.reserve(count);
for (size_t i = 0; i < count; ++i) {
stringifiedArgs.emplace_back(toTraceValue(args[i]));
}
return stringifiedArgs;
}
SynthTrace::TraceValue TracingRuntime::toTraceValue(const jsi::Value &value) {
if (value.isUndefined()) {
return SynthTrace::encodeUndefined();
} else if (value.isNull()) {
return SynthTrace::encodeNull();
} else if (value.isBool()) {
return SynthTrace::encodeBool(value.getBool());
} else if (value.isNumber()) {
return SynthTrace::encodeNumber(value.getNumber());
} else if (value.isString()) {
return trace_.encodeString(getUniqueID(value.getString(*this)));
} else if (value.isObject()) {
// Get a unique identifier from the object, and use that instead. This is
// so that object identity is tracked.
return SynthTrace::encodeObject(getUniqueID(value.getObject(*this)));
} else {
throw std::logic_error("Unsupported value reached");
}
}
SynthTrace::TimeSinceStart TracingRuntime::getTimeSinceStart() const {
return std::chrono::duration_cast<SynthTrace::TimeSinceStart>(
std::chrono::steady_clock::now() - startTime_);
}
TracingHermesRuntime::TracingHermesRuntime(
std::unique_ptr<HermesRuntime> runtime,
const ::hermes::vm::RuntimeConfig &runtimeConfig,
std::unique_ptr<llvh::raw_ostream> traceStream,
std::function<std::string()> commitAction,
std::function<void()> rollbackAction)
: TracingHermesRuntime(
runtime,
runtime->getUniqueID(runtime->global()),
runtimeConfig,
std::move(traceStream),
std::move(commitAction),
std::move(rollbackAction)) {}
TracingHermesRuntime::~TracingHermesRuntime() {
if (crashCallbackKey_) {
conf_.getCrashMgr()->unregisterCallback(*crashCallbackKey_);
}
if (flushedAndDisabled_) {
// If the trace is not flushed and disabled, flush the trace and
// run rollback action (e.g. delete the in-progress trace)
flushAndDisableTrace();
rollbackAction_();
}
}
TracingHermesRuntime::TracingHermesRuntime(
std::unique_ptr<HermesRuntime> &runtime,
uint64_t globalID,
const ::hermes::vm::RuntimeConfig &runtimeConfig,
std::unique_ptr<llvh::raw_ostream> traceStream,
std::function<std::string()> commitAction,
std::function<void()> rollbackAction)
: TracingRuntime(
std::move(runtime),
globalID,
runtimeConfig,
std::move(traceStream)),
conf_(runtimeConfig),
commitAction_(std::move(commitAction)),
rollbackAction_(std::move(rollbackAction)),
crashCallbackKey_(
conf_.getCrashMgr()
? llvh::Optional<::hermes::vm::CrashManager::CallbackKey>(
conf_.getCrashMgr()->registerCallback(
[this](int fd) { crashCallback(fd); }))
: llvh::None) {}
void TracingHermesRuntime::flushAndDisableTrace() {
(void)flushAndDisableBridgeTrafficTrace();
}
std::string TracingHermesRuntime::flushAndDisableBridgeTrafficTrace() {
if (flushedAndDisabled_) {
return committedTraceFilename_;
}
trace().flushAndDisable(
hermesRuntime().getMockedEnvironment(), hermesRuntime().getGCExecTrace());
flushedAndDisabled_ = true;
committedTraceFilename_ = commitAction_();
return committedTraceFilename_;
}
jsi::Value TracingHermesRuntime::evaluateJavaScript(
const std::shared_ptr<const jsi::Buffer> &buffer,
const std::string &sourceURL) {
return TracingRuntime::evaluateJavaScript(buffer, sourceURL);
}
void TracingHermesRuntime::crashCallback(int fd) {
if (flushedAndDisabled_) {
// The trace is disabled prior to the crash.
// As a result, this trace will likely not re-produce the crash.
return;
}
llvh::raw_fd_ostream jsonStream(fd, false);
::hermes::JSONEmitter json(jsonStream);
json.openDict();
json.emitKeyValue("type", "tracing");
std::string status = "Failed to flush";
try {
flushAndDisableBridgeTrafficTrace();
status = "Completed";
} catch (std::exception &ex) {
::hermes::hermesLog("Hermes", "Failed to flush trace: %s", ex.what());
// suppress; we're in a crash handler
} catch (...) {
// suppress; we're in a crash handler
}
json.emitKeyValue("status", status);
json.emitKeyValue("fileName", committedTraceFilename_);
json.closeDict();
}
namespace {
void addRecordMarker(TracingRuntime &tracingRuntime) {
jsi::Runtime &rt = tracingRuntime.plain();
const char *funcName = "__nativeRecordTraceMarker";
if (tracingRuntime.global().hasProperty(tracingRuntime, funcName)) {
// If this function is already defined, throw.
throw jsi::JSINativeException(
std::string("global.") + funcName +
" already exists, won't overwrite it");
}
rt.global().setProperty(
tracingRuntime,
funcName,
jsi::Function::createFromHostFunction(
tracingRuntime,
jsi::PropNameID::forAscii(tracingRuntime, funcName),
0,
[funcName, &tracingRuntime](
jsi::Runtime &rt,
const jsi::Value &,
const jsi::Value *args,
size_t argc) -> jsi::Value {
if (argc < 1) {
throw jsi::JSINativeException(
std::string(funcName) + " requires a single string argument");
}
tracingRuntime.addMarker(args[0].asString(rt).utf8(rt));
return jsi::Value::undefined();
}));
}
} // namespace
static std::unique_ptr<TracingHermesRuntime> makeTracingHermesRuntimeImpl(
std::unique_ptr<HermesRuntime> hermesRuntime,
const ::hermes::vm::RuntimeConfig &runtimeConfig,
std::unique_ptr<llvh::raw_ostream> traceStream,
std::function<std::string()> commitAction,
std::function<void()> rollbackAction,
bool forReplay) {
::hermes::hermesLog("Hermes", "Creating TracingHermesRuntime.");
auto ret = std::make_unique<TracingHermesRuntime>(
std::move(hermesRuntime),
runtimeConfig,
std::move(traceStream),
commitAction,
rollbackAction);
// In non-replay executions, add the __nativeRecordTraceMarker function.
// In replay executions, this will be simulated from the trace.
if (!forReplay) {
addRecordMarker(*ret);
}
return ret;
}
std::unique_ptr<TracingHermesRuntime> makeTracingHermesRuntime(
std::unique_ptr<HermesRuntime> hermesRuntime,
const ::hermes::vm::RuntimeConfig &runtimeConfig,
const std::string &traceScratchPath,
const std::string &traceResultPath,
std::function<bool()> traceCompletionCallback) {
std::error_code ec;
std::unique_ptr<llvh::raw_ostream> traceStream =
std::make_unique<llvh::raw_fd_ostream>(
traceScratchPath, ec, llvh::sys::fs::F_Text);
if (ec) {
::hermes::hermesLog(
"Hermes",
"Failed to open file %s for tracing: %s",
traceScratchPath.c_str(),
ec.message().c_str());
return makeTracingHermesRuntime(
std::move(hermesRuntime), runtimeConfig, nullptr, "");
}
return makeTracingHermesRuntimeImpl(
std::move(hermesRuntime),
runtimeConfig,
std::move(traceStream),
[traceCompletionCallback, traceScratchPath, traceResultPath]() {
if (traceScratchPath != traceResultPath) {
std::error_code ec =
llvh::sys::fs::rename(traceScratchPath, traceResultPath);
if (ec) {
::hermes::hermesLog(
"Hermes",
"Failed to rename tracing file from %s to %s: %s",
traceScratchPath.c_str(),
traceResultPath.c_str(),
ec.message().c_str());
return std::string();
}
}
bool success = traceCompletionCallback();
if (!success) {
::hermes::hermesLog(
"Hermes",
"Failed to invoke completion callback for tracing file %s",
traceResultPath.c_str());
return std::string();
}
::hermes::hermesLog(
"Hermes", "Completed tracing file at %s", traceResultPath.c_str());
return traceResultPath;
},
[traceScratchPath]() {
// Delete the in-progress trace
llvh::sys::fs::remove(traceScratchPath);
},
false);
}
std::unique_ptr<TracingHermesRuntime> makeTracingHermesRuntime(
std::unique_ptr<HermesRuntime> hermesRuntime,
const ::hermes::vm::RuntimeConfig &runtimeConfig,
std::unique_ptr<llvh::raw_ostream> traceStream,
bool forReplay) {
return makeTracingHermesRuntimeImpl(
std::move(hermesRuntime),
runtimeConfig,
std::move(traceStream),
[]() { return std::string(); },
[]() {},
forReplay);
}
} // namespace tracing
} // namespace hermes
} // namespace facebook
#endif