Debian Codegraph @

js/src/debugger/ExecutionTracer.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef debugger_ExecutionTracer_h
8 #define debugger_ExecutionTracer_h
9
10 #include "mozilla/Assertions.h" // MOZ_DIAGNOSTIC_ASSERT, MOZ_ASSERT
11 #include "mozilla/BaseProfilerUtils.h" // profiler_current_thread_id
12 #include "mozilla/MathAlgorithms.h" // mozilla::IsPowerOfTwo
13 #include "mozilla/Maybe.h" // mozilla::Maybe, mozilla::Some, mozilla::Nothing
14 #include "mozilla/Span.h"
15 #include "mozilla/TimeStamp.h"
16
17 #include <limits> // std::numeric_limits
18 #include <stddef.h> // size_t
19 #include <stdint.h> // uint8_t, uint16_t
20
21 #include "js/CharacterEncoding.h" // JS::UTF8Chars
22 #include "js/Debug.h" // JS::ExecutionTrace
23 #include "js/RootingAPI.h" // JS::Rooted
24 #include "js/Utility.h" // js_malloc, js_free
25 #include "js/Value.h" // JS::Value
26 #include "vm/JSContext.h" // JSContext
27 #include "vm/Stack.h" // js::AbstractFramePtr
28
29 namespace js {
30
31 enum class TracerStringEncoding {
32 Latin1,
33 TwoByte,
34 UTF8,
35 };
36
37 using TracingScratchBuffer = mozilla::Vector<char, 512>;
38
39 // TODO: it should be noted that part of this design is informed by the fact
40 // that it evolved from a prototype which wrote this data from a content
41 // process and read it from the parent process, allowing the parent process to
42 // display the trace in real time as the program executes. Bug 1910182 tracks
43 // the next steps for making that prototype a reality.
44 template <size_t BUFFER_SIZE>
45 class TracingBuffer {
46 static_assert(mozilla::IsPowerOfTwo(BUFFER_SIZE));
47
48 // BUFFER_SIZE is the size of the underlying ring buffer, and BUFFER_MASK
49 // masks off indices into it in order to wrap around
50 static const size_t BUFFER_MASK = BUFFER_SIZE - 1;
51
52 // The entry header is just a u16 that holds the size of the entry in bytes.
53 // This is used for asserting the integrity of the data as well as for
54 // skipping the read head forward if it's going to be overwritten by the
55 // write head
56 static const size_t ENTRY_HEADER_SIZE = sizeof(uint16_t);
57
58 // The underlying ring buffer
59 uint8_t* buffer_ = nullptr;
60
61 // NOTE: The following u64s are unwrapped indices into the ring buffer, so
62 // they must always be masked off with BUFFER_MASK before using them to
63 // access buffer_:
64
65 // Represents how much has been written into the ring buffer and is ready
66 // for reading
67 uint64_t writeHead_ = 0;
68
69 // Represents how much has been read from the ring buffer
70 uint64_t readHead_ = 0;
71
72 // When not equal to writeHead_, this represents unfinished write progress
73 // into the buffer. After each entry successfully finished writing,
74 // writeHead_ is set to this value
75 uint64_t uncommittedWriteHead_ = 0;
76
77 // Similar to uncommittedWriteHead_, but for the purposes of reading
78 uint64_t uncommittedReadHead_ = 0;
79
80 bool ensureScratchBufferSize(TracingScratchBuffer& scratchBuffer,
81 size_t requiredSize) {
82 if (scratchBuffer.length() >= requiredSize) {
83 return true;
84 }
85 return scratchBuffer.growByUninitialized(requiredSize -
86 scratchBuffer.length());
87 }
88
89 public:
90 ~TracingBuffer() {
91 if (buffer_) {
92 js_free(buffer_);
93 }
94 }
95
96 bool init() {
97 buffer_ = static_cast<uint8_t*>(js_malloc(BUFFER_SIZE));
98 return buffer_ != nullptr;
99 }
100
101 bool readable() { return writeHead_ > readHead_; }
102
103 void beginWritingEntry() {
104 // uncommittedWriteHead_ can be > writeHead_ if a previous write failed.
105 // In that case, this effectively discards whatever was written during that
106 // time
107 MOZ_ASSERT(uncommittedWriteHead_ >= writeHead_);
108 uncommittedWriteHead_ = writeHead_;
109 uncommittedWriteHead_ += ENTRY_HEADER_SIZE;
110 }
111
112 void finishWritingEntry() {
113 MOZ_ASSERT(uncommittedWriteHead_ - writeHead_ <=
114 std::numeric_limits<uint16_t>::max());
115 uint16_t entryHeader = uint16_t(uncommittedWriteHead_ - writeHead_);
116 writeBytesAtOffset(reinterpret_cast<const uint8_t*>(&entryHeader),
117 sizeof(entryHeader), writeHead_);
118 writeHead_ = uncommittedWriteHead_;
119 }
120
121 void beginReadingEntry() {
122 MOZ_ASSERT(uncommittedReadHead_ == readHead_);
123 // We will read the entry header (still pointed to by readHead_) from
124 // inside finishReadingEntry
125 uncommittedReadHead_ += ENTRY_HEADER_SIZE;
126 }
127
128 void finishReadingEntry() {
129 uint16_t entryHeader;
130 readBytesAtOffset(reinterpret_cast<uint8_t*>(&entryHeader),
131 sizeof(entryHeader), readHead_);
132 size_t read = uncommittedReadHead_ - readHead_;
133
134 MOZ_RELEASE_ASSERT(entryHeader == uint16_t(read));
135 readHead_ += entryHeader;
136 uncommittedReadHead_ = readHead_;
137 }
138
139 void skipEntry() {
140 uint16_t entryHeader;
141 readBytesAtOffset(reinterpret_cast<uint8_t*>(&entryHeader),
142 sizeof(entryHeader), readHead_);
143 readHead_ += entryHeader;
144 uncommittedReadHead_ = readHead_;
145 }
146
147 void writeBytesAtOffset(const uint8_t* bytes, size_t length,
148 uint64_t offset) {
149 MOZ_ASSERT(offset + length <= readHead_ + BUFFER_SIZE);
150
151 size_t maskedWriteHead = offset & BUFFER_MASK;
152 if (maskedWriteHead + length > BUFFER_SIZE) {
153 size_t firstChunk = BUFFER_SIZE - maskedWriteHead;
154 memcpy(buffer_ + maskedWriteHead, bytes, firstChunk);
155 memcpy(buffer_, bytes + firstChunk, length - firstChunk);
156 } else {
157 memcpy(buffer_ + maskedWriteHead, bytes, length);
158 }
159 }
160
161 void writeBytes(const uint8_t* bytes, size_t length) {
162 // Skip the read head forward if we're about to overwrite unread entries
163 while (MOZ_UNLIKELY(uncommittedWriteHead_ + length >
164 readHead_ + BUFFER_SIZE)) {
165 skipEntry();
166 }
167
168 writeBytesAtOffset(bytes, length, uncommittedWriteHead_);
169 uncommittedWriteHead_ += length;
170 }
171
172 template <typename T>
173 void write(T val) {
174 // No magic hidden work allowed here - we are just reducing duplicate code
175 // serializing integers and floats.
176 static_assert(std::is_arithmetic_v<T>);
177 writeBytes(reinterpret_cast<const uint8_t*>(&val), sizeof(T));
178 }
179
180 void writeEmptyString() {
181 write(uint8_t(TracerStringEncoding::Latin1));
182 write(uint32_t(0)); // length
183 }
184
185 bool writeString(JSContext* cx, JS::Handle<JSString*> str) {
186 TracerStringEncoding encoding;
187 if (str->hasLatin1Chars()) {
188 encoding = TracerStringEncoding::Latin1;
189 } else {
190 encoding = TracerStringEncoding::TwoByte;
191 }
192
193 // TODO: if ropes are common we can certainly serialize them without
194 // linearizing - this is just easy
195 JSLinearString* linear = str->ensureLinear(cx);
196 if (!linear) {
197 return false;
198 }
199 write(uint8_t(encoding));
200 size_t length = linear->length();
201 MOZ_ASSERT(length <= std::numeric_limits<uint32_t>::max());
202 write(uint32_t(length));
203 size_t size = length;
204 JS::AutoAssertNoGC nogc;
205 const uint8_t* charBuffer = nullptr;
206 if (encoding == TracerStringEncoding::TwoByte) {
207 size *= sizeof(char16_t);
208 charBuffer = reinterpret_cast<const uint8_t*>(linear->twoByteChars(nogc));
209 } else {
210 charBuffer = reinterpret_cast<const uint8_t*>(linear->latin1Chars(nogc));
211 }
212 writeBytes(charBuffer, size);
213 return true;
214 }
215
216 template <typename CharType, TracerStringEncoding Encoding>
217 void writeCString(const CharType* chars) {
218 size_t length = std::char_traits<CharType>::length(chars);
219 static_assert(sizeof(CharType) == 1 ||
220 Encoding == TracerStringEncoding::TwoByte);
221 static_assert(sizeof(CharType) <= 2);
222 write(uint8_t(Encoding));
223 MOZ_ASSERT(length <= std::numeric_limits<uint32_t>::max());
224 write(uint32_t(length));
225 const size_t size = length * sizeof(CharType);
226 writeBytes(reinterpret_cast<const uint8_t*>(chars), size);
227 }
228
229 void readBytesAtOffset(uint8_t* bytes, size_t length, uint64_t offset) {
230 size_t maskedReadHead = offset & BUFFER_MASK;
231 if (maskedReadHead + length > BUFFER_SIZE) {
232 size_t firstChunk = BUFFER_SIZE - maskedReadHead;
233 memcpy(bytes, buffer_ + maskedReadHead, firstChunk);
234 memcpy(bytes + firstChunk, buffer_, length - firstChunk);
235 } else {
236 memcpy(bytes, buffer_ + maskedReadHead, length);
237 }
238 }
239
240 void readBytes(uint8_t* bytes, size_t length) {
241 readBytesAtOffset(bytes, length, uncommittedReadHead_);
242 uncommittedReadHead_ += length;
243 }
244
245 template <typename T>
246 void read(T* val) {
247 static_assert(std::is_arithmetic_v<T>);
248 readBytes(reinterpret_cast<uint8_t*>(val), sizeof(T));
249 }
250
251 // Reads a string from our buffer into the stringBuffer. Converts everything
252 // to null-terminated UTF-8
253 bool readString(TracingScratchBuffer& scratchBuffer,
254 mozilla::Vector<char>& stringBuffer, size_t* index) {
255 uint8_t encodingByte;
256 read(&encodingByte);
257 TracerStringEncoding encoding = TracerStringEncoding(encodingByte);
258
259 uint32_t length;
260 read(&length);
261
262 *index = stringBuffer.length();
263
264 if (length == 0) {
265 if (!stringBuffer.append('\0')) {
266 return false;
267 }
268 return true;
269 }
270
271 if (encoding == TracerStringEncoding::UTF8) {
272 size_t reserveLength = length + 1;
273 if (!stringBuffer.growByUninitialized(reserveLength)) {
274 return false;
275 }
276 char* writePtr = stringBuffer.end() - reserveLength;
277 readBytes(reinterpret_cast<uint8_t*>(writePtr), length);
278 writePtr[length] = '\0';
279 } else if (encoding == TracerStringEncoding::Latin1) {
280 if (!ensureScratchBufferSize(scratchBuffer, length)) {
281 return false;
282 }
283 readBytes(reinterpret_cast<uint8_t*>(scratchBuffer.begin()), length);
284
285 // A single latin-1 code point maps to either 1 or 2 UTF-8 code units.
286 // The + 1 is for the null terminator.
287 size_t reserveLength = length * 2 + 1;
288 if (!stringBuffer.reserve(stringBuffer.length() + reserveLength)) {
289 return false;
290 }
291 char* writePtr = stringBuffer.end();
292
293 size_t convertedLength = mozilla::ConvertLatin1toUtf8(
294 mozilla::Span<const char>(scratchBuffer.begin(), length),
295 mozilla::Span<char>(writePtr, reserveLength));
296 writePtr[convertedLength] = 0;
297
298 // We reserved above, which just grows the capacity but not the length.
299 // This just commits the exact length increase.
300 if (!stringBuffer.growByUninitialized(convertedLength + 1)) {
301 return false;
302 }
303 } else {
304 MOZ_ASSERT(encoding == TracerStringEncoding::TwoByte);
305 if (!ensureScratchBufferSize(scratchBuffer, length * sizeof(char16_t))) {
306 return false;
307 }
308 readBytes(reinterpret_cast<uint8_t*>(scratchBuffer.begin()),
309 length * sizeof(char16_t));
310
311 // Non-surrogate-paired single UTF-16 code unit maps to 1 to 3 UTF-8
312 // code units. Surrogate paired UTF-16 code units map to 4 to 6 UTF-8
313 // code units.
314 size_t reserveLength = length * 3 + 1;
315 if (!stringBuffer.reserve(stringBuffer.length() + reserveLength)) {
316 return false;
317 }
318 char* writePtr = stringBuffer.end();
319
320 size_t convertedLength = mozilla::ConvertUtf16toUtf8(
321 mozilla::Span<const char16_t>(
322 reinterpret_cast<char16_t*>(scratchBuffer.begin()), length),
323 mozilla::Span<char>(writePtr, reserveLength));
324 writePtr[convertedLength] = 0;
325
326 // We reserved above, which just grows the capacity but not the length.
327 // This just commits the exact length increase.
328 if (!stringBuffer.growByUninitialized(convertedLength + 1)) {
329 return false;
330 }
331 }
332
333 return true;
334 }
335 };
336
337 // These sizes are to some degree picked out of a hat, and eventually it might
338 // be nice to make them configurable. For reference, I measured it costing
339 // 145MB to open gdocs and create an empty document, so 256MB is just some
340 // extra wiggle room for complex use cases.
341 using InlineDataBuffer = TracingBuffer<1 << 28>;
342
343 // The size for the out of line data is much smaller, so I just picked a size
344 // that was much smaller but big enough that I didn't see us running out of it
345 // when playing around on various complex apps. Again, it would be great in the
346 // future for this to be configurable.
347 using OutOfLineDataBuffer = TracingBuffer<1 << 22>;
348
349 // An ExecutionTracer is responsible for recording JS execution while it is
350 // enabled to a set of ring buffers, and providing that information as a JS
351 // object when requested. See Debugger.md (collectNativeTrace) for more details.
352 class ExecutionTracer {
353 private:
354 // The fields below should only be accessed while we hold the lock.
355 static Mutex globalInstanceLock MOZ_UNANNOTATED;
356 static mozilla::Vector<ExecutionTracer*> globalInstances;
357
358 // The buffers below should only be accessed while we hold the lock.
359 Mutex bufferLock_ MOZ_UNANNOTATED;
360
361 // This holds the actual entries, one for each push or pop of a frame or label
362 InlineDataBuffer inlineData_;
363
364 // This holds data that may be duplicated across entries, like script URLs or
365 // function names. This should generally be much smaller in terms of raw
366 // bytes. Note however that we can still wrap around this buffer and lose
367 // entries - the system is best effort, and the consumer must accomodate the
368 // fact that entries from inlineData_ may reference expired data from
369 // outOfLineData_
370 OutOfLineDataBuffer outOfLineData_;
371
372 // This is just an ID that allows the profiler to easily correlate the trace
373 // for a given context with the correct thread in the output profile.
374 // We're operating on the assumption that there is one JSContext per thread,
375 // which should be true enough for our uses in Firefox, but doesn't have to
376 // be true everywhere.
377 mozilla::baseprofiler::BaseProfilerThreadId threadId_;
378
379 // When we encounter an error during tracing, we write one final Error entry
380 // and suspend tracing indefinitely. This allows the consumer to get some
381 // information about what led up to the error, while preventing any
382 // additional future overhead. An alternative to this approach would be to
383 // clean up all of our buffers on error, but since the user must have elected
384 // to turn on tracing, we assume that they would rather have a greater chance
385 // of more information about what led up to the error rather than a greater
386 // chance of avoiding a crash due to OOM.
387 void handleError(JSContext* cx);
388
389 void writeScriptUrl(ScriptSource* scriptSource);
390
391 // Writes an atom into the outOfLineData_, associating it with the specified
392 // id. In practice, `id` comes from an atom id inside a cache in the
393 // JSContext which is incremented each time a new atom is registered and
394 // cleared when tracing is done.
395 bool writeAtom(JSContext* cx, JS::Handle<JSAtom*> atom, uint32_t id);
396 bool writeFunctionFrame(JSContext* cx, AbstractFramePtr frame);
397
398 // The below functions read data from the inlineData_ and outOfLineData_ ring
399 // buffers into structs to be consumed by clients of the
400 // JS_TracerSnapshotTrace API.
401 bool readFunctionFrame(JS::ExecutionTrace::EventKind kind,
402 JS::ExecutionTrace::TracedEvent& event);
403 bool readLabel(JS::ExecutionTrace::EventKind kind,
404 JS::ExecutionTrace::TracedEvent& event,
405 TracingScratchBuffer& scratchBuffer,
406 mozilla::Vector<char>& stringBuffer);
407 bool readInlineEntry(mozilla::Vector<JS::ExecutionTrace::TracedEvent>& events,
408 TracingScratchBuffer& scratchBuffer,
409 mozilla::Vector<char>& stringBuffer);
410 bool readOutOfLineEntry(mozilla::HashMap<uint32_t, size_t>& scriptUrls,
411 mozilla::HashMap<uint32_t, size_t>& atoms,
412 TracingScratchBuffer& scratchBuffer,
413 mozilla::Vector<char>& stringBuffer);
414 bool readInlineEntries(
415 mozilla::Vector<JS::ExecutionTrace::TracedEvent>& events,
416 TracingScratchBuffer& scratchBuffer, mozilla::Vector<char>& stringBuffer);
417 bool readOutOfLineEntries(mozilla::HashMap<uint32_t, size_t>& scriptUrls,
418 mozilla::HashMap<uint32_t, size_t>& atoms,
419 TracingScratchBuffer& scratchBuffer,
420 mozilla::Vector<char>& stringBuffer);
421
422 public:
423 ExecutionTracer() : bufferLock_(mutexid::ExecutionTracerInstanceLock) {}
424
425 ~ExecutionTracer() {
426 LockGuard<Mutex> guard(globalInstanceLock);
427
428 globalInstances.eraseIfEqual(this);
429 }
430
431 mozilla::baseprofiler::BaseProfilerThreadId threadId() const {
432 return threadId_;
433 }
434
435 bool init() {
436 LockGuard<Mutex> guard(globalInstanceLock);
437 LockGuard<Mutex> guard2(bufferLock_);
438
439 threadId_ = mozilla::baseprofiler::profiler_current_thread_id();
440
441 if (!inlineData_.init()) {
442 return false;
443 }
444 if (!outOfLineData_.init()) {
445 return false;
446 }
447
448 if (!globalInstances.append(this)) {
449 return false;
450 }
451
452 return true;
453 }
454
455 void onEnterFrame(JSContext* cx, AbstractFramePtr frame);
456 void onLeaveFrame(JSContext* cx, AbstractFramePtr frame);
457
458 template <typename CharType, TracerStringEncoding Encoding>
459 void onEnterLabel(const CharType* eventType);
460 template <typename CharType, TracerStringEncoding Encoding>
461 void onLeaveLabel(const CharType* eventType);
462
463 // Reads the execution trace from the underlying ring buffers and outputs it
464 // into a native struct. For more information about this struct, see
465 // js/public/Debug.h
466 bool getNativeTrace(JS::ExecutionTrace::TracedJSContext& context,
467 TracingScratchBuffer& scratchBuffer,
468 mozilla::Vector<char>& stringBuffer);
469
470 // Calls getNativeTrace for every JSContext in the process, populating the
471 // provided ExecutionTrace with the result.
472 static bool getNativeTraceForAllContexts(JS::ExecutionTrace& trace);
473 };
474
475 } // namespace js
476
477 #endif /* debugger_ExecutionTracer_h */