-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsopcode.c
4794 lines (4297 loc) · 165 KB
/
jsopcode.c
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=78:
*
* ***** 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 "jsconfig.h"
#include "jsdbgapi.h"
#include "jsemit.h"
#include "jsfun.h"
#include "jslock.h"
#include "jsobj.h"
#include "jsopcode.h"
#include "jsregexp.h"
#include "jsscan.h"
#include "jsscope.h"
#include "jsscript.h"
#include "jsstr.h"
#if JS_HAS_DESTRUCTURING
# include "jsnum.h"
#endif
static const char js_incop_strs[][3] = {"++", "--"};
/* Pollute the namespace locally for MSVC Win16, but not for WatCom. */
#ifdef __WINDOWS_386__
#ifdef FAR
#undef FAR
#endif
#else /* !__WINDOWS_386__ */
#ifndef FAR
#define FAR
#endif
#endif /* !__WINDOWS_386__ */
const JSCodeSpec FAR js_CodeSpec[] = {
#define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
{name,token,length,nuses,ndefs,prec,format},
#include "jsopcode.tbl"
#undef OPDEF
};
uintN js_NumCodeSpecs = sizeof (js_CodeSpec) / sizeof js_CodeSpec[0];
/************************************************************************/
static ptrdiff_t
GetJumpOffset(jsbytecode *pc, jsbytecode *pc2)
{
uint32 type;
type = (js_CodeSpec[*pc].format & JOF_TYPEMASK);
if (JOF_TYPE_IS_EXTENDED_JUMP(type))
return GET_JUMPX_OFFSET(pc2);
return GET_JUMP_OFFSET(pc2);
}
#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(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;
const char *bytes;
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", cs->name);
type = cs->format & JOF_TYPEMASK;
switch (type) {
case JOF_BYTE:
if (op == JSOP_TRAP) {
op = JS_GetTrapOpcode(cx, script, pc);
if (op == JSOP_LIMIT)
return 0;
len = (ptrdiff_t) js_CodeSpec[op].length;
}
break;
case JOF_JUMP:
case JOF_JUMPX:
off = GetJumpOffset(pc, pc);
fprintf(fp, " %u (%d)", loc + off, off);
break;
case JOF_CONST:
atom = GET_ATOM(cx, script, pc);
bytes = ToDisassemblySource(cx, ATOM_KEY(atom));
if (!bytes)
return 0;
fprintf(fp, " %s", bytes);
break;
case JOF_UINT16:
case JOF_LOCAL:
fprintf(fp, " %u", GET_UINT16(pc));
break;
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", off, low, high);
for (i = low; i <= high; i++) {
off = GetJumpOffset(pc, pc2);
fprintf(fp, "\n\t%d: %d", i, 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_ATOM_INDEX(pc2);
pc2 += ATOM_INDEX_LEN;
fprintf(fp, " offset %d npairs %u", off, (uintN) npairs);
while (npairs) {
atom = GET_ATOM(cx, script, pc2);
pc2 += ATOM_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, off);
npairs--;
}
len = 1 + pc2 - pc;
break;
}
case JOF_QARG:
fprintf(fp, " %u", GET_ARGNO(pc));
break;
case JOF_QVAR:
fprintf(fp, " %u", GET_VARNO(pc));
break;
case JOF_INDEXCONST:
fprintf(fp, " %u", GET_VARNO(pc));
pc += VARNO_LEN;
atom = GET_ATOM(cx, script, pc);
bytes = ToDisassemblySource(cx, ATOM_KEY(atom));
if (!bytes)
return 0;
fprintf(fp, " %s", bytes);
break;
case JOF_UINT24:
if (op == JSOP_FINDNAME) {
/* Special case to avoid a JOF_FINDNAME just for this op. */
atom = js_GetAtom(cx, &script->atomMap, GET_UINT24(pc));
bytes = ToDisassemblySource(cx, ATOM_KEY(atom));
if (!bytes)
return 0;
fprintf(fp, " %s", bytes);
break;
}
JS_ASSERT(op == JSOP_UINT24 || op == JSOP_LITERAL);
fprintf(fp, " %u", GET_UINT24(pc));
break;
case JOF_LITOPX:
atom = js_GetAtom(cx, &script->atomMap, GET_LITERAL_INDEX(pc));
bytes = ToDisassemblySource(cx, ATOM_KEY(atom));
if (!bytes)
return 0;
/*
* Bytecode: JSOP_LITOPX <uint24> op [<varno> if JSOP_DEFLOCALFUN].
* Advance pc to point at op.
*/
pc += 1 + LITERAL_INDEX_LEN;
op = *pc;
cs = &js_CodeSpec[op];
fprintf(fp, " %s op %s", bytes, cs->name);
if ((cs->format & JOF_TYPEMASK) == JOF_INDEXCONST)
fprintf(fp, " %u", GET_VARNO(pc));
/*
* Set len to advance pc to skip op and any other immediates (namely,
* <varno> if JSOP_DEFLOCALFUN).
*/
JS_ASSERT(cs->length > ATOM_INDEX_LEN);
len = cs->length - ATOM_INDEX_LEN;
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
SprintAlloc(Sprinter *sp, size_t nb)
{
char *base;
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_ReportOutOfMemory(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 nb, offset;
char *bp;
/* Allocate space for s, including the '\0' at the end. */
nb = (sp->offset + len + 1) - sp->size;
if (nb > 0 && !SprintAlloc(sp, nb))
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
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 jschar js_EscapeMap[] = {
'\b', 'b',
'\f', 'f',
'\n', 'n',
'\r', 'r',
'\t', 't',
'\v', 'v',
'"', '"',
'\'', '\'',
'\\', '\\',
0
};
#define DONT_ESCAPE 0x10000
static char *
QuoteString(Sprinter *sp, JSString *str, uint32 quote)
{
JSBool dontEscape, ok;
jschar qc, c;
ptrdiff_t off, len, nb;
const jschar *s, *t, *u, *z;
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. */
s = JSSTRING_CHARS(str);
z = s + JSSTRING_LENGTH(str);
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 >> 8)) {
c = *++t;
if (t == z)
break;
}
len = PTRDIFF(t, s, jschar);
/* Allocate space for s, including the '\0' at the end. */
nb = (sp->offset + len + 1) - sp->size;
if (nb > 0 && !SprintAlloc(sp, nb))
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 ((u = js_strchr(js_EscapeMap, c)) != NULL) {
ok = dontEscape
? Sprint(sp, "%c", (char)c) >= 0
: Sprint(sp, "\\%c", (char)u[1]) >= 0;
} else {
#ifdef JS_C_STRINGS_ARE_UTF8
/* If this is a surrogate pair, make sure to print the pair. */
if (c >= 0xD800 && c <= 0xDBFF) {
jschar buffer[3];
buffer[0] = c;
buffer[1] = *++t;
buffer[2] = 0;
if (t == z) {
char numbuf[10];
JS_snprintf(numbuf, sizeof numbuf, "0x%x", c);
JS_ReportErrorFlagsAndNumber(sp->context, JSREPORT_ERROR,
js_GetErrorMessage, NULL,
JSMSG_BAD_SURROGATE_CHAR,
numbuf);
ok = JS_FALSE;
break;
}
ok = Sprint(sp, "%hs", buffer) >= 0;
} else {
/* Print as UTF-8 string. */
ok = Sprint(sp, "%hc", c) >= 0;
}
#else
/* Use \uXXXX or \xXX if the string can't be displayed as UTF-8. */
ok = Sprint(sp, (c >> 8) ? "\\u%04X" : "\\x%02X", c) >= 0;
#endif
}
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;
}
/************************************************************************/
#if JS_HAS_BLOCK_SCOPE
typedef enum JSBraceState {
ALWAYS_BRACE,
MAYBE_BRACE,
DONT_BRACE
} JSBraceState;
#endif
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; /* js_DecompileValueGenerator fencepost */
JSScope *scope; /* script function scope */
#if JS_HAS_BLOCK_SCOPE
JSBraceState braceState; /* remove braces around let declaration */
ptrdiff_t spaceOffset; /* -1 or offset of space before maybe-{ */
#endif
};
/*
* 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_NewPrinter(JSContext *cx, const char *name, 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_InitArenaPool(&jp->pool, name, 256, 1);
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->scope = NULL;
#if JS_HAS_BLOCK_SCOPE
jp->braceState = ALWAYS_BRACE;
jp->spaceOffset = -1;
#endif
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;
}
#if !JS_HAS_BLOCK_SCOPE
# define SET_MAYBE_BRACE(jp) jp
# define CLEAR_MAYBE_BRACE(jp) jp
#else
# define SET_MAYBE_BRACE(jp) ((jp)->braceState = MAYBE_BRACE, (jp))
# define CLEAR_MAYBE_BRACE(jp) ((jp)->braceState = ALWAYS_BRACE, (jp))
static void
SetDontBrace(JSPrinter *jp)
{
ptrdiff_t offset;
const char *bp;
/* When not pretty-printing, newline after brace is chopped. */
JS_ASSERT(jp->spaceOffset < 0);
offset = jp->sprinter.offset - (jp->pretty ? 3 : 2);
/* The shortest case is "if (x) {". */
JS_ASSERT(offset >= 6);
bp = jp->sprinter.base;
if (bp[offset+0] == ' ' && bp[offset+1] == '{') {
JS_ASSERT(!jp->pretty || bp[offset+2] == '\n');
jp->spaceOffset = offset;
jp->braceState = DONT_BRACE;
}
}
#endif
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 JS_HAS_BLOCK_SCOPE
if (*format == '}' && jp->braceState != ALWAYS_BRACE) {
JSBraceState braceState;
braceState = jp->braceState;
jp->braceState = ALWAYS_BRACE;
if (braceState == DONT_BRACE) {
ptrdiff_t offset, delta, from;
JS_ASSERT(format[1] == '\n' || format[1] == ' ');
offset = jp->spaceOffset;
JS_ASSERT(offset >= 6);
/* Replace " {\n" at the end of jp->sprinter with "\n". */
bp = jp->sprinter.base;
if (bp[offset+0] == ' ' && bp[offset+1] == '{') {
delta = 2;
if (jp->pretty) {
/* If pretty, we don't have to worry about 'else'. */
JS_ASSERT(bp[offset+2] == '\n');
} else if (bp[offset-1] != ')') {
/* Must keep ' ' to avoid 'dolet' or 'elselet'. */
++offset;
delta = 1;
}
from = offset + delta;
memmove(bp + offset, bp + from, jp->sprinter.offset - from);
jp->sprinter.offset -= delta;
jp->spaceOffset = -1;
format += 2;
if (*format == '\0')
return 0;
}
}
}
#endif
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 */
JSPrinter *printer; /* permanent output goes here */
} SprintStack;
/*
* Get a stacked offset from ss->sprinter.base, or if the stacked value |off|
* is negative, lazily fetch the generating pc at |spindex = 1 + off| and try
* to 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 js_DecompileValueGenerator and js_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;
JSString *str;
off = ss->offsets[i];
if (off < 0) {
#if defined DEBUG_brendan || defined DEBUG_mrbkap || defined DEBUG_crowder
JS_ASSERT(off < -1);
#endif
if (++off == 0) {
if (!ss->sprinter.base && SprintPut(&ss->sprinter, "", 0) >= 0)
memset(ss->sprinter.base, 0, ss->sprinter.offset);
return 0;
}
str = js_DecompileValueGenerator(ss->sprinter.context, off,
JSVAL_NULL, NULL);
if (!str)
return 0;
off = SprintCString(&ss->sprinter, JS_GetStringBytes(str));
if (off < 0)
off = 0;
ss->offsets[i] = off;
}
return off;
}
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. */
#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 JSBool
PushOff(SprintStack *ss, ptrdiff_t off, JSOp op)
{
uintN top;
if (!SprintAlloc(&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 < ss->printer->script->depth);
if (top >= ss->printer->script->depth) {
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;
memset(OFF2STR(&ss->sprinter, ss->sprinter.offset), 0, PAREN_SLOP);
ss->sprinter.offset += PAREN_SLOP;
return JS_TRUE;
}
static ptrdiff_t
PopOff(SprintStack *ss, JSOp op)
{
uintN top;
const JSCodeSpec *cs, *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]];
cs = &js_CodeSpec[op];
if (topcs->prec != 0 && topcs->prec < cs->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 *
PopStr(SprintStack *ss, JSOp op)
{
ptrdiff_t off;
off = PopOff(ss, op);
return OFF2STR(&ss->sprinter, off);
}
typedef struct TableEntry {
jsval key;
ptrdiff_t offset;
JSAtom *label;
jsint order; /* source order for stable tableswitch sort */
} TableEntry;
static JSBool
CompareOffsets(void *arg, const void *v1, const void *v2, int *result)
{
ptrdiff_t offset_diff;
const TableEntry *te1 = (const TableEntry *) v1,
*te2 = (const TableEntry *) v2;
offset_diff = te1->offset - te2->offset;
*result = (offset_diff == 0 ? te1->order - te2->order
: offset_diff < 0 ? -1
: 1);
return JS_TRUE;
}
static jsbytecode *
Decompile(SprintStack *ss, jsbytecode *pc, intN nb);
static JSBool
DecompileSwitch(SprintStack *ss, TableEntry *table, uintN tableLength,
jsbytecode *pc, ptrdiff_t switchLength,
ptrdiff_t defaultOffset, JSBool isCondSwitch)
{
JSContext *cx;
JSPrinter *jp;
ptrdiff_t off, off2, diff, caseExprOff;
char *lval, *rval;
uintN i;
jsval key;
JSString *str;
cx = ss->sprinter.context;
jp = ss->printer;
/* JSOP_CONDSWITCH doesn't pop, unlike JSOP_{LOOKUP,TABLE}SWITCH. */
off = isCondSwitch ? GetOff(ss, ss->top-1) : PopOff(ss, JSOP_NOP);
lval = OFF2STR(&ss->sprinter, off);
js_printf(CLEAR_MAYBE_BRACE(jp), "\tswitch (%s) {\n", lval);
if (tableLength) {
diff = table[0].offset - defaultOffset;
if (diff > 0) {
jp->indent += 2;
js_printf(jp, "\t%s:\n", js_default_str);
jp->indent += 2;
if (!Decompile(ss, pc + defaultOffset, diff))
return JS_FALSE;
jp->indent -= 4;
}
caseExprOff = isCondSwitch ? JSOP_CONDSWITCH_LENGTH : 0;
for (i = 0; i < tableLength; i++) {
off = table[i].offset;
off2 = (i + 1 < tableLength) ? table[i + 1].offset : switchLength;
key = table[i].key;
if (isCondSwitch) {
ptrdiff_t nextCaseExprOff;
/*
* key encodes the JSOP_CASE bytecode's offset from switchtop.
* The next case expression follows immediately, unless we are
* at the last case.
*/
nextCaseExprOff = (ptrdiff_t)JSVAL_TO_INT(key);
nextCaseExprOff += js_CodeSpec[pc[nextCaseExprOff]].length;
jp->indent += 2;
if (!Decompile(ss, pc + caseExprOff,
nextCaseExprOff - caseExprOff)) {
return JS_FALSE;
}
caseExprOff = nextCaseExprOff;
/* Balance the stack as if this JSOP_CASE matched. */
--ss->top;
} else {
/*
* key comes from an atom, not the decompiler, so we need to
* quote it if it's a string literal. But if table[i].label
* is non-null, key was constant-propagated and label is the
* name of the const we should show as the case label. We set
* key to undefined so this identifier is escaped, if required
* by non-ASCII characters, but not quoted, by QuoteString.
*/
if (table[i].label) {
str = ATOM_TO_STRING(table[i].label);
key = JSVAL_VOID;
} else {