PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
C++ | 1891 lines | 1413 code | 233 blank | 245 comment | 330 complexity | 976c94b2ccb4ded5f3ff922ec272d6c8 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2. * vim: set ts=8 sw=4 et tw=78:
  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 script operations.
  42. */
  43. #include "jsstddef.h"
  44. #include <string.h>
  45. #include "jstypes.h"
  46. #include "jsutil.h" /* Added by JSIFY */
  47. #include "jsprf.h"
  48. #include "jsapi.h"
  49. #include "jsatom.h"
  50. #include "jscntxt.h"
  51. #include "jsversion.h"
  52. #include "jsdbgapi.h"
  53. #include "jsemit.h"
  54. #include "jsfun.h"
  55. #include "jsinterp.h"
  56. #include "jslock.h"
  57. #include "jsnum.h"
  58. #include "jsopcode.h"
  59. #include "jsparse.h"
  60. #include "jsscope.h"
  61. #include "jsscript.h"
  62. #if JS_HAS_XDR
  63. #include "jsxdrapi.h"
  64. #endif
  65. #if JS_HAS_SCRIPT_OBJECT
  66. static const char js_script_exec_str[] = "Script.prototype.exec";
  67. static const char js_script_compile_str[] = "Script.prototype.compile";
  68. /*
  69. * This routine requires that obj has been locked previously.
  70. */
  71. static jsint
  72. GetScriptExecDepth(JSContext *cx, JSObject *obj)
  73. {
  74. jsval v;
  75. JS_ASSERT(JS_IS_OBJ_LOCKED(cx, obj));
  76. v = LOCKED_OBJ_GET_SLOT(obj, JSSLOT_START(&js_ScriptClass));
  77. return JSVAL_TO_INT(v);
  78. }
  79. static void
  80. AdjustScriptExecDepth(JSContext *cx, JSObject *obj, jsint delta)
  81. {
  82. jsint execDepth;
  83. JS_LOCK_OBJ(cx, obj);
  84. execDepth = GetScriptExecDepth(cx, obj);
  85. LOCKED_OBJ_SET_SLOT(obj, JSSLOT_START(&js_ScriptClass),
  86. INT_TO_JSVAL(execDepth + delta));
  87. JS_UNLOCK_OBJ(cx, obj);
  88. }
  89. #if JS_HAS_TOSOURCE
  90. static JSBool
  91. script_toSource(JSContext *cx, uintN argc, jsval *vp)
  92. {
  93. JSObject *obj;
  94. uint32 indent;
  95. JSScript *script;
  96. size_t i, j, k, n;
  97. char buf[16];
  98. jschar *s, *t;
  99. JSString *str;
  100. obj = JS_THIS_OBJECT(cx, vp);
  101. if (!JS_InstanceOf(cx, obj, &js_ScriptClass, vp + 2))
  102. return JS_FALSE;
  103. indent = 0;
  104. if (argc != 0) {
  105. indent = js_ValueToECMAUint32(cx, &vp[2]);
  106. if (JSVAL_IS_NULL(vp[2]))
  107. return JS_FALSE;
  108. }
  109. script = (JSScript *) JS_GetPrivate(cx, obj);
  110. /* Let n count the source string length, j the "front porch" length. */
  111. j = JS_snprintf(buf, sizeof buf, "(new %s(", js_ScriptClass.name);
  112. n = j + 2;
  113. if (!script) {
  114. /* Let k count the constructor argument string length. */
  115. k = 0;
  116. s = NULL; /* quell GCC overwarning */
  117. } else {
  118. str = JS_DecompileScript(cx, script, "Script.prototype.toSource",
  119. (uintN)indent);
  120. if (!str)
  121. return JS_FALSE;
  122. str = js_QuoteString(cx, str, '\'');
  123. if (!str)
  124. return JS_FALSE;
  125. JSSTRING_CHARS_AND_LENGTH(str, s, k);
  126. n += k;
  127. }
  128. /* Allocate the source string and copy into it. */
  129. t = (jschar *) JS_malloc(cx, (n + 1) * sizeof(jschar));
  130. if (!t)
  131. return JS_FALSE;
  132. for (i = 0; i < j; i++)
  133. t[i] = buf[i];
  134. for (j = 0; j < k; i++, j++)
  135. t[i] = s[j];
  136. t[i++] = ')';
  137. t[i++] = ')';
  138. t[i] = 0;
  139. /* Create and return a JS string for t. */
  140. str = JS_NewUCString(cx, t, n);
  141. if (!str) {
  142. JS_free(cx, t);
  143. return JS_FALSE;
  144. }
  145. *vp = STRING_TO_JSVAL(str);
  146. return JS_TRUE;
  147. }
  148. #endif /* JS_HAS_TOSOURCE */
  149. static JSBool
  150. script_toString(JSContext *cx, uintN argc, jsval *vp)
  151. {
  152. uint32 indent;
  153. JSObject *obj;
  154. JSScript *script;
  155. JSString *str;
  156. indent = 0;
  157. if (argc != 0) {
  158. indent = js_ValueToECMAUint32(cx, &vp[2]);
  159. if (JSVAL_IS_NULL(vp[2]))
  160. return JS_FALSE;
  161. }
  162. obj = JS_THIS_OBJECT(cx, vp);
  163. if (!JS_InstanceOf(cx, obj, &js_ScriptClass, vp + 2))
  164. return JS_FALSE;
  165. script = (JSScript *) JS_GetPrivate(cx, obj);
  166. if (!script) {
  167. *vp = STRING_TO_JSVAL(cx->runtime->emptyString);
  168. return JS_TRUE;
  169. }
  170. str = JS_DecompileScript(cx, script, "Script.prototype.toString",
  171. (uintN)indent);
  172. if (!str)
  173. return JS_FALSE;
  174. *vp = STRING_TO_JSVAL(str);
  175. return JS_TRUE;
  176. }
  177. static JSBool
  178. script_compile_sub(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
  179. jsval *rval)
  180. {
  181. JSString *str;
  182. JSObject *scopeobj;
  183. jsval v;
  184. JSScript *script, *oldscript;
  185. JSStackFrame *caller;
  186. const char *file;
  187. uintN line;
  188. JSPrincipals *principals;
  189. uint32 tcflags;
  190. jsint execDepth;
  191. /* Make sure obj is a Script object. */
  192. if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
  193. return JS_FALSE;
  194. /* If no args, leave private undefined and return early. */
  195. if (argc == 0)
  196. goto out;
  197. /* Otherwise, the first arg is the script source to compile. */
  198. str = js_ValueToString(cx, argv[0]);
  199. if (!str)
  200. return JS_FALSE;
  201. argv[0] = STRING_TO_JSVAL(str);
  202. scopeobj = NULL;
  203. if (argc >= 2) {
  204. if (!js_ValueToObject(cx, argv[1], &scopeobj))
  205. return JS_FALSE;
  206. argv[1] = OBJECT_TO_JSVAL(scopeobj);
  207. }
  208. /* Compile using the caller's scope chain, which js_Invoke passes to fp. */
  209. caller = JS_GetScriptedCaller(cx, cx->fp);
  210. JS_ASSERT(!caller || cx->fp->scopeChain == caller->scopeChain);
  211. if (caller) {
  212. if (!scopeobj) {
  213. scopeobj = js_GetScopeChain(cx, caller);
  214. if (!scopeobj)
  215. return JS_FALSE;
  216. }
  217. principals = JS_EvalFramePrincipals(cx, cx->fp, caller);
  218. file = js_ComputeFilename(cx, caller, principals, &line);
  219. } else {
  220. file = NULL;
  221. line = 0;
  222. principals = NULL;
  223. }
  224. /* Ensure we compile this script with the right (inner) principals. */
  225. scopeobj = js_CheckScopeChainValidity(cx, scopeobj, js_script_compile_str);
  226. if (!scopeobj)
  227. return JS_FALSE;
  228. /*
  229. * Compile the new script using the caller's scope chain, a la eval().
  230. * Unlike jsobj.c:obj_eval, however, we do not pass TCF_COMPILE_N_GO in
  231. * tcflags and use NULL for the callerFrame argument, because compilation
  232. * is here separated from execution, and the run-time scope chain may not
  233. * match the compile-time. TCF_COMPILE_N_GO is tested in jsemit.c and
  234. * jsparse.c to optimize based on identity of run- and compile-time scope.
  235. */
  236. tcflags = 0;
  237. script = js_CompileScript(cx, scopeobj, NULL, principals, tcflags,
  238. JSSTRING_CHARS(str), JSSTRING_LENGTH(str),
  239. NULL, file, line);
  240. if (!script)
  241. return JS_FALSE;
  242. JS_LOCK_OBJ(cx, obj);
  243. execDepth = GetScriptExecDepth(cx, obj);
  244. /*
  245. * execDepth must be 0 to allow compilation here, otherwise the JSScript
  246. * struct can be released while running.
  247. */
  248. if (execDepth > 0) {
  249. JS_UNLOCK_OBJ(cx, obj);
  250. JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
  251. JSMSG_COMPILE_EXECED_SCRIPT);
  252. return JS_FALSE;
  253. }
  254. /* Swap script for obj's old script, if any. */
  255. v = LOCKED_OBJ_GET_SLOT(obj, JSSLOT_PRIVATE);
  256. oldscript = (JSScript*) (!JSVAL_IS_VOID(v) ? JSVAL_TO_PRIVATE(v) : NULL);
  257. LOCKED_OBJ_SET_SLOT(obj, JSSLOT_PRIVATE, PRIVATE_TO_JSVAL(script));
  258. JS_UNLOCK_OBJ(cx, obj);
  259. if (oldscript)
  260. js_DestroyScript(cx, oldscript);
  261. script->u.object = obj;
  262. js_CallNewScriptHook(cx, script, NULL);
  263. out:
  264. /* Return the object. */
  265. *rval = OBJECT_TO_JSVAL(obj);
  266. return JS_TRUE;
  267. }
  268. static JSBool
  269. script_compile(JSContext *cx, uintN argc, jsval *vp)
  270. {
  271. return script_compile_sub(cx, JS_THIS_OBJECT(cx, vp), argc, vp + 2, vp);
  272. }
  273. static JSBool
  274. script_exec_sub(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
  275. jsval *rval)
  276. {
  277. JSObject *scopeobj, *parent;
  278. JSStackFrame *fp, *caller;
  279. JSPrincipals *principals;
  280. JSScript *script;
  281. JSBool ok;
  282. if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
  283. return JS_FALSE;
  284. scopeobj = NULL;
  285. if (argc != 0) {
  286. if (!js_ValueToObject(cx, argv[0], &scopeobj))
  287. return JS_FALSE;
  288. argv[0] = OBJECT_TO_JSVAL(scopeobj);
  289. }
  290. /*
  291. * Emulate eval() by using caller's this, var object, sharp array, etc.,
  292. * all propagated by js_Execute via a non-null fourth (down) argument to
  293. * js_Execute. If there is no scripted caller, js_Execute uses its second
  294. * (chain) argument to set the exec frame's varobj, thisp, and scopeChain.
  295. *
  296. * Unlike eval, which the compiler detects, Script.prototype.exec may be
  297. * called from a lightweight function, or even from native code (in which
  298. * case fp->varobj and fp->scopeChain are null). If exec is called from
  299. * a lightweight function, we will need to get a Call object representing
  300. * its frame, to act as the var object and scope chain head.
  301. */
  302. fp = cx->fp;
  303. caller = JS_GetScriptedCaller(cx, fp);
  304. if (caller && !caller->varobj) {
  305. /* Called from a lightweight function. */
  306. JS_ASSERT(caller->fun && !JSFUN_HEAVYWEIGHT_TEST(caller->fun->flags));
  307. /* Scope chain links from Call object to callee's parent. */
  308. parent = OBJ_GET_PARENT(cx, caller->callee);
  309. if (!js_GetCallObject(cx, caller, parent))
  310. return JS_FALSE;
  311. }
  312. if (!scopeobj) {
  313. /* No scope object passed in: try to use the caller's scope chain. */
  314. if (caller) {
  315. /*
  316. * Load caller->scopeChain after the conditional js_GetCallObject
  317. * call above, which resets scopeChain as well as varobj.
  318. */
  319. scopeobj = js_GetScopeChain(cx, caller);
  320. if (!scopeobj)
  321. return JS_FALSE;
  322. } else {
  323. /*
  324. * Called from native code, so we don't know what scope object to
  325. * use. We could use parent (see above), but Script.prototype.exec
  326. * might be a shared/sealed "superglobal" method. A more general
  327. * approach would use cx->globalObject, which will be the same as
  328. * exec.__parent__ in the non-superglobal case. In the superglobal
  329. * case it's the right object: the global, not the superglobal.
  330. */
  331. scopeobj = cx->globalObject;
  332. }
  333. }
  334. scopeobj = js_CheckScopeChainValidity(cx, scopeobj, js_script_exec_str);
  335. if (!scopeobj)
  336. return JS_FALSE;
  337. /* Keep track of nesting depth for the script. */
  338. AdjustScriptExecDepth(cx, obj, 1);
  339. /* Must get to out label after this */
  340. script = (JSScript *) JS_GetPrivate(cx, obj);
  341. if (!script) {
  342. ok = JS_FALSE;
  343. goto out;
  344. }
  345. /* Belt-and-braces: check that this script object has access to scopeobj. */
  346. principals = script->principals;
  347. ok = js_CheckPrincipalsAccess(cx, scopeobj, principals,
  348. CLASS_ATOM(cx, Script));
  349. if (!ok)
  350. goto out;
  351. ok = js_Execute(cx, scopeobj, script, caller, JSFRAME_EVAL, rval);
  352. out:
  353. AdjustScriptExecDepth(cx, obj, -1);
  354. return ok;
  355. }
  356. static JSBool
  357. script_exec(JSContext *cx, uintN argc, jsval *vp)
  358. {
  359. return script_exec_sub(cx, JS_THIS_OBJECT(cx, vp), argc, vp + 2, vp);
  360. }
  361. #endif /* JS_HAS_SCRIPT_OBJECT */
  362. #if JS_HAS_XDR
  363. JSBool
  364. js_XDRScript(JSXDRState *xdr, JSScript **scriptp, JSBool *hasMagic)
  365. {
  366. JSContext *cx;
  367. JSScript *script, *oldscript;
  368. JSBool ok;
  369. jsbytecode *code;
  370. uint32 length, lineno, nslots, magic;
  371. uint32 natoms, nsrcnotes, ntrynotes, nobjects, nupvars, nregexps, i;
  372. uint32 prologLength, version;
  373. JSTempValueRooter tvr;
  374. JSPrincipals *principals;
  375. uint32 encodeable;
  376. JSBool filenameWasSaved;
  377. jssrcnote *notes, *sn;
  378. JSSecurityCallbacks *callbacks;
  379. cx = xdr->cx;
  380. script = *scriptp;
  381. nsrcnotes = ntrynotes = natoms = nobjects = nupvars = nregexps = 0;
  382. filenameWasSaved = JS_FALSE;
  383. notes = NULL;
  384. if (xdr->mode == JSXDR_ENCODE)
  385. magic = JSXDR_MAGIC_SCRIPT_CURRENT;
  386. if (!JS_XDRUint32(xdr, &magic))
  387. return JS_FALSE;
  388. if (magic != JSXDR_MAGIC_SCRIPT_CURRENT) {
  389. /* We do not provide binary compatibility with older scripts. */
  390. if (!hasMagic) {
  391. JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
  392. JSMSG_BAD_SCRIPT_MAGIC);
  393. return JS_FALSE;
  394. }
  395. *hasMagic = JS_FALSE;
  396. return JS_TRUE;
  397. }
  398. if (hasMagic)
  399. *hasMagic = JS_TRUE;
  400. if (xdr->mode == JSXDR_ENCODE) {
  401. length = script->length;
  402. prologLength = PTRDIFF(script->main, script->code, jsbytecode);
  403. JS_ASSERT((int16)script->version != JSVERSION_UNKNOWN);
  404. version = (uint32)script->version | (script->nfixed << 16);
  405. lineno = (uint32)script->lineno;
  406. nslots = (uint32)script->nslots;
  407. nslots = (uint32)((script->staticDepth << 16) | script->nslots);
  408. natoms = (uint32)script->atomMap.length;
  409. /* Count the srcnotes, keeping notes pointing at the first one. */
  410. notes = SCRIPT_NOTES(script);
  411. for (sn = notes; !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn))
  412. continue;
  413. nsrcnotes = PTRDIFF(sn, notes, jssrcnote);
  414. nsrcnotes++; /* room for the terminator */
  415. if (script->objectsOffset != 0)
  416. nobjects = JS_SCRIPT_OBJECTS(script)->length;
  417. if (script->upvarsOffset != 0)
  418. nupvars = JS_SCRIPT_UPVARS(script)->length;
  419. if (script->regexpsOffset != 0)
  420. nregexps = JS_SCRIPT_REGEXPS(script)->length;
  421. if (script->trynotesOffset != 0)
  422. ntrynotes = JS_SCRIPT_TRYNOTES(script)->length;
  423. }
  424. if (!JS_XDRUint32(xdr, &length))
  425. return JS_FALSE;
  426. if (!JS_XDRUint32(xdr, &prologLength))
  427. return JS_FALSE;
  428. if (!JS_XDRUint32(xdr, &version))
  429. return JS_FALSE;
  430. /*
  431. * To fuse allocations, we need srcnote, atom, objects, upvar, regexp,
  432. * and trynote counts early.
  433. */
  434. if (!JS_XDRUint32(xdr, &natoms))
  435. return JS_FALSE;
  436. if (!JS_XDRUint32(xdr, &nsrcnotes))
  437. return JS_FALSE;
  438. if (!JS_XDRUint32(xdr, &ntrynotes))
  439. return JS_FALSE;
  440. if (!JS_XDRUint32(xdr, &nobjects))
  441. return JS_FALSE;
  442. if (!JS_XDRUint32(xdr, &nupvars))
  443. return JS_FALSE;
  444. if (!JS_XDRUint32(xdr, &nregexps))
  445. return JS_FALSE;
  446. if (xdr->mode == JSXDR_DECODE) {
  447. script = js_NewScript(cx, length, nsrcnotes, natoms, nobjects, nupvars,
  448. nregexps, ntrynotes);
  449. if (!script)
  450. return JS_FALSE;
  451. script->main += prologLength;
  452. script->version = (JSVersion) (version & 0xffff);
  453. script->nfixed = (uint16) (version >> 16);
  454. /* If we know nsrcnotes, we allocated space for notes in script. */
  455. notes = SCRIPT_NOTES(script);
  456. *scriptp = script;
  457. JS_PUSH_TEMP_ROOT_SCRIPT(cx, script, &tvr);
  458. }
  459. /*
  460. * Control hereafter must goto error on failure, in order for the
  461. * DECODE case to destroy script.
  462. */
  463. oldscript = xdr->script;
  464. code = script->code;
  465. if (xdr->mode == JSXDR_ENCODE) {
  466. code = js_UntrapScriptCode(cx, script);
  467. if (!code)
  468. goto error;
  469. }
  470. xdr->script = script;
  471. ok = JS_XDRBytes(xdr, (char *) code, length * sizeof(jsbytecode));
  472. if (code != script->code)
  473. JS_free(cx, code);
  474. if (!ok)
  475. goto error;
  476. if (!JS_XDRBytes(xdr, (char *)notes, nsrcnotes * sizeof(jssrcnote)) ||
  477. !JS_XDRCStringOrNull(xdr, (char **)&script->filename) ||
  478. !JS_XDRUint32(xdr, &lineno) ||
  479. !JS_XDRUint32(xdr, &nslots)) {
  480. goto error;
  481. }
  482. callbacks = JS_GetSecurityCallbacks(cx);
  483. if (xdr->mode == JSXDR_ENCODE) {
  484. principals = script->principals;
  485. encodeable = callbacks && callbacks->principalsTranscoder;
  486. if (!JS_XDRUint32(xdr, &encodeable))
  487. goto error;
  488. if (encodeable &&
  489. !callbacks->principalsTranscoder(xdr, &principals)) {
  490. goto error;
  491. }
  492. } else {
  493. if (!JS_XDRUint32(xdr, &encodeable))
  494. goto error;
  495. if (encodeable) {
  496. if (!(callbacks && callbacks->principalsTranscoder)) {
  497. JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
  498. JSMSG_CANT_DECODE_PRINCIPALS);
  499. goto error;
  500. }
  501. if (!callbacks->principalsTranscoder(xdr, &principals))
  502. goto error;
  503. script->principals = principals;
  504. }
  505. }
  506. if (xdr->mode == JSXDR_DECODE) {
  507. const char *filename = script->filename;
  508. if (filename) {
  509. filename = js_SaveScriptFilename(cx, filename);
  510. if (!filename)
  511. goto error;
  512. JS_free(cx, (void *) script->filename);
  513. script->filename = filename;
  514. filenameWasSaved = JS_TRUE;
  515. }
  516. script->lineno = (uintN)lineno;
  517. script->nslots = (uint16)nslots;
  518. script->staticDepth = nslots >> 16;
  519. }
  520. for (i = 0; i != natoms; ++i) {
  521. if (!js_XDRAtom(xdr, &script->atomMap.vector[i]))
  522. goto error;
  523. }
  524. /*
  525. * Here looping from 0-to-length to xdr objects is essential. It ensures
  526. * that block objects from the script->objects array will be written and
  527. * restored in the outer-to-inner order. block_xdrObject relies on this to
  528. * restore the parent chain.
  529. */
  530. for (i = 0; i != nobjects; ++i) {
  531. if (!js_XDRObject(xdr, &JS_SCRIPT_OBJECTS(script)->vector[i]))
  532. goto error;
  533. }
  534. for (i = 0; i != nupvars; ++i) {
  535. if (!JS_XDRUint32(xdr, &JS_SCRIPT_UPVARS(script)->vector[i]))
  536. goto error;
  537. }
  538. for (i = 0; i != nregexps; ++i) {
  539. if (!js_XDRObject(xdr, &JS_SCRIPT_REGEXPS(script)->vector[i]))
  540. goto error;
  541. }
  542. if (ntrynotes != 0) {
  543. /*
  544. * We combine tn->kind and tn->stackDepth when serializing as XDR is not
  545. * efficient when serializing small integer types.
  546. */
  547. JSTryNote *tn, *tnfirst;
  548. uint32 kindAndDepth;
  549. JS_STATIC_ASSERT(sizeof(tn->kind) == sizeof(uint8));
  550. JS_STATIC_ASSERT(sizeof(tn->stackDepth) == sizeof(uint16));
  551. tnfirst = JS_SCRIPT_TRYNOTES(script)->vector;
  552. JS_ASSERT(JS_SCRIPT_TRYNOTES(script)->length == ntrynotes);
  553. tn = tnfirst + ntrynotes;
  554. do {
  555. --tn;
  556. if (xdr->mode == JSXDR_ENCODE) {
  557. kindAndDepth = ((uint32)tn->kind << 16)
  558. | (uint32)tn->stackDepth;
  559. }
  560. if (!JS_XDRUint32(xdr, &kindAndDepth) ||
  561. !JS_XDRUint32(xdr, &tn->start) ||
  562. !JS_XDRUint32(xdr, &tn->length)) {
  563. goto error;
  564. }
  565. if (xdr->mode == JSXDR_DECODE) {
  566. tn->kind = (uint8)(kindAndDepth >> 16);
  567. tn->stackDepth = (uint16)kindAndDepth;
  568. }
  569. } while (tn != tnfirst);
  570. }
  571. xdr->script = oldscript;
  572. if (xdr->mode == JSXDR_DECODE)
  573. JS_POP_TEMP_ROOT(cx, &tvr);
  574. return JS_TRUE;
  575. error:
  576. if (xdr->mode == JSXDR_DECODE) {
  577. JS_POP_TEMP_ROOT(cx, &tvr);
  578. if (script->filename && !filenameWasSaved) {
  579. JS_free(cx, (void *) script->filename);
  580. script->filename = NULL;
  581. }
  582. js_DestroyScript(cx, script);
  583. *scriptp = NULL;
  584. }
  585. xdr->script = oldscript;
  586. return JS_FALSE;
  587. }
  588. #if JS_HAS_SCRIPT_OBJECT && JS_HAS_XDR_FREEZE_THAW
  589. /*
  590. * These cannot be exposed to web content, and chrome does not need them, so
  591. * we take them out of the Mozilla client altogether. Fortunately, there is
  592. * no way to serialize a native function (see fun_xdrObject in jsfun.c).
  593. */
  594. static JSBool
  595. script_freeze(JSContext *cx, uintN argc, jsval *vp)
  596. {
  597. JSObject *obj;
  598. JSXDRState *xdr;
  599. JSScript *script;
  600. JSBool ok, hasMagic;
  601. uint32 len;
  602. void *buf;
  603. JSString *str;
  604. obj = JS_THIS_OBJECT(cx, vp);
  605. if (!JS_InstanceOf(cx, obj, &js_ScriptClass, vp + 2))
  606. return JS_FALSE;
  607. script = (JSScript *) JS_GetPrivate(cx, obj);
  608. if (!script)
  609. return JS_TRUE;
  610. /* create new XDR */
  611. xdr = JS_XDRNewMem(cx, JSXDR_ENCODE);
  612. if (!xdr)
  613. return JS_FALSE;
  614. /* write */
  615. ok = js_XDRScript(xdr, &script, &hasMagic);
  616. if (!ok)
  617. goto out;
  618. if (!hasMagic) {
  619. *vp = JSVAL_VOID;
  620. goto out;
  621. }
  622. buf = JS_XDRMemGetData(xdr, &len);
  623. if (!buf) {
  624. ok = JS_FALSE;
  625. goto out;
  626. }
  627. JS_ASSERT((jsword)buf % sizeof(jschar) == 0);
  628. len /= sizeof(jschar);
  629. #if IS_BIG_ENDIAN
  630. {
  631. jschar *chars;
  632. uint32 i;
  633. /* Swap bytes in Unichars to keep frozen strings machine-independent. */
  634. chars = (jschar *)buf;
  635. for (i = 0; i < len; i++)
  636. chars[i] = JSXDR_SWAB16(chars[i]);
  637. }
  638. #endif
  639. str = JS_NewUCStringCopyN(cx, (jschar *)buf, len);
  640. if (!str) {
  641. ok = JS_FALSE;
  642. goto out;
  643. }
  644. *vp = STRING_TO_JSVAL(str);
  645. out:
  646. JS_XDRDestroy(xdr);
  647. return ok;
  648. }
  649. static JSBool
  650. script_thaw(JSContext *cx, uintN argc, jsval *vp)
  651. {
  652. JSObject *obj;
  653. JSXDRState *xdr;
  654. JSString *str;
  655. void *buf;
  656. uint32 len;
  657. jsval v;
  658. JSScript *script, *oldscript;
  659. JSBool ok, hasMagic;
  660. jsint execDepth;
  661. obj = JS_THIS_OBJECT(cx, vp);
  662. if (!JS_InstanceOf(cx, obj, &js_ScriptClass, vp + 2))
  663. return JS_FALSE;
  664. if (argc == 0)
  665. return JS_TRUE;
  666. str = js_ValueToString(cx, vp[2]);
  667. if (!str)
  668. return JS_FALSE;
  669. vp[2] = STRING_TO_JSVAL(str);
  670. /* create new XDR */
  671. xdr = JS_XDRNewMem(cx, JSXDR_DECODE);
  672. if (!xdr)
  673. return JS_FALSE;
  674. JSSTRING_CHARS_AND_LENGTH(str, buf, len);
  675. #if IS_BIG_ENDIAN
  676. {
  677. jschar *from, *to;
  678. uint32 i;
  679. /* Swap bytes in Unichars to keep frozen strings machine-independent. */
  680. from = (jschar *)buf;
  681. to = (jschar *) JS_malloc(cx, len * sizeof(jschar));
  682. if (!to) {
  683. JS_XDRDestroy(xdr);
  684. return JS_FALSE;
  685. }
  686. for (i = 0; i < len; i++)
  687. to[i] = JSXDR_SWAB16(from[i]);
  688. buf = (char *)to;
  689. }
  690. #endif
  691. len *= sizeof(jschar);
  692. JS_XDRMemSetData(xdr, buf, len);
  693. /* XXXbe should magic mismatch be error, or false return value? */
  694. ok = js_XDRScript(xdr, &script, &hasMagic);
  695. if (!ok)
  696. goto out;
  697. if (!hasMagic) {
  698. *vp = JSVAL_FALSE;
  699. goto out;
  700. }
  701. JS_LOCK_OBJ(cx, obj);
  702. execDepth = GetScriptExecDepth(cx, obj);
  703. /*
  704. * execDepth must be 0 to allow compilation here, otherwise the JSScript
  705. * struct can be released while running.
  706. */
  707. if (execDepth > 0) {
  708. JS_UNLOCK_OBJ(cx, obj);
  709. JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
  710. JSMSG_COMPILE_EXECED_SCRIPT);
  711. goto out;
  712. }
  713. /* Swap script for obj's old script, if any. */
  714. v = LOCKED_OBJ_GET_SLOT(obj, JSSLOT_PRIVATE);
  715. oldscript = !JSVAL_IS_VOID(v) ? JSVAL_TO_PRIVATE(v) : NULL;
  716. LOCKED_OBJ_SET_SLOT(obj, JSSLOT_PRIVATE, PRIVATE_TO_JSVAL(script));
  717. JS_UNLOCK_OBJ(cx, obj);
  718. if (oldscript)
  719. js_DestroyScript(cx, oldscript);
  720. script->u.object = obj;
  721. js_CallNewScriptHook(cx, script, NULL);
  722. out:
  723. /*
  724. * We reset the buffer to be NULL so that it doesn't free the chars
  725. * memory owned by str (vp[2]).
  726. */
  727. JS_XDRMemSetData(xdr, NULL, 0);
  728. JS_XDRDestroy(xdr);
  729. #if IS_BIG_ENDIAN
  730. JS_free(cx, buf);
  731. #endif
  732. *vp = JSVAL_TRUE;
  733. return ok;
  734. }
  735. static const char js_thaw_str[] = "thaw";
  736. #endif /* JS_HAS_SCRIPT_OBJECT && JS_HAS_XDR_FREEZE_THAW */
  737. #endif /* JS_HAS_XDR */
  738. #if JS_HAS_SCRIPT_OBJECT
  739. static JSFunctionSpec script_methods[] = {
  740. #if JS_HAS_TOSOURCE
  741. JS_FN(js_toSource_str, script_toSource, 0,0),
  742. #endif
  743. JS_FN(js_toString_str, script_toString, 0,0),
  744. JS_FN("compile", script_compile, 2,0),
  745. JS_FN("exec", script_exec, 1,0),
  746. #if JS_HAS_XDR_FREEZE_THAW
  747. JS_FN("freeze", script_freeze, 0,0),
  748. JS_FN(js_thaw_str, script_thaw, 1,0),
  749. #endif /* JS_HAS_XDR_FREEZE_THAW */
  750. JS_FS_END
  751. };
  752. #endif /* JS_HAS_SCRIPT_OBJECT */
  753. static void
  754. script_finalize(JSContext *cx, JSObject *obj)
  755. {
  756. JSScript *script;
  757. script = (JSScript *) JS_GetPrivate(cx, obj);
  758. if (script)
  759. js_DestroyScript(cx, script);
  760. }
  761. static JSBool
  762. script_call(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
  763. {
  764. #if JS_HAS_SCRIPT_OBJECT
  765. return script_exec_sub(cx, JSVAL_TO_OBJECT(argv[-2]), argc, argv, rval);
  766. #else
  767. return JS_FALSE;
  768. #endif
  769. }
  770. static void
  771. script_trace(JSTracer *trc, JSObject *obj)
  772. {
  773. JSScript *script;
  774. script = (JSScript *) JS_GetPrivate(trc->context, obj);
  775. if (script)
  776. js_TraceScript(trc, script);
  777. }
  778. #if !JS_HAS_SCRIPT_OBJECT
  779. #define JSProto_Script JSProto_Object
  780. #endif
  781. JS_FRIEND_DATA(JSClass) js_ScriptClass = {
  782. js_Script_str,
  783. JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(1) |
  784. JSCLASS_MARK_IS_TRACE | JSCLASS_HAS_CACHED_PROTO(JSProto_Script),
  785. JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
  786. JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, script_finalize,
  787. NULL, NULL, script_call, NULL,/*XXXbe xdr*/
  788. NULL, NULL, JS_CLASS_TRACE(script_trace), NULL
  789. };
  790. #if JS_HAS_SCRIPT_OBJECT
  791. static JSBool
  792. Script(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
  793. {
  794. /* If not constructing, replace obj with a new Script object. */
  795. if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) {
  796. obj = js_NewObject(cx, &js_ScriptClass, NULL, NULL, 0);
  797. if (!obj)
  798. return JS_FALSE;
  799. /*
  800. * script_compile_sub does not use rval to root its temporaries so we
  801. * can use it to root obj.
  802. */
  803. *rval = OBJECT_TO_JSVAL(obj);
  804. }
  805. if (!JS_SetReservedSlot(cx, obj, 0, INT_TO_JSVAL(0)))
  806. return JS_FALSE;
  807. return script_compile_sub(cx, obj, argc, argv, rval);
  808. }
  809. #if JS_HAS_SCRIPT_OBJECT && JS_HAS_XDR_FREEZE_THAW
  810. static JSBool
  811. script_static_thaw(JSContext *cx, uintN argc, jsval *vp)
  812. {
  813. JSObject *obj;
  814. obj = js_NewObject(cx, &js_ScriptClass, NULL, NULL);
  815. if (!obj)
  816. return JS_FALSE;
  817. vp[1] = OBJECT_TO_JSVAL(obj);
  818. if (!script_thaw(cx, argc, vp))
  819. return JS_FALSE;
  820. *vp = OBJECT_TO_JSVAL(obj);
  821. return JS_TRUE;
  822. }
  823. static JSFunctionSpec script_static_methods[] = {
  824. JS_FN(js_thaw_str, script_static_thaw, 1,0),
  825. JS_FS_END
  826. };
  827. #else /* !JS_HAS_SCRIPT_OBJECT || !JS_HAS_XDR_FREEZE_THAW */
  828. #define script_static_methods NULL
  829. #endif /* !JS_HAS_SCRIPT_OBJECT || !JS_HAS_XDR_FREEZE_THAW */
  830. JSObject *
  831. js_InitScriptClass(JSContext *cx, JSObject *obj)
  832. {
  833. return JS_InitClass(cx, obj, NULL, &js_ScriptClass, Script, 1,
  834. NULL, script_methods, NULL, script_static_methods);
  835. }
  836. #endif /* JS_HAS_SCRIPT_OBJECT */
  837. /*
  838. * Shared script filename management.
  839. */
  840. static int
  841. js_compare_strings(const void *k1, const void *k2)
  842. {
  843. return strcmp((const char *) k1, (const char *) k2) == 0;
  844. }
  845. /* NB: This struct overlays JSHashEntry -- see jshash.h, do not reorganize. */
  846. typedef struct ScriptFilenameEntry {
  847. JSHashEntry *next; /* hash chain linkage */
  848. JSHashNumber keyHash; /* key hash function result */
  849. const void *key; /* ptr to filename, below */
  850. uint32 flags; /* user-defined filename prefix flags */
  851. JSPackedBool mark; /* GC mark flag */
  852. char filename[3]; /* two or more bytes, NUL-terminated */
  853. } ScriptFilenameEntry;
  854. static void *
  855. js_alloc_table_space(void *priv, size_t size)
  856. {
  857. return malloc(size);
  858. }
  859. static void
  860. js_free_table_space(void *priv, void *item)
  861. {
  862. free(item);
  863. }
  864. static JSHashEntry *
  865. js_alloc_sftbl_entry(void *priv, const void *key)
  866. {
  867. size_t nbytes = offsetof(ScriptFilenameEntry, filename) +
  868. strlen((const char *) key) + 1;
  869. return (JSHashEntry *) malloc(JS_MAX(nbytes, sizeof(JSHashEntry)));
  870. }
  871. static void
  872. js_free_sftbl_entry(void *priv, JSHashEntry *he, uintN flag)
  873. {
  874. if (flag != HT_FREE_ENTRY)
  875. return;
  876. free(he);
  877. }
  878. static JSHashAllocOps sftbl_alloc_ops = {
  879. js_alloc_table_space, js_free_table_space,
  880. js_alloc_sftbl_entry, js_free_sftbl_entry
  881. };
  882. JSBool
  883. js_InitRuntimeScriptState(JSRuntime *rt)
  884. {
  885. #ifdef JS_THREADSAFE
  886. JS_ASSERT(!rt->scriptFilenameTableLock);
  887. rt->scriptFilenameTableLock = JS_NEW_LOCK();
  888. if (!rt->scriptFilenameTableLock)
  889. return JS_FALSE;
  890. #endif
  891. JS_ASSERT(!rt->scriptFilenameTable);
  892. rt->scriptFilenameTable =
  893. JS_NewHashTable(16, JS_HashString, js_compare_strings, NULL,
  894. &sftbl_alloc_ops, NULL);
  895. if (!rt->scriptFilenameTable) {
  896. js_FinishRuntimeScriptState(rt); /* free lock if threadsafe */
  897. return JS_FALSE;
  898. }
  899. JS_INIT_CLIST(&rt->scriptFilenamePrefixes);
  900. return JS_TRUE;
  901. }
  902. typedef struct ScriptFilenamePrefix {
  903. JSCList links; /* circular list linkage for easy deletion */
  904. const char *name; /* pointer to pinned ScriptFilenameEntry string */
  905. size_t length; /* prefix string length, precomputed */
  906. uint32 flags; /* user-defined flags to inherit from this prefix */
  907. } ScriptFilenamePrefix;
  908. void
  909. js_FinishRuntimeScriptState(JSRuntime *rt)
  910. {
  911. if (rt->scriptFilenameTable) {
  912. JS_HashTableDestroy(rt->scriptFilenameTable);
  913. rt->scriptFilenameTable = NULL;
  914. }
  915. #ifdef JS_THREADSAFE
  916. if (rt->scriptFilenameTableLock) {
  917. JS_DESTROY_LOCK(rt->scriptFilenameTableLock);
  918. rt->scriptFilenameTableLock = NULL;
  919. }
  920. #endif
  921. }
  922. void
  923. js_FreeRuntimeScriptState(JSRuntime *rt)
  924. {
  925. ScriptFilenamePrefix *sfp;
  926. if (!rt->scriptFilenameTable)
  927. return;
  928. while (!JS_CLIST_IS_EMPTY(&rt->scriptFilenamePrefixes)) {
  929. sfp = (ScriptFilenamePrefix *) rt->scriptFilenamePrefixes.next;
  930. JS_REMOVE_LINK(&sfp->links);
  931. free(sfp);
  932. }
  933. js_FinishRuntimeScriptState(rt);
  934. }
  935. #ifdef DEBUG_brendan
  936. #define DEBUG_SFTBL
  937. #endif
  938. #ifdef DEBUG_SFTBL
  939. size_t sftbl_savings = 0;
  940. #endif
  941. static ScriptFilenameEntry *
  942. SaveScriptFilename(JSRuntime *rt, const char *filename, uint32 flags)
  943. {
  944. JSHashTable *table;
  945. JSHashNumber hash;
  946. JSHashEntry **hep;
  947. ScriptFilenameEntry *sfe;
  948. size_t length;
  949. JSCList *head, *link;
  950. ScriptFilenamePrefix *sfp;
  951. table = rt->scriptFilenameTable;
  952. hash = JS_HashString(filename);
  953. hep = JS_HashTableRawLookup(table, hash, filename);
  954. sfe = (ScriptFilenameEntry *) *hep;
  955. #ifdef DEBUG_SFTBL
  956. if (sfe)
  957. sftbl_savings += strlen(sfe->filename);
  958. #endif
  959. if (!sfe) {
  960. sfe = (ScriptFilenameEntry *)
  961. JS_HashTableRawAdd(table, hep, hash, filename, NULL);
  962. if (!sfe)
  963. return NULL;
  964. sfe->key = strcpy(sfe->filename, filename);
  965. sfe->flags = 0;
  966. sfe->mark = JS_FALSE;
  967. }
  968. /* If saving a prefix, add it to the set in rt->scriptFilenamePrefixes. */
  969. if (flags != 0) {
  970. /* Search in case filename was saved already; we must be idempotent. */
  971. sfp = NULL;
  972. length = strlen(filename);
  973. for (head = link = &rt->scriptFilenamePrefixes;
  974. link->next != head;
  975. link = link->next) {
  976. /* Lag link behind sfp to insert in non-increasing length order. */
  977. sfp = (ScriptFilenamePrefix *) link->next;
  978. if (!strcmp(sfp->name, filename))
  979. break;
  980. if (sfp->length <= length) {
  981. sfp = NULL;
  982. break;
  983. }
  984. sfp = NULL;
  985. }
  986. if (!sfp) {
  987. /* No such prefix: add one now. */
  988. sfp = (ScriptFilenamePrefix *) malloc(sizeof(ScriptFilenamePrefix));
  989. if (!sfp)
  990. return NULL;
  991. JS_INSERT_AFTER(&sfp->links, link);
  992. sfp->name = sfe->filename;
  993. sfp->length = length;
  994. sfp->flags = 0;
  995. }
  996. /*
  997. * Accumulate flags in both sfe and sfp: sfe for later access from the
  998. * JS_GetScriptedCallerFilenameFlags debug-API, and sfp so that longer
  999. * filename entries can inherit by prefix.
  1000. */
  1001. sfe->flags |= flags;
  1002. sfp->flags |= flags;
  1003. }
  1004. return sfe;
  1005. }
  1006. const char *
  1007. js_SaveScriptFilename(JSContext *cx, const char *filename)
  1008. {
  1009. JSRuntime *rt;
  1010. ScriptFilenameEntry *sfe;
  1011. JSCList *head, *link;
  1012. ScriptFilenamePrefix *sfp;
  1013. rt = cx->runtime;
  1014. JS_ACQUIRE_LOCK(rt->scriptFilenameTableLock);
  1015. sfe = SaveScriptFilename(rt, filename, 0);
  1016. if (!sfe) {
  1017. JS_RELEASE_LOCK(rt->scriptFilenameTableLock);
  1018. JS_ReportOutOfMemory(cx);
  1019. return NULL;
  1020. }
  1021. /*
  1022. * Try to inherit flags by prefix. We assume there won't be more than a
  1023. * few (dozen! ;-) prefixes, so linear search is tolerable.
  1024. * XXXbe every time I've assumed that in the JS engine, I've been wrong!
  1025. */
  1026. for (head = &rt->scriptFilenamePrefixes, link = head->next;
  1027. link != head;
  1028. link = link->next) {
  1029. sfp = (ScriptFilenamePrefix *) link;
  1030. if (!strncmp(sfp->name, filename, sfp->length)) {
  1031. sfe->flags |= sfp->flags;
  1032. break;
  1033. }
  1034. }
  1035. JS_RELEASE_LOCK(rt->scriptFilenameTableLock);
  1036. return sfe->filename;
  1037. }
  1038. const char *
  1039. js_SaveScriptFilenameRT(JSRuntime *rt, const char *filename, uint32 flags)
  1040. {
  1041. ScriptFilenameEntry *sfe;
  1042. /* This may be called very early, via the jsdbgapi.h entry point. */
  1043. if (!rt->scriptFilenameTable && !js_InitRuntimeScriptState(rt))
  1044. return NULL;
  1045. JS_ACQUIRE_LOCK(rt->scriptFilenameTableLock);
  1046. sfe = SaveScriptFilename(rt, filename, flags);
  1047. JS_RELEASE_LOCK(rt->scriptFilenameTableLock);
  1048. if (!sfe)
  1049. return NULL;
  1050. return sfe->filename;
  1051. }
  1052. /*
  1053. * Back up from a saved filename by its offset within its hash table entry.
  1054. */
  1055. #define FILENAME_TO_SFE(fn) \
  1056. ((ScriptFilenameEntry *) ((fn) - offsetof(ScriptFilenameEntry, filename)))
  1057. /*
  1058. * The sfe->key member, redundant given sfe->filename but required by the old
  1059. * jshash.c code, here gives us a useful sanity check. This assertion will
  1060. * very likely botch if someone tries to mark a string that wasn't allocated
  1061. * as an sfe->filename.
  1062. */
  1063. #define ASSERT_VALID_SFE(sfe) JS_ASSERT((sfe)->key == (sfe)->filename)
  1064. uint32
  1065. js_GetScriptFilenameFlags(const char *filename)
  1066. {
  1067. ScriptFilenameEntry *sfe;
  1068. sfe = FILENAME_TO_SFE(filename);
  1069. ASSERT_VALID_SFE(sfe);
  1070. return sfe->flags;
  1071. }
  1072. void
  1073. js_MarkScriptFilename(const char *filename)
  1074. {
  1075. ScriptFilenameEntry *sfe;
  1076. sfe = FILENAME_TO_SFE(filename);
  1077. ASSERT_VALID_SFE(sfe);
  1078. sfe->mark = JS_TRUE;
  1079. }
  1080. static intN
  1081. js_script_filename_marker(JSHashEntry *he, intN i, void *arg)
  1082. {
  1083. ScriptFilenameEntry *sfe = (ScriptFilenameEntry *) he;
  1084. sfe->mark = JS_TRUE;
  1085. return HT_ENUMERATE_NEXT;
  1086. }
  1087. void
  1088. js_MarkScriptFilenames(JSRuntime *rt, JSBool keepAtoms)
  1089. {
  1090. JSCList *head, *link;
  1091. ScriptFilenamePrefix *sfp;
  1092. if (!rt->scriptFilenameTable)
  1093. return;
  1094. if (keepAtoms) {
  1095. JS_HashTableEnumerateEntries(rt->scriptFilenameTable,
  1096. js_script_filename_marker,
  1097. rt);
  1098. }
  1099. for (head = &rt->scriptFilenamePrefixes, link = head->next;
  1100. link != head;
  1101. link = link->next) {
  1102. sfp = (ScriptFilenamePrefix *) link;
  1103. js_MarkScriptFilename(sfp->name);
  1104. }
  1105. }
  1106. static intN
  1107. js_script_filename_sweeper(JSHashEntry *he, intN i, void *arg)
  1108. {
  1109. ScriptFilenameEntry *sfe = (ScriptFilenameEntry *) he;
  1110. if (!sfe->mark)
  1111. return HT_ENUMERATE_REMOVE;
  1112. sfe->mark = JS_FALSE;
  1113. return HT_ENUMERATE_NEXT;
  1114. }
  1115. void
  1116. js_SweepScriptFilenames(JSRuntime *rt)
  1117. {
  1118. if (!rt->scriptFilenameTable)
  1119. return;
  1120. JS_HashTableEnumerateEntries(rt->scriptFilenameTable,
  1121. js_script_filename_sweeper,
  1122. rt);
  1123. #ifdef DEBUG_notme
  1124. #ifdef DEBUG_SFTBL
  1125. printf("script filename table savings so far: %u\n", sftbl_savings);
  1126. #endif
  1127. #endif
  1128. }
  1129. /*
  1130. * JSScript data structures memory alignment:
  1131. *
  1132. * JSScript
  1133. * JSObjectArray script objects' descriptor if JSScript.objectsOffset != 0,
  1134. * use JS_SCRIPT_OBJECTS(script) macro to access it.
  1135. * JSObjectArray script regexps' descriptor if JSScript.regexpsOffset != 0,
  1136. * use JS_SCRIPT_REGEXPS(script) macro to access it.
  1137. * JSTryNoteArray script try notes' descriptor if JSScript.tryNotesOffset
  1138. * != 0, use JS_SCRIPT_TRYNOTES(script) macro to access it.
  1139. * JSAtom *a[] array of JSScript.atomMap.length atoms pointed by
  1140. * JSScript.atomMap.vector if any.
  1141. * JSObject *o[] array of JS_SCRIPT_OBJECTS(script)->length objects if any
  1142. * pointed by JS_SCRIPT_OBJECTS(script)->vector.
  1143. * JSObject *r[] array of JS_SCRIPT_REGEXPS(script)->length regexps if any
  1144. * pointed by JS_SCRIPT_REGEXPS(script)->vector.
  1145. * JSTryNote t[] array of JS_SCRIPT_TRYNOTES(script)->length try notes if any
  1146. * pointed by JS_SCRIPT_TRYNOTES(script)->vector.
  1147. * jsbytecode b[] script bytecode pointed by JSScript.code.
  1148. * jssrcnote s[] script source notes, use SCRIPT_NOTES(script) to access it
  1149. *
  1150. * The alignment avoids gaps between entries as alignment requirement for each
  1151. * subsequent structure or array is the same or divides the alignment
  1152. * requirement for the previous one.
  1153. *
  1154. * The followings asserts checks that assuming that the alignment requirement
  1155. * for JSObjectArray and JSTryNoteArray are sizeof(void *) and for JSTryNote
  1156. * it is sizeof(uint32) as the structure consists of 3 uint32 fields.
  1157. */
  1158. JS_STATIC_ASSERT(sizeof(JSScript) % sizeof(void *) == 0);
  1159. JS_STATIC_ASSERT(sizeof(JSObjectArray) % sizeof(void *) == 0);
  1160. JS_STATIC_ASSERT(sizeof(JSTryNoteArray) == sizeof(JSObjectArray));
  1161. JS_STATIC_ASSERT(sizeof(JSAtom *) == sizeof(JSObject *));
  1162. JS_STATIC_ASSERT(sizeof(JSObject *) % sizeof(uint32) == 0);
  1163. JS_STATIC_ASSERT(sizeof(JSTryNote) == 3 * sizeof(uint32));
  1164. JS_STATIC_ASSERT(sizeof(uint32) % sizeof(jsbytecode) == 0);
  1165. JS_STATIC_ASSERT(sizeof(jsbytecode) % sizeof(jssrcnote) == 0);
  1166. /*
  1167. * Check that uint8 offset for object, upvar, regexp, and try note arrays is
  1168. * sufficient.
  1169. */
  1170. JS_STATIC_ASSERT(sizeof(JSScript) + 2 * sizeof(JSObjectArray) +
  1171. sizeof(JSUpvarArray) < JS_BIT(8));
  1172. JSScript *
  1173. js_NewScript(JSContext *cx, uint32 length, uint32 nsrcnotes, uint32 natoms,
  1174. uint32 nobjects, uint32 nupvars, uint32 nregexps,
  1175. uint32 ntrynotes)
  1176. {
  1177. size_t size, vectorSize;
  1178. JSScript *script;
  1179. uint8 *cursor;
  1180. size = sizeof(JSScript) +
  1181. sizeof(JSAtom *) * natoms +
  1182. length * sizeof(jsbytecode) +
  1183. nsrcnotes * sizeof(jssrcnote);
  1184. if (nobjects != 0)
  1185. size += sizeof(JSObjectArray) + nobjects * sizeof(JSObject *);
  1186. if (nupvars != 0)
  1187. size += sizeof(JSUpvarArray) + nupvars * sizeof(uint32);
  1188. if (nregexps != 0)
  1189. size += sizeof(JSObjectArray) + nregexps * sizeof(JSObject *);
  1190. if (ntrynotes != 0)
  1191. size += sizeof(JSTryNoteArray) + ntrynotes * sizeof(JSTryNote);
  1192. script = (JSScript *) JS_malloc(cx, size);
  1193. if (!script)
  1194. return NULL;
  1195. memset(script, 0, sizeof(JSScript));
  1196. script->length = length;
  1197. script->version = cx->version;
  1198. cursor = (uint8 *)script + sizeof(JSScript);
  1199. if (nobjects != 0) {
  1200. script->objectsOffset = (uint8)(cursor - (uint8 *)script);
  1201. cursor += sizeof(JSObjectArray);
  1202. }
  1203. if (nupvars != 0) {
  1204. script->upvarsOffset = (uint8)(cursor - (uint8 *)script);
  1205. cursor += sizeof(JSUpvarArray);
  1206. }
  1207. if (nregexps != 0) {
  1208. script->regexpsOffset = (uint8)(cursor - (uint8 *)script);
  1209. cursor += sizeof(JSObjectArray);
  1210. }
  1211. if (ntrynotes != 0) {
  1212. script->trynotesOffset = (uint8)(cursor - (uint8 *)script);
  1213. cursor += sizeof(JSTryNoteArray);
  1214. }
  1215. if (natoms != 0) {
  1216. script->atomMap.length = natoms;
  1217. script->atomMap.vector = (JSAtom **)cursor;
  1218. vectorSize = natoms * sizeof(script->atomMap.vector[0]);
  1219. /*
  1220. * Clear object map's vector so the GC tracing can run when not yet
  1221. * all atoms are copied to the array.
  1222. */
  1223. memset(cursor, 0, vectorSize);
  1224. cursor += vectorSize;
  1225. }
  1226. if (nobjects != 0) {
  1227. JS_SCRIPT_OBJECTS(script)->length = nobjects;
  1228. JS_SCRIPT_OBJECTS(script)->vector = (JSObject **)cursor;
  1229. vectorSize = nobjects * sizeof(JS_SCRIPT_OBJECTS(script)->vector[0]);
  1230. memset(cursor, 0, vectorSize);
  1231. cursor += vectorSize;
  1232. }
  1233. if (nupvars != 0) {
  1234. JS_SCRIPT_UPVARS(script)->length = nupvars;
  1235. JS_SCRIPT_UPVARS(script)->vector = (uint32 *)cursor;
  1236. vectorSize = nupvars * sizeof(JS_SCRIPT_UPVARS(script)->vector[0]);
  1237. memset(cursor, 0, vectorSize);
  1238. cursor += vectorSize;
  1239. }
  1240. if (nregexps != 0) {
  1241. JS_SCRIPT_REGEXPS(script)->length = nregexps;
  1242. JS_SCRIPT_REGEXPS(script)->vector = (JSObject **)cursor;
  1243. vectorSize = nregexps * sizeof(JS_SCRIPT_REGEXPS(script)->vector[0]);
  1244. memset(cursor, 0, vectorSize);
  1245. cursor += vectorSize;
  1246. }
  1247. if (ntrynotes != 0) {
  1248. JS_SCRIPT_TRYNOTES(script)->length = ntrynotes;
  1249. JS_SCRIPT_TRYNOTES(script)->vector = (JSTryNote *)cursor;
  1250. vectorSize = ntrynotes * sizeof(JS_SCRIPT_TRYNOTES(script)->vector[0]);
  1251. #ifdef DEBUG
  1252. memset(cursor, 0, vectorSize);
  1253. #endif
  1254. cursor += vectorSize;
  1255. }
  1256. script->code = script->main = (jsbytecode *)cursor;
  1257. JS_ASSERT(cursor +
  1258. length * sizeof(jsbytecode) +
  1259. nsrcnotes * sizeof(jssrcnote) ==
  1260. (uint8 *)script + size);
  1261. #ifdef CHECK_SCRIPT_OWNER
  1262. script->owner = cx->thread;
  1263. #endif
  1264. return script;
  1265. }
  1266. JSScript *
  1267. js_NewScriptFromCG(JSContext *cx, JSCodeGenerator *cg)
  1268. {
  1269. uint32 mainLength, prologLength, nsrcnotes, nfixed;
  1270. JSScript *script;
  1271. const char *filename;
  1272. JSFunction *fun;
  1273. /* The counts of indexed things must be checked during code generation. */
  1274. JS_ASSERT(cg->atomList.count <= INDEX_LIMIT);
  1275. JS_ASSERT(cg->objectList.length <= INDEX_LIMIT);
  1276. JS_ASSERT(cg->regexpList.length <= INDEX_LIMIT);
  1277. mainLength = CG_OFFSET(cg);
  1278. prologLength = CG_PROLOG_OFFSET(cg);
  1279. CG_COUNT_FINAL_SRCNOTES(cg, nsrcnotes);
  1280. script = js_NewScript(cx, prologLength + mainLength, nsrcnotes,
  1281. cg->atomList.count, cg->objectList.length,
  1282. cg->upvarList.count, cg->regexpList.length,
  1283. cg->ntrynotes);
  1284. if (!script)
  1285. return NULL;
  1286. /* Now that we have script, error control flow must go to label bad. */
  1287. script->main += prologLength;
  1288. memcpy(script->code, CG_PROLOG_BASE(cg), prologLength * sizeof(jsbytecode));
  1289. memcpy(script->main, CG_BASE(cg), mainLength * sizeof(jsbytecode));
  1290. nfixed = (cg->treeContext.flags & TCF_IN_FUNCTION)
  1291. ? cg->treeContext.u.fun->u.i.nvars
  1292. : cg->treeContext.ngvars + cg->regexpList.length;
  1293. JS_ASSERT(nfixed < SLOTNO_LIMIT);
  1294. script->nfixed = (uint16) nfixed;
  1295. js_InitAtomMap(cx, &script->atomMap, &cg->atomList);
  1296. filename = cg->treeContext.parseContext->tokenStream.filename;
  1297. if (filename) {
  1298. script->filename = js_SaveScriptFilename(cx, filename);
  1299. if (!script->filename)
  1300. goto bad;
  1301. }
  1302. script->lineno = cg->firstLine;
  1303. if (script->nfixed + cg->maxStackDepth >= JS_BIT(16)) {
  1304. js_ReportCompileErrorNumber(cx, CG_TS(cg), NULL, JSREPORT_ERROR,
  1305. JSMSG_NEED_DIET, "script");
  1306. goto bad;
  1307. }
  1308. script->nslots = script->nfixed + cg->maxStackDepth;
  1309. script->staticDepth = cg->staticDepth;
  1310. script->principals = cg->treeContext.parseContext->principals;
  1311. if (script->principals)
  1312. JSPRINCIPALS_HOLD(cx, script->principals);
  1313. if (!js_FinishTakingSrcNotes(cx, cg, SCRIPT_NOTES(script)))
  1314. goto bad;
  1315. if (cg->ntrynotes != 0)
  1316. js_FinishTakingTryNotes(cg, JS_SCRIPT_TRYNOTES(script));
  1317. if (cg->objectList.length != 0)
  1318. FinishParsedObjects(&cg->objectList, JS_SCRIPT_OBJECTS(script));
  1319. if (cg->regexpList.length != 0)
  1320. FinishParsedObjects(&cg->regexpList, JS_SCRIPT_REGEXPS(script));
  1321. if (cg->treeContext.flags & TCF_NO_SCRIPT_RVAL)
  1322. script->flags |= JSSF_NO_SCRIPT_RVAL;
  1323. if (cg->upvarList.count != 0) {
  1324. JS_ASSERT(cg->upvarList.count <= cg->upvarMap.length);
  1325. memcpy(JS_SCRIPT_UPVARS(script)->vector, cg->upvarMap.vector,
  1326. cg->upvarList.count * sizeof(uint32));
  1327. ATOM_LIST_INIT(&cg->upvarList);
  1328. JS_free(cx, cg->upvarMap.vector);
  1329. cg->upvarMap.vector = NULL;
  1330. }
  1331. /*
  1332. * We initialize fun->u.script to be the script constructed above
  1333. * so that the debugger has a valid FUN_SCRIPT(fun).
  1334. */
  1335. fun = NULL;
  1336. if (cg->treeContext.flags & TCF_IN_FUNCTION) {
  1337. fun = cg->treeContext.u.fun;
  1338. JS_ASSERT(FUN_INTERPRETED(fun) && !FUN_SCRIPT(fun));
  1339. JS_ASSERT_IF(script->upvarsOffset != 0,
  1340. JS_SCRIPT_UPVARS(script)->length == fun->u.i.nupvars);
  1341. js_FreezeLocalNames(cx, fun);
  1342. fun->u.i.script = script;
  1343. #ifdef CHECK_SCRIPT_OWNER
  1344. script->owner = NULL;
  1345. #endif
  1346. if (cg->treeContext.flags & TCF_FUN_HEAVYWEIGHT)
  1347. fun->flags |= JSFUN_HEAVYWEIGHT;
  1348. }
  1349. /* Tell the debugger about this compiled script. */
  1350. js_CallNewScriptHook(cx, script, fun);
  1351. return script;
  1352. bad:
  1353. js_DestroyScript(cx, script);
  1354. return NULL;
  1355. }
  1356. JS_FRIEND_API(void)
  1357. js_CallNewScriptHook(JSContext *cx, JSScript *script, JSFunction *fun)
  1358. {
  1359. JSNewScriptHook hook;
  1360. hook = cx->debugHooks->newScriptHook;
  1361. if (hook) {
  1362. JS_KEEP_ATOMS(cx->runtime);
  1363. hook(cx, script->filename, script->lineno, script, fun,
  1364. cx->debugHooks->newScriptHookData);
  1365. JS_UNKEEP_ATOMS(cx->runtime);
  1366. }
  1367. }
  1368. JS_FRIEND_API(void)
  1369. js_CallDestroyScriptHook(JSContext *cx, JSScript *script)
  1370. {
  1371. JSDestroyScriptHook hook;
  1372. hook = cx->debugHooks->destroyScriptHook;
  1373. if (hook)
  1374. hook(cx, script, cx->debugHooks->destroyScriptHookData);
  1375. }
  1376. void
  1377. js_DestroyScript(JSContext *cx, JSScript *script)
  1378. {
  1379. js_CallDestroyScriptHook(cx, script);
  1380. JS_ClearScriptTraps(cx, script);
  1381. if (script->principals)
  1382. JSPRINCIPALS_DROP(cx, script->principals);
  1383. if (JS_GSN_CACHE(cx).code == script->code)
  1384. JS_CLEAR_GSN_CACHE(cx);
  1385. /*
  1386. * The GC flushes all property caches, so no need to purge just the
  1387. * entries for this script.
  1388. *
  1389. * JS_THREADSAFE note: js_FlushPropertyCacheForScript flushes only the
  1390. * current thread's property cache, so a script not owned by a function
  1391. * or object, which hands off lifetime management for that script to the
  1392. * GC, must be used by only one thread over its lifetime.
  1393. *
  1394. * This should be an API-compatible change, since a script is never safe
  1395. * against premature GC if shared among threads without a rooted object
  1396. * wrapping it to protect the script's mapped atoms against GC. We use
  1397. * script->owner to enforce this requirement via assertions.
  1398. */
  1399. #ifdef CHECK_SCRIPT_OWNER
  1400. JS_ASSERT_IF(cx->runtime->gcRunning, !script->owner);
  1401. #endif
  1402. if (!cx->runtime->gcRunning) {
  1403. if (!(cx->fp && (cx->fp->flags & JSFRAME_EVAL))) {
  1404. #ifdef CHECK_SCRIPT_OWNER
  1405. JS_ASSERT(script->owner == cx->thread);
  1406. #endif
  1407. js_FlushPropertyCacheForScript(cx, script);
  1408. }
  1409. }
  1410. JS_free(cx, script);
  1411. }
  1412. void
  1413. js_TraceScript(JSTracer *trc, JSScript *script)
  1414. {
  1415. JSAtomMap *map;
  1416. uintN i, length;
  1417. JSAtom **vector;
  1418. jsval v;
  1419. JSObjectArray *objarray;
  1420. map = &script->atomMap;
  1421. length = map->length;
  1422. vector = map->vector;
  1423. for (i = 0; i < length; i++) {
  1424. v = ATOM_KEY(vector[i]);
  1425. if (JSVAL_IS_TRACEABLE(v)) {
  1426. JS_SET_TRACING_INDEX(trc, "atomMap", i);
  1427. JS_CallTracer(trc, JSVAL_TO_TRACEABLE(v), JSVAL_TRACE_KIND(v));
  1428. }
  1429. }

Large files files are truncated, but you can click here to view the full file