forked from visionmedia/node-jscoverage
/
jsopcode.cpp
5304 lines (4744 loc) · 183 KB
/
jsopcode.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 sw=4 ts=8 et tw=99:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* JS bytecode descriptors, disassemblers, and decompilers.
*/
#include "jsstddef.h"
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jstypes.h"
#include "jsarena.h" /* Added by JSIFY */
#include "jsutil.h" /* Added by JSIFY */
#include "jsdtoa.h"
#include "jsprf.h"
#include "jsapi.h"
#include "jsarray.h"
#include "jsatom.h"
#include "jscntxt.h"
#include "jsversion.h"
#include "jsdbgapi.h"
#include "jsemit.h"
#include "jsfun.h"
#include "jsiter.h"
#include "jsnum.h"
#include "jsobj.h"
#include "jsopcode.h"
#include "jsregexp.h"
#include "jsscan.h"
#include "jsscope.h"
#include "jsscript.h"
#include "jsstr.h"
#include "jsstaticcheck.h"
#include "jstracer.h"
#include "jsautooplen.h"
/* Verify JSOP_XXX_LENGTH constant definitions. */
#define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
JS_STATIC_ASSERT(op##_LENGTH == length);
#include "jsopcode.tbl"
#undef OPDEF
static const char js_incop_strs[][3] = {"++", "--"};
static const char js_for_each_str[] = "for each";
const JSCodeSpec js_CodeSpec[] = {
#define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
{length,nuses,ndefs,prec,format},
#include "jsopcode.tbl"
#undef OPDEF
};
uintN js_NumCodeSpecs = JS_ARRAY_LENGTH(js_CodeSpec);
/*
* Each element of the array is either a source literal associated with JS
* bytecode or null.
*/
static const char *CodeToken[] = {
#define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
token,
#include "jsopcode.tbl"
#undef OPDEF
};
#if defined(DEBUG) || defined(JS_JIT_SPEW)
/*
* Array of JS bytecode names used by DEBUG-only js_Disassemble and by
* JIT debug spew.
*/
const char *js_CodeName[] = {
#define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
name,
#include "jsopcode.tbl"
#undef OPDEF
};
#endif
/************************************************************************/
static ptrdiff_t
GetJumpOffset(jsbytecode *pc, jsbytecode *pc2)
{
uint32 type;
type = JOF_OPTYPE(*pc);
if (JOF_TYPE_IS_EXTENDED_JUMP(type))
return GET_JUMPX_OFFSET(pc2);
return GET_JUMP_OFFSET(pc2);
}
uintN
js_GetIndexFromBytecode(JSContext *cx, JSScript *script, jsbytecode *pc,
ptrdiff_t pcoff)
{
JSOp op;
uintN span, base;
op = (JSOp)*pc;
if (op == JSOP_TRAP)
op = JS_GetTrapOpcode(cx, script, pc);
JS_ASSERT(js_CodeSpec[op].length >= 1 + pcoff + UINT16_LEN);
/*
* We need to detect index base prefix. It presents when resetbase
* follows the bytecode.
*/
span = js_CodeSpec[op].length;
base = 0;
if (pc - script->code + span < script->length) {
if (pc[span] == JSOP_RESETBASE) {
base = GET_INDEXBASE(pc - JSOP_INDEXBASE_LENGTH);
} else if (pc[span] == JSOP_RESETBASE0) {
JS_ASSERT(JSOP_INDEXBASE1 <= pc[-1] || pc[-1] <= JSOP_INDEXBASE3);
base = (pc[-1] - JSOP_INDEXBASE1 + 1) << 16;
}
}
return base + GET_UINT16(pc + pcoff);
}
uintN
js_GetVariableBytecodeLength(jsbytecode *pc)
{
JSOp op;
uintN jmplen, ncases;
jsint low, high;
op = (JSOp) *pc;
JS_ASSERT(js_CodeSpec[op].length == -1);
switch (op) {
case JSOP_TABLESWITCHX:
jmplen = JUMPX_OFFSET_LEN;
goto do_table;
case JSOP_TABLESWITCH:
jmplen = JUMP_OFFSET_LEN;
do_table:
/* Structure: default-jump case-low case-high case1-jump ... */
pc += jmplen;
low = GET_JUMP_OFFSET(pc);
pc += JUMP_OFFSET_LEN;
high = GET_JUMP_OFFSET(pc);
ncases = (uintN)(high - low + 1);
return 1 + jmplen + INDEX_LEN + INDEX_LEN + ncases * jmplen;
case JSOP_LOOKUPSWITCHX:
jmplen = JUMPX_OFFSET_LEN;
goto do_lookup;
default:
JS_ASSERT(op == JSOP_LOOKUPSWITCH);
jmplen = JUMP_OFFSET_LEN;
do_lookup:
/* Structure: default-jump case-count (case1-value case1-jump) ... */
pc += jmplen;
ncases = GET_UINT16(pc);
return 1 + jmplen + INDEX_LEN + ncases * (INDEX_LEN + jmplen);
}
}
uintN
js_GetVariableStackUseLength(JSOp op, jsbytecode *pc)
{
JS_ASSERT(*pc == op || *pc == JSOP_TRAP);
JS_ASSERT(js_CodeSpec[op].nuses == -1);
switch (op) {
case JSOP_POPN:
return GET_UINT16(pc);
case JSOP_LEAVEBLOCK:
return GET_UINT16(pc);
case JSOP_LEAVEBLOCKEXPR:
return GET_UINT16(pc) + 1;
case JSOP_NEWARRAY:
return GET_UINT24(pc);
default:
/* stack: fun, this, [argc arguments] */
JS_ASSERT(op == JSOP_NEW || op == JSOP_CALL ||
op == JSOP_EVAL || op == JSOP_SETCALL ||
op == JSOP_APPLY);
return 2 + GET_ARGC(pc);
}
}
#ifdef DEBUG
JS_FRIEND_API(JSBool)
js_Disassemble(JSContext *cx, JSScript *script, JSBool lines, FILE *fp)
{
jsbytecode *pc, *end;
uintN len;
pc = script->code;
end = pc + script->length;
while (pc < end) {
if (pc == script->main)
fputs("main:\n", fp);
len = js_Disassemble1(cx, script, pc,
PTRDIFF(pc, script->code, jsbytecode),
lines, fp);
if (!len)
return JS_FALSE;
pc += len;
}
return JS_TRUE;
}
const char *
ToDisassemblySource(JSContext *cx, jsval v)
{
JSObject *obj;
JSScopeProperty *sprop;
char *source;
const char *bytes;
JSString *str;
if (!JSVAL_IS_PRIMITIVE(v)) {
obj = JSVAL_TO_OBJECT(v);
if (OBJ_GET_CLASS(cx, obj) == &js_BlockClass) {
source = JS_sprintf_append(NULL, "depth %d {",
OBJ_BLOCK_DEPTH(cx, obj));
for (sprop = OBJ_SCOPE(obj)->lastProp; sprop;
sprop = sprop->parent) {
bytes = js_AtomToPrintableString(cx, JSID_TO_ATOM(sprop->id));
if (!bytes)
return NULL;
source = JS_sprintf_append(source, "%s: %d%s",
bytes, sprop->shortid,
sprop->parent ? ", " : "");
}
source = JS_sprintf_append(source, "}");
if (!source)
return NULL;
str = JS_NewString(cx, source, strlen(source));
if (!str)
return NULL;
return js_GetStringBytes(cx, str);
}
}
return js_ValueToPrintableSource(cx, v);
}
JS_FRIEND_API(uintN)
js_Disassemble1(JSContext *cx, JSScript *script, jsbytecode *pc,
uintN loc, JSBool lines, FILE *fp)
{
JSOp op;
const JSCodeSpec *cs;
ptrdiff_t len, off, jmplen;
uint32 type;
JSAtom *atom;
uintN index;
JSObject *obj;
jsval v;
const char *bytes;
jsint i;
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, js_GetErrorMessage, NULL,
JSMSG_BYTECODE_TOO_BIG, numBuf1, numBuf2);
return 0;
}
cs = &js_CodeSpec[op];
len = (ptrdiff_t) cs->length;
fprintf(fp, "%05u:", loc);
if (lines)
fprintf(fp, "%4u", JS_PCToLineNumber(cx, script, pc));
fprintf(fp, " %s", js_CodeName[op]);
type = JOF_TYPE(cs->format);
switch (type) {
case JOF_BYTE:
if (op == JSOP_TRAP) {
op = JS_GetTrapOpcode(cx, script, pc);
len = (ptrdiff_t) js_CodeSpec[op].length;
}
break;
case JOF_JUMP:
case JOF_JUMPX:
off = GetJumpOffset(pc, pc);
fprintf(fp, " %u (%d)", loc + (intN) off, (intN) off);
break;
case JOF_ATOM:
case JOF_OBJECT:
case JOF_REGEXP:
index = js_GetIndexFromBytecode(cx, script, pc, 0);
if (type == JOF_ATOM) {
JS_GET_SCRIPT_ATOM(script, index, atom);
v = ATOM_KEY(atom);
} else {
if (type == JOF_OBJECT)
JS_GET_SCRIPT_OBJECT(script, index, obj);
else
JS_GET_SCRIPT_REGEXP(script, index, obj);
v = OBJECT_TO_JSVAL(obj);
}
bytes = ToDisassemblySource(cx, v);
if (!bytes)
return 0;
fprintf(fp, " %s", bytes);
break;
case JOF_UINT16:
i = (jsint)GET_UINT16(pc);
goto print_int;
case JOF_TABLESWITCH:
case JOF_TABLESWITCHX:
{
jsbytecode *pc2;
jsint i, low, high;
jmplen = (type == JOF_TABLESWITCH) ? JUMP_OFFSET_LEN
: JUMPX_OFFSET_LEN;
pc2 = pc;
off = GetJumpOffset(pc, pc2);
pc2 += jmplen;
low = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
high = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
fprintf(fp, " defaultOffset %d low %d high %d", (intN) off, low, high);
for (i = low; i <= high; i++) {
off = GetJumpOffset(pc, pc2);
fprintf(fp, "\n\t%d: %d", i, (intN) off);
pc2 += jmplen;
}
len = 1 + pc2 - pc;
break;
}
case JOF_LOOKUPSWITCH:
case JOF_LOOKUPSWITCHX:
{
jsbytecode *pc2;
jsatomid npairs;
jmplen = (type == JOF_LOOKUPSWITCH) ? JUMP_OFFSET_LEN
: JUMPX_OFFSET_LEN;
pc2 = pc;
off = GetJumpOffset(pc, pc2);
pc2 += jmplen;
npairs = GET_UINT16(pc2);
pc2 += UINT16_LEN;
fprintf(fp, " offset %d npairs %u", (intN) off, (uintN) npairs);
while (npairs) {
JS_GET_SCRIPT_ATOM(script, GET_INDEX(pc2), atom);
pc2 += INDEX_LEN;
off = GetJumpOffset(pc, pc2);
pc2 += jmplen;
bytes = ToDisassemblySource(cx, ATOM_KEY(atom));
if (!bytes)
return 0;
fprintf(fp, "\n\t%s: %d", bytes, (intN) off);
npairs--;
}
len = 1 + pc2 - pc;
break;
}
case JOF_QARG:
fprintf(fp, " %u", GET_ARGNO(pc));
break;
case JOF_LOCAL:
fprintf(fp, " %u", GET_SLOTNO(pc));
break;
case JOF_SLOTATOM:
case JOF_SLOTOBJECT:
fprintf(fp, " %u", GET_SLOTNO(pc));
index = js_GetIndexFromBytecode(cx, script, pc, SLOTNO_LEN);
if (type == JOF_SLOTATOM) {
JS_GET_SCRIPT_ATOM(script, index, atom);
v = ATOM_KEY(atom);
} else {
JS_GET_SCRIPT_OBJECT(script, index, obj);
v = OBJECT_TO_JSVAL(obj);
}
bytes = ToDisassemblySource(cx, v);
if (!bytes)
return 0;
fprintf(fp, " %s", bytes);
break;
case JOF_UINT24:
JS_ASSERT(op == JSOP_UINT24 || op == JSOP_NEWARRAY);
i = (jsint)GET_UINT24(pc);
goto print_int;
case JOF_UINT8:
i = pc[1];
goto print_int;
case JOF_INT8:
i = GET_INT8(pc);
goto print_int;
case JOF_INT32:
JS_ASSERT(op == JSOP_INT32);
i = GET_INT32(pc);
print_int:
fprintf(fp, " %d", i);
break;
default: {
char numBuf[12];
JS_snprintf(numBuf, sizeof numBuf, "%lx", (unsigned long) cs->format);
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
JSMSG_UNKNOWN_FORMAT, numBuf);
return 0;
}
}
fputs("\n", fp);
return len;
}
#endif /* DEBUG */
/************************************************************************/
/*
* Sprintf, but with unlimited and automatically allocated buffering.
*/
typedef struct Sprinter {
JSContext *context; /* context executing the decompiler */
JSArenaPool *pool; /* string allocation pool */
char *base; /* base address of buffer in pool */
size_t size; /* size of buffer allocated at base */
ptrdiff_t offset; /* offset of next free char in buffer */
} Sprinter;
#define INIT_SPRINTER(cx, sp, ap, off) \
((sp)->context = cx, (sp)->pool = ap, (sp)->base = NULL, (sp)->size = 0, \
(sp)->offset = off)
#define OFF2STR(sp,off) ((sp)->base + (off))
#define STR2OFF(sp,str) ((str) - (sp)->base)
#define RETRACT(sp,str) ((sp)->offset = STR2OFF(sp, str))
static JSBool
SprintEnsureBuffer(Sprinter *sp, size_t len)
{
ptrdiff_t nb;
char *base;
nb = (sp->offset + len + 1) - sp->size;
if (nb < 0)
return JS_TRUE;
base = sp->base;
if (!base) {
JS_ARENA_ALLOCATE_CAST(base, char *, sp->pool, nb);
} else {
JS_ARENA_GROW_CAST(base, char *, sp->pool, sp->size, nb);
}
if (!base) {
js_ReportOutOfScriptQuota(sp->context);
return JS_FALSE;
}
sp->base = base;
sp->size += nb;
return JS_TRUE;
}
static ptrdiff_t
SprintPut(Sprinter *sp, const char *s, size_t len)
{
ptrdiff_t offset;
char *bp;
/* Allocate space for s, including the '\0' at the end. */
if (!SprintEnsureBuffer(sp, len))
return -1;
/* Advance offset and copy s into sp's buffer. */
offset = sp->offset;
sp->offset += len;
bp = sp->base + offset;
memmove(bp, s, len);
bp[len] = 0;
return offset;
}
static ptrdiff_t
SprintCString(Sprinter *sp, const char *s)
{
return SprintPut(sp, s, strlen(s));
}
static ptrdiff_t
SprintString(Sprinter *sp, JSString *str)
{
jschar *chars;
size_t length, size;
ptrdiff_t offset;
JSSTRING_CHARS_AND_LENGTH(str, chars, length);
if (length == 0)
return sp->offset;
size = js_GetDeflatedStringLength(sp->context, chars, length);
if (size == (size_t)-1 || !SprintEnsureBuffer(sp, size))
return -1;
offset = sp->offset;
sp->offset += size;
js_DeflateStringToBuffer(sp->context, chars, length, sp->base + offset,
&size);
sp->base[sp->offset] = 0;
return offset;
}
static ptrdiff_t
Sprint(Sprinter *sp, const char *format, ...)
{
va_list ap;
char *bp;
ptrdiff_t offset;
va_start(ap, format);
bp = JS_vsmprintf(format, ap); /* XXX vsaprintf */
va_end(ap);
if (!bp) {
JS_ReportOutOfMemory(sp->context);
return -1;
}
offset = SprintCString(sp, bp);
free(bp);
return offset;
}
const char js_EscapeMap[] = {
'\b', 'b',
'\f', 'f',
'\n', 'n',
'\r', 'r',
'\t', 't',
'\v', 'v',
'"', '"',
'\'', '\'',
'\\', '\\',
'\0', '0'
};
#define DONT_ESCAPE 0x10000
static char *
QuoteString(Sprinter *sp, JSString *str, uint32 quote)
{
JSBool dontEscape, ok;
jschar qc, c;
ptrdiff_t off, len;
const jschar *s, *t, *z;
const char *e;
char *bp;
/* Sample off first for later return value pointer computation. */
dontEscape = (quote & DONT_ESCAPE) != 0;
qc = (jschar) quote;
off = sp->offset;
if (qc && Sprint(sp, "%c", (char)qc) < 0)
return NULL;
/* Loop control variables: z points at end of string sentinel. */
JSSTRING_CHARS_AND_END(str, s, z);
for (t = s; t < z; s = ++t) {
/* Move t forward from s past un-quote-worthy characters. */
c = *t;
while (JS_ISPRINT(c) && c != qc && c != '\\' && c != '\t' &&
!(c >> 8)) {
c = *++t;
if (t == z)
break;
}
len = PTRDIFF(t, s, jschar);
/* Allocate space for s, including the '\0' at the end. */
if (!SprintEnsureBuffer(sp, len))
return NULL;
/* Advance sp->offset and copy s into sp's buffer. */
bp = sp->base + sp->offset;
sp->offset += len;
while (--len >= 0)
*bp++ = (char) *s++;
*bp = '\0';
if (t == z)
break;
/* Use js_EscapeMap, \u, or \x only if necessary. */
if (!(c >> 8) && (e = strchr(js_EscapeMap, (int)c)) != NULL) {
ok = dontEscape
? Sprint(sp, "%c", (char)c) >= 0
: Sprint(sp, "\\%c", e[1]) >= 0;
} else {
ok = Sprint(sp, (c >> 8) ? "\\u%04X" : "\\x%02X", c) >= 0;
}
if (!ok)
return NULL;
}
/* Sprint the closing quote and return the quoted string. */
if (qc && Sprint(sp, "%c", (char)qc) < 0)
return NULL;
/*
* If we haven't Sprint'd anything yet, Sprint an empty string so that
* the OFF2STR below gives a valid result.
*/
if (off == sp->offset && Sprint(sp, "") < 0)
return NULL;
return OFF2STR(sp, off);
}
JSString *
js_QuoteString(JSContext *cx, JSString *str, jschar quote)
{
void *mark;
Sprinter sprinter;
char *bytes;
JSString *escstr;
mark = JS_ARENA_MARK(&cx->tempPool);
INIT_SPRINTER(cx, &sprinter, &cx->tempPool, 0);
bytes = QuoteString(&sprinter, str, quote);
escstr = bytes ? JS_NewStringCopyZ(cx, bytes) : NULL;
JS_ARENA_RELEASE(&cx->tempPool, mark);
return escstr;
}
/************************************************************************/
struct JSPrinter {
Sprinter sprinter; /* base class state */
JSArenaPool pool; /* string allocation pool */
uintN indent; /* indentation in spaces */
JSPackedBool pretty; /* pretty-print: indent, use newlines */
JSPackedBool grouped; /* in parenthesized expression context */
JSScript *script; /* script being printed */
jsbytecode *dvgfence; /* DecompileExpression fencepost */
jsbytecode **pcstack; /* DecompileExpression modeled stack */
JSFunction *fun; /* interpreted function */
jsuword *localNames; /* argument and variable names */
};
/*
* Hack another flag, a la JS_DONT_PRETTY_PRINT, into uintN indent parameters
* to functions such as js_DecompileFunction and js_NewPrinter. This time, as
* opposed to JS_DONT_PRETTY_PRINT back in the dark ages, we can assume that a
* uintN is at least 32 bits.
*/
#define JS_IN_GROUP_CONTEXT 0x10000
JSPrinter *
JS_NEW_PRINTER(JSContext *cx, const char *name, JSFunction *fun,
uintN indent, JSBool pretty)
{
JSPrinter *jp;
jp = (JSPrinter *) JS_malloc(cx, sizeof(JSPrinter));
if (!jp)
return NULL;
INIT_SPRINTER(cx, &jp->sprinter, &jp->pool, 0);
JS_INIT_ARENA_POOL(&jp->pool, name, 256, 1, &cx->scriptStackQuota);
jp->indent = indent & ~JS_IN_GROUP_CONTEXT;
jp->pretty = pretty;
jp->grouped = (indent & JS_IN_GROUP_CONTEXT) != 0;
jp->script = NULL;
jp->dvgfence = NULL;
jp->pcstack = NULL;
jp->fun = fun;
jp->localNames = NULL;
if (fun && FUN_INTERPRETED(fun) && JS_GET_LOCAL_NAME_COUNT(fun)) {
jp->localNames = js_GetLocalNameArray(cx, fun, &jp->pool);
if (!jp->localNames) {
js_DestroyPrinter(jp);
return NULL;
}
}
return jp;
}
void
js_DestroyPrinter(JSPrinter *jp)
{
JS_FinishArenaPool(&jp->pool);
JS_free(jp->sprinter.context, jp);
}
JSString *
js_GetPrinterOutput(JSPrinter *jp)
{
JSContext *cx;
JSString *str;
cx = jp->sprinter.context;
if (!jp->sprinter.base)
return cx->runtime->emptyString;
str = JS_NewStringCopyZ(cx, jp->sprinter.base);
if (!str)
return NULL;
JS_FreeArenaPool(&jp->pool);
INIT_SPRINTER(cx, &jp->sprinter, &jp->pool, 0);
return str;
}
/*
* NB: Indexed by SRC_DECL_* defines from jsemit.h.
*/
static const char * const var_prefix[] = {"var ", "const ", "let "};
static const char *
VarPrefix(jssrcnote *sn)
{
if (sn && (SN_TYPE(sn) == SRC_DECL || SN_TYPE(sn) == SRC_GROUPASSIGN)) {
ptrdiff_t type = js_GetSrcNoteOffset(sn, 0);
if ((uintN)type <= SRC_DECL_LET)
return var_prefix[type];
}
return "";
}
int
js_printf(JSPrinter *jp, const char *format, ...)
{
va_list ap;
char *bp, *fp;
int cc;
if (*format == '\0')
return 0;
va_start(ap, format);
/* If pretty-printing, expand magic tab into a run of jp->indent spaces. */
if (*format == '\t') {
format++;
if (jp->pretty && Sprint(&jp->sprinter, "%*s", jp->indent, "") < 0)
return -1;
}
/* Suppress newlines (must be once per format, at the end) if not pretty. */
fp = NULL;
if (!jp->pretty && format[cc = strlen(format) - 1] == '\n') {
fp = JS_strdup(jp->sprinter.context, format);
if (!fp)
return -1;
fp[cc] = '\0';
format = fp;
}
/* Allocate temp space, convert format, and put. */
bp = JS_vsmprintf(format, ap); /* XXX vsaprintf */
if (fp) {
JS_free(jp->sprinter.context, fp);
format = NULL;
}
if (!bp) {
JS_ReportOutOfMemory(jp->sprinter.context);
return -1;
}
cc = strlen(bp);
if (SprintPut(&jp->sprinter, bp, (size_t)cc) < 0)
cc = -1;
free(bp);
va_end(ap);
return cc;
}
JSBool
js_puts(JSPrinter *jp, const char *s)
{
return SprintCString(&jp->sprinter, s) >= 0;
}
/************************************************************************/
typedef struct SprintStack {
Sprinter sprinter; /* sprinter for postfix to infix buffering */
ptrdiff_t *offsets; /* stack of postfix string offsets */
jsbytecode *opcodes; /* parallel stack of JS opcodes */
uintN top; /* top of stack index */
uintN inArrayInit; /* array initialiser/comprehension level */
JSBool inGenExp; /* in generator expression */
JSPrinter *printer; /* permanent output goes here */
} SprintStack;
/*
* Find the depth of the operand stack when the interpreter reaches the given
* pc in script. pcstack must have space for least script->depth elements. On
* return it will contain pointers to opcodes that populated the interpreter's
* current operand stack.
*
* This function cannot raise an exception or error. However, due to a risk of
* potential bugs when modeling the stack, the function returns -1 if it
* detects an inconsistency in the model. Such an inconsistency triggers an
* assert in a debug build.
*/
static intN
ReconstructPCStack(JSContext *cx, JSScript *script, jsbytecode *pc,
jsbytecode **pcstack);
#define FAILED_EXPRESSION_DECOMPILER ((char *) 1)
/*
* Decompile a part of expression up to the given pc. The function returns
* NULL on out-of-memory, or the FAILED_EXPRESSION_DECOMPILER sentinel when
* the decompiler fails due to a bug and/or unimplemented feature, or the
* decompiled string on success.
*/
static char *
DecompileExpression(JSContext *cx, JSScript *script, JSFunction *fun,
jsbytecode *pc);
/*
* Get a stacked offset from ss->sprinter.base, or if the stacked value |off|
* is negative, fetch the generating pc from printer->pcstack[-2 - off] and
* decompile the code that generated the missing value. This is used when
* reporting errors, where the model stack will lack |pcdepth| non-negative
* offsets (see DecompileExpression and DecompileCode).
*
* If the stacked offset is -1, return 0 to index the NUL padding at the start
* of ss->sprinter.base. If this happens, it means there is a decompiler bug
* to fix, but it won't violate memory safety.
*/
static ptrdiff_t
GetOff(SprintStack *ss, uintN i)
{
ptrdiff_t off;
jsbytecode *pc;
char *bytes;
off = ss->offsets[i];
if (off >= 0)
return off;
JS_ASSERT(off <= -2);
JS_ASSERT(ss->printer->pcstack);
if (off < -2 && ss->printer->pcstack) {
pc = ss->printer->pcstack[-2 - off];
bytes = DecompileExpression(ss->sprinter.context, ss->printer->script,
ss->printer->fun, pc);
if (!bytes)
return 0;
if (bytes != FAILED_EXPRESSION_DECOMPILER) {
off = SprintCString(&ss->sprinter, bytes);
if (off < 0)
off = 0;
ss->offsets[i] = off;
JS_free(ss->sprinter.context, bytes);
return off;
}
if (!ss->sprinter.base && SprintPut(&ss->sprinter, "", 0) >= 0) {
memset(ss->sprinter.base, 0, ss->sprinter.offset);
ss->offsets[i] = -1;
}
}
return 0;
}
static const char *
GetStr(SprintStack *ss, uintN i)
{
ptrdiff_t off;
/*
* Must call GetOff before using ss->sprinter.base, since it may be null
* until bootstrapped by GetOff.
*/
off = GetOff(ss, i);
return OFF2STR(&ss->sprinter, off);
}
/*
* Gap between stacked strings to allow for insertion of parens and commas
* when auto-parenthesizing expressions and decompiling array initialisers
* (see the JSOP_NEWARRAY case in Decompile).
*/
#define PAREN_SLOP (2 + 1)
/*
* These pseudo-ops help js_DecompileValueGenerator decompile JSOP_SETNAME,
* JSOP_SETPROP, and JSOP_SETELEM, respectively. They are never stored in
* bytecode, so they don't preempt valid opcodes.
*/
#define JSOP_GETPROP2 256
#define JSOP_GETELEM2 257
static void
AddParenSlop(SprintStack *ss)
{
memset(OFF2STR(&ss->sprinter, ss->sprinter.offset), 0, PAREN_SLOP);
ss->sprinter.offset += PAREN_SLOP;
}
static JSBool
PushOff(SprintStack *ss, ptrdiff_t off, JSOp op)
{
uintN top;
if (!SprintEnsureBuffer(&ss->sprinter, PAREN_SLOP))
return JS_FALSE;
/* ss->top points to the next free slot; be paranoid about overflow. */
top = ss->top;
JS_ASSERT(top < StackDepth(ss->printer->script));
if (top >= StackDepth(ss->printer->script)) {
JS_ReportOutOfMemory(ss->sprinter.context);
return JS_FALSE;
}
/* The opcodes stack must contain real bytecodes that index js_CodeSpec. */
ss->offsets[top] = off;
ss->opcodes[top] = (op == JSOP_GETPROP2) ? JSOP_GETPROP
: (op == JSOP_GETELEM2) ? JSOP_GETELEM
: (jsbytecode) op;
ss->top = ++top;
AddParenSlop(ss);
return JS_TRUE;
}
static ptrdiff_t
PopOffPrec(SprintStack *ss, uint8 prec)
{
uintN top;
const JSCodeSpec *topcs;
ptrdiff_t off;
/* ss->top points to the next free slot; be paranoid about underflow. */
top = ss->top;
JS_ASSERT(top != 0);
if (top == 0)
return 0;
ss->top = --top;
off = GetOff(ss, top);
topcs = &js_CodeSpec[ss->opcodes[top]];
if (topcs->prec != 0 && topcs->prec < prec) {
ss->sprinter.offset = ss->offsets[top] = off - 2;
off = Sprint(&ss->sprinter, "(%s)", OFF2STR(&ss->sprinter, off));
} else {
ss->sprinter.offset = off;
}
return off;
}
static const char *
PopStrPrec(SprintStack *ss, uint8 prec)
{
ptrdiff_t off;