summaryrefslogtreecommitdiffstats
path: root/js/src/debugger/DebuggerMemory.cpp
blob: 6a6c2d81235efe300792ed2dd2001cf106b911ab (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "debugger/DebuggerMemory.h"

#include "mozilla/Maybe.h"
#include "mozilla/Vector.h"

#include <stdlib.h>
#include <utility>

#include "jsapi.h"

#include "builtin/MapObject.h"
#include "debugger/Debugger.h"
#include "gc/Marking.h"
#include "js/AllocPolicy.h"
#include "js/Debug.h"
#include "js/friend/ErrorMessages.h"  // js::GetErrorMessage, JSMSG_*
#include "js/PropertySpec.h"
#include "js/TracingAPI.h"
#include "js/UbiNode.h"
#include "js/UbiNodeCensus.h"
#include "js/Utility.h"
#include "vm/GlobalObject.h"
#include "vm/JSContext.h"
#include "vm/PlainObject.h"  // js::PlainObject
#include "vm/Realm.h"
#include "vm/SavedStacks.h"

#include "debugger/Debugger-inl.h"
#include "gc/StableCellHasher-inl.h"
#include "vm/NativeObject-inl.h"

using namespace js;

using mozilla::Maybe;
using mozilla::Nothing;

/* static */
DebuggerMemory* DebuggerMemory::create(JSContext* cx, Debugger* dbg) {
  Value memoryProtoValue =
      dbg->object->getReservedSlot(Debugger::JSSLOT_DEBUG_MEMORY_PROTO);
  RootedObject memoryProto(cx, &memoryProtoValue.toObject());
  Rooted<DebuggerMemory*> memory(
      cx, NewObjectWithGivenProto<DebuggerMemory>(cx, memoryProto));
  if (!memory) {
    return nullptr;
  }

  dbg->object->setReservedSlot(Debugger::JSSLOT_DEBUG_MEMORY_INSTANCE,
                               ObjectValue(*memory));
  memory->setReservedSlot(JSSLOT_DEBUGGER, ObjectValue(*dbg->object));

  return memory;
}

Debugger* DebuggerMemory::getDebugger() {
  const Value& dbgVal = getReservedSlot(JSSLOT_DEBUGGER);
  return Debugger::fromJSObject(&dbgVal.toObject());
}

/* static */
bool DebuggerMemory::construct(JSContext* cx, unsigned argc, Value* vp) {
  JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR,
                            "Debugger.Source");
  return false;
}

/* static */ const JSClass DebuggerMemory::class_ = {
    "Memory", JSCLASS_HAS_RESERVED_SLOTS(JSSLOT_COUNT)};

/* static */
DebuggerMemory* DebuggerMemory::checkThis(JSContext* cx, CallArgs& args) {
  const Value& thisValue = args.thisv();

  if (!thisValue.isObject()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_OBJECT_REQUIRED,
                              InformalValueTypeName(thisValue));
    return nullptr;
  }

  JSObject& thisObject = thisValue.toObject();
  if (!thisObject.is<DebuggerMemory>()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_INCOMPATIBLE_PROTO, class_.name, "method",
                              thisObject.getClass()->name);
    return nullptr;
  }

  return &thisObject.as<DebuggerMemory>();
}

struct MOZ_STACK_CLASS DebuggerMemory::CallData {
  JSContext* cx;
  const CallArgs& args;

  Handle<DebuggerMemory*> memory;

  CallData(JSContext* cx, const CallArgs& args, Handle<DebuggerMemory*> memory)
      : cx(cx), args(args), memory(memory) {}

  // Accessor properties of Debugger.Memory.prototype.

  bool setTrackingAllocationSites();
  bool getTrackingAllocationSites();
  bool setMaxAllocationsLogLength();
  bool getMaxAllocationsLogLength();
  bool setAllocationSamplingProbability();
  bool getAllocationSamplingProbability();
  bool getAllocationsLogOverflowed();
  bool getOnGarbageCollection();
  bool setOnGarbageCollection();

  // Function properties of Debugger.Memory.prototype.

  bool takeCensus();
  bool drainAllocationsLog();

  using Method = bool (CallData::*)();

  template <Method MyMethod>
  static bool ToNative(JSContext* cx, unsigned argc, Value* vp);
};

template <DebuggerMemory::CallData::Method MyMethod>
/* static */
bool DebuggerMemory::CallData::ToNative(JSContext* cx, unsigned argc,
                                        Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  Rooted<DebuggerMemory*> memory(cx, DebuggerMemory::checkThis(cx, args));
  if (!memory) {
    return false;
  }

  CallData data(cx, args, memory);
  return (data.*MyMethod)();
}

static bool undefined(const CallArgs& args) {
  args.rval().setUndefined();
  return true;
}

bool DebuggerMemory::CallData::setTrackingAllocationSites() {
  if (!args.requireAtLeast(cx, "(set trackingAllocationSites)", 1)) {
    return false;
  }

  Debugger* dbg = memory->getDebugger();
  bool enabling = ToBoolean(args[0]);

  if (enabling == dbg->trackingAllocationSites) {
    return undefined(args);
  }

  dbg->trackingAllocationSites = enabling;

  if (enabling) {
    if (!dbg->addAllocationsTrackingForAllDebuggees(cx)) {
      dbg->trackingAllocationSites = false;
      return false;
    }
  } else {
    dbg->removeAllocationsTrackingForAllDebuggees();
  }

  return undefined(args);
}

bool DebuggerMemory::CallData::getTrackingAllocationSites() {
  args.rval().setBoolean(memory->getDebugger()->trackingAllocationSites);
  return true;
}

bool DebuggerMemory::CallData::drainAllocationsLog() {
  Debugger* dbg = memory->getDebugger();

  if (!dbg->trackingAllocationSites) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_NOT_TRACKING_ALLOCATIONS,
                              "drainAllocationsLog");
    return false;
  }

  size_t length = dbg->allocationsLog.length();

  Rooted<ArrayObject*> result(cx, NewDenseFullyAllocatedArray(cx, length));
  if (!result) {
    return false;
  }
  result->ensureDenseInitializedLength(0, length);

  for (size_t i = 0; i < length; i++) {
    Rooted<PlainObject*> obj(cx, NewPlainObject(cx));
    if (!obj) {
      return false;
    }

    // Don't pop the AllocationsLogEntry yet. The queue's links are followed
    // by the GC to find the AllocationsLogEntry, but are not barriered, so
    // we must edit them with great care. Use the queue entry in place, and
    // then pop and delete together.
    Debugger::AllocationsLogEntry& entry = dbg->allocationsLog.front();

    RootedValue frame(cx, ObjectOrNullValue(entry.frame));
    if (!DefineDataProperty(cx, obj, cx->names().frame, frame)) {
      return false;
    }

    double when =
        (entry.when - mozilla::TimeStamp::ProcessCreation()).ToMilliseconds();
    RootedValue timestampValue(cx, NumberValue(when));
    if (!DefineDataProperty(cx, obj, cx->names().timestamp, timestampValue)) {
      return false;
    }

    RootedString className(
        cx, Atomize(cx, entry.className, strlen(entry.className)));
    if (!className) {
      return false;
    }
    RootedValue classNameValue(cx, StringValue(className));
    if (!DefineDataProperty(cx, obj, cx->names().class_, classNameValue)) {
      return false;
    }

    RootedValue size(cx, NumberValue(entry.size));
    if (!DefineDataProperty(cx, obj, cx->names().size, size)) {
      return false;
    }

    RootedValue inNursery(cx, BooleanValue(entry.inNursery));
    if (!DefineDataProperty(cx, obj, cx->names().inNursery, inNursery)) {
      return false;
    }

    result->setDenseElement(i, ObjectValue(*obj));

    // Pop the front queue entry, and delete it immediately, so that the GC
    // sees the AllocationsLogEntry's HeapPtr barriers run atomically with
    // the change to the graph (the queue link).
    dbg->allocationsLog.popFront();
  }

  dbg->allocationsLogOverflowed = false;
  args.rval().setObject(*result);
  return true;
}

bool DebuggerMemory::CallData::getMaxAllocationsLogLength() {
  args.rval().setInt32(memory->getDebugger()->maxAllocationsLogLength);
  return true;
}

bool DebuggerMemory::CallData::setMaxAllocationsLogLength() {
  if (!args.requireAtLeast(cx, "(set maxAllocationsLogLength)", 1)) {
    return false;
  }

  int32_t max;
  if (!ToInt32(cx, args[0], &max)) {
    return false;
  }

  if (max < 1) {
    JS_ReportErrorNumberASCII(
        cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
        "(set maxAllocationsLogLength)'s parameter", "not a positive integer");
    return false;
  }

  Debugger* dbg = memory->getDebugger();
  dbg->maxAllocationsLogLength = max;

  while (dbg->allocationsLog.length() > dbg->maxAllocationsLogLength) {
    dbg->allocationsLog.popFront();
  }

  args.rval().setUndefined();
  return true;
}

bool DebuggerMemory::CallData::getAllocationSamplingProbability() {
  args.rval().setDouble(memory->getDebugger()->allocationSamplingProbability);
  return true;
}

bool DebuggerMemory::CallData::setAllocationSamplingProbability() {
  if (!args.requireAtLeast(cx, "(set allocationSamplingProbability)", 1)) {
    return false;
  }

  double probability;
  if (!ToNumber(cx, args[0], &probability)) {
    return false;
  }

  // Careful!  This must also reject NaN.
  if (!(0.0 <= probability && probability <= 1.0)) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_UNEXPECTED_TYPE,
                              "(set allocationSamplingProbability)'s parameter",
                              "not a number between 0 and 1");
    return false;
  }

  Debugger* dbg = memory->getDebugger();
  if (dbg->allocationSamplingProbability != probability) {
    dbg->allocationSamplingProbability = probability;

    // If this is a change any debuggees would observe, have all debuggee
    // realms recompute their sampling probabilities.
    if (dbg->trackingAllocationSites) {
      for (auto r = dbg->debuggees.all(); !r.empty(); r.popFront()) {
        r.front()->realm()->chooseAllocationSamplingProbability();
      }
    }
  }

  args.rval().setUndefined();
  return true;
}

bool DebuggerMemory::CallData::getAllocationsLogOverflowed() {
  args.rval().setBoolean(memory->getDebugger()->allocationsLogOverflowed);
  return true;
}

bool DebuggerMemory::CallData::getOnGarbageCollection() {
  return Debugger::getGarbageCollectionHook(cx, args, *memory->getDebugger());
}

bool DebuggerMemory::CallData::setOnGarbageCollection() {
  return Debugger::setGarbageCollectionHook(cx, args, *memory->getDebugger());
}

/* Debugger.Memory.prototype.takeCensus */

JS_PUBLIC_API void JS::dbg::SetDebuggerMallocSizeOf(
    JSContext* cx, mozilla::MallocSizeOf mallocSizeOf) {
  cx->runtime()->debuggerMallocSizeOf = mallocSizeOf;
}

JS_PUBLIC_API mozilla::MallocSizeOf JS::dbg::GetDebuggerMallocSizeOf(
    JSContext* cx) {
  return cx->runtime()->debuggerMallocSizeOf;
}

using JS::ubi::Census;
using JS::ubi::CountBasePtr;
using JS::ubi::CountTypePtr;

// The takeCensus function works in three phases:
//
// 1) We examine the 'breakdown' property of our 'options' argument, and
//    use that to build a CountType tree.
//
// 2) We create a count node for the root of our CountType tree, and then walk
//    the heap, counting each node we find, expanding our tree of counts as we
//    go.
//
// 3) We walk the tree of counts and produce JavaScript objects reporting the
//    accumulated results.
bool DebuggerMemory::CallData::takeCensus() {
  Census census(cx);
  CountTypePtr rootType;

  RootedObject options(cx);
  if (args.get(0).isObject()) {
    options = &args[0].toObject();
  }

  if (!JS::ubi::ParseCensusOptions(cx, census, options, rootType)) {
    return false;
  }

  JS::ubi::RootedCount rootCount(cx, rootType->makeCount());
  if (!rootCount) {
    ReportOutOfMemory(cx);
    return false;
  }
  JS::ubi::CensusHandler handler(census, rootCount,
                                 cx->runtime()->debuggerMallocSizeOf);

  Debugger* dbg = memory->getDebugger();
  RootedObject dbgObj(cx, dbg->object);

  // Populate our target set of debuggee zones.
  for (WeakGlobalObjectSet::Range r = dbg->allDebuggees(); !r.empty();
       r.popFront()) {
    if (!census.targetZones.put(r.front()->zone())) {
      ReportOutOfMemory(cx);
      return false;
    }
  }

  {
    JS::ubi::RootList rootList(cx);
    auto [ok, nogc] = rootList.init(dbgObj);
    if (!ok) {
      ReportOutOfMemory(cx);
      return false;
    }

    JS::ubi::CensusTraversal traversal(cx, handler, nogc);
    traversal.wantNames = false;

    if (!traversal.addStart(JS::ubi::Node(&rootList)) ||
        !traversal.traverse()) {
      ReportOutOfMemory(cx);
      return false;
    }
  }

  return handler.report(cx, args.rval());
}

/* Debugger.Memory property and method tables. */

/* static */ const JSPropertySpec DebuggerMemory::properties[] = {
    JS_DEBUG_PSGS("trackingAllocationSites", getTrackingAllocationSites,
                  setTrackingAllocationSites),
    JS_DEBUG_PSGS("maxAllocationsLogLength", getMaxAllocationsLogLength,
                  setMaxAllocationsLogLength),
    JS_DEBUG_PSGS("allocationSamplingProbability",
                  getAllocationSamplingProbability,
                  setAllocationSamplingProbability),
    JS_DEBUG_PSG("allocationsLogOverflowed", getAllocationsLogOverflowed),
    JS_DEBUG_PSGS("onGarbageCollection", getOnGarbageCollection,
                  setOnGarbageCollection),
    JS_PS_END};

/* static */ const JSFunctionSpec DebuggerMemory::methods[] = {
    JS_DEBUG_FN("drainAllocationsLog", drainAllocationsLog, 0),
    JS_DEBUG_FN("takeCensus", takeCensus, 0), JS_FS_END};