summaryrefslogtreecommitdiffstats
path: root/js/src/vm/UbiNode.cpp
blob: 80312bbb7ac5cebbe11ff081d791aab6d9968d02 (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
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * 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 "js/UbiNode.h"

#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/Range.h"
#include "mozilla/Scoped.h"

#include <algorithm>

#include "jscntxt.h"
#include "jsobj.h"
#include "jsscript.h"
#include "jsstr.h"

#include "jit/IonCode.h"
#include "js/Debug.h"
#include "js/TracingAPI.h"
#include "js/TypeDecls.h"
#include "js/Utility.h"
#include "js/Vector.h"
#include "vm/Debugger.h"
#include "vm/EnvironmentObject.h"
#include "vm/GlobalObject.h"
#include "vm/Scope.h"
#include "vm/Shape.h"
#include "vm/String.h"
#include "vm/Symbol.h"

#include "jsobjinlines.h"
#include "vm/Debugger-inl.h"

using namespace js;

using mozilla::Some;
using mozilla::RangedPtr;
using JS::DispatchTyped;
using JS::HandleValue;
using JS::Value;
using JS::ZoneSet;
using JS::ubi::AtomOrTwoByteChars;
using JS::ubi::CoarseType;
using JS::ubi::Concrete;
using JS::ubi::Edge;
using JS::ubi::EdgeRange;
using JS::ubi::Node;
using JS::ubi::EdgeVector;
using JS::ubi::StackFrame;
using JS::ubi::TracerConcrete;
using JS::ubi::TracerConcreteWithCompartment;

struct CopyToBufferMatcher
{
    RangedPtr<char16_t> destination;
    size_t              maxLength;

    CopyToBufferMatcher(RangedPtr<char16_t> destination, size_t maxLength)
      : destination(destination)
      , maxLength(maxLength)
    { }

    template<typename CharT>
    static size_t
    copyToBufferHelper(const CharT* src, RangedPtr<char16_t> dest, size_t length)
    {
        size_t i = 0;
        for ( ; i < length; i++)
            dest[i] = src[i];
        return i;
    }

    size_t
    match(JSAtom* atom)
    {
        if (!atom)
            return 0;

        size_t length = std::min(atom->length(), maxLength);
        JS::AutoCheckCannotGC noGC;
        return atom->hasTwoByteChars()
            ? copyToBufferHelper(atom->twoByteChars(noGC), destination, length)
            : copyToBufferHelper(atom->latin1Chars(noGC), destination, length);
    }

    size_t
    match(const char16_t* chars)
    {
        if (!chars)
            return 0;

        size_t length = std::min(js_strlen(chars), maxLength);
        return copyToBufferHelper(chars, destination, length);
    }
};

size_t
JS::ubi::AtomOrTwoByteChars::copyToBuffer(RangedPtr<char16_t> destination, size_t length)
{
    CopyToBufferMatcher m(destination, length);
    return match(m);
}

struct LengthMatcher
{
    size_t
    match(JSAtom* atom)
    {
        return atom ? atom->length() : 0;
    }

    size_t
    match(const char16_t* chars)
    {
        return chars ? js_strlen(chars) : 0;
    }
};

size_t
JS::ubi::AtomOrTwoByteChars::length()
{
    LengthMatcher m;
    return match(m);
}

size_t
StackFrame::source(RangedPtr<char16_t> destination, size_t length) const
{
    auto s = source();
    return s.copyToBuffer(destination, length);
}

size_t
StackFrame::functionDisplayName(RangedPtr<char16_t> destination, size_t length) const
{
    auto name = functionDisplayName();
    return name.copyToBuffer(destination, length);
}

size_t
StackFrame::sourceLength()
{
    return source().length();
}

size_t
StackFrame::functionDisplayNameLength()
{
    return functionDisplayName().length();
}

// All operations on null ubi::Nodes crash.
CoarseType Concrete<void>::coarseType() const      { MOZ_CRASH("null ubi::Node"); }
const char16_t* Concrete<void>::typeName() const   { MOZ_CRASH("null ubi::Node"); }
JS::Zone* Concrete<void>::zone() const             { MOZ_CRASH("null ubi::Node"); }
JSCompartment* Concrete<void>::compartment() const { MOZ_CRASH("null ubi::Node"); }

UniquePtr<EdgeRange>
Concrete<void>::edges(JSContext*, bool) const {
    MOZ_CRASH("null ubi::Node");
}

Node::Size
Concrete<void>::size(mozilla::MallocSizeOf mallocSizeof) const
{
    MOZ_CRASH("null ubi::Node");
}

struct Node::ConstructFunctor : public js::BoolDefaultAdaptor<Value, false> {
    template <typename T> bool operator()(T* t, Node* node) { node->construct(t); return true; }
};

Node::Node(const JS::GCCellPtr &thing)
{
    DispatchTyped(ConstructFunctor(), thing, this);
}

Node::Node(HandleValue value)
{
    if (!DispatchTyped(ConstructFunctor(), value, this))
        construct<void>(nullptr);
}

Value
Node::exposeToJS() const
{
    Value v;

    if (is<JSObject>()) {
        JSObject& obj = *as<JSObject>();
        if (obj.is<js::EnvironmentObject>()) {
            v.setUndefined();
        } else if (obj.is<JSFunction>() && js::IsInternalFunctionObject(obj)) {
            v.setUndefined();
        } else {
            v.setObject(obj);
        }
    } else if (is<JSString>()) {
        v.setString(as<JSString>());
    } else if (is<JS::Symbol>()) {
        v.setSymbol(as<JS::Symbol>());
    } else {
        v.setUndefined();
    }

    ExposeValueToActiveJS(v);

    return v;
}


// A JS::CallbackTracer subclass that adds a Edge to a Vector for each
// edge on which it is invoked.
class EdgeVectorTracer : public JS::CallbackTracer {
    // The vector to which we add Edges.
    EdgeVector* vec;

    // True if we should populate the edge's names.
    bool wantNames;

    void onChild(const JS::GCCellPtr& thing) override {
        if (!okay)
            return;

        // Don't trace permanent atoms and well-known symbols that are owned by
        // a parent JSRuntime.
        if (thing.is<JSString>() && thing.as<JSString>().isPermanentAtom())
            return;
        if (thing.is<JS::Symbol>() && thing.as<JS::Symbol>().isWellKnownSymbol())
            return;

        char16_t* name16 = nullptr;
        if (wantNames) {
            // Ask the tracer to compute an edge name for us.
            char buffer[1024];
            getTracingEdgeName(buffer, sizeof(buffer));
            const char* name = buffer;

            // Convert the name to char16_t characters.
            name16 = js_pod_malloc<char16_t>(strlen(name) + 1);
            if (!name16) {
                okay = false;
                return;
            }

            size_t i;
            for (i = 0; name[i]; i++)
                name16[i] = name[i];
            name16[i] = '\0';
        }

        // The simplest code is correct! The temporary Edge takes
        // ownership of name; if the append succeeds, the vector element
        // then takes ownership; if the append fails, then the temporary
        // retains it, and its destructor will free it.
        if (!vec->append(mozilla::Move(Edge(name16, Node(thing))))) {
            okay = false;
            return;
        }
    }

  public:
    // True if no errors (OOM, say) have yet occurred.
    bool okay;

    EdgeVectorTracer(JSRuntime* rt, EdgeVector* vec, bool wantNames)
      : JS::CallbackTracer(rt),
        vec(vec),
        wantNames(wantNames),
        okay(true)
    { }
};


// An EdgeRange concrete class that simply holds a vector of Edges,
// populated by the init method.
class SimpleEdgeRange : public EdgeRange {
    EdgeVector edges;
    size_t i;

    void settle() {
        front_ = i < edges.length() ? &edges[i] : nullptr;
    }

  public:
    explicit SimpleEdgeRange() : edges(), i(0) { }

    bool init(JSRuntime* rt, void* thing, JS::TraceKind kind, bool wantNames = true) {
        EdgeVectorTracer tracer(rt, &edges, wantNames);
        js::TraceChildren(&tracer, thing, kind);
        settle();
        return tracer.okay;
    }

    void popFront() override { i++; settle(); }
};


template<typename Referent>
JS::Zone*
TracerConcrete<Referent>::zone() const
{
    return get().zoneFromAnyThread();
}

template JS::Zone* TracerConcrete<JSScript>::zone() const;
template JS::Zone* TracerConcrete<js::LazyScript>::zone() const;
template JS::Zone* TracerConcrete<js::Shape>::zone() const;
template JS::Zone* TracerConcrete<js::BaseShape>::zone() const;
template JS::Zone* TracerConcrete<js::ObjectGroup>::zone() const;
template JS::Zone* TracerConcrete<js::Scope>::zone() const;
template JS::Zone* TracerConcrete<JS::Symbol>::zone() const;
template JS::Zone* TracerConcrete<JSString>::zone() const;

template<typename Referent>
UniquePtr<EdgeRange>
TracerConcrete<Referent>::edges(JSContext* cx, bool wantNames) const {
    UniquePtr<SimpleEdgeRange, JS::DeletePolicy<SimpleEdgeRange>> range(js_new<SimpleEdgeRange>());
    if (!range)
        return nullptr;

    if (!range->init(cx, ptr, JS::MapTypeToTraceKind<Referent>::kind, wantNames))
        return nullptr;

    return UniquePtr<EdgeRange>(range.release());
}

template UniquePtr<EdgeRange> TracerConcrete<JSScript>::edges(JSContext* cx, bool wantNames) const;
template UniquePtr<EdgeRange> TracerConcrete<js::LazyScript>::edges(JSContext* cx, bool wantNames) const;
template UniquePtr<EdgeRange> TracerConcrete<js::Shape>::edges(JSContext* cx, bool wantNames) const;
template UniquePtr<EdgeRange> TracerConcrete<js::BaseShape>::edges(JSContext* cx, bool wantNames) const;
template UniquePtr<EdgeRange> TracerConcrete<js::ObjectGroup>::edges(JSContext* cx, bool wantNames) const;
template UniquePtr<EdgeRange> TracerConcrete<js::Scope>::edges(JSContext* cx, bool wantNames) const;
template UniquePtr<EdgeRange> TracerConcrete<JS::Symbol>::edges(JSContext* cx, bool wantNames) const;
template UniquePtr<EdgeRange> TracerConcrete<JSString>::edges(JSContext* cx, bool wantNames) const;

template<typename Referent>
JSCompartment*
TracerConcreteWithCompartment<Referent>::compartment() const
{
    return TracerBase::get().compartment();
}

template JSCompartment* TracerConcreteWithCompartment<JSScript>::compartment() const;

bool
Concrete<JSObject>::hasAllocationStack() const
{
    return !!js::Debugger::getObjectAllocationSite(get());
}

StackFrame
Concrete<JSObject>::allocationStack() const
{
    MOZ_ASSERT(hasAllocationStack());
    return StackFrame(js::Debugger::getObjectAllocationSite(get()));
}

const char*
Concrete<JSObject>::jsObjectClassName() const
{
    return Concrete::get().getClass()->name;
}

bool
Concrete<JSObject>::jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) const
{
    JSAtom* name = Concrete::get().maybeConstructorDisplayAtom();
    if (!name) {
        outName.reset(nullptr);
        return true;
    }

    auto len = JS_GetStringLength(name);
    auto size = len + 1;

    outName.reset(cx->pod_malloc<char16_t>(size * sizeof(char16_t)));
    if (!outName)
        return false;

    mozilla::Range<char16_t> chars(outName.get(), size);
    if (!JS_CopyStringChars(cx, chars, name))
        return false;

    outName[len] = '\0';
    return true;
}

const char16_t Concrete<JS::Symbol>::concreteTypeName[] = u"JS::Symbol";
const char16_t Concrete<JSScript>::concreteTypeName[] = u"JSScript";
const char16_t Concrete<js::LazyScript>::concreteTypeName[] = u"js::LazyScript";
const char16_t Concrete<js::jit::JitCode>::concreteTypeName[] = u"js::jit::JitCode";
const char16_t Concrete<js::Shape>::concreteTypeName[] = u"js::Shape";
const char16_t Concrete<js::BaseShape>::concreteTypeName[] = u"js::BaseShape";
const char16_t Concrete<js::ObjectGroup>::concreteTypeName[] = u"js::ObjectGroup";
const char16_t Concrete<js::Scope>::concreteTypeName[] = u"js::Scope";

namespace JS {
namespace ubi {

RootList::RootList(JSContext* cx, Maybe<AutoCheckCannotGC>& noGC, bool wantNames /* = false */)
  : noGC(noGC),
    cx(cx),
    edges(),
    wantNames(wantNames)
{ }


bool
RootList::init()
{
    EdgeVectorTracer tracer(cx, &edges, wantNames);
    js::TraceRuntime(&tracer);
    if (!tracer.okay)
        return false;
    noGC.emplace(cx);
    return true;
}

bool
RootList::init(CompartmentSet& debuggees)
{
    EdgeVector allRootEdges;
    EdgeVectorTracer tracer(cx, &allRootEdges, wantNames);

    ZoneSet debuggeeZones;
    if (!debuggeeZones.init())
        return false;
    for (auto range = debuggees.all(); !range.empty(); range.popFront()) {
        if (!debuggeeZones.put(range.front()->zone()))
            return false;
    }

    js::TraceRuntime(&tracer);
    if (!tracer.okay)
        return false;
    TraceIncomingCCWs(&tracer, debuggees);
    if (!tracer.okay)
        return false;

    for (EdgeVector::Range r = allRootEdges.all(); !r.empty(); r.popFront()) {
        Edge& edge = r.front();

        JSCompartment* compartment = edge.referent.compartment();
        if (compartment && !debuggees.has(compartment))
            continue;

        Zone* zone = edge.referent.zone();
        if (zone && !debuggeeZones.has(zone))
            continue;

        if (!edges.append(mozilla::Move(edge)))
            return false;
    }

    noGC.emplace(cx);
    return true;
}

bool
RootList::init(HandleObject debuggees)
{
    MOZ_ASSERT(debuggees && JS::dbg::IsDebugger(*debuggees));
    js::Debugger* dbg = js::Debugger::fromJSObject(debuggees.get());

    CompartmentSet debuggeeCompartments;
    if (!debuggeeCompartments.init())
        return false;

    for (js::WeakGlobalObjectSet::Range r = dbg->allDebuggees(); !r.empty(); r.popFront()) {
        if (!debuggeeCompartments.put(r.front()->compartment()))
            return false;
    }

    if (!init(debuggeeCompartments))
        return false;

    // Ensure that each of our debuggee globals are in the root list.
    for (js::WeakGlobalObjectSet::Range r = dbg->allDebuggees(); !r.empty(); r.popFront()) {
        if (!addRoot(JS::ubi::Node(static_cast<JSObject*>(r.front())),
                     u"debuggee global"))
        {
            return false;
        }
    }

    return true;
}

bool
RootList::addRoot(Node node, const char16_t* edgeName)
{
    MOZ_ASSERT(noGC.isSome());
    MOZ_ASSERT_IF(wantNames, edgeName);

    UniqueTwoByteChars name;
    if (edgeName) {
        name = js::DuplicateString(edgeName);
        if (!name)
            return false;
    }

    return edges.append(mozilla::Move(Edge(name.release(), node)));
}

const char16_t Concrete<RootList>::concreteTypeName[] = u"JS::ubi::RootList";

UniquePtr<EdgeRange>
Concrete<RootList>::edges(JSContext* cx, bool wantNames) const {
    MOZ_ASSERT_IF(wantNames, get().wantNames);
    return UniquePtr<EdgeRange>(js_new<PreComputedEdgeRange>(get().edges));
}

} // namespace ubi
} // namespace JS