forked from classilla/tenfourfox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsopcode.cpp
More file actions
2058 lines (1753 loc) · 60 KB
/
jsopcode.cpp
File metadata and controls
2058 lines (1753 loc) · 60 KB
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/. */
/*
* JS bytecode descriptors, disassemblers, and (expression) decompilers.
*/
#include "jsopcodeinlines.h"
#define __STDC_FORMAT_MACROS
#include "mozilla/SizePrintfMacros.h"
#include <algorithm>
#include <ctype.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include "jsapi.h"
#include "jsatom.h"
#include "jscntxt.h"
#include "jscompartment.h"
#include "jsfun.h"
#include "jsnum.h"
#include "jsobj.h"
#include "jsprf.h"
#include "jsscript.h"
#include "jsstr.h"
#include "jstypes.h"
#include "jsutil.h"
#include "asmjs/AsmJSModule.h"
#include "frontend/BytecodeCompiler.h"
#include "frontend/SourceNotes.h"
#include "gc/GCInternals.h"
#include "js/CharacterEncoding.h"
#include "vm/CodeCoverage.h"
#include "vm/Opcodes.h"
#include "vm/ScopeObject.h"
#include "vm/Shape.h"
#include "vm/StringBuffer.h"
#include "jscntxtinlines.h"
#include "jscompartmentinlines.h"
#include "jsobjinlines.h"
#include "jsscriptinlines.h"
using namespace js;
using namespace js::gc;
using JS::AutoCheckCannotGC;
using js::frontend::IsIdentifier;
/*
* Index limit must stay within 32 bits.
*/
JS_STATIC_ASSERT(sizeof(uint32_t) * JS_BITS_PER_BYTE >= INDEX_LIMIT_LOG2 + 1);
const JSCodeSpec js::CodeSpec[] = {
#define MAKE_CODESPEC(op,val,name,token,length,nuses,ndefs,format) {length,nuses,ndefs,format},
FOR_EACH_OPCODE(MAKE_CODESPEC)
#undef MAKE_CODESPEC
};
const unsigned js::NumCodeSpecs = JS_ARRAY_LENGTH(CodeSpec);
/*
* Each element of the array is either a source literal associated with JS
* bytecode or null.
*/
static const char * const CodeToken[] = {
#define TOKEN(op, val, name, token, ...) token,
FOR_EACH_OPCODE(TOKEN)
#undef TOKEN
};
/*
* Array of JS bytecode names used by PC count JSON, DEBUG-only Disassemble
* and JIT debug spew.
*/
const char * const js::CodeName[] = {
#define OPNAME(op, val, name, ...) name,
FOR_EACH_OPCODE(OPNAME)
#undef OPNAME
};
/************************************************************************/
#define COUNTS_LEN 16
size_t
js::GetVariableBytecodeLength(jsbytecode* pc)
{
JSOp op = JSOp(*pc);
MOZ_ASSERT(CodeSpec[op].length == -1);
switch (op) {
case JSOP_TABLESWITCH: {
/* Structure: default-jump case-low case-high case1-jump ... */
pc += JUMP_OFFSET_LEN;
int32_t low = GET_JUMP_OFFSET(pc);
pc += JUMP_OFFSET_LEN;
int32_t high = GET_JUMP_OFFSET(pc);
unsigned ncases = unsigned(high - low + 1);
return 1 + 3 * JUMP_OFFSET_LEN + ncases * JUMP_OFFSET_LEN;
}
default:
MOZ_CRASH("Unexpected op");
}
}
unsigned
js::StackUses(JSScript* script, jsbytecode* pc)
{
JSOp op = (JSOp) *pc;
const JSCodeSpec& cs = CodeSpec[op];
if (cs.nuses >= 0)
return cs.nuses;
MOZ_ASSERT(CodeSpec[op].nuses == -1);
switch (op) {
case JSOP_POPN:
return GET_UINT16(pc);
case JSOP_NEW:
case JSOP_SUPERCALL:
return 2 + GET_ARGC(pc) + 1;
default:
/* stack: fun, this, [argc arguments] */
MOZ_ASSERT(op == JSOP_CALL || op == JSOP_EVAL || op == JSOP_CALLITER ||
op == JSOP_STRICTEVAL || op == JSOP_FUNCALL || op == JSOP_FUNAPPLY);
return 2 + GET_ARGC(pc);
}
}
unsigned
js::StackDefs(JSScript* script, jsbytecode* pc)
{
JSOp op = (JSOp) *pc;
const JSCodeSpec& cs = CodeSpec[op];
MOZ_ASSERT(cs.ndefs >= 0);
return cs.ndefs;
}
const char * PCCounts::numExecName = "interp";
void
js::DumpIonScriptCounts(Sprinter* sp, jit::IonScriptCounts* ionCounts)
{
Sprint(sp, "IonScript [%lu blocks]:\n", ionCounts->numBlocks());
for (size_t i = 0; i < ionCounts->numBlocks(); i++) {
const jit::IonBlockCounts& block = ionCounts->block(i);
Sprint(sp, "BB #%lu [%05u]", block.id(), block.offset());
if (block.description())
Sprint(sp, " [inlined %s]", block.description());
for (size_t j = 0; j < block.numSuccessors(); j++)
Sprint(sp, " -> #%lu", block.successor(j));
Sprint(sp, " :: %llu hits\n", block.hitCount());
Sprint(sp, "%s\n", block.code());
}
}
void
js::DumpPCCounts(JSContext* cx, HandleScript script, Sprinter* sp)
{
MOZ_ASSERT(script->hasScriptCounts());
#ifdef DEBUG
jsbytecode* pc = script->code();
while (pc < script->codeEnd()) {
jsbytecode* next = GetNextPc(pc);
if (!Disassemble1(cx, script, pc, script->pcToOffset(pc), true, sp))
return;
Sprint(sp, " {");
PCCounts* counts = script->maybeGetPCCounts(pc);
double val = counts ? counts->numExec() : 0.0;
if (val)
Sprint(sp, "\"%s\": %.0f", PCCounts::numExecName, val);
Sprint(sp, "}\n");
pc = next;
}
#endif
jit::IonScriptCounts* ionCounts = script->getIonCounts();
while (ionCounts) {
DumpIonScriptCounts(sp, ionCounts);
ionCounts = ionCounts->previous();
}
}
void
js::DumpCompartmentPCCounts(JSContext* cx)
{
for (ZoneCellIter i(cx->zone(), gc::AllocKind::SCRIPT); !i.done(); i.next()) {
RootedScript script(cx, i.get<JSScript>());
if (script->compartment() != cx->compartment())
continue;
if (script->hasScriptCounts()) {
Sprinter sprinter(cx);
if (!sprinter.init())
return;
fprintf(stdout, "--- SCRIPT %s:%" PRIuSIZE " ---\n", script->filename(), script->lineno());
DumpPCCounts(cx, script, &sprinter);
fputs(sprinter.string(), stdout);
fprintf(stdout, "--- END SCRIPT %s:%" PRIuSIZE " ---\n", script->filename(), script->lineno());
}
}
}
/////////////////////////////////////////////////////////////////////
// Bytecode Parser
/////////////////////////////////////////////////////////////////////
namespace {
class BytecodeParser
{
class Bytecode
{
public:
Bytecode() { mozilla::PodZero(this); }
// Whether this instruction has been analyzed to get its output defines
// and stack.
bool parsed : 1;
// Stack depth before this opcode.
uint32_t stackDepth;
// Pointer to array of |stackDepth| offsets. An element at position N
// in the array is the offset of the opcode that defined the
// corresponding stack slot. The top of the stack is at position
// |stackDepth - 1|.
uint32_t* offsetStack;
bool captureOffsetStack(LifoAlloc& alloc, const uint32_t* stack, uint32_t depth) {
stackDepth = depth;
offsetStack = alloc.newArray<uint32_t>(stackDepth);
if (!offsetStack)
return false;
if (stackDepth) {
for (uint32_t n = 0; n < stackDepth; n++)
offsetStack[n] = stack[n];
}
return true;
}
// When control-flow merges, intersect the stacks, marking slots that
// are defined by different offsets with the UINT32_MAX sentinel.
// This is sufficient for forward control-flow. It doesn't grok loops
// -- for that you would have to iterate to a fixed point -- but there
// shouldn't be operands on the stack at a loop back-edge anyway.
void mergeOffsetStack(const uint32_t* stack, uint32_t depth) {
MOZ_ASSERT(depth == stackDepth);
for (uint32_t n = 0; n < stackDepth; n++)
if (offsetStack[n] != stack[n])
offsetStack[n] = UINT32_MAX;
}
};
JSContext* cx_;
LifoAllocScope allocScope_;
RootedScript script_;
Bytecode** codeArray_;
public:
BytecodeParser(JSContext* cx, JSScript* script)
: cx_(cx),
allocScope_(&cx->tempLifoAlloc()),
script_(cx, script),
codeArray_(nullptr) { }
bool parse();
#ifdef DEBUG
bool isReachable(uint32_t offset) { return maybeCode(offset); }
bool isReachable(const jsbytecode* pc) { return maybeCode(pc); }
#endif
uint32_t stackDepthAtPC(uint32_t offset) {
// Sometimes the code generator in debug mode asks about the stack depth
// of unreachable code (bug 932180 comment 22). Assume that unreachable
// code has no operands on the stack.
return getCode(offset).stackDepth;
}
uint32_t stackDepthAtPC(const jsbytecode* pc) { return stackDepthAtPC(script_->pcToOffset(pc)); }
uint32_t offsetForStackOperand(uint32_t offset, int operand) {
Bytecode& code = getCode(offset);
if (operand < 0) {
operand += code.stackDepth;
MOZ_ASSERT(operand >= 0);
}
MOZ_ASSERT(uint32_t(operand) < code.stackDepth);
return code.offsetStack[operand];
}
jsbytecode* pcForStackOperand(jsbytecode* pc, int operand) {
uint32_t offset = offsetForStackOperand(script_->pcToOffset(pc), operand);
if (offset == UINT32_MAX)
return nullptr;
return script_->offsetToPC(offsetForStackOperand(script_->pcToOffset(pc), operand));
}
private:
LifoAlloc& alloc() {
return allocScope_.alloc();
}
void reportOOM() {
allocScope_.releaseEarly();
ReportOutOfMemory(cx_);
}
uint32_t numSlots() {
return 1 + script_->nfixed() +
(script_->functionNonDelazifying() ? script_->functionNonDelazifying()->nargs() : 0);
}
uint32_t maximumStackDepth() {
return script_->nslots() - script_->nfixed();
}
Bytecode& getCode(uint32_t offset) {
MOZ_ASSERT(offset < script_->length());
MOZ_ASSERT(codeArray_[offset]);
return *codeArray_[offset];
}
Bytecode& getCode(const jsbytecode* pc) { return getCode(script_->pcToOffset(pc)); }
Bytecode* maybeCode(uint32_t offset) {
MOZ_ASSERT(offset < script_->length());
return codeArray_[offset];
}
Bytecode* maybeCode(const jsbytecode* pc) { return maybeCode(script_->pcToOffset(pc)); }
uint32_t simulateOp(JSOp op, uint32_t offset, uint32_t* offsetStack, uint32_t stackDepth);
inline bool addJump(uint32_t offset, uint32_t* currentOffset,
uint32_t stackDepth, const uint32_t* offsetStack);
};
} // anonymous namespace
uint32_t
BytecodeParser::simulateOp(JSOp op, uint32_t offset, uint32_t* offsetStack, uint32_t stackDepth)
{
uint32_t nuses = GetUseCount(script_, offset);
uint32_t ndefs = GetDefCount(script_, offset);
MOZ_ASSERT(stackDepth >= nuses);
stackDepth -= nuses;
MOZ_ASSERT(stackDepth + ndefs <= maximumStackDepth());
// Mark the current offset as defining its values on the offset stack,
// unless it just reshuffles the stack. In that case we want to preserve
// the opcode that generated the original value.
switch (op) {
default:
for (uint32_t n = 0; n != ndefs; ++n)
offsetStack[stackDepth + n] = offset;
break;
case JSOP_CASE:
/* Keep the switch value. */
MOZ_ASSERT(ndefs == 1);
break;
case JSOP_DUP:
MOZ_ASSERT(ndefs == 2);
if (offsetStack)
offsetStack[stackDepth + 1] = offsetStack[stackDepth];
break;
case JSOP_DUP2:
MOZ_ASSERT(ndefs == 4);
if (offsetStack) {
offsetStack[stackDepth + 2] = offsetStack[stackDepth];
offsetStack[stackDepth + 3] = offsetStack[stackDepth + 1];
}
break;
case JSOP_DUPAT: {
MOZ_ASSERT(ndefs == 1);
jsbytecode* pc = script_->offsetToPC(offset);
unsigned n = GET_UINT24(pc);
MOZ_ASSERT(n < stackDepth);
if (offsetStack)
offsetStack[stackDepth] = offsetStack[stackDepth - 1 - n];
break;
}
case JSOP_SWAP:
MOZ_ASSERT(ndefs == 2);
if (offsetStack) {
uint32_t tmp = offsetStack[stackDepth + 1];
offsetStack[stackDepth + 1] = offsetStack[stackDepth];
offsetStack[stackDepth] = tmp;
}
break;
}
stackDepth += ndefs;
return stackDepth;
}
bool
BytecodeParser::addJump(uint32_t offset, uint32_t* currentOffset,
uint32_t stackDepth, const uint32_t* offsetStack)
{
MOZ_ASSERT(offset < script_->length());
Bytecode*& code = codeArray_[offset];
if (!code) {
code = alloc().new_<Bytecode>();
if (!code ||
!code->captureOffsetStack(alloc(), offsetStack, stackDepth))
{
reportOOM();
return false;
}
} else {
code->mergeOffsetStack(offsetStack, stackDepth);
}
if (offset < *currentOffset && !code->parsed) {
// Backedge in a while/for loop, whose body has not been parsed due
// to a lack of fallthrough at the loop head. Roll back the offset
// to analyze the body.
*currentOffset = offset;
}
return true;
}
bool
BytecodeParser::parse()
{
MOZ_ASSERT(!codeArray_);
uint32_t length = script_->length();
codeArray_ = alloc().newArray<Bytecode*>(length);
if (!codeArray_) {
reportOOM();
return false;
}
mozilla::PodZero(codeArray_, length);
// Fill in stack depth and definitions at initial bytecode.
Bytecode* startcode = alloc().new_<Bytecode>();
if (!startcode) {
reportOOM();
return false;
}
// Fill in stack depth and definitions at initial bytecode.
uint32_t* offsetStack = alloc().newArray<uint32_t>(maximumStackDepth());
if (maximumStackDepth() && !offsetStack) {
reportOOM();
return false;
}
startcode->stackDepth = 0;
codeArray_[0] = startcode;
uint32_t offset, nextOffset = 0;
while (nextOffset < length) {
offset = nextOffset;
Bytecode* code = maybeCode(offset);
jsbytecode* pc = script_->offsetToPC(offset);
JSOp op = (JSOp)*pc;
MOZ_ASSERT(op < JSOP_LIMIT);
// Immediate successor of this bytecode.
uint32_t successorOffset = offset + GetBytecodeLength(pc);
// Next bytecode to analyze. This is either the successor, or is an
// earlier bytecode if this bytecode has a loop backedge.
nextOffset = successorOffset;
if (!code) {
// Haven't found a path by which this bytecode is reachable.
continue;
}
if (code->parsed) {
// No need to reparse.
continue;
}
code->parsed = true;
uint32_t stackDepth = simulateOp(op, offset, offsetStack, code->stackDepth);
switch (op) {
case JSOP_TABLESWITCH: {
uint32_t defaultOffset = offset + GET_JUMP_OFFSET(pc);
jsbytecode* pc2 = pc + JUMP_OFFSET_LEN;
int32_t low = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
int32_t high = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
if (!addJump(defaultOffset, &nextOffset, stackDepth, offsetStack))
return false;
for (int32_t i = low; i <= high; i++) {
uint32_t targetOffset = offset + GET_JUMP_OFFSET(pc2);
if (targetOffset != offset) {
if (!addJump(targetOffset, &nextOffset, stackDepth, offsetStack))
return false;
}
pc2 += JUMP_OFFSET_LEN;
}
break;
}
case JSOP_TRY: {
// Everything between a try and corresponding catch or finally is conditional.
// Note that there is no problem with code which is skipped by a thrown
// exception but is not caught by a later handler in the same function:
// no more code will execute, and it does not matter what is defined.
JSTryNote* tn = script_->trynotes()->vector;
JSTryNote* tnlimit = tn + script_->trynotes()->length;
for (; tn < tnlimit; tn++) {
uint32_t startOffset = script_->mainOffset() + tn->start;
if (startOffset == offset + 1) {
uint32_t catchOffset = startOffset + tn->length;
if (tn->kind == JSTRY_CATCH || tn->kind == JSTRY_FINALLY) {
if (!addJump(catchOffset, &nextOffset, stackDepth, offsetStack))
return false;
}
}
}
break;
}
default:
break;
}
// Check basic jump opcodes, which may or may not have a fallthrough.
if (IsJumpOpcode(op)) {
// Case instructions do not push the lvalue back when branching.
uint32_t newStackDepth = stackDepth;
if (op == JSOP_CASE)
newStackDepth--;
uint32_t targetOffset = offset + GET_JUMP_OFFSET(pc);
if (!addJump(targetOffset, &nextOffset, newStackDepth, offsetStack))
return false;
}
// Handle any fallthrough from this opcode.
if (BytecodeFallsThrough(op)) {
MOZ_ASSERT(successorOffset < script_->length());
Bytecode*& nextcode = codeArray_[successorOffset];
if (!nextcode) {
nextcode = alloc().new_<Bytecode>();
if (!nextcode) {
reportOOM();
return false;
}
if (!nextcode->captureOffsetStack(alloc(), offsetStack, stackDepth)) {
reportOOM();
return false;
}
} else {
nextcode->mergeOffsetStack(offsetStack, stackDepth);
}
}
}
return true;
}
#ifdef DEBUG
bool
js::ReconstructStackDepth(JSContext* cx, JSScript* script, jsbytecode* pc, uint32_t* depth, bool* reachablePC)
{
BytecodeParser parser(cx, script);
if (!parser.parse())
return false;
*reachablePC = parser.isReachable(pc);
if (*reachablePC)
*depth = parser.stackDepthAtPC(pc);
return true;
}
/*
* If pc != nullptr, include a prefix indicating whether the PC is at the
* current line. If showAll is true, include the source note type and the
* entry stack depth.
*/
static bool
DisassembleAtPC(JSContext* cx, JSScript* scriptArg, bool lines,
jsbytecode* pc, bool showAll, Sprinter* sp)
{
RootedScript script(cx, scriptArg);
BytecodeParser parser(cx, script);
if (showAll && !parser.parse())
return false;
if (showAll)
Sprint(sp, "%s:%" PRIuSIZE "\n", script->filename(), script->lineno());
if (pc != nullptr)
sp->put(" ");
if (showAll)
sp->put("sn stack ");
sp->put("loc ");
if (lines)
sp->put("line");
sp->put(" op\n");
if (pc != nullptr)
sp->put(" ");
if (showAll)
sp->put("-- ----- ");
sp->put("----- ");
if (lines)
sp->put("----");
sp->put(" --\n");
jsbytecode* next = script->code();
jsbytecode* end = script->codeEnd();
while (next < end) {
if (next == script->main())
sp->put("main:\n");
if (pc != nullptr) {
if (pc == next)
sp->put("--> ");
else
sp->put(" ");
}
if (showAll) {
jssrcnote* sn = GetSrcNote(cx, script, next);
if (sn) {
MOZ_ASSERT(!SN_IS_TERMINATOR(sn));
jssrcnote* next = SN_NEXT(sn);
while (!SN_IS_TERMINATOR(next) && SN_DELTA(next) == 0) {
Sprint(sp, "%02u\n ", SN_TYPE(sn));
sn = next;
next = SN_NEXT(sn);
}
Sprint(sp, "%02u ", SN_TYPE(sn));
}
else
sp->put(" ");
if (parser.isReachable(next))
Sprint(sp, "%05u ", parser.stackDepthAtPC(next));
else
Sprint(sp, " ");
}
unsigned len = Disassemble1(cx, script, next, script->pcToOffset(next), lines, sp);
if (!len)
return false;
next += len;
}
return true;
}
bool
js::Disassemble(JSContext* cx, HandleScript script, bool lines, Sprinter* sp)
{
return DisassembleAtPC(cx, script, lines, nullptr, false, sp);
}
JS_FRIEND_API(bool)
js::DumpPC(JSContext* cx)
{
gc::AutoSuppressGC suppressGC(cx);
Sprinter sprinter(cx);
if (!sprinter.init())
return false;
ScriptFrameIter iter(cx);
if (iter.done()) {
fprintf(stdout, "Empty stack.\n");
return true;
}
RootedScript script(cx, iter.script());
bool ok = DisassembleAtPC(cx, script, true, iter.pc(), false, &sprinter);
fprintf(stdout, "%s", sprinter.string());
return ok;
}
JS_FRIEND_API(bool)
js::DumpScript(JSContext* cx, JSScript* scriptArg)
{
gc::AutoSuppressGC suppressGC(cx);
Sprinter sprinter(cx);
if (!sprinter.init())
return false;
RootedScript script(cx, scriptArg);
bool ok = Disassemble(cx, script, true, &sprinter);
fprintf(stdout, "%s", sprinter.string());
return ok;
}
static bool
ToDisassemblySource(JSContext* cx, HandleValue v, JSAutoByteString* bytes)
{
if (v.isString()) {
Sprinter sprinter(cx);
if (!sprinter.init())
return false;
char* nbytes = QuoteString(&sprinter, v.toString(), '"');
if (!nbytes)
return false;
nbytes = JS_sprintf_append(nullptr, "%s", nbytes);
if (!nbytes) {
ReportOutOfMemory(cx);
return false;
}
bytes->initBytes(nbytes);
return true;
}
JSRuntime* rt = cx->runtime();
if (rt->isHeapBusy() || !rt->gc.isAllocAllowed()) {
char* source = JS_sprintf_append(nullptr, "<value>");
if (!source) {
ReportOutOfMemory(cx);
return false;
}
bytes->initBytes(source);
return true;
}
if (v.isObject()) {
JSObject& obj = v.toObject();
if (obj.is<StaticBlockObject>()) {
Rooted<StaticBlockObject*> block(cx, &obj.as<StaticBlockObject>());
char* source = JS_sprintf_append(nullptr, "depth %d {", block->localOffset());
if (!source) {
ReportOutOfMemory(cx);
return false;
}
Shape::Range<CanGC> r(cx, block->lastProperty());
while (!r.empty()) {
Rooted<Shape*> shape(cx, &r.front());
JSAtom* atom = JSID_IS_INT(shape->propid())
? cx->names().empty
: JSID_TO_ATOM(shape->propid());
JSAutoByteString bytes;
if (!AtomToPrintableString(cx, atom, &bytes))
return false;
r.popFront();
source = JS_sprintf_append(source, "%s: %d%s",
bytes.ptr(),
block->shapeToIndex(*shape),
!r.empty() ? ", " : "");
if (!source) {
ReportOutOfMemory(cx);
return false;
}
}
source = JS_sprintf_append(source, "}");
if (!source) {
ReportOutOfMemory(cx);
return false;
}
bytes->initBytes(source);
return true;
}
if (obj.is<JSFunction>()) {
RootedFunction fun(cx, &obj.as<JSFunction>());
JSString* str = JS_DecompileFunction(cx, fun, JS_DONT_PRETTY_PRINT);
if (!str)
return false;
return bytes->encodeLatin1(cx, str);
}
if (obj.is<RegExpObject>()) {
JSString* source = obj.as<RegExpObject>().toString(cx);
if (!source)
return false;
return bytes->encodeLatin1(cx, source);
}
}
return !!ValueToPrintable(cx, v, bytes, true);
}
unsigned
js::Disassemble1(JSContext* cx, HandleScript script, jsbytecode* pc,
unsigned loc, bool lines, Sprinter* sp)
{
JSOp op = (JSOp)*pc;
if (op >= JSOP_LIMIT) {
char numBuf1[12], numBuf2[12];
JS_snprintf(numBuf1, sizeof numBuf1, "%d", op);
JS_snprintf(numBuf2, sizeof numBuf2, "%d", JSOP_LIMIT);
JS_ReportErrorNumber(cx, GetErrorMessage, nullptr,
JSMSG_BYTECODE_TOO_BIG, numBuf1, numBuf2);
return 0;
}
const JSCodeSpec* cs = &CodeSpec[op];
ptrdiff_t len = (ptrdiff_t) cs->length;
Sprint(sp, "%05u:", loc);
if (lines)
Sprint(sp, "%4u", PCToLineNumber(script, pc));
Sprint(sp, " %s", CodeName[op]);
switch (JOF_TYPE(cs->format)) {
case JOF_BYTE:
// Scan the trynotes to find the associated catch block
// and make the try opcode look like a jump instruction
// with an offset. This simplifies code coverage analysis
// based on this disassembled output.
if (op == JSOP_TRY) {
TryNoteArray* trynotes = script->trynotes();
uint32_t i;
for(i = 0; i < trynotes->length; i++) {
JSTryNote note = trynotes->vector[i];
if (note.kind == JSTRY_CATCH && note.start == loc + 1) {
Sprint(sp, " %u (%+d)",
(unsigned int) (loc+note.length+1),
(int) (note.length+1));
break;
}
}
}
break;
case JOF_JUMP: {
ptrdiff_t off = GET_JUMP_OFFSET(pc);
Sprint(sp, " %u (%+d)", loc + (int) off, (int) off);
break;
}
case JOF_SCOPECOORD: {
RootedValue v(cx,
StringValue(ScopeCoordinateName(cx->runtime()->scopeCoordinateNameCache, script, pc)));
JSAutoByteString bytes;
if (!ToDisassemblySource(cx, v, &bytes))
return 0;
ScopeCoordinate sc(pc);
Sprint(sp, " %s (hops = %u, slot = %u)", bytes.ptr(), sc.hops(), sc.slot());
break;
}
case JOF_ATOM: {
RootedValue v(cx, StringValue(script->getAtom(GET_UINT32_INDEX(pc))));
JSAutoByteString bytes;
if (!ToDisassemblySource(cx, v, &bytes))
return 0;
Sprint(sp, " %s", bytes.ptr());
break;
}
case JOF_DOUBLE: {
RootedValue v(cx, script->getConst(GET_UINT32_INDEX(pc)));
JSAutoByteString bytes;
if (!ToDisassemblySource(cx, v, &bytes))
return 0;
Sprint(sp, " %s", bytes.ptr());
break;
}
case JOF_OBJECT: {
/* Don't call obj.toSource if analysis/inference is active. */
if (script->zone()->types.activeAnalysis) {
Sprint(sp, " object");
break;
}
JSObject* obj = script->getObject(GET_UINT32_INDEX(pc));
{
JSAutoByteString bytes;
RootedValue v(cx, ObjectValue(*obj));
if (!ToDisassemblySource(cx, v, &bytes))
return 0;
Sprint(sp, " %s", bytes.ptr());
}
break;
}
case JOF_REGEXP: {
JSObject* obj = script->getRegExp(GET_UINT32_INDEX(pc));
JSAutoByteString bytes;
RootedValue v(cx, ObjectValue(*obj));
if (!ToDisassemblySource(cx, v, &bytes))
return 0;
Sprint(sp, " %s", bytes.ptr());
break;
}
case JOF_TABLESWITCH:
{
int32_t i, low, high;
ptrdiff_t off = GET_JUMP_OFFSET(pc);
jsbytecode* pc2 = pc + JUMP_OFFSET_LEN;
low = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
high = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
Sprint(sp, " defaultOffset %d low %d high %d", int(off), low, high);
for (i = low; i <= high; i++) {
off = GET_JUMP_OFFSET(pc2);
Sprint(sp, "\n\t%d: %d", i, int(off));
pc2 += JUMP_OFFSET_LEN;
}
len = 1 + pc2 - pc;
break;
}
case JOF_QARG:
Sprint(sp, " %u", GET_ARGNO(pc));
break;
case JOF_LOCAL:
Sprint(sp, " %u", GET_LOCALNO(pc));
break;
case JOF_UINT32:
Sprint(sp, " %u", GET_UINT32(pc));
break;
{
int i;
case JOF_UINT16:
i = (int)GET_UINT16(pc);
goto print_int;
case JOF_UINT24:
MOZ_ASSERT(len == 4);
i = (int)GET_UINT24(pc);
goto print_int;
case JOF_UINT8:
i = GET_UINT8(pc);
goto print_int;
case JOF_INT8:
i = GET_INT8(pc);
goto print_int;
case JOF_INT32:
MOZ_ASSERT(op == JSOP_INT32);
i = GET_INT32(pc);
print_int:
Sprint(sp, " %d", i);
break;
}
default: {
char numBuf[12];
JS_snprintf(numBuf, sizeof numBuf, "%lx", (unsigned long) cs->format);
JS_ReportErrorNumber(cx, GetErrorMessage, nullptr,
JSMSG_UNKNOWN_FORMAT, numBuf);
return 0;
}
}
sp->put("\n");
return len;
}
#endif /* DEBUG */
namespace {
/*
* The expression decompiler is invoked by error handling code to produce a
* string representation of the erroring expression. As it's only a debugging
* tool, it only supports basic expressions. For anything complicated, it simply
* puts "(intermediate value)" into the error result.
*
* Here's the basic algorithm:
*
* 1. Find the stack location of the value whose expression we wish to
* decompile. The error handler can explicitly pass this as an
* argument. Otherwise, we search backwards down the stack for the offending
* value.