forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSavedStacks.cpp
1568 lines (1346 loc) · 50.6 KB
/
SavedStacks.cpp
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* 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 "vm/SavedStacks.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Move.h"
#include <algorithm>
#include <math.h>
#include "jsapi.h"
#include "jscompartment.h"
#include "jsfriendapi.h"
#include "jshashutil.h"
#include "jsmath.h"
#include "jsnum.h"
#include "jsscript.h"
#include "gc/Marking.h"
#include "gc/Rooting.h"
#include "js/Vector.h"
#include "vm/Debugger.h"
#include "vm/SavedFrame.h"
#include "vm/StringBuffer.h"
#include "vm/Time.h"
#include "vm/WrapperObject.h"
#include "jscntxtinlines.h"
#include "vm/NativeObject-inl.h"
#include "vm/Stack-inl.h"
using mozilla::AddToHash;
using mozilla::DebugOnly;
using mozilla::HashString;
using mozilla::Maybe;
using mozilla::Move;
using mozilla::Nothing;
using mozilla::Some;
namespace js {
/**
* Maximum number of saved frames returned for an async stack.
*/
const unsigned ASYNC_STACK_MAX_FRAME_COUNT = 60;
/* static */ Maybe<LiveSavedFrameCache::FramePtr>
LiveSavedFrameCache::getFramePtr(FrameIter& iter)
{
if (iter.hasUsableAbstractFramePtr())
return Some(FramePtr(iter.abstractFramePtr()));
if (iter.isPhysicalIonFrame())
return Some(FramePtr(iter.physicalIonFrame()));
return Nothing();
}
/* static */ void
LiveSavedFrameCache::trace(LiveSavedFrameCache* cache, JSTracer* trc)
{
if (!cache->initialized())
return;
for (auto* entry = cache->frames->begin(); entry < cache->frames->end(); entry++) {
TraceEdge(trc,
&entry->savedFrame,
"LiveSavedFrameCache::frames SavedFrame");
}
}
bool
LiveSavedFrameCache::insert(JSContext* cx, FramePtr& framePtr, jsbytecode* pc,
HandleSavedFrame savedFrame)
{
MOZ_ASSERT(initialized());
if (!frames->emplaceBack(framePtr, pc, savedFrame)) {
ReportOutOfMemory(cx);
return false;
}
// Safe to dereference the cache key because the stack frames are still
// live. After this point, they should never be dereferenced again.
if (framePtr.is<AbstractFramePtr>())
framePtr.as<AbstractFramePtr>().setHasCachedSavedFrame();
else
framePtr.as<jit::CommonFrameLayout*>()->setHasCachedSavedFrame();
return true;
}
void
LiveSavedFrameCache::find(JSContext* cx, FrameIter& frameIter, MutableHandleSavedFrame frame) const
{
MOZ_ASSERT(initialized());
MOZ_ASSERT(!frameIter.done());
MOZ_ASSERT(frameIter.hasCachedSavedFrame());
Maybe<FramePtr> maybeFramePtr = getFramePtr(frameIter);
MOZ_ASSERT(maybeFramePtr.isSome());
FramePtr framePtr(*maybeFramePtr);
jsbytecode* pc = frameIter.pc();
size_t numberStillValid = 0;
frame.set(nullptr);
for (auto* p = frames->begin(); p < frames->end(); p++) {
numberStillValid++;
if (framePtr == p->framePtr && pc == p->pc) {
frame.set(p->savedFrame);
break;
}
}
if (!frame) {
frames->clear();
return;
}
MOZ_ASSERT(0 < numberStillValid && numberStillValid <= frames->length());
if (frame->compartment() != cx->compartment()) {
frame.set(nullptr);
numberStillValid--;
}
// Everything after the cached SavedFrame are stale younger frames we have
// since popped.
frames->shrinkBy(frames->length() - numberStillValid);
}
struct SavedFrame::Lookup {
Lookup(JSAtom* source, uint32_t line, uint32_t column,
JSAtom* functionDisplayName, JSAtom* asyncCause, SavedFrame* parent,
JSPrincipals* principals, Maybe<LiveSavedFrameCache::FramePtr> framePtr = Nothing(),
jsbytecode* pc = nullptr, Activation* activation = nullptr)
: source(source),
line(line),
column(column),
functionDisplayName(functionDisplayName),
asyncCause(asyncCause),
parent(parent),
principals(principals),
framePtr(framePtr),
pc(pc),
activation(activation)
{
MOZ_ASSERT(source);
MOZ_ASSERT_IF(framePtr.isSome(), pc);
MOZ_ASSERT_IF(framePtr.isSome(), activation);
}
explicit Lookup(SavedFrame& savedFrame)
: source(savedFrame.getSource()),
line(savedFrame.getLine()),
column(savedFrame.getColumn()),
functionDisplayName(savedFrame.getFunctionDisplayName()),
asyncCause(savedFrame.getAsyncCause()),
parent(savedFrame.getParent()),
principals(savedFrame.getPrincipals()),
framePtr(Nothing()),
pc(nullptr),
activation(nullptr)
{
MOZ_ASSERT(source);
}
JSAtom* source;
uint32_t line;
uint32_t column;
JSAtom* functionDisplayName;
JSAtom* asyncCause;
SavedFrame* parent;
JSPrincipals* principals;
// These are used only by the LiveSavedFrameCache and not used for identity or
// hashing.
Maybe<LiveSavedFrameCache::FramePtr> framePtr;
jsbytecode* pc;
Activation* activation;
void trace(JSTracer* trc) {
TraceManuallyBarrieredEdge(trc, &source, "SavedFrame::Lookup::source");
if (functionDisplayName) {
TraceManuallyBarrieredEdge(trc, &functionDisplayName,
"SavedFrame::Lookup::functionDisplayName");
}
if (asyncCause)
TraceManuallyBarrieredEdge(trc, &asyncCause, "SavedFrame::Lookup::asyncCause");
if (parent)
TraceManuallyBarrieredEdge(trc, &parent, "SavedFrame::Lookup::parent");
}
};
class MOZ_STACK_CLASS SavedFrame::AutoLookupVector : public JS::CustomAutoRooter {
public:
explicit AutoLookupVector(JSContext* cx)
: JS::CustomAutoRooter(cx),
lookups(cx)
{ }
typedef Vector<Lookup, ASYNC_STACK_MAX_FRAME_COUNT> LookupVector;
inline LookupVector* operator->() { return &lookups; }
inline HandleLookup operator[](size_t i) { return HandleLookup(lookups[i]); }
private:
LookupVector lookups;
virtual void trace(JSTracer* trc) {
for (size_t i = 0; i < lookups.length(); i++)
lookups[i].trace(trc);
}
};
/* static */ HashNumber
SavedFrame::HashPolicy::hash(const Lookup& lookup)
{
JS::AutoCheckCannotGC nogc;
// Assume that we can take line mod 2^32 without losing anything of
// interest. If that assumption changes, we'll just need to start with 0
// and add another overload of AddToHash with more arguments.
return AddToHash(lookup.line,
lookup.column,
lookup.source,
lookup.functionDisplayName,
lookup.asyncCause,
SavedFramePtrHasher::hash(lookup.parent),
JSPrincipalsPtrHasher::hash(lookup.principals));
}
/* static */ bool
SavedFrame::HashPolicy::match(SavedFrame* existing, const Lookup& lookup)
{
if (existing->getLine() != lookup.line)
return false;
if (existing->getColumn() != lookup.column)
return false;
if (existing->getParent() != lookup.parent)
return false;
if (existing->getPrincipals() != lookup.principals)
return false;
JSAtom* source = existing->getSource();
if (source != lookup.source)
return false;
JSAtom* functionDisplayName = existing->getFunctionDisplayName();
if (functionDisplayName != lookup.functionDisplayName)
return false;
JSAtom* asyncCause = existing->getAsyncCause();
if (asyncCause != lookup.asyncCause)
return false;
return true;
}
/* static */ void
SavedFrame::HashPolicy::rekey(Key& key, const Key& newKey)
{
key = newKey;
}
/* static */ bool
SavedFrame::finishSavedFrameInit(JSContext* cx, HandleObject ctor, HandleObject proto)
{
// The only object with the SavedFrame::class_ that doesn't have a source
// should be the prototype.
proto->as<NativeObject>().setReservedSlot(SavedFrame::JSSLOT_SOURCE, NullValue());
return FreezeObject(cx, proto);
}
/* static */ const Class SavedFrame::class_ = {
"SavedFrame",
JSCLASS_HAS_PRIVATE |
JSCLASS_HAS_RESERVED_SLOTS(SavedFrame::JSSLOT_COUNT) |
JSCLASS_HAS_CACHED_PROTO(JSProto_SavedFrame) |
JSCLASS_IS_ANONYMOUS,
nullptr, // addProperty
nullptr, // delProperty
nullptr, // getProperty
nullptr, // setProperty
nullptr, // enumerate
nullptr, // resolve
nullptr, // mayResolve
SavedFrame::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
nullptr, // trace
// ClassSpec
{
GenericCreateConstructor<SavedFrame::construct, 0, gc::AllocKind::FUNCTION>,
GenericCreatePrototype,
SavedFrame::staticFunctions,
nullptr,
SavedFrame::protoFunctions,
SavedFrame::protoAccessors,
SavedFrame::finishSavedFrameInit,
ClassSpec::DontDefineConstructor
}
};
/* static */ const JSFunctionSpec
SavedFrame::staticFunctions[] = {
JS_FS_END
};
/* static */ const JSFunctionSpec
SavedFrame::protoFunctions[] = {
JS_FN("constructor", SavedFrame::construct, 0, 0),
JS_FN("toString", SavedFrame::toStringMethod, 0, 0),
JS_FS_END
};
/* static */ const JSPropertySpec
SavedFrame::protoAccessors[] = {
JS_PSG("source", SavedFrame::sourceProperty, 0),
JS_PSG("line", SavedFrame::lineProperty, 0),
JS_PSG("column", SavedFrame::columnProperty, 0),
JS_PSG("functionDisplayName", SavedFrame::functionDisplayNameProperty, 0),
JS_PSG("asyncCause", SavedFrame::asyncCauseProperty, 0),
JS_PSG("asyncParent", SavedFrame::asyncParentProperty, 0),
JS_PSG("parent", SavedFrame::parentProperty, 0),
JS_PS_END
};
/* static */ void
SavedFrame::finalize(FreeOp* fop, JSObject* obj)
{
JSPrincipals* p = obj->as<SavedFrame>().getPrincipals();
if (p) {
JSRuntime* rt = obj->runtimeFromMainThread();
JS_DropPrincipals(rt, p);
}
}
JSAtom*
SavedFrame::getSource()
{
const Value& v = getReservedSlot(JSSLOT_SOURCE);
JSString* s = v.toString();
return &s->asAtom();
}
uint32_t
SavedFrame::getLine()
{
const Value& v = getReservedSlot(JSSLOT_LINE);
return v.toPrivateUint32();
}
uint32_t
SavedFrame::getColumn()
{
const Value& v = getReservedSlot(JSSLOT_COLUMN);
return v.toPrivateUint32();
}
JSAtom*
SavedFrame::getFunctionDisplayName()
{
const Value& v = getReservedSlot(JSSLOT_FUNCTIONDISPLAYNAME);
if (v.isNull())
return nullptr;
JSString* s = v.toString();
return &s->asAtom();
}
JSAtom*
SavedFrame::getAsyncCause()
{
const Value& v = getReservedSlot(JSSLOT_ASYNCCAUSE);
if (v.isNull())
return nullptr;
JSString* s = v.toString();
return &s->asAtom();
}
SavedFrame*
SavedFrame::getParent() const
{
const Value& v = getReservedSlot(JSSLOT_PARENT);
return v.isObject() ? &v.toObject().as<SavedFrame>() : nullptr;
}
JSPrincipals*
SavedFrame::getPrincipals()
{
const Value& v = getReservedSlot(JSSLOT_PRINCIPALS);
if (v.isUndefined())
return nullptr;
return static_cast<JSPrincipals*>(v.toPrivate());
}
void
SavedFrame::initSource(JSAtom* source)
{
MOZ_ASSERT(source);
initReservedSlot(JSSLOT_SOURCE, StringValue(source));
}
void
SavedFrame::initLine(uint32_t line)
{
initReservedSlot(JSSLOT_LINE, PrivateUint32Value(line));
}
void
SavedFrame::initColumn(uint32_t column)
{
initReservedSlot(JSSLOT_COLUMN, PrivateUint32Value(column));
}
void
SavedFrame::initPrincipals(JSPrincipals* principals)
{
if (principals)
JS_HoldPrincipals(principals);
initPrincipalsAlreadyHeld(principals);
}
void
SavedFrame::initPrincipalsAlreadyHeld(JSPrincipals* principals)
{
MOZ_ASSERT_IF(principals, principals->refcount > 0);
initReservedSlot(JSSLOT_PRINCIPALS, PrivateValue(principals));
}
void
SavedFrame::initFunctionDisplayName(JSAtom* maybeName)
{
initReservedSlot(JSSLOT_FUNCTIONDISPLAYNAME, maybeName ? StringValue(maybeName) : NullValue());
}
void
SavedFrame::initAsyncCause(JSAtom* maybeCause)
{
initReservedSlot(JSSLOT_ASYNCCAUSE, maybeCause ? StringValue(maybeCause) : NullValue());
}
void
SavedFrame::initParent(SavedFrame* maybeParent)
{
initReservedSlot(JSSLOT_PARENT, ObjectOrNullValue(maybeParent));
}
void
SavedFrame::initFromLookup(SavedFrame::HandleLookup lookup)
{
initSource(lookup->source);
initLine(lookup->line);
initColumn(lookup->column);
initFunctionDisplayName(lookup->functionDisplayName);
initAsyncCause(lookup->asyncCause);
initParent(lookup->parent);
initPrincipals(lookup->principals);
}
/* static */ SavedFrame*
SavedFrame::create(JSContext* cx)
{
RootedGlobalObject global(cx, cx->global());
assertSameCompartment(cx, global);
// Ensure that we don't try to capture the stack again in the
// `SavedStacksMetadataCallback` for this new SavedFrame object, and
// accidentally cause O(n^2) behavior.
SavedStacks::AutoReentrancyGuard guard(cx->compartment()->savedStacks());
RootedNativeObject proto(cx, GlobalObject::getOrCreateSavedFramePrototype(cx, global));
if (!proto)
return nullptr;
assertSameCompartment(cx, proto);
RootedObject frameObj(cx, NewObjectWithGivenProto(cx, &SavedFrame::class_, proto));
if (!frameObj)
return nullptr;
return &frameObj->as<SavedFrame>();
}
bool
SavedFrame::isSelfHosted()
{
JSAtom* source = getSource();
return StringEqualsAscii(source, "self-hosted");
}
/* static */ bool
SavedFrame::construct(JSContext* cx, unsigned argc, Value* vp)
{
JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR,
"SavedFrame");
return false;
}
static bool
SavedFrameSubsumedByCaller(JSContext* cx, HandleSavedFrame frame)
{
auto subsumes = cx->runtime()->securityCallbacks->subsumes;
if (!subsumes)
return true;
auto currentCompartmentPrincipals = cx->compartment()->principals();
MOZ_ASSERT(!ReconstructedSavedFramePrincipals::is(currentCompartmentPrincipals));
auto framePrincipals = frame->getPrincipals();
// Handle SavedFrames that have been reconstructed from stacks in a heap
// snapshot.
if (framePrincipals == &ReconstructedSavedFramePrincipals::IsSystem)
return cx->runningWithTrustedPrincipals();
if (framePrincipals == &ReconstructedSavedFramePrincipals::IsNotSystem)
return true;
return subsumes(currentCompartmentPrincipals, framePrincipals);
}
// Return the first SavedFrame in the chain that starts with |frame| whose
// principals are subsumed by |principals|, according to |subsumes|. If there is
// no such frame, return nullptr. |skippedAsync| is set to true if any of the
// skipped frames had the |asyncCause| property set, otherwise it is explicitly
// set to false.
static SavedFrame*
GetFirstSubsumedFrame(JSContext* cx, HandleSavedFrame frame, JS::SavedFrameSelfHosted selfHosted,
bool& skippedAsync)
{
skippedAsync = false;
RootedSavedFrame rootedFrame(cx, frame);
while (rootedFrame) {
if ((selfHosted == JS::SavedFrameSelfHosted::Include || !rootedFrame->isSelfHosted()) &&
SavedFrameSubsumedByCaller(cx, rootedFrame))
{
return rootedFrame;
}
if (rootedFrame->getAsyncCause())
skippedAsync = true;
rootedFrame = rootedFrame->getParent();
}
return nullptr;
}
JS_FRIEND_API(JSObject*)
GetFirstSubsumedSavedFrame(JSContext* cx, HandleObject savedFrame,
JS::SavedFrameSelfHosted selfHosted)
{
if (!savedFrame)
return nullptr;
bool skippedAsync;
RootedSavedFrame frame(cx, &savedFrame->as<SavedFrame>());
return GetFirstSubsumedFrame(cx, frame, selfHosted, skippedAsync);
}
/* static */ bool
SavedFrame::checkThis(JSContext* cx, CallArgs& args, const char* fnName,
MutableHandleObject frame)
{
const Value& thisValue = args.thisv();
if (!thisValue.isObject()) {
JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT, InformalValueTypeName(thisValue));
return false;
}
JSObject* thisObject = CheckedUnwrap(&thisValue.toObject());
if (!thisObject || !thisObject->is<SavedFrame>()) {
JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO,
SavedFrame::class_.name, fnName,
thisObject ? thisObject->getClass()->name : "object");
return false;
}
// Check for SavedFrame.prototype, which has the same class as SavedFrame
// instances, however doesn't actually represent a captured stack frame. It
// is the only object that is<SavedFrame>() but doesn't have a source.
if (thisObject->as<SavedFrame>().getReservedSlot(JSSLOT_SOURCE).isNull()) {
JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO,
SavedFrame::class_.name, fnName, "prototype object");
return false;
}
// Now set "frame" to the actual object we were invoked in (which may be a
// wrapper), not the unwrapped version. Consumers will need to know what
// that original object was, and will do principal checks as needed.
frame.set(&thisValue.toObject());
return true;
}
// Get the SavedFrame * from the current this value and handle any errors that
// might occur therein.
//
// These parameters must already exist when calling this macro:
// - JSContext* cx
// - unsigned argc
// - Value* vp
// - const char* fnName
// These parameters will be defined after calling this macro:
// - CallArgs args
// - Rooted<SavedFrame*> frame (will be non-null)
#define THIS_SAVEDFRAME(cx, argc, vp, fnName, args, frame) \
CallArgs args = CallArgsFromVp(argc, vp); \
RootedObject frame(cx); \
if (!checkThis(cx, args, fnName, &frame)) \
return false;
} /* namespace js */
namespace JS {
namespace {
// It's possible that our caller is privileged (and hence would see the entire
// stack) but we're working with an SavedFrame object that was captured in
// unprivileged code. If so, drop privileges down to its level. The idea is
// that this way devtools code that's asking an exception object for a stack to
// display will end up with the stack the web developer would see via doing
// .stack in a web page, with Firefox implementation details excluded.
//
// We want callers to pass us the object they were actually passed, not an
// unwrapped form of it. That way Xray access to SavedFrame objects should not
// be affected by AutoMaybeEnterFrameCompartment and the only things that will
// be affected will be cases in which privileged code works with some C++ object
// that then pokes at an unprivileged StackFrame it has on hand.
class MOZ_STACK_CLASS AutoMaybeEnterFrameCompartment
{
public:
AutoMaybeEnterFrameCompartment(JSContext* cx,
HandleObject obj
MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
{
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
// Note that obj might be null here, since we're doing this
// before UnwrapSavedFrame.
if (obj && cx->compartment() != obj->compartment())
{
JSSubsumesOp subsumes = cx->runtime()->securityCallbacks->subsumes;
if (subsumes && subsumes(cx->compartment()->principals(),
obj->compartment()->principals()))
{
ac_.emplace(cx, obj);
}
}
}
private:
Maybe<JSAutoCompartment> ac_;
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};
} // namespace
static inline js::SavedFrame*
UnwrapSavedFrame(JSContext* cx, HandleObject obj, SavedFrameSelfHosted selfHosted,
bool& skippedAsync)
{
if (!obj)
return nullptr;
RootedObject savedFrameObj(cx, CheckedUnwrap(obj));
if (!savedFrameObj)
return nullptr;
MOZ_ASSERT(js::SavedFrame::isSavedFrameAndNotProto(*savedFrameObj));
js::RootedSavedFrame frame(cx, &savedFrameObj->as<js::SavedFrame>());
return GetFirstSubsumedFrame(cx, frame, selfHosted, skippedAsync);
}
JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameSource(JSContext* cx, HandleObject savedFrame, MutableHandleString sourcep,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
AutoMaybeEnterFrameCompartment ac(cx, savedFrame);
bool skippedAsync;
js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, savedFrame, selfHosted, skippedAsync));
if (!frame) {
sourcep.set(cx->runtime()->emptyString);
return SavedFrameResult::AccessDenied;
}
sourcep.set(frame->getSource());
return SavedFrameResult::Ok;
}
JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameLine(JSContext* cx, HandleObject savedFrame, uint32_t* linep,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
MOZ_ASSERT(linep);
AutoMaybeEnterFrameCompartment ac(cx, savedFrame);
bool skippedAsync;
js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, savedFrame, selfHosted, skippedAsync));
if (!frame) {
*linep = 0;
return SavedFrameResult::AccessDenied;
}
*linep = frame->getLine();
return SavedFrameResult::Ok;
}
JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameColumn(JSContext* cx, HandleObject savedFrame, uint32_t* columnp,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
MOZ_ASSERT(columnp);
AutoMaybeEnterFrameCompartment ac(cx, savedFrame);
bool skippedAsync;
js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, savedFrame, selfHosted, skippedAsync));
if (!frame) {
*columnp = 0;
return SavedFrameResult::AccessDenied;
}
*columnp = frame->getColumn();
return SavedFrameResult::Ok;
}
JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameFunctionDisplayName(JSContext* cx, HandleObject savedFrame, MutableHandleString namep,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
AutoMaybeEnterFrameCompartment ac(cx, savedFrame);
bool skippedAsync;
js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, savedFrame, selfHosted, skippedAsync));
if (!frame) {
namep.set(nullptr);
return SavedFrameResult::AccessDenied;
}
namep.set(frame->getFunctionDisplayName());
return SavedFrameResult::Ok;
}
JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameAsyncCause(JSContext* cx, HandleObject savedFrame, MutableHandleString asyncCausep,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
AutoMaybeEnterFrameCompartment ac(cx, savedFrame);
bool skippedAsync;
js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, savedFrame, selfHosted, skippedAsync));
if (!frame) {
asyncCausep.set(nullptr);
return SavedFrameResult::AccessDenied;
}
asyncCausep.set(frame->getAsyncCause());
if (!asyncCausep && skippedAsync)
asyncCausep.set(cx->names().Async);
return SavedFrameResult::Ok;
}
JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameAsyncParent(JSContext* cx, HandleObject savedFrame, MutableHandleObject asyncParentp,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
AutoMaybeEnterFrameCompartment ac(cx, savedFrame);
bool skippedAsync;
js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, savedFrame, selfHosted, skippedAsync));
if (!frame) {
asyncParentp.set(nullptr);
return SavedFrameResult::AccessDenied;
}
js::RootedSavedFrame parent(cx, frame->getParent());
// The current value of |skippedAsync| is not interesting, because we are
// interested in whether we would cross any async parents to get from here
// to the first subsumed parent frame instead.
js::RootedSavedFrame subsumedParent(cx, GetFirstSubsumedFrame(cx, parent, selfHosted,
skippedAsync));
// Even if |parent| is not subsumed, we still want to return a pointer to it
// rather than |subsumedParent| so it can pick up any |asyncCause| from the
// inaccessible part of the chain.
if (subsumedParent && (subsumedParent->getAsyncCause() || skippedAsync))
asyncParentp.set(parent);
else
asyncParentp.set(nullptr);
return SavedFrameResult::Ok;
}
JS_PUBLIC_API(SavedFrameResult)
GetSavedFrameParent(JSContext* cx, HandleObject savedFrame, MutableHandleObject parentp,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */)
{
AutoMaybeEnterFrameCompartment ac(cx, savedFrame);
bool skippedAsync;
js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, savedFrame, selfHosted, skippedAsync));
if (!frame) {
parentp.set(nullptr);
return SavedFrameResult::AccessDenied;
}
js::RootedSavedFrame parent(cx, frame->getParent());
// The current value of |skippedAsync| is not interesting, because we are
// interested in whether we would cross any async parents to get from here
// to the first subsumed parent frame instead.
js::RootedSavedFrame subsumedParent(cx, GetFirstSubsumedFrame(cx, parent, selfHosted,
skippedAsync));
// Even if |parent| is not subsumed, we still want to return a pointer to it
// rather than |subsumedParent| so it can pick up any |asyncCause| from the
// inaccessible part of the chain.
if (subsumedParent && !(subsumedParent->getAsyncCause() || skippedAsync))
parentp.set(parent);
else
parentp.set(nullptr);
return SavedFrameResult::Ok;
}
JS_PUBLIC_API(bool)
BuildStackString(JSContext* cx, HandleObject stack, MutableHandleString stringp, size_t indent)
{
js::StringBuffer sb(cx);
// Enter a new block to constrain the scope of possibly entering the stack's
// compartment. This ensures that when we finish the StringBuffer, we are
// back in the cx's original compartment, and fulfill our contract with
// callers to place the output string in the cx's current compartment.
{
AutoMaybeEnterFrameCompartment ac(cx, stack);
bool skippedAsync;
js::RootedSavedFrame frame(cx, UnwrapSavedFrame(cx, stack, SavedFrameSelfHosted::Exclude,
skippedAsync));
if (!frame) {
stringp.set(cx->runtime()->emptyString);
return true;
}
js::RootedSavedFrame parent(cx);
do {
MOZ_ASSERT(SavedFrameSubsumedByCaller(cx, frame));
MOZ_ASSERT(!frame->isSelfHosted());
RootedString asyncCause(cx, frame->getAsyncCause());
if (!asyncCause && skippedAsync)
asyncCause.set(cx->names().Async);
js::RootedAtom name(cx, frame->getFunctionDisplayName());
if ((indent && !sb.appendN(' ', indent))
|| (asyncCause && (!sb.append(asyncCause) || !sb.append('*')))
|| (name && !sb.append(name))
|| !sb.append('@')
|| !sb.append(frame->getSource())
|| !sb.append(':')
|| !NumberValueToStringBuffer(cx, NumberValue(frame->getLine()), sb)
|| !sb.append(':')
|| !NumberValueToStringBuffer(cx, NumberValue(frame->getColumn()), sb)
|| !sb.append('\n'))
{
return false;
}
parent = frame->getParent();
frame = js::GetFirstSubsumedFrame(cx, parent, SavedFrameSelfHosted::Exclude, skippedAsync);
} while (frame);
}
JSString* str = sb.finishString();
if (!str)
return false;
assertSameCompartment(cx, str);
stringp.set(str);
return true;
}
} /* namespace JS */
namespace js {
/* static */ bool
SavedFrame::sourceProperty(JSContext* cx, unsigned argc, Value* vp)
{
THIS_SAVEDFRAME(cx, argc, vp, "(get source)", args, frame);
RootedString source(cx);
if (JS::GetSavedFrameSource(cx, frame, &source) == JS::SavedFrameResult::Ok) {
if (!cx->compartment()->wrap(cx, &source))
return false;
args.rval().setString(source);
} else {
args.rval().setNull();
}
return true;
}
/* static */ bool
SavedFrame::lineProperty(JSContext* cx, unsigned argc, Value* vp)
{
THIS_SAVEDFRAME(cx, argc, vp, "(get line)", args, frame);
uint32_t line;
if (JS::GetSavedFrameLine(cx, frame, &line) == JS::SavedFrameResult::Ok)
args.rval().setNumber(line);
else
args.rval().setNull();
return true;
}
/* static */ bool
SavedFrame::columnProperty(JSContext* cx, unsigned argc, Value* vp)
{
THIS_SAVEDFRAME(cx, argc, vp, "(get column)", args, frame);
uint32_t column;
if (JS::GetSavedFrameColumn(cx, frame, &column) == JS::SavedFrameResult::Ok)
args.rval().setNumber(column);
else
args.rval().setNull();
return true;
}
/* static */ bool
SavedFrame::functionDisplayNameProperty(JSContext* cx, unsigned argc, Value* vp)
{
THIS_SAVEDFRAME(cx, argc, vp, "(get functionDisplayName)", args, frame);
RootedString name(cx);
JS::SavedFrameResult result = JS::GetSavedFrameFunctionDisplayName(cx, frame, &name);
if (result == JS::SavedFrameResult::Ok && name) {
if (!cx->compartment()->wrap(cx, &name))
return false;
args.rval().setString(name);
} else {
args.rval().setNull();
}
return true;
}
/* static */ bool
SavedFrame::asyncCauseProperty(JSContext* cx, unsigned argc, Value* vp)
{
THIS_SAVEDFRAME(cx, argc, vp, "(get asyncCause)", args, frame);
RootedString asyncCause(cx);
JS::SavedFrameResult result = JS::GetSavedFrameAsyncCause(cx, frame, &asyncCause);
if (result == JS::SavedFrameResult::Ok && asyncCause) {
if (!cx->compartment()->wrap(cx, &asyncCause))
return false;
args.rval().setString(asyncCause);
} else {
args.rval().setNull();
}
return true;
}
/* static */ bool
SavedFrame::asyncParentProperty(JSContext* cx, unsigned argc, Value* vp)
{
THIS_SAVEDFRAME(cx, argc, vp, "(get asyncParent)", args, frame);
RootedObject asyncParent(cx);
(void) JS::GetSavedFrameAsyncParent(cx, frame, &asyncParent);
if (!cx->compartment()->wrap(cx, &asyncParent))
return false;
args.rval().setObjectOrNull(asyncParent);
return true;
}
/* static */ bool
SavedFrame::parentProperty(JSContext* cx, unsigned argc, Value* vp)
{
THIS_SAVEDFRAME(cx, argc, vp, "(get parent)", args, frame);
RootedObject parent(cx);
(void) JS::GetSavedFrameParent(cx, frame, &parent);
if (!cx->compartment()->wrap(cx, &parent))
return false;
args.rval().setObjectOrNull(parent);
return true;
}
/* static */ bool
SavedFrame::toStringMethod(JSContext* cx, unsigned argc, Value* vp)
{
THIS_SAVEDFRAME(cx, argc, vp, "toString", args, frame);
RootedString string(cx);
if (!JS::BuildStackString(cx, frame, &string))
return false;
args.rval().setString(string);
return true;
}
bool
SavedStacks::init()
{
if (!pcLocationMap.init())
return false;
return frames.init();
}
bool
SavedStacks::saveCurrentStack(JSContext* cx, MutableHandleSavedFrame frame, unsigned maxFrameCount)
{