Debian Codegraph @

js/public/Debug.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 // Interfaces by which the embedding can interact with the Debugger API.
8
9 #ifndef js_Debug_h
10 #define js_Debug_h
11
12 #include "mozilla/Assertions.h"
13 #include "mozilla/Attributes.h"
14 #include "mozilla/BaseProfilerUtils.h"
15 #include "mozilla/MemoryReporting.h"
16 #include "mozilla/Vector.h"
17
18 #include <utility>
19
20 #include "jstypes.h"
21
22 #include "js/GCAPI.h"
23 #include "js/RootingAPI.h"
24 #include "js/TypeDecls.h"
25
26 namespace js {
27 class Debugger;
28 } // namespace js
29
30 /* Defined in vm/Debugger.cpp. */
31 extern JS_PUBLIC_API bool JS_DefineDebuggerObject(JSContext* cx,
32 JS::HandleObject obj);
33
34 // If the JS execution tracer is running, this will generate a
35 // ENTRY_KIND_LABEL_ENTER entry with the specified label.
36 // The consumer of the trace can then, for instance, correlate all code running
37 // after this entry and before the corresponding ENTRY_KIND_LABEL_LEAVE with the
38 // provided label.
39 // If the tracer is not running, this does nothing.
40 extern JS_PUBLIC_API void JS_TracerEnterLabelLatin1(JSContext* cx,
41 const char* label);
42 extern JS_PUBLIC_API void JS_TracerEnterLabelTwoByte(JSContext* cx,
43 const char16_t* label);
44
45 extern JS_PUBLIC_API bool JS_TracerIsTracing(JSContext* cx);
46
47 // If the JS execution tracer is running, this will generate a
48 // ENTRY_KIND_LABEL_LEAVE entry with the specified label.
49 // It is up to the consumer to decide what to do with a ENTRY_KIND_LABEL_LEAVE
50 // entry is encountered without a corresponding ENTRY_KIND_LABEL_ENTER.
51 // If the tracer is not running, this does nothing.
52 extern JS_PUBLIC_API void JS_TracerLeaveLabelLatin1(JSContext* cx,
53 const char* label);
54 extern JS_PUBLIC_API void JS_TracerLeaveLabelTwoByte(JSContext* cx,
55 const char16_t* label);
56
57 #ifdef MOZ_EXECUTION_TRACING
58
59 // This will begin execution tracing for the JSContext, i.e., this will begin
60 // recording every entrance into / exit from a function for the given context.
61 // The trace can be read via JS_TracerSnapshotTrace, and populates the
62 // ExecutionTrace struct defined below.
63 //
64 // This throws if the code coverage is active for any realm in the context.
65 extern JS_PUBLIC_API bool JS_TracerBeginTracing(JSContext* cx);
66
67 // This ends execution tracing for the JSContext, discards the tracing
68 // buffers, and clears some caches used for tracing. JS_TracerSnapshotTrace
69 // should be called *before* JS_TracerEndTracing if you want to read the trace
70 // data for this JSContext.
71 extern JS_PUBLIC_API bool JS_TracerEndTracing(JSContext* cx);
72
73 namespace JS {
74
75 // This is populated by JS_TracerSnapshotTrace and just represent a minimal
76 // structure for natively representing an execution trace across a range of
77 // JSContexts (see below). The core of the trace is an array of events, each of
78 // which is a tagged union with data corresponding to that event. Events can
79 // also point into various tables, and store all of their string data in a
80 // contiguous UTF-8 stringBuffer (each string is null-terminated within the
81 // buffer.)
82 struct ExecutionTrace {
83 enum class EventKind : uint8_t {
84 FunctionEnter = 0,
85 FunctionLeave = 1,
86 LabelEnter = 2,
87 LabelLeave = 3,
88
89 // NOTE: the `Error` event has no TracedEvent payload, and will always
90 // represent the end of the trace when encountered.
91 Error = 4,
92 };
93
94 enum class ImplementationType : uint8_t {
95 Interpreter = 0,
96 Baseline = 1,
97 Ion = 2,
98 Wasm = 3,
99 };
100
101 struct TracedEvent {
102 EventKind kind;
103 union {
104 // For FunctionEnter / FunctionLeave
105 struct {
106 ImplementationType implementation;
107
108 // 1-origin line number of the function
109 uint32_t lineNumber;
110
111 // 1-origin column of the function
112 uint32_t column;
113
114 // Keys into the thread's scriptUrls HashMap. This key can be missing
115 // from the HashMap, although ideally that situation is rare (it is
116 // more likely in long running traces with *many* unique functions
117 // and/or scripts)
118 uint32_t scriptId;
119
120 // ID to the realm that the frame was in. It's used for finding which
121 // frame comes from which window/page.
122 uint64_t realmID;
123
124 // Keys into the thread's atoms HashMap. This key can be missing from
125 // the HashMap as well (see comment above scriptId)
126 uint32_t functionNameId;
127 } functionEvent;
128
129 // For LabelEnter / LabelLeave
130 struct {
131 size_t label; // Indexes directly into the trace's stringBuffer
132 } labelEvent;
133 };
134 // Milliseconds since process creation
135 double time;
136 };
137
138 struct TracedJSContext {
139 mozilla::baseprofiler::BaseProfilerThreadId id;
140
141 // Maps ids to indices into the trace's stringBuffer
142 mozilla::HashMap<uint32_t, size_t> scriptUrls;
143
144 // Similar to scriptUrls
145 mozilla::HashMap<uint32_t, size_t> atoms;
146
147 mozilla::Vector<TracedEvent> events;
148 };
149
150 mozilla::Vector<char> stringBuffer;
151
152 // This will be populated with an entry for each context which had tracing
153 // enabled via JS_TracerBeginTracing.
154 mozilla::Vector<TracedJSContext> contexts;
155 };
156 } // namespace JS
157
158 // Captures the trace for all JSContexts in the process which are currently
159 // tracing.
160 extern JS_PUBLIC_API bool JS_TracerSnapshotTrace(JS::ExecutionTrace& trace);
161
162 #endif /* MOZ_EXECUTION_TRACING */
163
164 namespace JS {
165 namespace dbg {
166
167 // [SMDOC] Debugger builder API
168 //
169 // Helping embedding code build objects for Debugger
170 // -------------------------------------------------
171 //
172 // Some Debugger API features lean on the embedding application to construct
173 // their result values. For example, Debugger.Frame.prototype.scriptEntryReason
174 // calls hooks provided by the embedding to construct values explaining why it
175 // invoked JavaScript; if F is a frame called from a mouse click event handler,
176 // F.scriptEntryReason would return an object of the form:
177 //
178 // { eventType: "mousedown", event: <object> }
179 //
180 // where <object> is a Debugger.Object whose referent is the event being
181 // dispatched.
182 //
183 // However, Debugger implements a trust boundary. Debuggee code may be
184 // considered untrusted; debugger code needs to be protected from debuggee
185 // getters, setters, proxies, Object.watch watchpoints, and any other feature
186 // that might accidentally cause debugger code to set the debuggee running. The
187 // Debugger API tries to make it easy to write safe debugger code by only
188 // offering access to debuggee objects via Debugger.Object instances, which
189 // ensure that only those operations whose explicit purpose is to invoke
190 // debuggee code do so. But this protective membrane is only helpful if we
191 // interpose Debugger.Object instances in all the necessary spots.
192 //
193 // SpiderMonkey's compartment system also implements a trust boundary. The
194 // debuggee and debugger are always in different compartments. Inter-compartment
195 // work requires carefully tracking which compartment each JSObject or JS::Value
196 // belongs to, and ensuring that is is correctly wrapped for each operation.
197 //
198 // It seems precarious to expect the embedding's hooks to implement these trust
199 // boundaries. Instead, the JS::dbg::Builder API segregates the code which
200 // constructs trusted objects from that which deals with untrusted objects.
201 // Trusted objects have an entirely different C++ type, so code that improperly
202 // mixes trusted and untrusted objects is caught at compile time.
203 //
204 // In the structure shown above, there are two trusted objects, and one
205 // untrusted object:
206 //
207 // - The overall object, with the 'eventType' and 'event' properties, is a
208 // trusted object. We're going to return it to D.F.p.scriptEntryReason's
209 // caller, which will handle it directly.
210 //
211 // - The Debugger.Object instance appearing as the value of the 'event' property
212 // is a trusted object. It belongs to the same Debugger instance as the
213 // Debugger.Frame instance whose scriptEntryReason accessor was called, and
214 // presents a safe reflection-oriented API for inspecting its referent, which
215 // is:
216 //
217 // - The actual event object, an untrusted object, and the referent of the
218 // Debugger.Object above. (Content can do things like replacing accessors on
219 // Event.prototype.)
220 //
221 // Using JS::dbg::Builder, all objects and values the embedding deals with
222 // directly are considered untrusted, and are assumed to be debuggee values. The
223 // only way to construct trusted objects is to use Builder's own methods, which
224 // return a separate Object type. The only way to set a property on a trusted
225 // object is through that Object type. The actual trusted object is never
226 // exposed to the embedding.
227 //
228 // So, for example, the embedding might use code like the following to construct
229 // the object shown above, given a Builder passed to it by Debugger:
230 //
231 // bool
232 // MyScriptEntryReason::explain(JSContext* cx,
233 // Builder& builder,
234 // Builder::Object& result)
235 // {
236 // JSObject* eventObject = ... obtain debuggee event object somehow ...;
237 // if (!eventObject) {
238 // return false;
239 // }
240 // result = builder.newObject(cx);
241 // return result &&
242 // result.defineProperty(cx, "eventType",
243 // SafelyFetchType(eventObject)) &&
244 // result.defineProperty(cx, "event", eventObject);
245 // }
246 //
247 //
248 // Object::defineProperty also accepts an Object as the value to store on the
249 // property. By its type, we know that the value is trusted, so we set it
250 // directly as the property's value, without interposing a Debugger.Object
251 // wrapper. This allows the embedding to builted nested structures of trusted
252 // objects.
253 //
254 // The Builder and Builder::Object methods take care of doing whatever
255 // compartment switching and wrapping are necessary to construct the trusted
256 // values in the Debugger's compartment.
257 //
258 // The Object type is self-rooting. Construction, assignment, and destruction
259 // all properly root the referent object.
260
261 class BuilderOrigin;
262
263 class Builder {
264 // The Debugger instance whose client we are building a value for. We build
265 // objects in this object's compartment.
266 PersistentRootedObject debuggerObject;
267
268 // debuggerObject's Debugger structure, for convenience.
269 js::Debugger* debugger;
270
271 // Check that |thing| is in the same compartment as our debuggerObject. Used
272 // for assertions when constructing BuiltThings. We can overload this as we
273 // add more instantiations of BuiltThing.
274 #ifdef DEBUG
275 void assertBuilt(JSObject* obj);
276 #else
277 void assertBuilt(JSObject* obj) {}
278 #endif
279
280 protected:
281 // A reference to a trusted object or value. At the moment, we only use it
282 // with JSObject*.
283 template <typename T>
284 class BuiltThing {
285 friend class BuilderOrigin;
286
287 protected:
288 // The Builder to which this trusted thing belongs.
289 Builder& owner;
290
291 // A rooted reference to our value.
292 PersistentRooted<T> value;
293
294 BuiltThing(JSContext* cx, Builder& owner_,
295 T value_ = SafelyInitialized<T>::create())
296 : owner(owner_), value(cx, value_) {
297 owner.assertBuilt(value_);
298 }
299
300 // Forward some things from our owner, for convenience.
301 js::Debugger* debugger() const { return owner.debugger; }
302 JSObject* debuggerObject() const { return owner.debuggerObject; }
303
304 public:
305 BuiltThing(const BuiltThing& rhs) : owner(rhs.owner), value(rhs.value) {}
306 BuiltThing& operator=(const BuiltThing& rhs) {
307 MOZ_ASSERT(&owner == &rhs.owner);
308 owner.assertBuilt(rhs.value);
309 value = rhs.value;
310 return *this;
311 }
312
313 explicit operator bool() const {
314 // If we ever instantiate BuiltThing<Value>, this might not suffice.
315 return value;
316 }
317
318 private:
319 BuiltThing() = delete;
320 };
321
322 public:
323 // A reference to a trusted object, possibly null. Instances of Object are
324 // always properly rooted. They can be copied and assigned, as if they were
325 // pointers.
326 class Object : private BuiltThing<JSObject*> {
327 friend class Builder; // for construction
328 friend class BuilderOrigin; // for unwrapping
329
330 typedef BuiltThing<JSObject*> Base;
331
332 // This is private, because only Builders can create Objects that
333 // actually point to something (hence the 'friend' declaration).
334 Object(JSContext* cx, Builder& owner_, HandleObject obj)
335 : Base(cx, owner_, obj.get()) {}
336
337 bool definePropertyToTrusted(JSContext* cx, const char* name,
338 JS::MutableHandleValue value);
339
340 public:
341 Object(JSContext* cx, Builder& owner_) : Base(cx, owner_, nullptr) {}
342 Object(const Object& rhs) = default;
343
344 // Our automatically-generated assignment operator can see our base
345 // class's assignment operator, so we don't need to write one out here.
346
347 // Set the property named |name| on this object to |value|.
348 //
349 // If |value| is a string or primitive, re-wrap it for the debugger's
350 // compartment.
351 //
352 // If |value| is an object, assume it is a debuggee object and make a
353 // Debugger.Object instance referring to it. Set that as the propery's
354 // value.
355 //
356 // If |value| is another trusted object, store it directly as the
357 // property's value.
358 //
359 // On error, report the problem on cx and return false.
360 bool defineProperty(JSContext* cx, const char* name, JS::HandleValue value);
361 bool defineProperty(JSContext* cx, const char* name,
362 JS::HandleObject value);
363 bool defineProperty(JSContext* cx, const char* name, Object& value);
364
365 using Base::operator bool;
366 };
367
368 // Build an empty object for direct use by debugger code, owned by this
369 // Builder. If an error occurs, report it on cx and return a false Object.
370 Object newObject(JSContext* cx);
371
372 protected:
373 Builder(JSContext* cx, js::Debugger* debugger);
374 };
375
376 // Debugger itself instantiates this subclass of Builder, which can unwrap
377 // BuiltThings that belong to it.
378 class BuilderOrigin : public Builder {
379 template <typename T>
380 T unwrapAny(const BuiltThing<T>& thing) {
381 MOZ_ASSERT(&thing.owner == this);
382 return thing.value.get();
383 }
384
385 public:
386 BuilderOrigin(JSContext* cx, js::Debugger* debugger_)
387 : Builder(cx, debugger_) {}
388
389 JSObject* unwrap(Object& object) { return unwrapAny(object); }
390 };
391
392 // Finding the size of blocks allocated with malloc
393 // ------------------------------------------------
394 //
395 // Debugger.Memory wants to be able to report how many bytes items in memory are
396 // consuming. To do this, it needs a function that accepts a pointer to a block,
397 // and returns the number of bytes allocated to that block. SpiderMonkey itself
398 // doesn't know which function is appropriate to use, but the embedding does.
399
400 // Tell Debuggers in |cx| to use |mallocSizeOf| to find the size of
401 // malloc'd blocks.
402 JS_PUBLIC_API void SetDebuggerMallocSizeOf(JSContext* cx,
403 mozilla::MallocSizeOf mallocSizeOf);
404
405 // Get the MallocSizeOf function that the given context is using to find the
406 // size of malloc'd blocks.
407 JS_PUBLIC_API mozilla::MallocSizeOf GetDebuggerMallocSizeOf(JSContext* cx);
408
409 // Debugger and Garbage Collection Events
410 // --------------------------------------
411 //
412 // The Debugger wants to report about its debuggees' GC cycles, however entering
413 // JS after a GC is troublesome since SpiderMonkey will often do something like
414 // force a GC and then rely on the nursery being empty. If we call into some
415 // Debugger's hook after the GC, then JS runs and the nursery won't be
416 // empty. Instead, we rely on embedders to call back into SpiderMonkey after a
417 // GC and notify Debuggers to call their onGarbageCollection hook.
418
419 // Determine whether it's necessary to call FireOnGarbageCollectionHook() after
420 // a GC. This is only required if there are debuggers with an
421 // onGarbageCollection hook observing a global in the set of collected zones.
422 JS_PUBLIC_API bool FireOnGarbageCollectionHookRequired(JSContext* cx);
423
424 // For each Debugger that observed a debuggee involved in the given GC event,
425 // call its `onGarbageCollection` hook.
426 JS_PUBLIC_API bool FireOnGarbageCollectionHook(
427 JSContext* cx, GarbageCollectionEvent::Ptr&& data);
428
429 // Return true if the given value is a Debugger object, false otherwise.
430 JS_PUBLIC_API bool IsDebugger(JSObject& obj);
431
432 // Append each of the debuggee global objects observed by the Debugger object
433 // |dbgObj| to |vector|. Returns true on success, false on failure.
434 JS_PUBLIC_API bool GetDebuggeeGlobals(JSContext* cx, JSObject& dbgObj,
435 MutableHandleObjectVector vector);
436
437 // Returns true if there's any debugger attached to the given context where
438 // the debugger's "shouldAvoidSideEffects" property is true.
439 //
440 // This is supposed to be used by native code that performs side-effectful
441 // operations where the debugger cannot hook it.
442 //
443 // If this function returns true, the native function should throw an
444 // uncatchable exception by returning `false` without setting any pending
445 // exception. The debugger will handle this exception by aborting the eager
446 // evaluation.
447 //
448 // The native code can opt into this behavior to help the debugger performing
449 // the side-effect-free evaluation.
450 //
451 // Expected consumers of this API include JSClassOps.resolve hooks which have
452 // any side-effect other than just resolving the property.
453 //
454 // Example:
455 // static bool ResolveHook(JSContext* cx, HandleObject obj, HandleId id,
456 // bool* resolvedp) {
457 // *resolvedp = false;
458 // if (JS::dbg::ShouldAvoidSideEffects()) {
459 // return false;
460 // }
461 // // Resolve the property with the side-effect.
462 // ...
463 // return true;
464 // }
465 bool ShouldAvoidSideEffects(JSContext* cx);
466
467 } // namespace dbg
468 } // namespace JS
469
470 #endif /* js_Debug_h */