PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/js/lib/Socket.IO-node/support/expresso/deps/jscoverage/js/jsopcode.cpp

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
C++ | 2044 lines | 1761 code | 132 blank | 151 comment | 168 complexity | 37f3a9e7670e3289ef5fc12c8b095fde MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause
  1. /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2. * vim: set sw=4 ts=8 et tw=99:
  3. *
  4. * ***** BEGIN LICENSE BLOCK *****
  5. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  6. *
  7. * The contents of this file are subject to the Mozilla Public License Version
  8. * 1.1 (the "License"); you may not use this file except in compliance with
  9. * the License. You may obtain a copy of the License at
  10. * http://www.mozilla.org/MPL/
  11. *
  12. * Software distributed under the License is distributed on an "AS IS" basis,
  13. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  14. * for the specific language governing rights and limitations under the
  15. * License.
  16. *
  17. * The Original Code is Mozilla Communicator client code, released
  18. * March 31, 1998.
  19. *
  20. * The Initial Developer of the Original Code is
  21. * Netscape Communications Corporation.
  22. * Portions created by the Initial Developer are Copyright (C) 1998
  23. * the Initial Developer. All Rights Reserved.
  24. *
  25. * Contributor(s):
  26. *
  27. * Alternatively, the contents of this file may be used under the terms of
  28. * either of the GNU General Public License Version 2 or later (the "GPL"),
  29. * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  30. * in which case the provisions of the GPL or the LGPL are applicable instead
  31. * of those above. If you wish to allow use of your version of this file only
  32. * under the terms of either the GPL or the LGPL, and not to allow others to
  33. * use your version of this file under the terms of the MPL, indicate your
  34. * decision by deleting the provisions above and replace them with the notice
  35. * and other provisions required by the GPL or the LGPL. If you do not delete
  36. * the provisions above, a recipient may use your version of this file under
  37. * the terms of any one of the MPL, the GPL or the LGPL.
  38. *
  39. * ***** END LICENSE BLOCK ***** */
  40. /*
  41. * JS bytecode descriptors, disassemblers, and decompilers.
  42. */
  43. #include "jsstddef.h"
  44. #ifdef HAVE_MEMORY_H
  45. #include <memory.h>
  46. #endif
  47. #include <stdarg.h>
  48. #include <stdio.h>
  49. #include <stdlib.h>
  50. #include <string.h>
  51. #include "jstypes.h"
  52. #include "jsarena.h" /* Added by JSIFY */
  53. #include "jsutil.h" /* Added by JSIFY */
  54. #include "jsdtoa.h"
  55. #include "jsprf.h"
  56. #include "jsapi.h"
  57. #include "jsarray.h"
  58. #include "jsatom.h"
  59. #include "jscntxt.h"
  60. #include "jsversion.h"
  61. #include "jsdbgapi.h"
  62. #include "jsemit.h"
  63. #include "jsfun.h"
  64. #include "jsiter.h"
  65. #include "jsnum.h"
  66. #include "jsobj.h"
  67. #include "jsopcode.h"
  68. #include "jsregexp.h"
  69. #include "jsscan.h"
  70. #include "jsscope.h"
  71. #include "jsscript.h"
  72. #include "jsstr.h"
  73. #include "jsstaticcheck.h"
  74. #include "jstracer.h"
  75. #include "jsautooplen.h"
  76. /* Verify JSOP_XXX_LENGTH constant definitions. */
  77. #define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
  78. JS_STATIC_ASSERT(op##_LENGTH == length);
  79. #include "jsopcode.tbl"
  80. #undef OPDEF
  81. static const char js_incop_strs[][3] = {"++", "--"};
  82. static const char js_for_each_str[] = "for each";
  83. const JSCodeSpec js_CodeSpec[] = {
  84. #define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
  85. {length,nuses,ndefs,prec,format},
  86. #include "jsopcode.tbl"
  87. #undef OPDEF
  88. };
  89. uintN js_NumCodeSpecs = JS_ARRAY_LENGTH(js_CodeSpec);
  90. /*
  91. * Each element of the array is either a source literal associated with JS
  92. * bytecode or null.
  93. */
  94. static const char *CodeToken[] = {
  95. #define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
  96. token,
  97. #include "jsopcode.tbl"
  98. #undef OPDEF
  99. };
  100. #if defined(DEBUG) || defined(JS_JIT_SPEW)
  101. /*
  102. * Array of JS bytecode names used by DEBUG-only js_Disassemble and by
  103. * JIT debug spew.
  104. */
  105. const char *js_CodeName[] = {
  106. #define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \
  107. name,
  108. #include "jsopcode.tbl"
  109. #undef OPDEF
  110. };
  111. #endif
  112. /************************************************************************/
  113. static ptrdiff_t
  114. GetJumpOffset(jsbytecode *pc, jsbytecode *pc2)
  115. {
  116. uint32 type;
  117. type = JOF_OPTYPE(*pc);
  118. if (JOF_TYPE_IS_EXTENDED_JUMP(type))
  119. return GET_JUMPX_OFFSET(pc2);
  120. return GET_JUMP_OFFSET(pc2);
  121. }
  122. uintN
  123. js_GetIndexFromBytecode(JSContext *cx, JSScript *script, jsbytecode *pc,
  124. ptrdiff_t pcoff)
  125. {
  126. JSOp op;
  127. uintN span, base;
  128. op = (JSOp)*pc;
  129. if (op == JSOP_TRAP)
  130. op = JS_GetTrapOpcode(cx, script, pc);
  131. JS_ASSERT(js_CodeSpec[op].length >= 1 + pcoff + UINT16_LEN);
  132. /*
  133. * We need to detect index base prefix. It presents when resetbase
  134. * follows the bytecode.
  135. */
  136. span = js_CodeSpec[op].length;
  137. base = 0;
  138. if (pc - script->code + span < script->length) {
  139. if (pc[span] == JSOP_RESETBASE) {
  140. base = GET_INDEXBASE(pc - JSOP_INDEXBASE_LENGTH);
  141. } else if (pc[span] == JSOP_RESETBASE0) {
  142. JS_ASSERT(JSOP_INDEXBASE1 <= pc[-1] || pc[-1] <= JSOP_INDEXBASE3);
  143. base = (pc[-1] - JSOP_INDEXBASE1 + 1) << 16;
  144. }
  145. }
  146. return base + GET_UINT16(pc + pcoff);
  147. }
  148. uintN
  149. js_GetVariableBytecodeLength(jsbytecode *pc)
  150. {
  151. JSOp op;
  152. uintN jmplen, ncases;
  153. jsint low, high;
  154. op = (JSOp) *pc;
  155. JS_ASSERT(js_CodeSpec[op].length == -1);
  156. switch (op) {
  157. case JSOP_TABLESWITCHX:
  158. jmplen = JUMPX_OFFSET_LEN;
  159. goto do_table;
  160. case JSOP_TABLESWITCH:
  161. jmplen = JUMP_OFFSET_LEN;
  162. do_table:
  163. /* Structure: default-jump case-low case-high case1-jump ... */
  164. pc += jmplen;
  165. low = GET_JUMP_OFFSET(pc);
  166. pc += JUMP_OFFSET_LEN;
  167. high = GET_JUMP_OFFSET(pc);
  168. ncases = (uintN)(high - low + 1);
  169. return 1 + jmplen + INDEX_LEN + INDEX_LEN + ncases * jmplen;
  170. case JSOP_LOOKUPSWITCHX:
  171. jmplen = JUMPX_OFFSET_LEN;
  172. goto do_lookup;
  173. default:
  174. JS_ASSERT(op == JSOP_LOOKUPSWITCH);
  175. jmplen = JUMP_OFFSET_LEN;
  176. do_lookup:
  177. /* Structure: default-jump case-count (case1-value case1-jump) ... */
  178. pc += jmplen;
  179. ncases = GET_UINT16(pc);
  180. return 1 + jmplen + INDEX_LEN + ncases * (INDEX_LEN + jmplen);
  181. }
  182. }
  183. uintN
  184. js_GetVariableStackUseLength(JSOp op, jsbytecode *pc)
  185. {
  186. JS_ASSERT(*pc == op || *pc == JSOP_TRAP);
  187. JS_ASSERT(js_CodeSpec[op].nuses == -1);
  188. switch (op) {
  189. case JSOP_POPN:
  190. return GET_UINT16(pc);
  191. case JSOP_LEAVEBLOCK:
  192. return GET_UINT16(pc);
  193. case JSOP_LEAVEBLOCKEXPR:
  194. return GET_UINT16(pc) + 1;
  195. case JSOP_NEWARRAY:
  196. return GET_UINT24(pc);
  197. default:
  198. /* stack: fun, this, [argc arguments] */
  199. JS_ASSERT(op == JSOP_NEW || op == JSOP_CALL ||
  200. op == JSOP_EVAL || op == JSOP_SETCALL ||
  201. op == JSOP_APPLY);
  202. return 2 + GET_ARGC(pc);
  203. }
  204. }
  205. #ifdef DEBUG
  206. JS_FRIEND_API(JSBool)
  207. js_Disassemble(JSContext *cx, JSScript *script, JSBool lines, FILE *fp)
  208. {
  209. jsbytecode *pc, *end;
  210. uintN len;
  211. pc = script->code;
  212. end = pc + script->length;
  213. while (pc < end) {
  214. if (pc == script->main)
  215. fputs("main:\n", fp);
  216. len = js_Disassemble1(cx, script, pc,
  217. PTRDIFF(pc, script->code, jsbytecode),
  218. lines, fp);
  219. if (!len)
  220. return JS_FALSE;
  221. pc += len;
  222. }
  223. return JS_TRUE;
  224. }
  225. const char *
  226. ToDisassemblySource(JSContext *cx, jsval v)
  227. {
  228. JSObject *obj;
  229. JSScopeProperty *sprop;
  230. char *source;
  231. const char *bytes;
  232. JSString *str;
  233. if (!JSVAL_IS_PRIMITIVE(v)) {
  234. obj = JSVAL_TO_OBJECT(v);
  235. if (OBJ_GET_CLASS(cx, obj) == &js_BlockClass) {
  236. source = JS_sprintf_append(NULL, "depth %d {",
  237. OBJ_BLOCK_DEPTH(cx, obj));
  238. for (sprop = OBJ_SCOPE(obj)->lastProp; sprop;
  239. sprop = sprop->parent) {
  240. bytes = js_AtomToPrintableString(cx, JSID_TO_ATOM(sprop->id));
  241. if (!bytes)
  242. return NULL;
  243. source = JS_sprintf_append(source, "%s: %d%s",
  244. bytes, sprop->shortid,
  245. sprop->parent ? ", " : "");
  246. }
  247. source = JS_sprintf_append(source, "}");
  248. if (!source)
  249. return NULL;
  250. str = JS_NewString(cx, source, strlen(source));
  251. if (!str)
  252. return NULL;
  253. return js_GetStringBytes(cx, str);
  254. }
  255. }
  256. return js_ValueToPrintableSource(cx, v);
  257. }
  258. JS_FRIEND_API(uintN)
  259. js_Disassemble1(JSContext *cx, JSScript *script, jsbytecode *pc,
  260. uintN loc, JSBool lines, FILE *fp)
  261. {
  262. JSOp op;
  263. const JSCodeSpec *cs;
  264. ptrdiff_t len, off, jmplen;
  265. uint32 type;
  266. JSAtom *atom;
  267. uintN index;
  268. JSObject *obj;
  269. jsval v;
  270. const char *bytes;
  271. jsint i;
  272. op = (JSOp)*pc;
  273. if (op >= JSOP_LIMIT) {
  274. char numBuf1[12], numBuf2[12];
  275. JS_snprintf(numBuf1, sizeof numBuf1, "%d", op);
  276. JS_snprintf(numBuf2, sizeof numBuf2, "%d", JSOP_LIMIT);
  277. JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
  278. JSMSG_BYTECODE_TOO_BIG, numBuf1, numBuf2);
  279. return 0;
  280. }
  281. cs = &js_CodeSpec[op];
  282. len = (ptrdiff_t) cs->length;
  283. fprintf(fp, "%05u:", loc);
  284. if (lines)
  285. fprintf(fp, "%4u", JS_PCToLineNumber(cx, script, pc));
  286. fprintf(fp, " %s", js_CodeName[op]);
  287. type = JOF_TYPE(cs->format);
  288. switch (type) {
  289. case JOF_BYTE:
  290. if (op == JSOP_TRAP) {
  291. op = JS_GetTrapOpcode(cx, script, pc);
  292. len = (ptrdiff_t) js_CodeSpec[op].length;
  293. }
  294. break;
  295. case JOF_JUMP:
  296. case JOF_JUMPX:
  297. off = GetJumpOffset(pc, pc);
  298. fprintf(fp, " %u (%d)", loc + (intN) off, (intN) off);
  299. break;
  300. case JOF_ATOM:
  301. case JOF_OBJECT:
  302. case JOF_REGEXP:
  303. index = js_GetIndexFromBytecode(cx, script, pc, 0);
  304. if (type == JOF_ATOM) {
  305. JS_GET_SCRIPT_ATOM(script, index, atom);
  306. v = ATOM_KEY(atom);
  307. } else {
  308. if (type == JOF_OBJECT)
  309. JS_GET_SCRIPT_OBJECT(script, index, obj);
  310. else
  311. JS_GET_SCRIPT_REGEXP(script, index, obj);
  312. v = OBJECT_TO_JSVAL(obj);
  313. }
  314. bytes = ToDisassemblySource(cx, v);
  315. if (!bytes)
  316. return 0;
  317. fprintf(fp, " %s", bytes);
  318. break;
  319. case JOF_UINT16:
  320. i = (jsint)GET_UINT16(pc);
  321. goto print_int;
  322. case JOF_TABLESWITCH:
  323. case JOF_TABLESWITCHX:
  324. {
  325. jsbytecode *pc2;
  326. jsint i, low, high;
  327. jmplen = (type == JOF_TABLESWITCH) ? JUMP_OFFSET_LEN
  328. : JUMPX_OFFSET_LEN;
  329. pc2 = pc;
  330. off = GetJumpOffset(pc, pc2);
  331. pc2 += jmplen;
  332. low = GET_JUMP_OFFSET(pc2);
  333. pc2 += JUMP_OFFSET_LEN;
  334. high = GET_JUMP_OFFSET(pc2);
  335. pc2 += JUMP_OFFSET_LEN;
  336. fprintf(fp, " defaultOffset %d low %d high %d", (intN) off, low, high);
  337. for (i = low; i <= high; i++) {
  338. off = GetJumpOffset(pc, pc2);
  339. fprintf(fp, "\n\t%d: %d", i, (intN) off);
  340. pc2 += jmplen;
  341. }
  342. len = 1 + pc2 - pc;
  343. break;
  344. }
  345. case JOF_LOOKUPSWITCH:
  346. case JOF_LOOKUPSWITCHX:
  347. {
  348. jsbytecode *pc2;
  349. jsatomid npairs;
  350. jmplen = (type == JOF_LOOKUPSWITCH) ? JUMP_OFFSET_LEN
  351. : JUMPX_OFFSET_LEN;
  352. pc2 = pc;
  353. off = GetJumpOffset(pc, pc2);
  354. pc2 += jmplen;
  355. npairs = GET_UINT16(pc2);
  356. pc2 += UINT16_LEN;
  357. fprintf(fp, " offset %d npairs %u", (intN) off, (uintN) npairs);
  358. while (npairs) {
  359. JS_GET_SCRIPT_ATOM(script, GET_INDEX(pc2), atom);
  360. pc2 += INDEX_LEN;
  361. off = GetJumpOffset(pc, pc2);
  362. pc2 += jmplen;
  363. bytes = ToDisassemblySource(cx, ATOM_KEY(atom));
  364. if (!bytes)
  365. return 0;
  366. fprintf(fp, "\n\t%s: %d", bytes, (intN) off);
  367. npairs--;
  368. }
  369. len = 1 + pc2 - pc;
  370. break;
  371. }
  372. case JOF_QARG:
  373. fprintf(fp, " %u", GET_ARGNO(pc));
  374. break;
  375. case JOF_LOCAL:
  376. fprintf(fp, " %u", GET_SLOTNO(pc));
  377. break;
  378. case JOF_SLOTATOM:
  379. case JOF_SLOTOBJECT:
  380. fprintf(fp, " %u", GET_SLOTNO(pc));
  381. index = js_GetIndexFromBytecode(cx, script, pc, SLOTNO_LEN);
  382. if (type == JOF_SLOTATOM) {
  383. JS_GET_SCRIPT_ATOM(script, index, atom);
  384. v = ATOM_KEY(atom);
  385. } else {
  386. JS_GET_SCRIPT_OBJECT(script, index, obj);
  387. v = OBJECT_TO_JSVAL(obj);
  388. }
  389. bytes = ToDisassemblySource(cx, v);
  390. if (!bytes)
  391. return 0;
  392. fprintf(fp, " %s", bytes);
  393. break;
  394. case JOF_UINT24:
  395. JS_ASSERT(op == JSOP_UINT24 || op == JSOP_NEWARRAY);
  396. i = (jsint)GET_UINT24(pc);
  397. goto print_int;
  398. case JOF_UINT8:
  399. i = pc[1];
  400. goto print_int;
  401. case JOF_INT8:
  402. i = GET_INT8(pc);
  403. goto print_int;
  404. case JOF_INT32:
  405. JS_ASSERT(op == JSOP_INT32);
  406. i = GET_INT32(pc);
  407. print_int:
  408. fprintf(fp, " %d", i);
  409. break;
  410. default: {
  411. char numBuf[12];
  412. JS_snprintf(numBuf, sizeof numBuf, "%lx", (unsigned long) cs->format);
  413. JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
  414. JSMSG_UNKNOWN_FORMAT, numBuf);
  415. return 0;
  416. }
  417. }
  418. fputs("\n", fp);
  419. return len;
  420. }
  421. #endif /* DEBUG */
  422. /************************************************************************/
  423. /*
  424. * Sprintf, but with unlimited and automatically allocated buffering.
  425. */
  426. typedef struct Sprinter {
  427. JSContext *context; /* context executing the decompiler */
  428. JSArenaPool *pool; /* string allocation pool */
  429. char *base; /* base address of buffer in pool */
  430. size_t size; /* size of buffer allocated at base */
  431. ptrdiff_t offset; /* offset of next free char in buffer */
  432. } Sprinter;
  433. #define INIT_SPRINTER(cx, sp, ap, off) \
  434. ((sp)->context = cx, (sp)->pool = ap, (sp)->base = NULL, (sp)->size = 0, \
  435. (sp)->offset = off)
  436. #define OFF2STR(sp,off) ((sp)->base + (off))
  437. #define STR2OFF(sp,str) ((str) - (sp)->base)
  438. #define RETRACT(sp,str) ((sp)->offset = STR2OFF(sp, str))
  439. static JSBool
  440. SprintEnsureBuffer(Sprinter *sp, size_t len)
  441. {
  442. ptrdiff_t nb;
  443. char *base;
  444. nb = (sp->offset + len + 1) - sp->size;
  445. if (nb < 0)
  446. return JS_TRUE;
  447. base = sp->base;
  448. if (!base) {
  449. JS_ARENA_ALLOCATE_CAST(base, char *, sp->pool, nb);
  450. } else {
  451. JS_ARENA_GROW_CAST(base, char *, sp->pool, sp->size, nb);
  452. }
  453. if (!base) {
  454. js_ReportOutOfScriptQuota(sp->context);
  455. return JS_FALSE;
  456. }
  457. sp->base = base;
  458. sp->size += nb;
  459. return JS_TRUE;
  460. }
  461. static ptrdiff_t
  462. SprintPut(Sprinter *sp, const char *s, size_t len)
  463. {
  464. ptrdiff_t offset;
  465. char *bp;
  466. /* Allocate space for s, including the '\0' at the end. */
  467. if (!SprintEnsureBuffer(sp, len))
  468. return -1;
  469. /* Advance offset and copy s into sp's buffer. */
  470. offset = sp->offset;
  471. sp->offset += len;
  472. bp = sp->base + offset;
  473. memmove(bp, s, len);
  474. bp[len] = 0;
  475. return offset;
  476. }
  477. static ptrdiff_t
  478. SprintCString(Sprinter *sp, const char *s)
  479. {
  480. return SprintPut(sp, s, strlen(s));
  481. }
  482. static ptrdiff_t
  483. SprintString(Sprinter *sp, JSString *str)
  484. {
  485. jschar *chars;
  486. size_t length, size;
  487. ptrdiff_t offset;
  488. JSSTRING_CHARS_AND_LENGTH(str, chars, length);
  489. if (length == 0)
  490. return sp->offset;
  491. size = js_GetDeflatedStringLength(sp->context, chars, length);
  492. if (size == (size_t)-1 || !SprintEnsureBuffer(sp, size))
  493. return -1;
  494. offset = sp->offset;
  495. sp->offset += size;
  496. js_DeflateStringToBuffer(sp->context, chars, length, sp->base + offset,
  497. &size);
  498. sp->base[sp->offset] = 0;
  499. return offset;
  500. }
  501. static ptrdiff_t
  502. Sprint(Sprinter *sp, const char *format, ...)
  503. {
  504. va_list ap;
  505. char *bp;
  506. ptrdiff_t offset;
  507. va_start(ap, format);
  508. bp = JS_vsmprintf(format, ap); /* XXX vsaprintf */
  509. va_end(ap);
  510. if (!bp) {
  511. JS_ReportOutOfMemory(sp->context);
  512. return -1;
  513. }
  514. offset = SprintCString(sp, bp);
  515. free(bp);
  516. return offset;
  517. }
  518. const char js_EscapeMap[] = {
  519. '\b', 'b',
  520. '\f', 'f',
  521. '\n', 'n',
  522. '\r', 'r',
  523. '\t', 't',
  524. '\v', 'v',
  525. '"', '"',
  526. '\'', '\'',
  527. '\\', '\\',
  528. '\0', '0'
  529. };
  530. #define DONT_ESCAPE 0x10000
  531. static char *
  532. QuoteString(Sprinter *sp, JSString *str, uint32 quote)
  533. {
  534. JSBool dontEscape, ok;
  535. jschar qc, c;
  536. ptrdiff_t off, len;
  537. const jschar *s, *t, *z;
  538. const char *e;
  539. char *bp;
  540. /* Sample off first for later return value pointer computation. */
  541. dontEscape = (quote & DONT_ESCAPE) != 0;
  542. qc = (jschar) quote;
  543. off = sp->offset;
  544. if (qc && Sprint(sp, "%c", (char)qc) < 0)
  545. return NULL;
  546. /* Loop control variables: z points at end of string sentinel. */
  547. JSSTRING_CHARS_AND_END(str, s, z);
  548. for (t = s; t < z; s = ++t) {
  549. /* Move t forward from s past un-quote-worthy characters. */
  550. c = *t;
  551. while (JS_ISPRINT(c) && c != qc && c != '\\' && c != '\t' &&
  552. !(c >> 8)) {
  553. c = *++t;
  554. if (t == z)
  555. break;
  556. }
  557. len = PTRDIFF(t, s, jschar);
  558. /* Allocate space for s, including the '\0' at the end. */
  559. if (!SprintEnsureBuffer(sp, len))
  560. return NULL;
  561. /* Advance sp->offset and copy s into sp's buffer. */
  562. bp = sp->base + sp->offset;
  563. sp->offset += len;
  564. while (--len >= 0)
  565. *bp++ = (char) *s++;
  566. *bp = '\0';
  567. if (t == z)
  568. break;
  569. /* Use js_EscapeMap, \u, or \x only if necessary. */
  570. if (!(c >> 8) && (e = strchr(js_EscapeMap, (int)c)) != NULL) {
  571. ok = dontEscape
  572. ? Sprint(sp, "%c", (char)c) >= 0
  573. : Sprint(sp, "\\%c", e[1]) >= 0;
  574. } else {
  575. ok = Sprint(sp, (c >> 8) ? "\\u%04X" : "\\x%02X", c) >= 0;
  576. }
  577. if (!ok)
  578. return NULL;
  579. }
  580. /* Sprint the closing quote and return the quoted string. */
  581. if (qc && Sprint(sp, "%c", (char)qc) < 0)
  582. return NULL;
  583. /*
  584. * If we haven't Sprint'd anything yet, Sprint an empty string so that
  585. * the OFF2STR below gives a valid result.
  586. */
  587. if (off == sp->offset && Sprint(sp, "") < 0)
  588. return NULL;
  589. return OFF2STR(sp, off);
  590. }
  591. JSString *
  592. js_QuoteString(JSContext *cx, JSString *str, jschar quote)
  593. {
  594. void *mark;
  595. Sprinter sprinter;
  596. char *bytes;
  597. JSString *escstr;
  598. mark = JS_ARENA_MARK(&cx->tempPool);
  599. INIT_SPRINTER(cx, &sprinter, &cx->tempPool, 0);
  600. bytes = QuoteString(&sprinter, str, quote);
  601. escstr = bytes ? JS_NewStringCopyZ(cx, bytes) : NULL;
  602. JS_ARENA_RELEASE(&cx->tempPool, mark);
  603. return escstr;
  604. }
  605. /************************************************************************/
  606. struct JSPrinter {
  607. Sprinter sprinter; /* base class state */
  608. JSArenaPool pool; /* string allocation pool */
  609. uintN indent; /* indentation in spaces */
  610. JSPackedBool pretty; /* pretty-print: indent, use newlines */
  611. JSPackedBool grouped; /* in parenthesized expression context */
  612. JSScript *script; /* script being printed */
  613. jsbytecode *dvgfence; /* DecompileExpression fencepost */
  614. jsbytecode **pcstack; /* DecompileExpression modeled stack */
  615. JSFunction *fun; /* interpreted function */
  616. jsuword *localNames; /* argument and variable names */
  617. };
  618. /*
  619. * Hack another flag, a la JS_DONT_PRETTY_PRINT, into uintN indent parameters
  620. * to functions such as js_DecompileFunction and js_NewPrinter. This time, as
  621. * opposed to JS_DONT_PRETTY_PRINT back in the dark ages, we can assume that a
  622. * uintN is at least 32 bits.
  623. */
  624. #define JS_IN_GROUP_CONTEXT 0x10000
  625. JSPrinter *
  626. JS_NEW_PRINTER(JSContext *cx, const char *name, JSFunction *fun,
  627. uintN indent, JSBool pretty)
  628. {
  629. JSPrinter *jp;
  630. jp = (JSPrinter *) JS_malloc(cx, sizeof(JSPrinter));
  631. if (!jp)
  632. return NULL;
  633. INIT_SPRINTER(cx, &jp->sprinter, &jp->pool, 0);
  634. JS_INIT_ARENA_POOL(&jp->pool, name, 256, 1, &cx->scriptStackQuota);
  635. jp->indent = indent & ~JS_IN_GROUP_CONTEXT;
  636. jp->pretty = pretty;
  637. jp->grouped = (indent & JS_IN_GROUP_CONTEXT) != 0;
  638. jp->script = NULL;
  639. jp->dvgfence = NULL;
  640. jp->pcstack = NULL;
  641. jp->fun = fun;
  642. jp->localNames = NULL;
  643. if (fun && FUN_INTERPRETED(fun) && JS_GET_LOCAL_NAME_COUNT(fun)) {
  644. jp->localNames = js_GetLocalNameArray(cx, fun, &jp->pool);
  645. if (!jp->localNames) {
  646. js_DestroyPrinter(jp);
  647. return NULL;
  648. }
  649. }
  650. return jp;
  651. }
  652. void
  653. js_DestroyPrinter(JSPrinter *jp)
  654. {
  655. JS_FinishArenaPool(&jp->pool);
  656. JS_free(jp->sprinter.context, jp);
  657. }
  658. JSString *
  659. js_GetPrinterOutput(JSPrinter *jp)
  660. {
  661. JSContext *cx;
  662. JSString *str;
  663. cx = jp->sprinter.context;
  664. if (!jp->sprinter.base)
  665. return cx->runtime->emptyString;
  666. str = JS_NewStringCopyZ(cx, jp->sprinter.base);
  667. if (!str)
  668. return NULL;
  669. JS_FreeArenaPool(&jp->pool);
  670. INIT_SPRINTER(cx, &jp->sprinter, &jp->pool, 0);
  671. return str;
  672. }
  673. /*
  674. * NB: Indexed by SRC_DECL_* defines from jsemit.h.
  675. */
  676. static const char * const var_prefix[] = {"var ", "const ", "let "};
  677. static const char *
  678. VarPrefix(jssrcnote *sn)
  679. {
  680. if (sn && (SN_TYPE(sn) == SRC_DECL || SN_TYPE(sn) == SRC_GROUPASSIGN)) {
  681. ptrdiff_t type = js_GetSrcNoteOffset(sn, 0);
  682. if ((uintN)type <= SRC_DECL_LET)
  683. return var_prefix[type];
  684. }
  685. return "";
  686. }
  687. int
  688. js_printf(JSPrinter *jp, const char *format, ...)
  689. {
  690. va_list ap;
  691. char *bp, *fp;
  692. int cc;
  693. if (*format == '\0')
  694. return 0;
  695. va_start(ap, format);
  696. /* If pretty-printing, expand magic tab into a run of jp->indent spaces. */
  697. if (*format == '\t') {
  698. format++;
  699. if (jp->pretty && Sprint(&jp->sprinter, "%*s", jp->indent, "") < 0)
  700. return -1;
  701. }
  702. /* Suppress newlines (must be once per format, at the end) if not pretty. */
  703. fp = NULL;
  704. if (!jp->pretty && format[cc = strlen(format) - 1] == '\n') {
  705. fp = JS_strdup(jp->sprinter.context, format);
  706. if (!fp)
  707. return -1;
  708. fp[cc] = '\0';
  709. format = fp;
  710. }
  711. /* Allocate temp space, convert format, and put. */
  712. bp = JS_vsmprintf(format, ap); /* XXX vsaprintf */
  713. if (fp) {
  714. JS_free(jp->sprinter.context, fp);
  715. format = NULL;
  716. }
  717. if (!bp) {
  718. JS_ReportOutOfMemory(jp->sprinter.context);
  719. return -1;
  720. }
  721. cc = strlen(bp);
  722. if (SprintPut(&jp->sprinter, bp, (size_t)cc) < 0)
  723. cc = -1;
  724. free(bp);
  725. va_end(ap);
  726. return cc;
  727. }
  728. JSBool
  729. js_puts(JSPrinter *jp, const char *s)
  730. {
  731. return SprintCString(&jp->sprinter, s) >= 0;
  732. }
  733. /************************************************************************/
  734. typedef struct SprintStack {
  735. Sprinter sprinter; /* sprinter for postfix to infix buffering */
  736. ptrdiff_t *offsets; /* stack of postfix string offsets */
  737. jsbytecode *opcodes; /* parallel stack of JS opcodes */
  738. uintN top; /* top of stack index */
  739. uintN inArrayInit; /* array initialiser/comprehension level */
  740. JSBool inGenExp; /* in generator expression */
  741. JSPrinter *printer; /* permanent output goes here */
  742. } SprintStack;
  743. /*
  744. * Find the depth of the operand stack when the interpreter reaches the given
  745. * pc in script. pcstack must have space for least script->depth elements. On
  746. * return it will contain pointers to opcodes that populated the interpreter's
  747. * current operand stack.
  748. *
  749. * This function cannot raise an exception or error. However, due to a risk of
  750. * potential bugs when modeling the stack, the function returns -1 if it
  751. * detects an inconsistency in the model. Such an inconsistency triggers an
  752. * assert in a debug build.
  753. */
  754. static intN
  755. ReconstructPCStack(JSContext *cx, JSScript *script, jsbytecode *pc,
  756. jsbytecode **pcstack);
  757. #define FAILED_EXPRESSION_DECOMPILER ((char *) 1)
  758. /*
  759. * Decompile a part of expression up to the given pc. The function returns
  760. * NULL on out-of-memory, or the FAILED_EXPRESSION_DECOMPILER sentinel when
  761. * the decompiler fails due to a bug and/or unimplemented feature, or the
  762. * decompiled string on success.
  763. */
  764. static char *
  765. DecompileExpression(JSContext *cx, JSScript *script, JSFunction *fun,
  766. jsbytecode *pc);
  767. /*
  768. * Get a stacked offset from ss->sprinter.base, or if the stacked value |off|
  769. * is negative, fetch the generating pc from printer->pcstack[-2 - off] and
  770. * decompile the code that generated the missing value. This is used when
  771. * reporting errors, where the model stack will lack |pcdepth| non-negative
  772. * offsets (see DecompileExpression and DecompileCode).
  773. *
  774. * If the stacked offset is -1, return 0 to index the NUL padding at the start
  775. * of ss->sprinter.base. If this happens, it means there is a decompiler bug
  776. * to fix, but it won't violate memory safety.
  777. */
  778. static ptrdiff_t
  779. GetOff(SprintStack *ss, uintN i)
  780. {
  781. ptrdiff_t off;
  782. jsbytecode *pc;
  783. char *bytes;
  784. off = ss->offsets[i];
  785. if (off >= 0)
  786. return off;
  787. JS_ASSERT(off <= -2);
  788. JS_ASSERT(ss->printer->pcstack);
  789. if (off < -2 && ss->printer->pcstack) {
  790. pc = ss->printer->pcstack[-2 - off];
  791. bytes = DecompileExpression(ss->sprinter.context, ss->printer->script,
  792. ss->printer->fun, pc);
  793. if (!bytes)
  794. return 0;
  795. if (bytes != FAILED_EXPRESSION_DECOMPILER) {
  796. off = SprintCString(&ss->sprinter, bytes);
  797. if (off < 0)
  798. off = 0;
  799. ss->offsets[i] = off;
  800. JS_free(ss->sprinter.context, bytes);
  801. return off;
  802. }
  803. if (!ss->sprinter.base && SprintPut(&ss->sprinter, "", 0) >= 0) {
  804. memset(ss->sprinter.base, 0, ss->sprinter.offset);
  805. ss->offsets[i] = -1;
  806. }
  807. }
  808. return 0;
  809. }
  810. static const char *
  811. GetStr(SprintStack *ss, uintN i)
  812. {
  813. ptrdiff_t off;
  814. /*
  815. * Must call GetOff before using ss->sprinter.base, since it may be null
  816. * until bootstrapped by GetOff.
  817. */
  818. off = GetOff(ss, i);
  819. return OFF2STR(&ss->sprinter, off);
  820. }
  821. /*
  822. * Gap between stacked strings to allow for insertion of parens and commas
  823. * when auto-parenthesizing expressions and decompiling array initialisers
  824. * (see the JSOP_NEWARRAY case in Decompile).
  825. */
  826. #define PAREN_SLOP (2 + 1)
  827. /*
  828. * These pseudo-ops help js_DecompileValueGenerator decompile JSOP_SETNAME,
  829. * JSOP_SETPROP, and JSOP_SETELEM, respectively. They are never stored in
  830. * bytecode, so they don't preempt valid opcodes.
  831. */
  832. #define JSOP_GETPROP2 256
  833. #define JSOP_GETELEM2 257
  834. static void
  835. AddParenSlop(SprintStack *ss)
  836. {
  837. memset(OFF2STR(&ss->sprinter, ss->sprinter.offset), 0, PAREN_SLOP);
  838. ss->sprinter.offset += PAREN_SLOP;
  839. }
  840. static JSBool
  841. PushOff(SprintStack *ss, ptrdiff_t off, JSOp op)
  842. {
  843. uintN top;
  844. if (!SprintEnsureBuffer(&ss->sprinter, PAREN_SLOP))
  845. return JS_FALSE;
  846. /* ss->top points to the next free slot; be paranoid about overflow. */
  847. top = ss->top;
  848. JS_ASSERT(top < StackDepth(ss->printer->script));
  849. if (top >= StackDepth(ss->printer->script)) {
  850. JS_ReportOutOfMemory(ss->sprinter.context);
  851. return JS_FALSE;
  852. }
  853. /* The opcodes stack must contain real bytecodes that index js_CodeSpec. */
  854. ss->offsets[top] = off;
  855. ss->opcodes[top] = (op == JSOP_GETPROP2) ? JSOP_GETPROP
  856. : (op == JSOP_GETELEM2) ? JSOP_GETELEM
  857. : (jsbytecode) op;
  858. ss->top = ++top;
  859. AddParenSlop(ss);
  860. return JS_TRUE;
  861. }
  862. static ptrdiff_t
  863. PopOffPrec(SprintStack *ss, uint8 prec)
  864. {
  865. uintN top;
  866. const JSCodeSpec *topcs;
  867. ptrdiff_t off;
  868. /* ss->top points to the next free slot; be paranoid about underflow. */
  869. top = ss->top;
  870. JS_ASSERT(top != 0);
  871. if (top == 0)
  872. return 0;
  873. ss->top = --top;
  874. off = GetOff(ss, top);
  875. topcs = &js_CodeSpec[ss->opcodes[top]];
  876. if (topcs->prec != 0 && topcs->prec < prec) {
  877. ss->sprinter.offset = ss->offsets[top] = off - 2;
  878. off = Sprint(&ss->sprinter, "(%s)", OFF2STR(&ss->sprinter, off));
  879. } else {
  880. ss->sprinter.offset = off;
  881. }
  882. return off;
  883. }
  884. static const char *
  885. PopStrPrec(SprintStack *ss, uint8 prec)
  886. {
  887. ptrdiff_t off;
  888. off = PopOffPrec(ss, prec);
  889. return OFF2STR(&ss->sprinter, off);
  890. }
  891. static ptrdiff_t
  892. PopOff(SprintStack *ss, JSOp op)
  893. {
  894. return PopOffPrec(ss, js_CodeSpec[op].prec);
  895. }
  896. static const char *
  897. PopStr(SprintStack *ss, JSOp op)
  898. {
  899. return PopStrPrec(ss, js_CodeSpec[op].prec);
  900. }
  901. typedef struct TableEntry {
  902. jsval key;
  903. ptrdiff_t offset;
  904. JSAtom *label;
  905. jsint order; /* source order for stable tableswitch sort */
  906. } TableEntry;
  907. static JSBool
  908. CompareOffsets(void *arg, const void *v1, const void *v2, int *result)
  909. {
  910. ptrdiff_t offset_diff;
  911. const TableEntry *te1 = (const TableEntry *) v1,
  912. *te2 = (const TableEntry *) v2;
  913. offset_diff = te1->offset - te2->offset;
  914. *result = (offset_diff == 0 ? te1->order - te2->order
  915. : offset_diff < 0 ? -1
  916. : 1);
  917. return JS_TRUE;
  918. }
  919. static ptrdiff_t
  920. SprintDoubleValue(Sprinter *sp, jsval v, JSOp *opp)
  921. {
  922. jsdouble d;
  923. ptrdiff_t todo;
  924. char *s, buf[DTOSTR_STANDARD_BUFFER_SIZE];
  925. JS_ASSERT(JSVAL_IS_DOUBLE(v));
  926. d = *JSVAL_TO_DOUBLE(v);
  927. if (JSDOUBLE_IS_NEGZERO(d)) {
  928. todo = SprintCString(sp, "-0");
  929. *opp = JSOP_NEG;
  930. } else if (!JSDOUBLE_IS_FINITE(d)) {
  931. /* Don't use Infinity and NaN, they're mutable. */
  932. todo = SprintCString(sp,
  933. JSDOUBLE_IS_NaN(d)
  934. ? "0 / 0"
  935. : (d < 0)
  936. ? "1 / -0"
  937. : "1 / 0");
  938. *opp = JSOP_DIV;
  939. } else {
  940. s = JS_dtostr(buf, sizeof buf, DTOSTR_STANDARD, 0, d);
  941. if (!s) {
  942. JS_ReportOutOfMemory(sp->context);
  943. return -1;
  944. }
  945. JS_ASSERT(strcmp(s, js_Infinity_str) &&
  946. (*s != '-' ||
  947. strcmp(s + 1, js_Infinity_str)) &&
  948. strcmp(s, js_NaN_str));
  949. todo = Sprint(sp, s);
  950. }
  951. return todo;
  952. }
  953. static jsbytecode *
  954. Decompile(SprintStack *ss, jsbytecode *pc, intN nb, JSOp nextop);
  955. static JSBool
  956. DecompileSwitch(SprintStack *ss, TableEntry *table, uintN tableLength,
  957. jsbytecode *pc, ptrdiff_t switchLength,
  958. ptrdiff_t defaultOffset, JSBool isCondSwitch)
  959. {
  960. JSContext *cx;
  961. JSPrinter *jp;
  962. ptrdiff_t off, off2, diff, caseExprOff, todo;
  963. char *lval, *rval;
  964. uintN i;
  965. jsval key;
  966. JSString *str;
  967. cx = ss->sprinter.context;
  968. jp = ss->printer;
  969. /* JSOP_CONDSWITCH doesn't pop, unlike JSOP_{LOOKUP,TABLE}SWITCH. */
  970. off = isCondSwitch ? GetOff(ss, ss->top-1) : PopOff(ss, JSOP_NOP);
  971. lval = OFF2STR(&ss->sprinter, off);
  972. js_printf(jp, "\tswitch (%s) {\n", lval);
  973. if (tableLength) {
  974. diff = table[0].offset - defaultOffset;
  975. if (diff > 0) {
  976. jp->indent += 2;
  977. js_printf(jp, "\t%s:\n", js_default_str);
  978. jp->indent += 2;
  979. if (!Decompile(ss, pc + defaultOffset, diff, JSOP_NOP))
  980. return JS_FALSE;
  981. jp->indent -= 4;
  982. }
  983. caseExprOff = isCondSwitch ? JSOP_CONDSWITCH_LENGTH : 0;
  984. for (i = 0; i < tableLength; i++) {
  985. off = table[i].offset;
  986. off2 = (i + 1 < tableLength) ? table[i + 1].offset : switchLength;
  987. key = table[i].key;
  988. if (isCondSwitch) {
  989. ptrdiff_t nextCaseExprOff;
  990. /*
  991. * key encodes the JSOP_CASE bytecode's offset from switchtop.
  992. * The next case expression follows immediately, unless we are
  993. * at the last case.
  994. */
  995. nextCaseExprOff = (ptrdiff_t)JSVAL_TO_INT(key);
  996. nextCaseExprOff += js_CodeSpec[pc[nextCaseExprOff]].length;
  997. jp->indent += 2;
  998. if (!Decompile(ss, pc + caseExprOff,
  999. nextCaseExprOff - caseExprOff, JSOP_NOP)) {
  1000. return JS_FALSE;
  1001. }
  1002. caseExprOff = nextCaseExprOff;
  1003. /* Balance the stack as if this JSOP_CASE matched. */
  1004. --ss->top;
  1005. } else {
  1006. /*
  1007. * key comes from an atom, not the decompiler, so we need to
  1008. * quote it if it's a string literal. But if table[i].label
  1009. * is non-null, key was constant-propagated and label is the
  1010. * name of the const we should show as the case label. We set
  1011. * key to undefined so this identifier is escaped, if required
  1012. * by non-ASCII characters, but not quoted, by QuoteString.
  1013. */
  1014. todo = -1;
  1015. if (table[i].label) {
  1016. str = ATOM_TO_STRING(table[i].label);
  1017. key = JSVAL_VOID;
  1018. } else if (JSVAL_IS_DOUBLE(key)) {
  1019. JSOp junk;
  1020. todo = SprintDoubleValue(&ss->sprinter, key, &junk);
  1021. str = NULL;
  1022. } else {
  1023. str = js_ValueToString(cx, key);
  1024. if (!str)
  1025. return JS_FALSE;
  1026. }
  1027. if (todo >= 0) {
  1028. rval = OFF2STR(&ss->sprinter, todo);
  1029. } else {
  1030. rval = QuoteString(&ss->sprinter, str, (jschar)
  1031. (JSVAL_IS_STRING(key) ? '"' : 0));
  1032. if (!rval)
  1033. return JS_FALSE;
  1034. }
  1035. RETRACT(&ss->sprinter, rval);
  1036. jp->indent += 2;
  1037. js_printf(jp, "\tcase %s:\n", rval);
  1038. }
  1039. jp->indent += 2;
  1040. if (off <= defaultOffset && defaultOffset < off2) {
  1041. diff = defaultOffset - off;
  1042. if (diff != 0) {
  1043. if (!Decompile(ss, pc + off, diff, JSOP_NOP))
  1044. return JS_FALSE;
  1045. off = defaultOffset;
  1046. }
  1047. jp->indent -= 2;
  1048. js_printf(jp, "\t%s:\n", js_default_str);
  1049. jp->indent += 2;
  1050. }
  1051. if (!Decompile(ss, pc + off, off2 - off, JSOP_NOP))
  1052. return JS_FALSE;
  1053. jp->indent -= 4;
  1054. /* Re-balance as if last JSOP_CASE or JSOP_DEFAULT mismatched. */
  1055. if (isCondSwitch)
  1056. ++ss->top;
  1057. }
  1058. }
  1059. if (defaultOffset == switchLength) {
  1060. jp->indent += 2;
  1061. js_printf(jp, "\t%s:;\n", js_default_str);
  1062. jp->indent -= 2;
  1063. }
  1064. js_printf(jp, "\t}\n");
  1065. /* By the end of a JSOP_CONDSWITCH, the discriminant has been popped. */
  1066. if (isCondSwitch)
  1067. --ss->top;
  1068. return JS_TRUE;
  1069. }
  1070. #define LOCAL_ASSERT_CUSTOM(expr, BAD_EXIT) \
  1071. JS_BEGIN_MACRO \
  1072. JS_ASSERT(expr); \
  1073. if (!(expr)) { BAD_EXIT; } \
  1074. JS_END_MACRO
  1075. #define LOCAL_ASSERT_RV(expr, rv) \
  1076. LOCAL_ASSERT_CUSTOM(expr, return (rv))
  1077. static JSAtom *
  1078. GetArgOrVarAtom(JSPrinter *jp, uintN slot)
  1079. {
  1080. JSAtom *name;
  1081. LOCAL_ASSERT_RV(jp->fun, NULL);
  1082. LOCAL_ASSERT_RV(slot < (uintN) JS_GET_LOCAL_NAME_COUNT(jp->fun), NULL);
  1083. name = JS_LOCAL_NAME_TO_ATOM(jp->localNames[slot]);
  1084. #if !JS_HAS_DESTRUCTURING
  1085. LOCAL_ASSERT_RV(name, NULL);
  1086. #endif
  1087. return name;
  1088. }
  1089. const char *
  1090. GetLocal(SprintStack *ss, jsint i)
  1091. {
  1092. ptrdiff_t off;
  1093. JSContext *cx;
  1094. JSScript *script;
  1095. jsatomid j, n;
  1096. JSAtom *atom;
  1097. JSObject *obj;
  1098. jsint depth, count;
  1099. JSScopeProperty *sprop;
  1100. const char *rval;
  1101. #define LOCAL_ASSERT(expr) LOCAL_ASSERT_RV(expr, "")
  1102. off = ss->offsets[i];
  1103. if (off >= 0)
  1104. return OFF2STR(&ss->sprinter, off);
  1105. /*
  1106. * We must be called from js_DecompileValueGenerator (via Decompile) when
  1107. * dereferencing a local that's undefined or null. Search script->objects
  1108. * for the block containing this local by its stack index, i.
  1109. */
  1110. cx = ss->sprinter.context;
  1111. script = ss->printer->script;
  1112. LOCAL_ASSERT(script->objectsOffset != 0);
  1113. for (j = 0, n = JS_SCRIPT_OBJECTS(script)->length; ; j++) {
  1114. LOCAL_ASSERT(j < n);
  1115. JS_GET_SCRIPT_OBJECT(script, j, obj);
  1116. if (OBJ_GET_CLASS(cx, obj) == &js_BlockClass) {
  1117. depth = OBJ_BLOCK_DEPTH(cx, obj);
  1118. count = OBJ_BLOCK_COUNT(cx, obj);
  1119. if ((jsuint)(i - depth) < (jsuint)count)
  1120. break;
  1121. }
  1122. }
  1123. i -= depth;
  1124. for (sprop = OBJ_SCOPE(obj)->lastProp; sprop; sprop = sprop->parent) {
  1125. if (sprop->shortid == i)
  1126. break;
  1127. }
  1128. LOCAL_ASSERT(sprop && JSID_IS_ATOM(sprop->id));
  1129. atom = JSID_TO_ATOM(sprop->id);
  1130. rval = QuoteString(&ss->sprinter, ATOM_TO_STRING(atom), 0);
  1131. if (!rval)
  1132. return NULL;
  1133. RETRACT(&ss->sprinter, rval);
  1134. return rval;
  1135. #undef LOCAL_ASSERT
  1136. }
  1137. static JSBool
  1138. IsVarSlot(JSPrinter *jp, jsbytecode *pc, jsint *indexp)
  1139. {
  1140. uintN slot;
  1141. slot = GET_SLOTNO(pc);
  1142. if (slot < jp->script->nfixed) {
  1143. /* The slot refers to a variable with name stored in jp->localNames. */
  1144. *indexp = jp->fun->nargs + slot;
  1145. return JS_TRUE;
  1146. }
  1147. /* We have a local which index is relative to the stack base. */
  1148. slot -= jp->script->nfixed;
  1149. JS_ASSERT(slot < StackDepth(jp->script));
  1150. *indexp = slot;
  1151. return JS_FALSE;
  1152. }
  1153. #if JS_HAS_DESTRUCTURING
  1154. #define LOCAL_ASSERT(expr) LOCAL_ASSERT_RV(expr, NULL)
  1155. #define LOAD_OP_DATA(pc) (oplen = (cs = &js_CodeSpec[op=(JSOp)*pc])->length)
  1156. static jsbytecode *
  1157. DecompileDestructuring(SprintStack *ss, jsbytecode *pc, jsbytecode *endpc);
  1158. static jsbytecode *
  1159. DecompileDestructuringLHS(SprintStack *ss, jsbytecode *pc, jsbytecode *endpc,
  1160. JSBool *hole)
  1161. {
  1162. JSContext *cx;
  1163. JSPrinter *jp;
  1164. JSOp op;
  1165. const JSCodeSpec *cs;
  1166. uintN oplen;
  1167. jsint i;
  1168. const char *lval, *xval;
  1169. ptrdiff_t todo;
  1170. JSAtom *atom;
  1171. *hole = JS_FALSE;
  1172. cx = ss->sprinter.context;
  1173. jp = ss->printer;
  1174. LOAD_OP_DATA(pc);
  1175. switch (op) {
  1176. case JSOP_POP:
  1177. *hole = JS_TRUE;
  1178. todo = SprintPut(&ss->sprinter, ", ", 2);
  1179. break;
  1180. case JSOP_DUP:
  1181. pc = DecompileDestructuring(ss, pc, endpc);
  1182. if (!pc)
  1183. return NULL;
  1184. if (pc == endpc)
  1185. return pc;
  1186. LOAD_OP_DATA(pc);
  1187. lval = PopStr(ss, JSOP_NOP);
  1188. todo = SprintCString(&ss->sprinter, lval);
  1189. if (op == JSOP_POPN)
  1190. return pc;
  1191. LOCAL_ASSERT(*pc == JSOP_POP);
  1192. break;
  1193. case JSOP_SETARG:
  1194. case JSOP_SETGVAR:
  1195. case JSOP_SETLOCAL:
  1196. LOCAL_ASSERT(pc[oplen] == JSOP_POP || pc[oplen] == JSOP_POPN);
  1197. /* FALL THROUGH */
  1198. case JSOP_SETLOCALPOP:
  1199. atom = NULL;
  1200. lval = NULL;
  1201. if (op == JSOP_SETARG) {
  1202. atom = GetArgOrVarAtom(jp, GET_SLOTNO(pc));
  1203. LOCAL_ASSERT(atom);
  1204. } else if (op == JSOP_SETGVAR) {
  1205. GET_ATOM_FROM_BYTECODE(jp->script, pc, 0, atom);
  1206. } else if (IsVarSlot(jp, pc, &i)) {
  1207. atom = GetArgOrVarAtom(jp, i);
  1208. LOCAL_ASSERT(atom);
  1209. } else {
  1210. lval = GetLocal(ss, i);
  1211. }
  1212. if (atom)
  1213. lval = js_AtomToPrintableString(cx, atom);
  1214. LOCAL_ASSERT(lval);
  1215. todo = SprintCString(&ss->sprinter, lval);
  1216. if (op != JSOP_SETLOCALPOP) {
  1217. pc += oplen;
  1218. if (pc == endpc)
  1219. return pc;
  1220. LOAD_OP_DATA(pc);
  1221. if (op == JSOP_POPN)
  1222. return pc;
  1223. LOCAL_ASSERT(op == JSOP_POP);
  1224. }
  1225. break;
  1226. default:
  1227. /*
  1228. * We may need to auto-parenthesize the left-most value decompiled
  1229. * here, so add back PAREN_SLOP temporarily. Then decompile until the
  1230. * opcode that would reduce the stack depth to (ss->top-1), which we
  1231. * pass to Decompile encoded as -(ss->top-1) - 1 or just -ss->top for
  1232. * the nb parameter.
  1233. */
  1234. todo = ss->sprinter.offset;
  1235. ss->sprinter.offset = todo + PAREN_SLOP;
  1236. pc = Decompile(ss, pc, -((intN)ss->top), JSOP_NOP);
  1237. if (!pc)
  1238. return NULL;
  1239. if (pc == endpc)
  1240. return pc;
  1241. LOAD_OP_DATA(pc);
  1242. LOCAL_ASSERT(op == JSOP_ENUMELEM || op == JSOP_ENUMCONSTELEM);
  1243. xval = PopStr(ss, JSOP_NOP);
  1244. lval = PopStr(ss, JSOP_GETPROP);
  1245. ss->sprinter.offset = todo;
  1246. if (*lval == '\0') {
  1247. /* lval is from JSOP_BINDNAME, so just print xval. */
  1248. todo = SprintCString(&ss->sprinter, xval);
  1249. } else if (*xval == '\0') {
  1250. /* xval is from JSOP_SETCALL or JSOP_BINDXMLNAME, print lval. */
  1251. todo = SprintCString(&ss->sprinter, lval);
  1252. } else {
  1253. todo = Sprint(&ss->sprinter,
  1254. (JOF_OPMODE(ss->opcodes[ss->top+1]) == JOF_XMLNAME)
  1255. ? "%s.%s"
  1256. : "%s[%s]",
  1257. lval, xval);
  1258. }
  1259. break;
  1260. }
  1261. if (todo < 0)
  1262. return NULL;
  1263. LOCAL_ASSERT(pc < endpc);
  1264. pc += oplen;
  1265. return pc;
  1266. }
  1267. /*
  1268. * Starting with a SRC_DESTRUCT-annotated JSOP_DUP, decompile a destructuring
  1269. * left-hand side object or array initialiser, including nested destructuring
  1270. * initialisers. On successful return, the decompilation will be pushed on ss
  1271. * and the return value will point to the POP or GROUP bytecode following the
  1272. * destructuring expression.
  1273. *
  1274. * At any point, if pc is equal to endpc and would otherwise advance, we stop
  1275. * immediately and return endpc.
  1276. */
  1277. static jsbytecode *
  1278. DecompileDestructuring(SprintStack *ss, jsbytecode *pc, jsbytecode *endpc)
  1279. {
  1280. ptrdiff_t head;
  1281. JSContext *cx;
  1282. JSPrinter *jp;
  1283. JSOp op, saveop;
  1284. const JSCodeSpec *cs;
  1285. uintN oplen;
  1286. jsint i, lasti;
  1287. jsdouble d;
  1288. const char *lval;
  1289. JSAtom *atom;
  1290. jssrcnote *sn;
  1291. JSString *str;
  1292. JSBool hole;
  1293. LOCAL_ASSERT(*pc == JSOP_DUP);
  1294. pc += JSOP_DUP_LENGTH;
  1295. /*
  1296. * Set head so we can rewrite '[' to '{' as needed. Back up PAREN_SLOP
  1297. * chars so the destructuring decompilation accumulates contiguously in
  1298. * ss->sprinter starting with "[".
  1299. */
  1300. head = SprintPut(&ss->sprinter, "[", 1);
  1301. if (head < 0 || !PushOff(ss, head, JSOP_NOP))
  1302. return NULL;
  1303. ss->sprinter.offset -= PAREN_SLOP;
  1304. LOCAL_ASSERT(head == ss->sprinter.offset - 1);
  1305. LOCAL_ASSERT(*OFF2STR(&ss->sprinter, head) == '[');
  1306. cx = ss->sprinter.context;
  1307. jp = ss->printer;
  1308. lasti = -1;
  1309. while (pc < endpc) {
  1310. #if JS_HAS_DESTRUCTURING_SHORTHAND
  1311. ptrdiff_t nameoff = -1;
  1312. #endif
  1313. LOAD_OP_DATA(pc);
  1314. saveop = op;
  1315. switch (op) {
  1316. case JSOP_POP:
  1317. pc += oplen;
  1318. goto out;
  1319. /* Handle the optimized number-pushing opcodes. */
  1320. case JSOP_ZERO: d = i = 0; goto do_getelem;
  1321. case JSOP_ONE: d = i = 1; goto do_getelem;
  1322. case JSOP_UINT16: d = i = GET_UINT16(pc); goto do_getelem;
  1323. case JSOP_UINT24: d = i = GET_UINT24(pc); goto do_getelem;
  1324. case JSOP_INT8: d = i = GET_INT8(pc); goto do_getelem;
  1325. case JSOP_INT32: d = i = GET_INT32(pc); goto do_getelem;
  1326. case JSOP_DOUBLE:
  1327. GET_ATOM_FROM_BYTECODE(jp->script, pc, 0, atom);
  1328. d = *ATOM_TO_DOUBLE(atom);
  1329. LOCAL_ASSERT(JSDOUBLE_IS_FINITE(d) && !JSDOUBLE_IS_NEGZERO(d));
  1330. i = (jsint)d;
  1331. do_getelem:
  1332. sn = js_GetSrcNote(jp->script, pc);
  1333. pc += oplen;
  1334. if (pc == endpc)
  1335. return pc;
  1336. LOAD_OP_DATA(pc);
  1337. LOCAL_ASSERT(op == JSOP_GETELEM);
  1338. /* Distinguish object from array by opcode or source note. */
  1339. if (sn && SN_TYPE(sn) == SRC_INITPROP) {
  1340. *OFF2STR(&ss->sprinter, head) = '{';
  1341. if (Sprint(&ss->sprinter, "%g: ", d) < 0)
  1342. return NULL;
  1343. } else {
  1344. /* Sanity check for the gnarly control flow above. */
  1345. LOCAL_ASSERT(i == d);
  1346. /* Fill in any holes (holes at the end don't matter). */
  1347. while (++lasti < i) {
  1348. if (SprintPut(&ss->sprinter, ", ", 2) < 0)
  1349. return NULL;
  1350. }
  1351. }
  1352. break;
  1353. case JSOP_LENGTH:
  1354. atom = cx->runtime->atomState.lengthAtom;
  1355. goto do_destructure_atom;
  1356. case JSOP_CALLPROP:
  1357. case JSOP_GETPROP:
  1358. GET_ATOM_FROM_BYTECODE(jp->script, pc, 0, atom);
  1359. do_destructure_atom:
  1360. *OFF2STR(&ss->sprinter, head) = '{';
  1361. str = ATOM_TO_STRING(atom);
  1362. #if JS_HAS_DESTRUCTURING_SHORTHAND
  1363. nameoff = ss->sprinter.offset;
  1364. #endif
  1365. if (!QuoteString(&ss->sprinter, str,
  1366. js_IsIdentifier(str) ? 0 : (jschar)'\'')) {
  1367. return NULL;
  1368. }
  1369. if (SprintPut(&ss->sprinter, ": ", 2) < 0)
  1370. return NULL;
  1371. break;
  1372. default:
  1373. LOCAL_ASSERT(0);
  1374. }
  1375. pc += oplen;
  1376. if (pc == endpc)
  1377. return pc;
  1378. /*
  1379. * Decompile the left-hand side expression whose bytecode starts at pc
  1380. * and continues for a bounded number of bytecodes or stack operations
  1381. * (and which in any event stops before endpc).
  1382. */
  1383. pc = DecompileDestructuringLHS(ss, pc, endpc, &hole);
  1384. if (!pc)
  1385. return NULL;
  1386. #if JS_HAS_DESTRUCTURING_SHORTHAND
  1387. if (nameoff >= 0) {
  1388. ptrdiff_t offset, initlen;
  1389. offset = ss->sprinter.offset;
  1390. LOCAL_ASSERT(*OFF2STR(&ss->sprinter, offset) == '\0');
  1391. initlen = offset - nameoff;
  1392. LOCAL_ASSERT(initlen >= 4);
  1393. /* Early check to rule out odd "name: lval" length. */
  1394. if (((size_t)initlen & 1) == 0) {
  1395. size_t namelen;
  1396. const char *name;
  1397. /*
  1398. * Even "name: lval" string length: check for "x: x" and the
  1399. * like, and apply the shorthand if we can.
  1400. */
  1401. namelen = (size_t)(initlen - 2) >> 1;
  1402. name = OFF2STR(&ss->sprinter, nameoff);
  1403. if (!strncmp(name + namelen, ": ", 2) &&
  1404. !strncmp(name, name + namelen + 2, namelen)) {
  1405. offset -= namelen + 2;
  1406. *OFF2STR(&ss->sprinter, offset) = '\0';
  1407. ss->sprinter.offset = offset;
  1408. }
  1409. }
  1410. }
  1411. #endif
  1412. if (pc == endpc || *pc != JSOP_DUP)
  1413. break;
  1414. /*
  1415. * Check for SRC_DESTRUCT on this JSOP_DUP, which would mean another
  1416. * destructuring initialiser abuts this one, and we should stop. This
  1417. * happens with source of the form '[a] = [b] = c'.
  1418. */
  1419. sn = js_GetSrcNote(jp->script, pc);
  1420. if (sn && SN_TYPE(sn) == SRC_DESTRUCT)
  1421. break;
  1422. if (!hole && SprintPut(&ss->sprinter, ", ", 2) < 0)
  1423. return NULL;
  1424. pc += JSOP_DUP_LENGTH;
  1425. }
  1426. out:
  1427. lval = OFF2STR(&ss->sprinter, head);
  1428. if (SprintPut(&ss->sprinter, (*lval == '[') ? "]" : "}", 1) < 0)
  1429. return NULL;
  1430. return pc;
  1431. }
  1432. static jsbytecode *
  1433. DecompileGroupAssignment(SprintStack *ss, jsbytecode *pc, jsbytecode *endpc,
  1434. jssrcnote *sn, ptrdiff_t *todop)
  1435. {
  1436. JSOp op;
  1437. const JSCodeSpec *cs;
  1438. uintN oplen, start, end, i;
  1439. ptrdiff_t todo;
  1440. JSBool hole;
  1441. const char *rval;
  1442. LOAD_OP_DATA(pc);
  1443. LOCAL_ASSERT(op == JSOP_PUSH || op == JSOP_GETLOCAL);
  1444. todo = Sprint(&ss->sprinter, "%s[", VarPrefix(sn));
  1445. if (todo < 0 || !PushOff(ss, todo, JSOP_NOP))
  1446. return NULL;
  1447. ss->sprinter.offset -= PAREN_SLOP;
  1448. for (;;) {
  1449. pc += oplen;
  1450. if (pc == endpc)
  1451. return pc;
  1452. pc = DecompileDestructuringLHS(ss, pc, endpc, &hole);
  1453. if (!pc)
  1454. return NULL;
  1455. if (pc == endpc)
  1456. return pc;
  1457. LOAD_OP_DATA(pc);
  1458. if (op != JSOP_PUSH && op != JSOP_GETLOCAL)
  1459. break;
  1460. if (!hole && SprintPut(&ss->sprinter, ", ", 2) < 0)
  1461. return NULL;
  1462. }
  1463. LOCAL_ASSERT(op == JSOP_POPN);
  1464. if (SprintPut(&ss->sprinter, "] = [", 5) < 0)
  1465. return NULL;
  1466. end = ss->top - 1;
  1467. start = end - GET_UINT16(pc);
  1468. for (i = start; i < end; i++) {
  1469. rval = GetStr(ss, i);
  1470. if (Sprint(&ss->sprinter,
  1471. (i == start) ? "%s" : ", %s",
  1472. (i == end - 1 && *rval == '\0') ? ", " : rval) < 0) {
  1473. return NULL;
  1474. }
  1475. }
  1476. if (SprintPut(&ss->sprinter, "]", 1) < 0)
  1477. return NULL;
  1478. ss->sprinter.offset = ss->offsets[i];
  1479. ss->top = start;
  1480. *todop = todo;
  1481. return pc;
  1482. }
  1483. #undef LOCAL_ASSERT
  1484. #undef LOAD_OP_DATA
  1485. #endif /* JS_HAS_DESTRUCTURING */
  1486. static JSBool
  1487. InitSprintStack(JSContext *cx, SprintStack *ss, JSPrinter *jp, uintN depth)
  1488. {
  1489. size_t offsetsz, opcodesz;
  1490. void *space;
  1491. INIT_SPRINTER(cx, &ss->sprinter, &cx->tempPool, PAREN_SLOP);
  1492. /* Allocate the parallel (to avoid padding) offset and opcode stacks. */
  1493. offsetsz = depth * sizeof(ptrdiff_t);
  1494. opcodesz = depth * sizeof(jsbytecode);
  1495. JS_ARENA_ALLOCATE(space, &cx->tempPool, offsetsz + opcodesz);
  1496. if (!space) {
  1497. js_ReportOutOfScriptQuota(cx);
  1498. return JS_FALSE;
  1499. }
  1500. ss->offsets = (ptrdiff_t *) space;
  1501. ss->opcodes = (jsbytecode *) ((char *)space + offsetsz);
  1502. ss->top = ss->inArrayInit = 0;
  1503. ss->inGenExp = JS_FALSE;
  1504. ss->printer = jp;
  1505. return JS_TRUE;
  1506. }
  1507. /*
  1508. * If nb is non-negative, decompile nb bytecodes starting at pc. Otherwise
  1509. * the decompiler starts at pc and continues until it reaches an opcode for
  1510. * which decompiling would result in the stack depth equaling -(nb + 1).
  1511. *
  1512. * The nextop parameter is either JSOP_NOP or the "next" opcode in order of
  1513. * abstract interpretation (not necessarily physically next in a bytecode
  1514. * vector). So nextop is JSOP_POP for the last operand in a comma expression,
  1515. * or JSOP_AND for the right operand of &&.
  1516. */
  1517. static jsbytecode *
  1518. Decompile(SprintStack *ss, jsbytecode *pc, intN nb, JSOp nextop)
  1519. {
  1520. JSContext *cx;
  1521. JSPrinter *jp, *jp2;
  1522. jsbytecode *startpc, *endpc, *pc2, *done;
  1523. ptrdiff_t tail, todo, len, oplen, cond, next;
  1524. JSOp op, lastop, saveop;
  1525. const JSCodeSpec *cs;
  1526. jssrcnote *sn, *sn2;
  1527. const char *lval, *rval, *xval, *fmt, *token;
  1528. jsint i, argc;
  1529. char **argv;
  1530. JSAtom *atom;
  1531. JSObject *obj;
  1532. JSFunction *fun;
  1533. JSString *str;
  1534. JSBool ok;
  1535. #if JS_HAS_XML_SUPPORT
  1536. JSBool foreach, inXML, quoteAttr;
  1537. #else
  1538. #define inXML JS_FALSE
  1539. #endif
  1540. jsval val;
  1541. static const char exception_cookie[] = "/*EXCEPTION*/";
  1542. static const char retsub_pc_cookie[] = "/*RETSUB_PC*/";
  1543. static const char iter_cookie[] = "/*ITER*/";
  1544. static const char forelem_cookie[] = "/*FORELEM*/";
  1545. static const char with_cookie[] = "/*WITH*/";
  1546. static const char dot_format[] = "%s.%s";
  1547. static const char index_format[] = "%s[%s]";
  1548. static const char predot_format[] = "%s%s.%s";
  1549. static const char postdot_format[] = "%s.%s%s";
  1550. static const char preindex_format[] = "%s%s[%s]";
  1551. static const char postindex_format[] = "%s[%s]%s";
  1552. static const char ss_format[] = "%s%s";
  1553. static const char sss_format[] = "%s%s%s";
  1554. /* Argument and variables decompilation uses the following to share code. */
  1555. JS_STATIC_ASSERT(ARGNO_LEN == SLOTNO_LEN);
  1556. /*
  1557. * Local macros
  1558. */
  1559. #define LOCAL_ASSERT(expr) LOCAL_ASSERT_RV(expr, NULL)
  1560. #define DECOMPILE_CODE(pc,nb) if (!Decompile(ss, pc, nb, JSOP_NOP)) return NULL
  1561. #define NEXT_OP(pc) (((pc) + (len) == endpc) ? nextop : pc[len])
  1562. #define TOP_STR() GetStr(ss, ss->top - 1)
  1563. #define POP_STR() PopStr(ss, op)
  1564. #define POP_STR_PREC(prec) PopStrPrec(ss, prec)
  1565. /*
  1566. * Pop a condition expression for if/for/while. JSOP_IFEQ's precedence forces
  1567. * extra parens around assignment, which avoids a strict-mode warning.
  1568. */
  1569. #define POP_COND_STR() \
  1570. PopStr(ss, (js_CodeSpec[ss->opcodes[ss->top - 1]].format & JOF_SET) \
  1571. ? JSOP_IFEQ \
  1572. : JSOP_NOP)
  1573. /*
  1574. * Callers know that ATOM_IS_STRING(atom), and we leave it to the optimizer to
  1575. * common ATOM_TO_STRING(atom) here and near the call sites.
  1576. */
  1577. #define ATOM_IS_IDENTIFIER(atom) js_IsIdentifier(ATOM_TO_STRING(atom))
  1578. #define ATOM_IS_KEYWORD(atom) \
  1579. (js_CheckKeyword(JSSTRING_CHARS(ATOM_TO_STRING(atom)), \
  1580. JSSTRING_LENGTH(ATOM_TO_STRING(atom))) != TOK_EOF)
  1581. /*
  1582. * Given an atom already fetched from jp->script's atom map, quote/escape its
  1583. * string appropriately into rval, and select fmt from the quoted and unquoted
  1584. * alternatives.
  1585. */
  1586. #define GET_QUOTE_AND_FMT(qfmt, ufmt, rval) \
  1587. JS_BEGIN_MACRO \
  1588. jschar quote_; \
  1589. if (!ATOM_IS_IDENTIFIER(atom)) { \
  1590. quote_ = '\''; \
  1591. fmt = qfmt; \
  1592. } else { \
  1593. quote_ = 0; \
  1594. fmt = ufmt; \
  1595. } \
  1596. rval = QuoteString(&ss->sprinter, ATOM_TO_STRING(atom), quote_); \
  1597. if (!rval) \
  1598. return NULL; \
  1599. JS_END_MACRO
  1600. #define LOAD_ATOM(PCOFF) \
  1601. GET_ATOM_FROM_BYTECODE(jp->script, pc, PCOFF, atom)
  1602. #define LOAD_OBJECT(PCOFF) \
  1603. GET_OBJECT_FROM_BYTECODE(jp->script, pc, PCOFF, obj)
  1604. #define LOAD_FUNCTION(PCOFF) \
  1605. GET_FUNCTION_FROM_BYTECODE(jp->script, pc, PCOFF, fun)
  1606. #define LOAD_REGEXP(PCOFF) \
  1607. GET_REGEXP_FROM_BYTECODE(jp->script, pc, PCOFF, obj)
  1608. #define GET_SOURCE_NOTE_ATOM(sn, atom) \
  1609. JS_BEGIN_MACRO \
  1610. jsatomid atomIndex_ = (jsatomid) js_GetSrcNoteOffset((sn), 0); \
  1611. \
  1612. LOCAL_ASSERT(atomIndex_ < jp->script->atomMap.length); \
  1613. (atom) = jp->script->atomMap.vector[atomIndex_]; \
  1614. JS_END_MACRO
  1615. /*
  1616. * Get atom from jp->script's atom map, quote/escape its string appropriately
  1617. * into rval, and select fmt from the quoted and unquoted alternatives.
  1618. */
  1619. #define GET_ATOM_QUOTE_AND_FMT(qfmt, ufmt, rval) \
  1620. JS_BEGIN_MACRO \
  1621. LOAD_ATOM(0); \
  1622. GET_QUOTE_AND_FMT(qfmt, ufmt, rval); \
  1623. JS_END_MACRO
  1624. /*
  1625. * Per spec, new x(y).z means (new x(y))).z. For example new (x(y).z) must
  1626. * decompile with the constructor parenthesized, but new x.z should not. The
  1627. * normal rules give x(y).z and x.z identical precedence: both are produced by
  1628. * JSOP_GETPROP.
  1629. *
  1630. * Therefore, we need to know in case JSOP_NEW whether the constructor
  1631. * expression contains any unparenthesized function calls. So when building a
  1632. * MemberExpression or CallExpression, we set ss->opcodes[n] to JSOP_CALL if
  1633. * this is true. x(y).z gets JSOP_CALL, not JSOP_GETPROP.
  1634. */
  1635. #define PROPAGATE_CALLNESS() \
  1636. JS_BEGIN_MACRO \
  1637. if (ss->opcodes[ss->top - 1] == JSOP_CALL) \
  1638. saveop = JSOP_CALL; \
  1639. JS_END_MACRO
  1640. cx = ss->sprinter.context;
  1641. JS_CHECK_RECURSION(cx, return NULL);
  1642. jp = ss->printer;
  1643. startpc = pc;
  1644. endpc = (nb < 0) ? jp->script->code + jp->script->length : pc + nb;
  1645. tail = -1;
  1646. todo = -2; /* NB: different from Sprint() error return. */
  1647. saveop = JSOP_NOP;
  1648. sn = NULL;
  1649. rval = NULL;
  1650. #if JS_HAS_XML_SUPPORT
  1651. foreach = inXML = quoteAttr = JS_FALSE;
  1652. #endif
  1653. while (nb < 0 || pc < endpc) {
  1654. /*
  1655. * Move saveop to lastop so prefixed bytecodes can take special action
  1656. * while sharing maximal code. Set op and saveop to the new bytecode,
  1657. * use op in POP_STR to trigger automatic parenthesization, but push
  1658. * saveop at the bottom of the loop if this op pushes. Thus op may be
  1659. * set to nop or otherwise mutated to suppress auto-parens.
  1660. */
  1661. lastop = saveop;
  1662. op = (JSOp) *pc;
  1663. cs = &js_CodeSpec[op];
  1664. if (cs->format & JOF_INDEXBASE) {
  1665. /*
  1666. * The decompiler uses js_GetIndexFromBytecode to get atoms and
  1667. * objects and ignores these suffix/prefix bytecodes, thus
  1668. * simplifying code that must process JSOP_GETTER/JSOP_SETTER
  1669. * prefixes.
  1670. */
  1671. pc += cs->length;
  1672. if (pc >= endpc)
  1673. break;
  1674. op = (JSOp) *pc;
  1675. cs = &js_CodeSpec[op];
  1676. }
  1677. saveop = op;
  1678. len = oplen = cs->length;
  1679. if (nb < 0 && -(nb + 1) == (intN)ss->top - cs->nuses + cs->ndefs)
  1680. return pc;
  1681. /*
  1682. * Save source literal associated with JS now before the following
  1683. * rewrite changes op. See bug 380197.
  1684. */
  1685. token = CodeToken[op];
  1686. if (pc + oplen == jp->dvgfence) {
  1687. JSStackFrame *fp;
  1688. uint32 format, mode, type;
  1689. /*
  1690. * Rewrite non-get ops to their "get" format if the error is in
  1691. * the bytecode at pc, so we don't decompile more than the error
  1692. * expression.
  1693. */
  1694. for (fp = cx->fp; fp && !fp->script; fp = fp->down)
  1695. continue;
  1696. format = cs->format;
  1697. if (((fp && fp->regs && pc == fp->regs->pc) ||
  1698. (pc == startpc && cs->nuses != 0)) &&
  1699. format & (JOF_SET|JOF_DEL|JOF_INCDEC|JOF_FOR|JOF_VARPROP)) {
  1700. mode = JOF_MODE(format);
  1701. if (mode == JOF_NAME) {
  1702. /*
  1703. * JOF_NAME does not imply JOF_ATOM, so we must check for
  1704. * the QARG and QVAR format types, and translate those to
  1705. * JSOP_GETARG or JSOP_GETLOCAL appropriately, instead of
  1706. * to JSOP_NAME.
  1707. */
  1708. type = JOF_TYPE(format);
  1709. op = (type == JOF_QARG)
  1710. ? JSOP_GETARG
  1711. : (type == JOF_LOCAL)
  1712. ? JSOP_GETLOCAL
  1713. : JSOP_NAME;
  1714. i = cs->nuses - js_CodeSpec[op].nuses;
  1715. while (--i >= 0)
  1716. PopOff(ss, JSOP_NOP);
  1717. } else {
  1718. /*
  1719. * We must replace the faulting pc's bytecode with a
  1720. * corresponding JSOP_GET* code. For JSOP_SET{PROP,ELEM},
  1721. * we must use the "2nd" form of JSOP_GET{PROP,ELEM}, to
  1722. * throw away the assignment op's right-hand operand and
  1723. * decompile it as if it were a GET of its left-hand
  1724. * operand.
  1725. */
  1726. if (mode == JOF_PROP) {
  1727. op = (JSOp) ((format & JOF_SET)
  1728. ? JSOP_GETPROP2
  1729. : JSOP_GETPROP);
  1730. } else if (mode == JOF_ELEM) {
  1731. op = (JSOp) ((format & JOF_SET)
  1732. ? JSOP_GETELEM2
  1733. : JSOP_GETELEM);
  1734. } else {
  1735. /*
  1736. * Unknown mode (including mode 0) means that op is
  1737. * uncategorized for our purposes, so we must write
  1738. * per-op special case code here.
  1739. */
  1740. switch (op) {
  1741. case JSOP_ENUMELEM:
  1742. case JSOP_ENUMCONSTELEM:
  1743. op = JSOP_GETELEM;
  1744. break;
  1745. #if JS_HAS_LVALUE_RETURN
  1746. case JSOP_SETCALL:
  1747. op = JSOP_CALL;
  1748. break;
  1749. #endif
  1750. case JSOP_GETTHISPROP:
  1751. /*
  1752. * NB: JSOP_GETTHISPROP can't fail due to |this|
  1753. * being null or undefined at runtime (beware that
  1754. * this may change for ES4). Therefore any error
  1755. * resulting from this op must be due to the value
  1756. * of the property accessed via |this|, so do not
  1757. * rewrite op to JSOP_THIS.
  1758. *
  1759. * The next two cases should not change op if
  1760. * js_DecompileValueGenerator was called from the
  1761. * the property getter. They should rewrite only
  1762. * if the base object in the arg/var/local is null
  1763. * or undefined. FIXME: bug 431569.
  1764. */
  1765. break;
  1766. case JSOP_GETARGPROP:
  1767. op = JSOP_GETARG;
  1768. break;
  1769. case JSOP_GETLOCALPROP:
  1770. op = JSOP_GETLOCAL;
  1771. break;
  1772. default:
  1773. LOCAL_ASSERT(0);
  1774. }
  1775. }
  1776. }
  1777. }
  1778. saveop = op;
  1779. if (op >= JSOP_LIMIT) {
  1780. switch (op) {
  1781. case JSOP_GETPROP2:
  1782. saveop = JSOP_GETPROP;
  1783. break;
  1784. case JSOP_GETELEM2:
  1785. saveop = JSOP_GETELEM;
  1786. break;
  1787. default:;
  1788. }
  1789. }
  1790. LOCAL_ASSERT(js_CodeSpec[saveop].length == oplen ||
  1791. JOF_TYPE(format) == JOF_SLOTATOM);
  1792. jp->dvgfence = NULL;
  1793. }
  1794. if (token) {
  1795. switch (cs->nuses) {
  1796. case 2:
  1797. sn = js_GetSrcNote(jp->script, pc);
  1798. if (sn && SN_TYPE(sn) == SRC_ASSIGNOP) {
  1799. /*
  1800. * Avoid over-parenthesizing y in x op= y based on its
  1801. * expansion: x = x op y (replace y by z = w to see the
  1802. * problem).
  1803. */
  1804. op = (JSOp) pc[oplen];
  1805. rval = POP_STR();
  1806. lval = POP_STR();
  1807. /* Print only the right operand of the assignment-op. */
  1808. todo = SprintCString(&ss->sprinter, rval);
  1809. op = saveop;
  1810. } else if (!inXML) {
  1811. rval = POP_STR_PREC(cs->prec + !!(cs->format & JOF_LEFTASSOC));
  1812. lval = POP_STR_PREC(cs->prec + !(cs->format & JOF_LEFTASSOC));
  1813. todo = Sprint(&ss->sprinter, "%s %s %s",
  1814. lval, token, rval);
  1815. } else {
  1816. /* In XML, just concatenate the two operands. */
  1817. LOCAL_ASSERT(op == JSOP_ADD);