Code

r11451@tres: ted | 2006-04-17 22:21:33 -0700
[inkscape.git] / src / dom / js / jsscript.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  *
3  * ***** BEGIN LICENSE BLOCK *****
4  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is Mozilla Communicator client code, released
17  * March 31, 1998.
18  *
19  * The Initial Developer of the Original Code is
20  * Netscape Communications Corporation.
21  * Portions created by the Initial Developer are Copyright (C) 1998
22  * the Initial Developer. All Rights Reserved.
23  *
24  * Contributor(s):
25  *
26  * Alternatively, the contents of this file may be used under the terms of
27  * either of the GNU General Public License Version 2 or later (the "GPL"),
28  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29  * in which case the provisions of the GPL or the LGPL are applicable instead
30  * of those above. If you wish to allow use of your version of this file only
31  * under the terms of either the GPL or the LGPL, and not to allow others to
32  * use your version of this file under the terms of the MPL, indicate your
33  * decision by deleting the provisions above and replace them with the notice
34  * and other provisions required by the GPL or the LGPL. If you do not delete
35  * the provisions above, a recipient may use your version of this file under
36  * the terms of any one of the MPL, the GPL or the LGPL.
37  *
38  * ***** 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 "jsconfig.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 "jsscript.h"
60 #if JS_HAS_XDR
61 #include "jsxdrapi.h"
62 #endif
64 #if JS_HAS_SCRIPT_OBJECT
66 #if JS_HAS_TOSOURCE
67 static JSBool
68 script_toSource(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
69                 jsval *rval)
70 {
71     JSScript *script;
72     size_t i, j, k, n;
73     char buf[16];
74     jschar *s, *t;
75     uint32 indent;
76     JSString *str;
78     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
79         return JS_FALSE;
80     script = (JSScript *) JS_GetPrivate(cx, obj);
82     /* Let n count the source string length, j the "front porch" length. */
83     j = JS_snprintf(buf, sizeof buf, "(new %s(", js_ScriptClass.name);
84     n = j + 2;
85     if (!script) {
86         /* Let k count the constructor argument string length. */
87         k = 0;
88         s = NULL;               /* quell GCC overwarning */
89     } else {
90         indent = 0;
91         if (argc && !js_ValueToECMAUint32(cx, argv[0], &indent))
92             return JS_FALSE;
93         str = JS_DecompileScript(cx, script, "Script.prototype.toSource",
94                                  (uintN)indent);
95         if (!str)
96             return JS_FALSE;
97         str = js_QuoteString(cx, str, '\'');
98         if (!str)
99             return JS_FALSE;
100         s = JSSTRING_CHARS(str);
101         k = JSSTRING_LENGTH(str);
102         n += k;
103     }
105     /* Allocate the source string and copy into it. */
106     t = (jschar *) JS_malloc(cx, (n + 1) * sizeof(jschar));
107     if (!t)
108         return JS_FALSE;
109     for (i = 0; i < j; i++)
110         t[i] = buf[i];
111     for (j = 0; j < k; i++, j++)
112         t[i] = s[j];
113     t[i++] = ')';
114     t[i++] = ')';
115     t[i] = 0;
117     /* Create and return a JS string for t. */
118     str = JS_NewUCString(cx, t, n);
119     if (!str) {
120         JS_free(cx, t);
121         return JS_FALSE;
122     }
123     *rval = STRING_TO_JSVAL(str);
124     return JS_TRUE;
126 #endif /* JS_HAS_TOSOURCE */
128 static JSBool
129 script_toString(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
130                 jsval *rval)
132     JSScript *script;
133     uint32 indent;
134     JSString *str;
136     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
137         return JS_FALSE;
138     script = (JSScript *) JS_GetPrivate(cx, obj);
139     if (!script) {
140         *rval = STRING_TO_JSVAL(cx->runtime->emptyString);
141         return JS_TRUE;
142     }
144     indent = 0;
145     if (argc && !js_ValueToECMAUint32(cx, argv[0], &indent))
146         return JS_FALSE;
147     str = JS_DecompileScript(cx, script, "Script.prototype.toString",
148                              (uintN)indent);
149     if (!str)
150         return JS_FALSE;
151     *rval = STRING_TO_JSVAL(str);
152     return JS_TRUE;
155 static JSBool
156 script_compile(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
157                jsval *rval)
159     JSScript *oldscript, *script;
160     JSString *str;
161     JSStackFrame *fp, *caller;
162     JSObject *scopeobj;
163     const char *file;
164     uintN line;
165     JSPrincipals *principals;
167     /* Make sure obj is a Script object. */
168     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
169         return JS_FALSE;
171     /* If no args, leave private undefined and return early. */
172     if (argc == 0)
173         goto out;
175     /* Otherwise, the first arg is the script source to compile. */
176     str = js_ValueToString(cx, argv[0]);
177     if (!str)
178         return JS_FALSE;
180     /* Compile using the caller's scope chain, which js_Invoke passes to fp. */
181     fp = cx->fp;
182     caller = JS_GetScriptedCaller(cx, fp);
183     JS_ASSERT(!caller || fp->scopeChain == caller->scopeChain);
185     scopeobj = NULL;
186     if (argc >= 2) {
187         if (!js_ValueToObject(cx, argv[1], &scopeobj))
188             return JS_FALSE;
189         argv[1] = OBJECT_TO_JSVAL(scopeobj);
190     }
191     if (caller) {
192         if (!scopeobj)
193             scopeobj = caller->scopeChain;
195         file = caller->script->filename;
196         line = js_PCToLineNumber(cx, caller->script, caller->pc);
197         principals = JS_EvalFramePrincipals(cx, fp, caller);
198     } else {
199         file = NULL;
200         line = 0;
201         principals = NULL;
202     }
204     /*
205      * Compile the new script using the caller's scope chain, a la eval().
206      * Unlike jsobj.c:obj_eval, however, we do not set JSFRAME_EVAL in fp's
207      * flags, because compilation is here separated from execution, and the
208      * run-time scope chain may not match the compile-time.  JSFRAME_EVAL is
209      * tested in jsemit.c and jsscan.c to optimize based on identity of run-
210      * and compile-time scope.
211      */
212     script = JS_CompileUCScriptForPrincipals(cx, scopeobj, principals,
213                                              JSSTRING_CHARS(str),
214                                              JSSTRING_LENGTH(str),
215                                              file, line);
216     if (!script)
217         return JS_FALSE;
219     /* Swap script for obj's old script, if any. */
220     oldscript = (JSScript *) JS_GetPrivate(cx, obj);
221     if (!JS_SetPrivate(cx, obj, script)) {
222         js_DestroyScript(cx, script);
223         return JS_FALSE;
224     }
225     if (oldscript)
226         js_DestroyScript(cx, oldscript);
228     script->object = obj;
229 out:
230     /* Return the object. */
231     *rval = OBJECT_TO_JSVAL(obj);
232     return JS_TRUE;
235 static JSBool
236 script_exec(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
238     JSScript *script;
239     JSObject *scopeobj, *parent;
240     JSStackFrame *fp, *caller;
242     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
243         return JS_FALSE;
244     script = (JSScript *) JS_GetPrivate(cx, obj);
245     if (!script)
246         return JS_TRUE;
248     scopeobj = NULL;
249     if (argc) {
250         if (!js_ValueToObject(cx, argv[0], &scopeobj))
251             return JS_FALSE;
252         argv[0] = OBJECT_TO_JSVAL(scopeobj);
253     }
255     /*
256      * Emulate eval() by using caller's this, var object, sharp array, etc.,
257      * all propagated by js_Execute via a non-null fourth (down) argument to
258      * js_Execute.  If there is no scripted caller, js_Execute uses its second
259      * (chain) argument to set the exec frame's varobj, thisp, and scopeChain.
260      *
261      * Unlike eval, which the compiler detects, Script.prototype.exec may be
262      * called from a lightweight function, or even from native code (in which
263      * case fp->varobj and fp->scopeChain are null).  If exec is called from
264      * a lightweight function, we will need to get a Call object representing
265      * its frame, to act as the var object and scope chain head.
266      */
267     fp = cx->fp;
268     caller = JS_GetScriptedCaller(cx, fp);
269     if (caller && !caller->varobj) {
270         /* Called from a lightweight function. */
271         JS_ASSERT(caller->fun && !(caller->fun->flags & JSFUN_HEAVYWEIGHT));
273         /* Scope chain links from Call object to callee's parent. */
274         parent = OBJ_GET_PARENT(cx, JSVAL_TO_OBJECT(caller->argv[-2]));
275         if (!js_GetCallObject(cx, caller, parent))
276             return JS_FALSE;
277     }
279     if (!scopeobj) {
280         /* No scope object passed in: try to use the caller's scope chain. */
281         if (caller) {
282             /*
283              * Load caller->scopeChain after the conditional js_GetCallObject
284              * call above, which resets scopeChain as well as varobj.
285              */
286             scopeobj = caller->scopeChain;
287         } else {
288             /*
289              * Called from native code, so we don't know what scope object to
290              * use.  We could use parent (see above), but Script.prototype.exec
291              * might be a shared/sealed "superglobal" method.  A more general
292              * approach would use cx->globalObject, which will be the same as
293              * exec.__parent__ in the non-superglobal case.  In the superglobal
294              * case it's the right object: the global, not the superglobal.
295              */
296             scopeobj = cx->globalObject;
297         }
298     }
300     return js_Execute(cx, scopeobj, script, caller, JSFRAME_EVAL, rval);
303 #if JS_HAS_XDR
305 static JSBool
306 XDRAtomListElement(JSXDRState *xdr, JSAtomListElement *ale)
308     jsval value;
309     jsatomid index;
311     if (xdr->mode == JSXDR_ENCODE)
312         value = ATOM_KEY(ALE_ATOM(ale));
314     index = ALE_INDEX(ale);
315     if (!JS_XDRUint32(xdr, &index))
316         return JS_FALSE;
317     ALE_SET_INDEX(ale, index);
319     if (!JS_XDRValue(xdr, &value))
320         return JS_FALSE;
322     if (xdr->mode == JSXDR_DECODE) {
323         if (!ALE_SET_ATOM(ale, js_AtomizeValue(xdr->cx, value, 0)))
324             return JS_FALSE;
325     }
326     return JS_TRUE;
329 static JSBool
330 XDRAtomMap(JSXDRState *xdr, JSAtomMap *map)
332     uint32 length;
333     uintN i;
334     JSBool ok;
336     if (xdr->mode == JSXDR_ENCODE)
337         length = map->length;
339     if (!JS_XDRUint32(xdr, &length))
340         return JS_FALSE;
342     if (xdr->mode == JSXDR_DECODE) {
343         JSContext *cx;
344         void *mark;
345         JSAtomList al;
346         JSAtomListElement *ale;
348         cx = xdr->cx;
349         mark = JS_ARENA_MARK(&cx->tempPool);
350         ATOM_LIST_INIT(&al);
351         for (i = 0; i < length; i++) {
352             JS_ARENA_ALLOCATE_TYPE(ale, JSAtomListElement, &cx->tempPool);
353             if (!ale ||
354                 !XDRAtomListElement(xdr, ale)) {
355                 if (!ale)
356                     JS_ReportOutOfMemory(cx);
357                 JS_ARENA_RELEASE(&cx->tempPool, mark);
358                 return JS_FALSE;
359             }
360             ALE_SET_NEXT(ale, al.list);
361             al.count++;
362             al.list = ale;
363         }
364         ok = js_InitAtomMap(cx, map, &al);
365         JS_ARENA_RELEASE(&cx->tempPool, mark);
366         return ok;
367     }
369     if (xdr->mode == JSXDR_ENCODE) {
370         JSAtomListElement ale;
372         for (i = 0; i < map->length; i++) {
373             ALE_SET_ATOM(&ale, map->vector[i]);
374             ALE_SET_INDEX(&ale, i);
375             if (!XDRAtomListElement(xdr, &ale))
376                 return JS_FALSE;
377         }
378     }
379     return JS_TRUE;
382 JSBool
383 js_XDRScript(JSXDRState *xdr, JSScript **scriptp, JSBool *hasMagic)
385     JSContext *cx;
386     JSScript *script, *newscript;
387     uint32 length, lineno, depth, magic, nsrcnotes, ntrynotes;
388     uint32 prologLength, version;
389     JSBool filenameWasSaved;
390     jssrcnote *notes, *sn;
392     cx = xdr->cx;
393     script = *scriptp;
394     nsrcnotes = ntrynotes = 0;
395     filenameWasSaved = JS_FALSE;
396     notes = NULL;
398     /*
399      * Encode prologLength and version after script->length (_2 or greater),
400      * but decode both new (>= _2) and old, prolog&version-free (_1) scripts.
401      * Version _3 supports principals serialization.  Version _4 reorders the
402      * nsrcnotes and ntrynotes fields to come before everything except magic,
403      * length, prologLength, and version, so that srcnote and trynote storage
404      * can be allocated as part of the JSScript (along with bytecode storage).
405      */
406     if (xdr->mode == JSXDR_ENCODE)
407         magic = JSXDR_MAGIC_SCRIPT_CURRENT;
408     if (!JS_XDRUint32(xdr, &magic))
409         return JS_FALSE;
410     if (magic != JSXDR_MAGIC_SCRIPT_4 &&
411         magic != JSXDR_MAGIC_SCRIPT_3 &&
412         magic != JSXDR_MAGIC_SCRIPT_2 &&
413         magic != JSXDR_MAGIC_SCRIPT_1) {
414         if (!hasMagic) {
415             JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
416                                  JSMSG_BAD_SCRIPT_MAGIC);
417             return JS_FALSE;
418         }
419         *hasMagic = JS_FALSE;
420         return JS_TRUE;
421     }
422     if (hasMagic)
423         *hasMagic = JS_TRUE;
425     if (xdr->mode == JSXDR_ENCODE) {
426         length = script->length;
427         prologLength = PTRDIFF(script->main, script->code, jsbytecode);
428         JS_ASSERT((int16)script->version != JSVERSION_UNKNOWN);
429         version = (uint32)script->version | (script->numGlobalVars << 16);
430         lineno = (uint32)script->lineno;
431         depth = (uint32)script->depth;
433         /* Count the srcnotes, keeping notes pointing at the first one. */
434         notes = SCRIPT_NOTES(script);
435         for (sn = notes; !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn))
436             continue;
437         nsrcnotes = PTRDIFF(sn, notes, jssrcnote);
438         nsrcnotes++;            /* room for the terminator */
440         /* Count the trynotes. */
441         if (script->trynotes) {
442             while (script->trynotes[ntrynotes].catchStart)
443                 ntrynotes++;
444             ntrynotes++;        /* room for the end marker */
445         }
446     }
448     if (!JS_XDRUint32(xdr, &length))
449         return JS_FALSE;
450     if (magic >= JSXDR_MAGIC_SCRIPT_2) {
451         if (!JS_XDRUint32(xdr, &prologLength))
452             return JS_FALSE;
453         if (!JS_XDRUint32(xdr, &version))
454             return JS_FALSE;
456         /* To fuse allocations, we need srcnote and trynote counts early. */
457         if (magic >= JSXDR_MAGIC_SCRIPT_4) {
458             if (!JS_XDRUint32(xdr, &nsrcnotes))
459                 return JS_FALSE;
460             if (!JS_XDRUint32(xdr, &ntrynotes))
461                 return JS_FALSE;
462         }
463     }
465     if (xdr->mode == JSXDR_DECODE) {
466         script = js_NewScript(cx, length, nsrcnotes, ntrynotes);
467         if (!script)
468             return JS_FALSE;
469         if (magic >= JSXDR_MAGIC_SCRIPT_2) {
470             script->main += prologLength;
471             script->version = (JSVersion) (version & 0xffff);
472             script->numGlobalVars = (uint16) (version >> 16);
474             /* If we know nsrcnotes, we allocated space for notes in script. */
475             if (magic >= JSXDR_MAGIC_SCRIPT_4)
476                 notes = SCRIPT_NOTES(script);
477         }
478         *scriptp = script;
479     }
481     /*
482      * Control hereafter must goto error on failure, in order for the DECODE
483      * case to destroy script and conditionally free notes, which if non-null
484      * in the (DECODE and magic < _4) case must point at a temporary vector
485      * allocated just below.
486      */
487     if (!JS_XDRBytes(xdr, (char *)script->code, length * sizeof(jsbytecode)) ||
488         !XDRAtomMap(xdr, &script->atomMap)) {
489         goto error;
490     }
492     if (magic < JSXDR_MAGIC_SCRIPT_4) {
493         if (!JS_XDRUint32(xdr, &nsrcnotes))
494             goto error;
495         if (xdr->mode == JSXDR_DECODE) {
496             notes = (jssrcnote *) JS_malloc(cx, nsrcnotes * sizeof(jssrcnote));
497             if (!notes)
498                 goto error;
499         }
500     }
502     if (!JS_XDRBytes(xdr, (char *)notes, nsrcnotes * sizeof(jssrcnote)) ||
503         !JS_XDRCStringOrNull(xdr, (char **)&script->filename) ||
504         !JS_XDRUint32(xdr, &lineno) ||
505         !JS_XDRUint32(xdr, &depth) ||
506         (magic < JSXDR_MAGIC_SCRIPT_4 && !JS_XDRUint32(xdr, &ntrynotes))) {
507         goto error;
508     }
510     /* Script principals transcoding support comes with versions >= _3. */
511     if (magic >= JSXDR_MAGIC_SCRIPT_3) {
512         JSPrincipals *principals;
513         uint32 encodeable;
515         if (xdr->mode == JSXDR_ENCODE) {
516             principals = script->principals;
517             encodeable = (cx->runtime->principalsTranscoder != NULL);
518             if (!JS_XDRUint32(xdr, &encodeable))
519                 goto error;
520             if (encodeable &&
521                 !cx->runtime->principalsTranscoder(xdr, &principals)) {
522                 goto error;
523             }
524         } else {
525             if (!JS_XDRUint32(xdr, &encodeable))
526                 goto error;
527             if (encodeable) {
528                 if (!cx->runtime->principalsTranscoder) {
529                     JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
530                                          JSMSG_CANT_DECODE_PRINCIPALS);
531                     goto error;
532                 }
533                 if (!cx->runtime->principalsTranscoder(xdr, &principals))
534                     goto error;
535                 script->principals = principals;
536             }
537         }
538     }
540     if (xdr->mode == JSXDR_DECODE) {
541         const char *filename = script->filename;
542         if (filename) {
543             filename = js_SaveScriptFilename(cx, filename);
544             if (!filename)
545                 goto error;
546             JS_free(cx, (void *) script->filename);
547             script->filename = filename;
548             filenameWasSaved = JS_TRUE;
549         }
550         script->lineno = (uintN)lineno;
551         script->depth = (uintN)depth;
553         if (magic < JSXDR_MAGIC_SCRIPT_4) {
554             /*
555              * Argh, we have to reallocate script, copy notes into the extra
556              * space after the bytecodes, and free the temporary notes vector.
557              * First, add enough slop to nsrcnotes so we can align the address
558              * after the srcnotes of the first trynote.
559              */
560             uint32 osrcnotes = nsrcnotes;
562             if (ntrynotes)
563                 nsrcnotes += JSTRYNOTE_ALIGNMASK;
564             newscript = (JSScript *) JS_realloc(cx, script,
565                                                 sizeof(JSScript) +
566                                                 length * sizeof(jsbytecode) +
567                                                 nsrcnotes * sizeof(jssrcnote) +
568                                                 ntrynotes * sizeof(JSTryNote));
569             if (!newscript)
570                 goto error;
572             *scriptp = script = newscript;
573             script->code = (jsbytecode *)(script + 1);
574             script->main = script->code + prologLength;
575             memcpy(script->code + length, notes, osrcnotes * sizeof(jssrcnote));
576             JS_free(cx, (void *) notes);
577             notes = NULL;
578             if (ntrynotes) {
579                 script->trynotes = (JSTryNote *)
580                                    ((jsword)(SCRIPT_NOTES(script) + nsrcnotes) &
581                                     ~(jsword)JSTRYNOTE_ALIGNMASK);
582                 memset(script->trynotes, 0, ntrynotes * sizeof(JSTryNote));
583             }
584         }
585     }
587     while (ntrynotes) {
588         JSTryNote *tn = &script->trynotes[--ntrynotes];
589         uint32 start = (uint32) tn->start,
590                catchLength = (uint32) tn->length,
591                catchStart = (uint32) tn->catchStart;
593         if (!JS_XDRUint32(xdr, &start) ||
594             !JS_XDRUint32(xdr, &catchLength) ||
595             !JS_XDRUint32(xdr, &catchStart)) {
596             goto error;
597         }
598         tn->start = (ptrdiff_t) start;
599         tn->length = (ptrdiff_t) catchLength;
600         tn->catchStart = (ptrdiff_t) catchStart;
601     }
602     return JS_TRUE;
604   error:
605     if (xdr->mode == JSXDR_DECODE) {
606         if (script->filename && !filenameWasSaved) {
607             JS_free(cx, (void *) script->filename);
608             script->filename = NULL;
609         }
610         if (notes && magic < JSXDR_MAGIC_SCRIPT_4)
611             JS_free(cx, (void *) notes);
612         js_DestroyScript(cx, script);
613         *scriptp = NULL;
614     }
615     return JS_FALSE;
618 #if JS_HAS_XDR_FREEZE_THAW
619 /*
620  * These cannot be exposed to web content, and chrome does not need them, so
621  * we take them out of the Mozilla client altogether.  Fortunately, there is
622  * no way to serialize a native function (see fun_xdrObject in jsfun.c).
623  */
625 static JSBool
626 script_freeze(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
627               jsval *rval)
629     JSXDRState *xdr;
630     JSScript *script;
631     JSBool ok, hasMagic;
632     uint32 len;
633     void *buf;
634     JSString *str;
636     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
637         return JS_FALSE;
638     script = (JSScript *) JS_GetPrivate(cx, obj);
639     if (!script)
640         return JS_TRUE;
642     /* create new XDR */
643     xdr = JS_XDRNewMem(cx, JSXDR_ENCODE);
644     if (!xdr)
645         return JS_FALSE;
647     /* write  */
648     ok = js_XDRScript(xdr, &script, &hasMagic);
649     if (!ok)
650         goto out;
651     if (!hasMagic) {
652         *rval = JSVAL_VOID;
653         goto out;
654     }
656     buf = JS_XDRMemGetData(xdr, &len);
657     if (!buf) {
658         ok = JS_FALSE;
659         goto out;
660     }
662     JS_ASSERT((jsword)buf % sizeof(jschar) == 0);
663     len /= sizeof(jschar);
664     str = JS_NewUCStringCopyN(cx, (jschar *)buf, len);
665     if (!str) {
666         ok = JS_FALSE;
667         goto out;
668     }
670 #if IS_BIG_ENDIAN
671   {
672     jschar *chars;
673     uint32 i;
675     /* Swap bytes in Unichars to keep frozen strings machine-independent. */
676     chars = JS_GetStringChars(str);
677     for (i = 0; i < len; i++)
678         chars[i] = JSXDR_SWAB16(chars[i]);
679   }
680 #endif
681     *rval = STRING_TO_JSVAL(str);
683 out:
684     JS_XDRDestroy(xdr);
685     return ok;
688 static JSBool
689 script_thaw(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
690             jsval *rval)
692     JSXDRState *xdr;
693     JSString *str;
694     void *buf;
695     uint32 len;
696     JSScript *script, *oldscript;
697     JSBool ok, hasMagic;
699     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
700         return JS_FALSE;
702     if (argc == 0)
703         return JS_TRUE;
704     str = js_ValueToString(cx, argv[0]);
705     if (!str)
706         return JS_FALSE;
708     /* create new XDR */
709     xdr = JS_XDRNewMem(cx, JSXDR_DECODE);
710     if (!xdr)
711         return JS_FALSE;
713     buf = JS_GetStringChars(str);
714     len = JS_GetStringLength(str);
715 #if IS_BIG_ENDIAN
716   {
717     jschar *from, *to;
718     uint32 i;
720     /* Swap bytes in Unichars to keep frozen strings machine-independent. */
721     from = (jschar *)buf;
722     to = (jschar *) JS_malloc(cx, len * sizeof(jschar));
723     if (!to) {
724         JS_XDRDestroy(xdr);
725         return JS_FALSE;
726     }
727     for (i = 0; i < len; i++)
728         to[i] = JSXDR_SWAB16(from[i]);
729     buf = (char *)to;
730   }
731 #endif
732     len *= sizeof(jschar);
733     JS_XDRMemSetData(xdr, buf, len);
735     /* XXXbe should magic mismatch be error, or false return value? */
736     ok = js_XDRScript(xdr, &script, &hasMagic);
737     if (!ok)
738         goto out;
739     if (!hasMagic) {
740         *rval = JSVAL_FALSE;
741         goto out;
742     }
744     /* Swap script for obj's old script, if any. */
745     oldscript = (JSScript *) JS_GetPrivate(cx, obj);
746     ok = JS_SetPrivate(cx, obj, script);
747     if (!ok) {
748         JS_free(cx, script);
749         goto out;
750     }
751     if (oldscript)
752         js_DestroyScript(cx, oldscript);
754     script->object = obj;
755     js_CallNewScriptHook(cx, script, NULL);
757 out:
758     /*
759      * We reset the buffer to be NULL so that it doesn't free the chars
760      * memory owned by str (argv[0]).
761      */
762     JS_XDRMemSetData(xdr, NULL, 0);
763     JS_XDRDestroy(xdr);
764 #if IS_BIG_ENDIAN
765     JS_free(cx, buf);
766 #endif
767     *rval = JSVAL_TRUE;
768     return ok;
771 static const char js_thaw_str[] = "thaw";
773 #endif /* JS_HAS_XDR_FREEZE_THAW */
774 #endif /* JS_HAS_XDR */
776 static JSFunctionSpec script_methods[] = {
777 #if JS_HAS_TOSOURCE
778     {js_toSource_str,   script_toSource,        0,0,0},
779 #endif
780     {js_toString_str,   script_toString,        0,0,0},
781     {"compile",         script_compile,         2,0,0},
782     {"exec",            script_exec,            1,0,0},
783 #if JS_HAS_XDR_FREEZE_THAW
784     {"freeze",          script_freeze,          0,0,0},
785     {js_thaw_str,       script_thaw,            1,0,0},
786 #endif /* JS_HAS_XDR_FREEZE_THAW */
787     {0,0,0,0,0}
788 };
790 #endif /* JS_HAS_SCRIPT_OBJECT */
792 static void
793 script_finalize(JSContext *cx, JSObject *obj)
795     JSScript *script;
797     script = (JSScript *) JS_GetPrivate(cx, obj);
798     if (script)
799         js_DestroyScript(cx, script);
802 static JSBool
803 script_call(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
805 #if JS_HAS_SCRIPT_OBJECT
806     return script_exec(cx, JSVAL_TO_OBJECT(argv[-2]), argc, argv, rval);
807 #else
808     return JS_FALSE;
809 #endif
812 static uint32
813 script_mark(JSContext *cx, JSObject *obj, void *arg)
815     JSScript *script;
817     script = (JSScript *) JS_GetPrivate(cx, obj);
818     if (script)
819         js_MarkScript(cx, script, arg);
820     return 0;
823 JS_FRIEND_DATA(JSClass) js_ScriptClass = {
824     js_Script_str,
825     JSCLASS_HAS_PRIVATE,
826     JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,
827     JS_EnumerateStub, JS_ResolveStub,   JS_ConvertStub,   script_finalize,
828     NULL,             NULL,             script_call,      NULL,/*XXXbe xdr*/
829     NULL,             NULL,             script_mark,      0
830 };
832 #if JS_HAS_SCRIPT_OBJECT
834 static JSBool
835 Script(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
837     /* If not constructing, replace obj with a new Script object. */
838     if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) {
839         obj = js_NewObject(cx, &js_ScriptClass, NULL, NULL);
840         if (!obj)
841             return JS_FALSE;
842     }
843     return script_compile(cx, obj, argc, argv, rval);
846 #if JS_HAS_XDR_FREEZE_THAW
848 static JSBool
849 script_static_thaw(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
850                    jsval *rval)
852     obj = js_NewObject(cx, &js_ScriptClass, NULL, NULL);
853     if (!obj)
854         return JS_FALSE;
855     if (!script_thaw(cx, obj, argc, argv, rval))
856         return JS_FALSE;
857     *rval = OBJECT_TO_JSVAL(obj);
858     return JS_TRUE;
861 static JSFunctionSpec script_static_methods[] = {
862     {js_thaw_str,       script_static_thaw,     1,0,0},
863     {0,0,0,0,0}
864 };
866 #else  /* !JS_HAS_XDR_FREEZE_THAW */
868 #define script_static_methods   NULL
870 #endif /* !JS_HAS_XDR_FREEZE_THAW */
872 JSObject *
873 js_InitScriptClass(JSContext *cx, JSObject *obj)
875     return JS_InitClass(cx, obj, NULL, &js_ScriptClass, Script, 1,
876                         NULL, script_methods, NULL, script_static_methods);
879 #endif /* JS_HAS_SCRIPT_OBJECT */
881 /*
882  * Shared script filename management.
883  */
884 JS_STATIC_DLL_CALLBACK(int)
885 js_compare_strings(const void *k1, const void *k2)
887     return strcmp(k1, k2) == 0;
890 /* Shared with jsatom.c to save code space. */
891 extern void * JS_DLL_CALLBACK
892 js_alloc_table_space(void *priv, size_t size);
894 extern void JS_DLL_CALLBACK
895 js_free_table_space(void *priv, void *item);
897 /* NB: This struct overlays JSHashEntry -- see jshash.h, do not reorganize. */
898 typedef struct ScriptFilenameEntry {
899     JSHashEntry         *next;          /* hash chain linkage */
900     JSHashNumber        keyHash;        /* key hash function result */
901     const void          *key;           /* ptr to filename, below */
902     JSPackedBool        mark;           /* mark flag, for GC */
903     char                filename[3];    /* two or more bytes, NUL-terminated */
904 } ScriptFilenameEntry;
906 JS_STATIC_DLL_CALLBACK(JSHashEntry *)
907 js_alloc_sftbl_entry(void *priv, const void *key)
909     size_t nbytes = offsetof(ScriptFilenameEntry, filename) + strlen(key) + 1;
911     return (JSHashEntry *) malloc(JS_MAX(nbytes, sizeof(JSHashEntry)));
914 JS_STATIC_DLL_CALLBACK(void)
915 js_free_sftbl_entry(void *priv, JSHashEntry *he, uintN flag)
917     if (flag != HT_FREE_ENTRY)
918         return;
919     free(he);
922 static JSHashAllocOps table_alloc_ops = {
923     js_alloc_table_space,   js_free_table_space,
924     js_alloc_sftbl_entry,   js_free_sftbl_entry
925 };
927 JSBool
928 js_InitRuntimeScriptState(JSContext *cx)
930     JSRuntime *rt = cx->runtime;
932 #ifdef JS_THREADSAFE
933     /* Must come through here once in primordial thread to init safely! */
934     if (!rt->scriptFilenameTableLock) {
935         rt->scriptFilenameTableLock = JS_NEW_LOCK();
936         if (!rt->scriptFilenameTableLock)
937             return JS_FALSE;
938     }
939 #endif
940     if (!rt->scriptFilenameTable) {
941         JS_ACQUIRE_LOCK(rt->scriptFilenameTableLock);
942         if (!rt->scriptFilenameTable) {
943             rt->scriptFilenameTable =
944                 JS_NewHashTable(16, JS_HashString, js_compare_strings, NULL,
945                                 &table_alloc_ops, NULL);
946         }
947         JS_RELEASE_LOCK(rt->scriptFilenameTableLock);
948         if (!rt->scriptFilenameTable) {
949             js_FinishRuntimeScriptState(cx);    /* free lock if threadsafe */
950             return JS_FALSE;
951         }
952     }
953     return JS_TRUE;
956 void
957 js_FinishRuntimeScriptState(JSContext *cx)
959     JSRuntime *rt = cx->runtime;
961     if (rt->scriptFilenameTable) {
962         JS_HashTableDestroy(rt->scriptFilenameTable);
963         rt->scriptFilenameTable = NULL;
964     }
965 #ifdef JS_THREADSAFE
966     if (rt->scriptFilenameTableLock) {
967         JS_DESTROY_LOCK(rt->scriptFilenameTableLock);
968         rt->scriptFilenameTableLock = NULL;
969     }
970 #endif
973 #ifdef DEBUG_brendan
974 size_t sftbl_savings = 0;
975 #endif
977 const char *
978 js_SaveScriptFilename(JSContext *cx, const char *filename)
980     JSRuntime *rt = cx->runtime;
981     JSHashTable *table;
982     JSHashNumber hash;
983     JSHashEntry **hep;
984     ScriptFilenameEntry *sfe;
986     JS_ACQUIRE_LOCK(rt->scriptFilenameTableLock);
987     table = rt->scriptFilenameTable;
988     hash = JS_HashString(filename);
989     hep = JS_HashTableRawLookup(table, hash, filename);
990     sfe = (ScriptFilenameEntry *) *hep;
991 #ifdef DEBUG_brendan
992     if (sfe)
993         sftbl_savings += strlen(sfe->filename);
994 #endif
995     if (!sfe) {
996         sfe = (ScriptFilenameEntry *)
997               JS_HashTableRawAdd(table, hep, hash, filename, NULL);
998         if (sfe) {
999             sfe->key = strcpy(sfe->filename, filename);
1000             JS_ASSERT(!sfe->mark);
1001         }
1002     }
1003     JS_RELEASE_LOCK(rt->scriptFilenameTableLock);
1004     if (!sfe) {
1005         JS_ReportOutOfMemory(cx);
1006         return NULL;
1007     }
1008     return sfe->filename;
1011 void
1012 js_MarkScriptFilename(const char *filename)
1014     ScriptFilenameEntry *sfe;
1016     /*
1017      * Back up from filename by its offset within its hash table entry.
1018      * The sfe->key member, redundant given sfe->filename but required by
1019      * the old jshash.c code, here gives us a useful sanity check.  This
1020      * assertion will very likely botch if someone tries to mark a string
1021      * that wasn't allocated as an sfe->filename.
1022      */
1023     sfe = (ScriptFilenameEntry *)
1024           (filename - offsetof(ScriptFilenameEntry, filename));
1025     JS_ASSERT(sfe->key == sfe->filename);
1026     sfe->mark = JS_TRUE;
1029 JS_STATIC_DLL_CALLBACK(intN)
1030 js_script_filename_sweeper(JSHashEntry *he, intN i, void *arg)
1032     ScriptFilenameEntry *sfe = (ScriptFilenameEntry *) he;
1034     if (!sfe->mark)
1035         return HT_ENUMERATE_REMOVE;
1036     sfe->mark = JS_FALSE;
1037     return HT_ENUMERATE_NEXT;
1040 void
1041 js_SweepScriptFilenames(JSRuntime *rt)
1043     JS_HashTableEnumerateEntries(rt->scriptFilenameTable,
1044                                  js_script_filename_sweeper,
1045                                  rt);
1046 #ifdef DEBUG_brendan
1047     printf("script filename table savings so far: %u\n", sftbl_savings);
1048 #endif
1051 JSScript *
1052 js_NewScript(JSContext *cx, uint32 length, uint32 nsrcnotes, uint32 ntrynotes)
1054     JSScript *script;
1056     /* Round up source note count to align script->trynotes for its type. */
1057     if (ntrynotes)
1058         nsrcnotes += JSTRYNOTE_ALIGNMASK;
1059     script = (JSScript *) JS_malloc(cx,
1060                                     sizeof(JSScript) +
1061                                     length * sizeof(jsbytecode) +
1062                                     nsrcnotes * sizeof(jssrcnote) +
1063                                     ntrynotes * sizeof(JSTryNote));
1064     if (!script)
1065         return NULL;
1066     memset(script, 0, sizeof(JSScript));
1067     script->code = script->main = (jsbytecode *)(script + 1);
1068     script->length = length;
1069     script->version = cx->version;
1070     if (ntrynotes) {
1071         script->trynotes = (JSTryNote *)
1072                            ((jsword)(SCRIPT_NOTES(script) + nsrcnotes) &
1073                             ~(jsword)JSTRYNOTE_ALIGNMASK);
1074         memset(script->trynotes, 0, ntrynotes * sizeof(JSTryNote));
1075     }
1076     return script;
1079 JS_FRIEND_API(JSScript *)
1080 js_NewScriptFromCG(JSContext *cx, JSCodeGenerator *cg, JSFunction *fun)
1082     uint32 mainLength, prologLength, nsrcnotes, ntrynotes;
1083     JSScript *script;
1084     const char *filename;
1086     mainLength = CG_OFFSET(cg);
1087     prologLength = CG_PROLOG_OFFSET(cg);
1088     CG_COUNT_FINAL_SRCNOTES(cg, nsrcnotes);
1089     CG_COUNT_FINAL_TRYNOTES(cg, ntrynotes);
1090     script = js_NewScript(cx, prologLength + mainLength, nsrcnotes, ntrynotes);
1091     if (!script)
1092         return NULL;
1094     /* Now that we have script, error control flow must go to label bad. */
1095     script->main += prologLength;
1096     memcpy(script->code, CG_PROLOG_BASE(cg), prologLength * sizeof(jsbytecode));
1097     memcpy(script->main, CG_BASE(cg), mainLength * sizeof(jsbytecode));
1098     script->numGlobalVars = cg->treeContext.numGlobalVars;
1099     if (!js_InitAtomMap(cx, &script->atomMap, &cg->atomList))
1100         goto bad;
1102     filename = cg->filename;
1103     if (filename) {
1104         script->filename = js_SaveScriptFilename(cx, filename);
1105         if (!script->filename)
1106             goto bad;
1107     }
1108     script->lineno = cg->firstLine;
1109     script->depth = cg->maxStackDepth;
1110     if (cg->principals) {
1111         script->principals = cg->principals;
1112         JSPRINCIPALS_HOLD(cx, script->principals);
1113     }
1115     if (!js_FinishTakingSrcNotes(cx, cg, SCRIPT_NOTES(script)))
1116         goto bad;
1117     if (script->trynotes)
1118         js_FinishTakingTryNotes(cx, cg, script->trynotes);
1120     /* Tell the debugger about this compiled script. */
1121     js_CallNewScriptHook(cx, script, fun);
1122     return script;
1124 bad:
1125     js_DestroyScript(cx, script);
1126     return NULL;
1129 JS_FRIEND_API(void)
1130 js_CallNewScriptHook(JSContext *cx, JSScript *script, JSFunction *fun)
1132     JSRuntime *rt;
1133     JSNewScriptHook hook;
1135     rt = cx->runtime;
1136     hook = rt->newScriptHook;
1137     if (hook) {
1138         JS_KEEP_ATOMS(rt);
1139         hook(cx, script->filename, script->lineno, script, fun,
1140              rt->newScriptHookData);
1141         JS_UNKEEP_ATOMS(rt);
1142     }
1145 void
1146 js_DestroyScript(JSContext *cx, JSScript *script)
1148     JSRuntime *rt;
1149     JSDestroyScriptHook hook;
1151     rt = cx->runtime;
1152     hook = rt->destroyScriptHook;
1153     if (hook)
1154         hook(cx, script, rt->destroyScriptHookData);
1156     JS_ClearScriptTraps(cx, script);
1157     js_FreeAtomMap(cx, &script->atomMap);
1158     if (script->principals)
1159         JSPRINCIPALS_DROP(cx, script->principals);
1160     JS_free(cx, script);
1163 void
1164 js_MarkScript(JSContext *cx, JSScript *script, void *arg)
1166     JSAtomMap *map;
1167     uintN i, length;
1168     JSAtom **vector;
1170     map = &script->atomMap;
1171     length = map->length;
1172     vector = map->vector;
1173     for (i = 0; i < length; i++)
1174         GC_MARK_ATOM(cx, vector[i], arg);
1176     if (script->filename)
1177         js_MarkScriptFilename(script->filename);
1180 jssrcnote *
1181 js_GetSrcNote(JSScript *script, jsbytecode *pc)
1183     jssrcnote *sn;
1184     ptrdiff_t offset, target;
1186     target = PTRDIFF(pc, script->code, jsbytecode);
1187     if ((uint32)target >= script->length)
1188         return NULL;
1189     offset = 0;
1190     for (sn = SCRIPT_NOTES(script); !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn)) {
1191         offset += SN_DELTA(sn);
1192         if (offset == target && SN_IS_GETTABLE(sn))
1193             return sn;
1194     }
1195     return NULL;
1198 uintN
1199 js_PCToLineNumber(JSContext *cx, JSScript *script, jsbytecode *pc)
1201     JSAtom *atom;
1202     JSFunction *fun;
1203     uintN lineno;
1204     ptrdiff_t offset, target;
1205     jssrcnote *sn;
1206     JSSrcNoteType type;
1208     /*
1209      * Special case: function definition needs no line number note because
1210      * the function's script contains its starting line number.
1211      */
1212     if (*pc == JSOP_DEFFUN) {
1213         atom = GET_ATOM(cx, script, pc);
1214         fun = (JSFunction *) JS_GetPrivate(cx, ATOM_TO_OBJECT(atom));
1215         JS_ASSERT(fun->interpreted);
1216         return fun->u.script->lineno;
1217     }
1219     /*
1220      * General case: walk through source notes accumulating their deltas,
1221      * keeping track of line-number notes, until we pass the note for pc's
1222      * offset within script->code.
1223      */
1224     lineno = script->lineno;
1225     offset = 0;
1226     target = PTRDIFF(pc, script->code, jsbytecode);
1227     for (sn = SCRIPT_NOTES(script); !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn)) {
1228         offset += SN_DELTA(sn);
1229         type = (JSSrcNoteType) SN_TYPE(sn);
1230         if (type == SRC_SETLINE) {
1231             if (offset <= target)
1232                 lineno = (uintN) js_GetSrcNoteOffset(sn, 0);
1233         } else if (type == SRC_NEWLINE) {
1234             if (offset <= target)
1235                 lineno++;
1236         }
1237         if (offset > target)
1238             break;
1239     }
1240     return lineno;
1243 jsbytecode *
1244 js_LineNumberToPC(JSScript *script, uintN target)
1246     ptrdiff_t offset;
1247     uintN lineno;
1248     jssrcnote *sn;
1249     JSSrcNoteType type;
1251     offset = 0;
1252     lineno = script->lineno;
1253     for (sn = SCRIPT_NOTES(script); !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn)) {
1254         if (lineno >= target)
1255             break;
1256         offset += SN_DELTA(sn);
1257         type = (JSSrcNoteType) SN_TYPE(sn);
1258         if (type == SRC_SETLINE) {
1259             lineno = (uintN) js_GetSrcNoteOffset(sn, 0);
1260         } else if (type == SRC_NEWLINE) {
1261             lineno++;
1262         }
1263     }
1264     return script->code + offset;
1267 uintN
1268 js_GetScriptLineExtent(JSScript *script)
1270     uintN lineno;
1271     jssrcnote *sn;
1272     JSSrcNoteType type;
1274     lineno = script->lineno;
1275     for (sn = SCRIPT_NOTES(script); !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn)) {
1276         type = (JSSrcNoteType) SN_TYPE(sn);
1277         if (type == SRC_SETLINE) {
1278             lineno = (uintN) js_GetSrcNoteOffset(sn, 0);
1279         } else if (type == SRC_NEWLINE) {
1280             lineno++;
1281         }
1282     }
1283     return 1 + lineno - script->lineno;