Code

moving trunk for module inkscape
[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     /* XXXbe set only for the compiler, which does not currently test it */
205     fp->flags |= JSFRAME_EVAL;
207     /* Compile the new script using the caller's scope chain, a la eval(). */
208     script = JS_CompileUCScriptForPrincipals(cx, scopeobj, principals,
209                                              JSSTRING_CHARS(str),
210                                              JSSTRING_LENGTH(str),
211                                              file, line);
212     if (!script)
213         return JS_FALSE;
215     /* Swap script for obj's old script, if any. */
216     oldscript = (JSScript *) JS_GetPrivate(cx, obj);
217     if (!JS_SetPrivate(cx, obj, script)) {
218         js_DestroyScript(cx, script);
219         return JS_FALSE;
220     }
221     if (oldscript)
222         js_DestroyScript(cx, oldscript);
224     script->object = obj;
225 out:
226     /* Return the object. */
227     *rval = OBJECT_TO_JSVAL(obj);
228     return JS_TRUE;
231 static JSBool
232 script_exec(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
234     JSScript *script;
235     JSObject *scopeobj, *parent;
236     JSStackFrame *fp, *caller;
238     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
239         return JS_FALSE;
240     script = (JSScript *) JS_GetPrivate(cx, obj);
241     if (!script)
242         return JS_TRUE;
244     scopeobj = NULL;
245     if (argc) {
246         if (!js_ValueToObject(cx, argv[0], &scopeobj))
247             return JS_FALSE;
248         argv[0] = OBJECT_TO_JSVAL(scopeobj);
249     }
251     /*
252      * Emulate eval() by using caller's this, var object, sharp array, etc.,
253      * all propagated by js_Execute via a non-null fourth (down) argument to
254      * js_Execute.  If there is no scripted caller, js_Execute uses its second
255      * (chain) argument to set the exec frame's varobj, thisp, and scopeChain.
256      *
257      * Unlike eval, which the compiler detects, Script.prototype.exec may be
258      * called from a lightweight function, or even from native code (in which
259      * case fp->varobj and fp->scopeChain are null).  If exec is called from
260      * a lightweight function, we will need to get a Call object representing
261      * its frame, to act as the var object and scope chain head.
262      */
263     fp = cx->fp;
264     caller = JS_GetScriptedCaller(cx, fp);
265     if (caller && !caller->varobj) {
266         /* Called from a lightweight function. */
267         JS_ASSERT(caller->fun && !(caller->fun->flags & JSFUN_HEAVYWEIGHT));
269         /* Scope chain links from Call object to callee's parent. */
270         parent = OBJ_GET_PARENT(cx, JSVAL_TO_OBJECT(caller->argv[-2]));
271         if (!js_GetCallObject(cx, caller, parent))
272             return JS_FALSE;
273     }
275     if (!scopeobj) {
276         /* No scope object passed in: try to use the caller's scope chain. */
277         if (caller) {
278             /*
279              * Load caller->scopeChain after the conditional js_GetCallObject
280              * call above, which resets scopeChain as well as varobj.
281              */
282             scopeobj = caller->scopeChain;
283         } else {
284             /*
285              * Called from native code, so we don't know what scope object to
286              * use.  We could use parent (see above), but Script.prototype.exec
287              * might be a shared/sealed "superglobal" method.  A more general
288              * approach would use cx->globalObject, which will be the same as
289              * exec.__parent__ in the non-superglobal case.  In the superglobal
290              * case it's the right object: the global, not the superglobal.
291              */
292             scopeobj = cx->globalObject;
293         }
294     }
296     return js_Execute(cx, scopeobj, script, caller, JSFRAME_EVAL, rval);
299 #if JS_HAS_XDR
301 static JSBool
302 XDRAtomListElement(JSXDRState *xdr, JSAtomListElement *ale)
304     jsval value;
305     jsatomid index;
307     if (xdr->mode == JSXDR_ENCODE)
308         value = ATOM_KEY(ALE_ATOM(ale));
310     index = ALE_INDEX(ale);
311     if (!JS_XDRUint32(xdr, &index))
312         return JS_FALSE;
313     ALE_SET_INDEX(ale, index);
315     if (!JS_XDRValue(xdr, &value))
316         return JS_FALSE;
318     if (xdr->mode == JSXDR_DECODE) {
319         if (!ALE_SET_ATOM(ale, js_AtomizeValue(xdr->cx, value, 0)))
320             return JS_FALSE;
321     }
322     return JS_TRUE;
325 static JSBool
326 XDRAtomMap(JSXDRState *xdr, JSAtomMap *map)
328     uint32 length;
329     uintN i;
330     JSBool ok;
332     if (xdr->mode == JSXDR_ENCODE)
333         length = map->length;
335     if (!JS_XDRUint32(xdr, &length))
336         return JS_FALSE;
338     if (xdr->mode == JSXDR_DECODE) {
339         JSContext *cx;
340         void *mark;
341         JSAtomList al;
342         JSAtomListElement *ale;
344         cx = xdr->cx;
345         mark = JS_ARENA_MARK(&cx->tempPool);
346         ATOM_LIST_INIT(&al);
347         for (i = 0; i < length; i++) {
348             JS_ARENA_ALLOCATE_TYPE(ale, JSAtomListElement, &cx->tempPool);
349             if (!ale ||
350                 !XDRAtomListElement(xdr, ale)) {
351                 if (!ale)
352                     JS_ReportOutOfMemory(cx);
353                 JS_ARENA_RELEASE(&cx->tempPool, mark);
354                 return JS_FALSE;
355             }
356             ALE_SET_NEXT(ale, al.list);
357             al.count++;
358             al.list = ale;
359         }
360         ok = js_InitAtomMap(cx, map, &al);
361         JS_ARENA_RELEASE(&cx->tempPool, mark);
362         return ok;
363     }
365     if (xdr->mode == JSXDR_ENCODE) {
366         JSAtomListElement ale;
368         for (i = 0; i < map->length; i++) {
369             ALE_SET_ATOM(&ale, map->vector[i]);
370             ALE_SET_INDEX(&ale, i);
371             if (!XDRAtomListElement(xdr, &ale))
372                 return JS_FALSE;
373         }
374     }
375     return JS_TRUE;
378 JSBool
379 js_XDRScript(JSXDRState *xdr, JSScript **scriptp, JSBool *hasMagic)
381     JSContext *cx;
382     JSScript *script, *newscript;
383     uint32 length, lineno, depth, magic, nsrcnotes, ntrynotes;
384     uint32 prologLength, version;
385     JSBool filenameWasSaved;
386     jssrcnote *notes, *sn;
388     cx = xdr->cx;
389     script = *scriptp;
390     nsrcnotes = ntrynotes = 0;
391     filenameWasSaved = JS_FALSE;
392     notes = NULL;
394     /*
395      * Encode prologLength and version after script->length (_2 or greater),
396      * but decode both new (>= _2) and old, prolog&version-free (_1) scripts.
397      * Version _3 supports principals serialization.  Version _4 reorders the
398      * nsrcnotes and ntrynotes fields to come before everything except magic,
399      * length, prologLength, and version, so that srcnote and trynote storage
400      * can be allocated as part of the JSScript (along with bytecode storage).
401      */
402     if (xdr->mode == JSXDR_ENCODE)
403         magic = JSXDR_MAGIC_SCRIPT_CURRENT;
404     if (!JS_XDRUint32(xdr, &magic))
405         return JS_FALSE;
406     if (magic != JSXDR_MAGIC_SCRIPT_4 &&
407         magic != JSXDR_MAGIC_SCRIPT_3 &&
408         magic != JSXDR_MAGIC_SCRIPT_2 &&
409         magic != JSXDR_MAGIC_SCRIPT_1) {
410         if (!hasMagic) {
411             JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
412                                  JSMSG_BAD_SCRIPT_MAGIC);
413             return JS_FALSE;
414         }
415         *hasMagic = JS_FALSE;
416         return JS_TRUE;
417     }
418     if (hasMagic)
419         *hasMagic = JS_TRUE;
421     if (xdr->mode == JSXDR_ENCODE) {
422         length = script->length;
423         prologLength = PTRDIFF(script->main, script->code, jsbytecode);
424         version = (int32)script->version;
425         lineno = (uint32)script->lineno;
426         depth = (uint32)script->depth;
428         /* Count the srcnotes, keeping notes pointing at the first one. */
429         notes = SCRIPT_NOTES(script);
430         for (sn = notes; !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn))
431             continue;
432         nsrcnotes = PTRDIFF(sn, notes, jssrcnote);
433         nsrcnotes++;            /* room for the terminator */
435         /* Count the trynotes. */
436         if (script->trynotes) {
437             while (script->trynotes[ntrynotes].catchStart)
438                 ntrynotes++;
439             ntrynotes++;        /* room for the end marker */
440         }
441     }
443     if (!JS_XDRUint32(xdr, &length))
444         return JS_FALSE;
445     if (magic >= JSXDR_MAGIC_SCRIPT_2) {
446         if (!JS_XDRUint32(xdr, &prologLength))
447             return JS_FALSE;
448         if (!JS_XDRUint32(xdr, &version))
449             return JS_FALSE;
451         /* To fuse allocations, we need srcnote and trynote counts early. */
452         if (magic >= JSXDR_MAGIC_SCRIPT_4) {
453             if (!JS_XDRUint32(xdr, &nsrcnotes))
454                 return JS_FALSE;
455             if (!JS_XDRUint32(xdr, &ntrynotes))
456                 return JS_FALSE;
457         }
458     }
460     if (xdr->mode == JSXDR_DECODE) {
461         script = js_NewScript(cx, length, nsrcnotes, ntrynotes);
462         if (!script)
463             return JS_FALSE;
464         if (magic >= JSXDR_MAGIC_SCRIPT_2) {
465             script->main += prologLength;
466             script->version = (JSVersion) version;
468             /* If we know nsrcnotes, we allocated space for notes in script. */
469             if (magic >= JSXDR_MAGIC_SCRIPT_4)
470                 notes = SCRIPT_NOTES(script);
471         }
472         *scriptp = script;
473     }
475     /*
476      * Control hereafter must goto error on failure, in order for the DECODE
477      * case to destroy script and conditionally free notes, which if non-null
478      * in the (DECODE and version < _4) case must point at a temporary vector
479      * allocated just below.
480      */
481     if (!JS_XDRBytes(xdr, (char *)script->code, length * sizeof(jsbytecode)) ||
482         !XDRAtomMap(xdr, &script->atomMap)) {
483         goto error;
484     }
486     if (magic < JSXDR_MAGIC_SCRIPT_4) {
487         if (!JS_XDRUint32(xdr, &nsrcnotes))
488             goto error;
489         if (xdr->mode == JSXDR_DECODE) {
490             notes = (jssrcnote *) JS_malloc(cx, nsrcnotes * sizeof(jssrcnote));
491             if (!notes)
492                 goto error;
493         }
494     }
496     if (!JS_XDRBytes(xdr, (char *)notes, nsrcnotes * sizeof(jssrcnote)) ||
497         !JS_XDRCStringOrNull(xdr, (char **)&script->filename) ||
498         !JS_XDRUint32(xdr, &lineno) ||
499         !JS_XDRUint32(xdr, &depth) ||
500         (magic < JSXDR_MAGIC_SCRIPT_4 && !JS_XDRUint32(xdr, &ntrynotes))) {
501         goto error;
502     }
504     /* Script principals transcoding support comes with versions >= _3. */
505     if (magic >= JSXDR_MAGIC_SCRIPT_3) {
506         JSPrincipals *principals;
507         uint32 encodeable;
509         if (xdr->mode == JSXDR_ENCODE) {
510             principals = script->principals;
511             encodeable = (cx->runtime->principalsTranscoder != NULL);
512             if (!JS_XDRUint32(xdr, &encodeable))
513                 goto error;
514             if (encodeable &&
515                 !cx->runtime->principalsTranscoder(xdr, &principals)) {
516                 goto error;
517             }
518         } else {
519             if (!JS_XDRUint32(xdr, &encodeable))
520                 goto error;
521             if (encodeable) {
522                 if (!cx->runtime->principalsTranscoder) {
523                     JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
524                                          JSMSG_CANT_DECODE_PRINCIPALS);
525                     goto error;
526                 }
527                 if (!cx->runtime->principalsTranscoder(xdr, &principals))
528                     goto error;
529                 script->principals = principals;
530             }
531         }
532     }
534     if (xdr->mode == JSXDR_DECODE) {
535         const char *filename = script->filename;
536         if (filename) {
537             filename = js_SaveScriptFilename(cx, filename);
538             if (!filename)
539                 goto error;
540             JS_free(cx, (void *) script->filename);
541             script->filename = filename;
542             filenameWasSaved = JS_TRUE;
543         }
544         script->lineno = (uintN)lineno;
545         script->depth = (uintN)depth;
547         if (magic < JSXDR_MAGIC_SCRIPT_4) {
548             /*
549              * Argh, we have to reallocate script, copy notes into the extra
550              * space after the bytecodes, and free the temporary notes vector.
551              * First, add enough slop to nsrcnotes so we can align the address
552              * after the srcnotes of the first trynote.
553              */
554             uint32 osrcnotes = nsrcnotes;
556             if (ntrynotes)
557                 nsrcnotes += JSTRYNOTE_ALIGNMASK;
558             newscript = (JSScript *) JS_realloc(cx, script,
559                                                 sizeof(JSScript) +
560                                                 length * sizeof(jsbytecode) +
561                                                 nsrcnotes * sizeof(jssrcnote) +
562                                                 ntrynotes * sizeof(JSTryNote));
563             if (!newscript)
564                 goto error;
566             *scriptp = script = newscript;
567             script->code = (jsbytecode *)(script + 1);
568             script->main = script->code + prologLength;
569             memcpy(script->code + length, notes, osrcnotes * sizeof(jssrcnote));
570             JS_free(cx, (void *) notes);
571             notes = NULL;
572             if (ntrynotes) {
573                 script->trynotes = (JSTryNote *)
574                                    ((jsword)(SCRIPT_NOTES(script) + nsrcnotes) &
575                                     ~(jsword)JSTRYNOTE_ALIGNMASK);
576             }
577         }
578     }
580     while (ntrynotes) {
581         JSTryNote *tn = &script->trynotes[--ntrynotes];
582         uint32 start = (uint32) tn->start,
583                catchLength = (uint32) tn->length,
584                catchStart = (uint32) tn->catchStart;
586         if (!JS_XDRUint32(xdr, &start) ||
587             !JS_XDRUint32(xdr, &catchLength) ||
588             !JS_XDRUint32(xdr, &catchStart)) {
589             goto error;
590         }
591         tn->start = (ptrdiff_t) start;
592         tn->length = (ptrdiff_t) catchLength;
593         tn->catchStart = (ptrdiff_t) catchStart;
594     }
595     return JS_TRUE;
597   error:
598     if (xdr->mode == JSXDR_DECODE) {
599         if (script->filename && !filenameWasSaved) {
600             JS_free(cx, (void *) script->filename);
601             script->filename = NULL;
602         }
603         if (notes && magic < JSXDR_MAGIC_SCRIPT_4)
604             JS_free(cx, (void *) notes);
605         js_DestroyScript(cx, script);
606         *scriptp = NULL;
607     }
608     return JS_FALSE;
611 #if JS_HAS_XDR_FREEZE_THAW
612 /*
613  * These cannot be exposed to web content, and chrome does not need them, so
614  * we take them out of the Mozilla client altogether.  Fortunately, there is
615  * no way to serialize a native function (see fun_xdrObject in jsfun.c).
616  */
618 static JSBool
619 script_freeze(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
620               jsval *rval)
622     JSXDRState *xdr;
623     JSScript *script;
624     JSBool ok, hasMagic;
625     uint32 len;
626     void *buf;
627     JSString *str;
629     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
630         return JS_FALSE;
631     script = (JSScript *) JS_GetPrivate(cx, obj);
632     if (!script)
633         return JS_TRUE;
635     /* create new XDR */
636     xdr = JS_XDRNewMem(cx, JSXDR_ENCODE);
637     if (!xdr)
638         return JS_FALSE;
640     /* write  */
641     ok = js_XDRScript(xdr, &script, &hasMagic);
642     if (!ok)
643         goto out;
644     if (!hasMagic) {
645         *rval = JSVAL_VOID;
646         goto out;
647     }
649     buf = JS_XDRMemGetData(xdr, &len);
650     if (!buf) {
651         ok = JS_FALSE;
652         goto out;
653     }
655     JS_ASSERT((jsword)buf % sizeof(jschar) == 0);
656     len /= sizeof(jschar);
657     str = JS_NewUCStringCopyN(cx, (jschar *)buf, len);
658     if (!str) {
659         ok = JS_FALSE;
660         goto out;
661     }
663 #if IS_BIG_ENDIAN
664   {
665     jschar *chars;
666     uint32 i;
668     /* Swap bytes in Unichars to keep frozen strings machine-independent. */
669     chars = JS_GetStringChars(str);
670     for (i = 0; i < len; i++)
671         chars[i] = JSXDR_SWAB16(chars[i]);
672   }
673 #endif
674     *rval = STRING_TO_JSVAL(str);
676 out:
677     JS_XDRDestroy(xdr);
678     return ok;
681 static JSBool
682 script_thaw(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
683             jsval *rval)
685     JSXDRState *xdr;
686     JSString *str;
687     void *buf;
688     uint32 len;
689     JSScript *script, *oldscript;
690     JSBool ok, hasMagic;
692     if (!JS_InstanceOf(cx, obj, &js_ScriptClass, argv))
693         return JS_FALSE;
695     if (argc == 0)
696         return JS_TRUE;
697     str = js_ValueToString(cx, argv[0]);
698     if (!str)
699         return JS_FALSE;
701     /* create new XDR */
702     xdr = JS_XDRNewMem(cx, JSXDR_DECODE);
703     if (!xdr)
704         return JS_FALSE;
706     buf = JS_GetStringChars(str);
707     len = JS_GetStringLength(str);
708 #if IS_BIG_ENDIAN
709   {
710     jschar *from, *to;
711     uint32 i;
713     /* Swap bytes in Unichars to keep frozen strings machine-independent. */
714     from = (jschar *)buf;
715     to = (jschar *) JS_malloc(cx, len * sizeof(jschar));
716     if (!to) {
717         JS_XDRDestroy(xdr);
718         return JS_FALSE;
719     }
720     for (i = 0; i < len; i++)
721         to[i] = JSXDR_SWAB16(from[i]);
722     buf = (char *)to;
723   }
724 #endif
725     len *= sizeof(jschar);
726     JS_XDRMemSetData(xdr, buf, len);
728     /* XXXbe should magic mismatch be error, or false return value? */
729     ok = js_XDRScript(xdr, &script, &hasMagic);
730     if (!ok)
731         goto out;
732     if (!hasMagic) {
733         *rval = JSVAL_FALSE;
734         goto out;
735     }
737     /* Swap script for obj's old script, if any. */
738     oldscript = (JSScript *) JS_GetPrivate(cx, obj);
739     ok = JS_SetPrivate(cx, obj, script);
740     if (!ok) {
741         JS_free(cx, script);
742         goto out;
743     }
744     if (oldscript)
745         js_DestroyScript(cx, oldscript);
747     script->object = obj;
748     js_CallNewScriptHook(cx, script, NULL);
750 out:
751     /*
752      * We reset the buffer to be NULL so that it doesn't free the chars
753      * memory owned by str (argv[0]).
754      */
755     JS_XDRMemSetData(xdr, NULL, 0);
756     JS_XDRDestroy(xdr);
757 #if IS_BIG_ENDIAN
758     JS_free(cx, buf);
759 #endif
760     *rval = JSVAL_TRUE;
761     return ok;
764 static const char js_thaw_str[] = "thaw";
766 #endif /* JS_HAS_XDR_FREEZE_THAW */
767 #endif /* JS_HAS_XDR */
769 static JSFunctionSpec script_methods[] = {
770 #if JS_HAS_TOSOURCE
771     {js_toSource_str,   script_toSource,        0,0,0},
772 #endif
773     {js_toString_str,   script_toString,        0,0,0},
774     {"compile",         script_compile,         2,0,0},
775     {"exec",            script_exec,            1,0,0},
776 #if JS_HAS_XDR_FREEZE_THAW
777     {"freeze",          script_freeze,          0,0,0},
778     {js_thaw_str,       script_thaw,            1,0,0},
779 #endif /* JS_HAS_XDR_FREEZE_THAW */
780     {0,0,0,0,0}
781 };
783 #endif /* JS_HAS_SCRIPT_OBJECT */
785 static void
786 script_finalize(JSContext *cx, JSObject *obj)
788     JSScript *script;
790     script = (JSScript *) JS_GetPrivate(cx, obj);
791     if (script)
792         js_DestroyScript(cx, script);
795 static JSBool
796 script_call(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
798 #if JS_HAS_SCRIPT_OBJECT
799     return script_exec(cx, JSVAL_TO_OBJECT(argv[-2]), argc, argv, rval);
800 #else
801     return JS_FALSE;
802 #endif
805 static uint32
806 script_mark(JSContext *cx, JSObject *obj, void *arg)
808     JSScript *script;
810     script = (JSScript *) JS_GetPrivate(cx, obj);
811     if (script)
812         js_MarkScript(cx, script, arg);
813     return 0;
816 JS_FRIEND_DATA(JSClass) js_ScriptClass = {
817     js_Script_str,
818     JSCLASS_HAS_PRIVATE,
819     JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,
820     JS_EnumerateStub, JS_ResolveStub,   JS_ConvertStub,   script_finalize,
821     NULL,             NULL,             script_call,      NULL,/*XXXbe xdr*/
822     NULL,             NULL,             script_mark,      0
823 };
825 #if JS_HAS_SCRIPT_OBJECT
827 static JSBool
828 Script(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
830     /* If not constructing, replace obj with a new Script object. */
831     if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) {
832         obj = js_NewObject(cx, &js_ScriptClass, NULL, NULL);
833         if (!obj)
834             return JS_FALSE;
835     }
836     return script_compile(cx, obj, argc, argv, rval);
839 #if JS_HAS_XDR_FREEZE_THAW
841 static JSBool
842 script_static_thaw(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
843                    jsval *rval)
845     obj = js_NewObject(cx, &js_ScriptClass, NULL, NULL);
846     if (!obj)
847         return JS_FALSE;
848     if (!script_thaw(cx, obj, argc, argv, rval))
849         return JS_FALSE;
850     *rval = OBJECT_TO_JSVAL(obj);
851     return JS_TRUE;
854 static JSFunctionSpec script_static_methods[] = {
855     {js_thaw_str,       script_static_thaw,     1,0,0},
856     {0,0,0,0,0}
857 };
859 #else  /* !JS_HAS_XDR_FREEZE_THAW */
861 #define script_static_methods   NULL
863 #endif /* !JS_HAS_XDR_FREEZE_THAW */
865 JSObject *
866 js_InitScriptClass(JSContext *cx, JSObject *obj)
868     return JS_InitClass(cx, obj, NULL, &js_ScriptClass, Script, 1,
869                         NULL, script_methods, NULL, script_static_methods);
872 #endif /* JS_HAS_SCRIPT_OBJECT */
874 /*
875  * Shared script filename management.
876  */
877 static JSHashTable  *script_filename_table;
878 #ifdef JS_THREADSAFE
879 static JSLock       *script_filename_table_lock;
880 #endif
882 JS_STATIC_DLL_CALLBACK(int)
883 js_compare_strings(const void *k1, const void *k2)
885     return strcmp(k1, k2) == 0;
888 /* Shared with jsatom.c to save code space. */
889 extern void * JS_DLL_CALLBACK
890 js_alloc_table_space(void *priv, size_t size);
892 extern void JS_DLL_CALLBACK
893 js_free_table_space(void *priv, void *item);
895 /* NB: This struct overlays JSHashEntry -- see jshash.h, do not reorganize. */
896 typedef struct ScriptFilenameEntry {
897     JSHashEntry         *next;          /* hash chain linkage */
898     JSHashNumber        keyHash;        /* key hash function result */
899     const void          *key;           /* ptr to filename, below */
900     JSPackedBool        mark;           /* mark flag, for GC */
901     char                filename[3];    /* two or more bytes, NUL-terminated */
902 } ScriptFilenameEntry;
904 JS_STATIC_DLL_CALLBACK(JSHashEntry *)
905 js_alloc_entry(void *priv, const void *key)
907     size_t nbytes = offsetof(ScriptFilenameEntry, filename) + strlen(key) + 1;
909     return (JSHashEntry *) malloc(JS_MAX(nbytes, sizeof(JSHashEntry)));
912 JS_STATIC_DLL_CALLBACK(void)
913 js_free_entry(void *priv, JSHashEntry *he, uintN flag)
915     if (flag != HT_FREE_ENTRY)
916         return;
917     free(he);
920 static JSHashAllocOps table_alloc_ops = {
921     js_alloc_table_space,   js_free_table_space,
922     js_alloc_entry,         js_free_entry
923 };
925 JSBool
926 js_InitScriptGlobals()
928 #ifdef JS_THREADSAFE
929     /* Must come through here once in primordial thread to init safely! */
930     if (!script_filename_table_lock) {
931         script_filename_table_lock = JS_NEW_LOCK();
932         if (!script_filename_table_lock)
933             return JS_FALSE;
934     }
935 #endif
936     if (!script_filename_table) {
937         JS_ACQUIRE_LOCK(script_filename_table_lock);
938         if (!script_filename_table) {
939             script_filename_table =
940                 JS_NewHashTable(16, JS_HashString, js_compare_strings, NULL,
941                                 &table_alloc_ops, NULL);
942         }
943         JS_RELEASE_LOCK(script_filename_table_lock);
944         if (!script_filename_table)
945             return JS_FALSE;
946     }
947     return JS_TRUE;
950 void
951 js_FreeScriptGlobals()
953     if (script_filename_table) {
954         JS_HashTableDestroy(script_filename_table);
955         script_filename_table = NULL;
956     }
957 #ifdef JS_THREADSAFE
958     if (script_filename_table_lock) {
959         JS_DESTROY_LOCK(script_filename_table_lock);
960         script_filename_table_lock = NULL;
961     }
962 #endif
965 #ifdef DEBUG_brendan
966 size_t sft_savings = 0;
967 #endif
969 const char *
970 js_SaveScriptFilename(JSContext *cx, const char *filename)
972     JSHashTable *table;
973     JSHashNumber hash;
974     JSHashEntry **hep;
975     ScriptFilenameEntry *sfe;
977     JS_ACQUIRE_LOCK(script_filename_table_lock);
978     table = script_filename_table;
979     hash = JS_HashString(filename);
980     hep = JS_HashTableRawLookup(table, hash, filename);
981     sfe = (ScriptFilenameEntry *) *hep;
982 #ifdef DEBUG_brendan
983     if (sfe)
984         sft_savings += strlen(sfe->filename);
985 #endif
986     if (!sfe) {
987         sfe = (ScriptFilenameEntry *)
988               JS_HashTableRawAdd(table, hep, hash, filename, NULL);
989         if (sfe) {
990             sfe->key = strcpy(sfe->filename, filename);
991             JS_ASSERT(!sfe->mark);
992         }
993     }
994     JS_RELEASE_LOCK(script_filename_table_lock);
995     if (!sfe) {
996         JS_ReportOutOfMemory(cx);
997         return NULL;
998     }
999     return sfe->filename;
1002 void
1003 js_MarkScriptFilename(const char *filename)
1005     ScriptFilenameEntry *sfe;
1007     /*
1008      * Back up from filename by its offset within its hash table entry.
1009      * The sfe->key member, redundant given sfe->filename but required by
1010      * the old jshash.c code, here gives us a useful sanity check.  This
1011      * assertion will very likely botch if someone tries to mark a string
1012      * that wasn't allocated as an sfe->filename.
1013      */
1014     sfe = (ScriptFilenameEntry *)
1015           (filename - offsetof(ScriptFilenameEntry, filename));
1016     JS_ASSERT(sfe->key == sfe->filename);
1017     sfe->mark = JS_TRUE;
1020 JS_STATIC_DLL_CALLBACK(intN)
1021 js_script_filename_sweeper(JSHashEntry *he, intN i, void *arg)
1023     ScriptFilenameEntry *sfe = (ScriptFilenameEntry *) he;
1025     if (!sfe->mark)
1026         return HT_ENUMERATE_REMOVE;
1027     sfe->mark = JS_FALSE;
1028     return HT_ENUMERATE_NEXT;
1031 void
1032 js_SweepScriptFilenames(JSRuntime *rt)
1034     JS_HashTableEnumerateEntries(script_filename_table,
1035                                  js_script_filename_sweeper,
1036                                  rt);
1037 #ifdef DEBUG_brendan
1038     printf("script filename table savings so far: %u\n", sft_savings);
1039 #endif
1042 JSScript *
1043 js_NewScript(JSContext *cx, uint32 length, uint32 nsrcnotes, uint32 ntrynotes)
1045     JSScript *script;
1047     /* Round up source note count to align script->trynotes for its type. */
1048     if (ntrynotes)
1049         nsrcnotes += JSTRYNOTE_ALIGNMASK;
1050     script = (JSScript *) JS_malloc(cx,
1051                                     sizeof(JSScript) +
1052                                     length * sizeof(jsbytecode) +
1053                                     nsrcnotes * sizeof(jssrcnote) +
1054                                     ntrynotes * sizeof(JSTryNote));
1055     if (!script)
1056         return NULL;
1057     memset(script, 0, sizeof(JSScript));
1058     script->code = script->main = (jsbytecode *)(script + 1);
1059     script->length = length;
1060     script->version = cx->version;
1061     if (ntrynotes) {
1062         script->trynotes = (JSTryNote *)
1063                            ((jsword)(SCRIPT_NOTES(script) + nsrcnotes) &
1064                             ~(jsword)JSTRYNOTE_ALIGNMASK);
1065     }
1066     return script;
1069 JS_FRIEND_API(JSScript *)
1070 js_NewScriptFromCG(JSContext *cx, JSCodeGenerator *cg, JSFunction *fun)
1072     uint32 mainLength, prologLength, nsrcnotes, ntrynotes;
1073     JSScript *script;
1074     const char *filename;
1076     mainLength = CG_OFFSET(cg);
1077     prologLength = CG_PROLOG_OFFSET(cg);
1078     CG_COUNT_FINAL_SRCNOTES(cg, nsrcnotes);
1079     CG_COUNT_FINAL_TRYNOTES(cg, ntrynotes);
1080     script = js_NewScript(cx, prologLength + mainLength, nsrcnotes, ntrynotes);
1081     if (!script)
1082         return NULL;
1084     /* Now that we have script, error control flow must go to label bad. */
1085     script->main += prologLength;
1086     memcpy(script->code, CG_PROLOG_BASE(cg), prologLength * sizeof(jsbytecode));
1087     memcpy(script->main, CG_BASE(cg), mainLength * sizeof(jsbytecode));
1088     if (!js_InitAtomMap(cx, &script->atomMap, &cg->atomList))
1089         goto bad;
1091     filename = cg->filename;
1092     if (filename) {
1093         script->filename = js_SaveScriptFilename(cx, filename);
1094         if (!script->filename)
1095             goto bad;
1096     }
1097     script->lineno = cg->firstLine;
1098     script->depth = cg->maxStackDepth;
1099     if (cg->principals) {
1100         script->principals = cg->principals;
1101         JSPRINCIPALS_HOLD(cx, script->principals);
1102     }
1104     if (!js_FinishTakingSrcNotes(cx, cg, SCRIPT_NOTES(script)))
1105         goto bad;
1106     if (script->trynotes)
1107         js_FinishTakingTryNotes(cx, cg, script->trynotes);
1109     /* Tell the debugger about this compiled script. */
1110     js_CallNewScriptHook(cx, script, fun);
1111     return script;
1113 bad:
1114     js_DestroyScript(cx, script);
1115     return NULL;
1118 JS_FRIEND_API(void)
1119 js_CallNewScriptHook(JSContext *cx, JSScript *script, JSFunction *fun)
1121     JSRuntime *rt;
1122     JSNewScriptHook hook;
1124     rt = cx->runtime;
1125     hook = rt->newScriptHook;
1126     if (hook) {
1127         /*
1128          * We use a dummy stack frame to protect the script from a GC caused
1129          * by debugger-hook execution.
1130          *
1131          * XXX We really need a way to manage local roots and such more
1132          * XXX automatically, at which point we can remove this one-off hack
1133          * XXX and others within the engine.  See bug 40757 for discussion.
1134          */
1135         JSStackFrame dummy;
1137         memset(&dummy, 0, sizeof dummy);
1138         dummy.down = cx->fp;
1139         dummy.script = script;
1140         cx->fp = &dummy;
1142         hook(cx, script->filename, script->lineno, script, fun,
1143              rt->newScriptHookData);
1145         cx->fp = dummy.down;
1146     }
1149 void
1150 js_DestroyScript(JSContext *cx, JSScript *script)
1152     JSRuntime *rt;
1153     JSDestroyScriptHook hook;
1155     rt = cx->runtime;
1156     hook = rt->destroyScriptHook;
1157     if (hook)
1158         hook(cx, script, rt->destroyScriptHookData);
1160     JS_ClearScriptTraps(cx, script);
1161     js_FreeAtomMap(cx, &script->atomMap);
1162     if (script->principals)
1163         JSPRINCIPALS_DROP(cx, script->principals);
1164     JS_free(cx, script);
1167 void
1168 js_MarkScript(JSContext *cx, JSScript *script, void *arg)
1170     JSAtomMap *map;
1171     uintN i, length;
1172     JSAtom **vector;
1174     map = &script->atomMap;
1175     length = map->length;
1176     vector = map->vector;
1177     for (i = 0; i < length; i++)
1178         GC_MARK_ATOM(cx, vector[i], arg);
1180     if (script->filename)
1181         js_MarkScriptFilename(script->filename);
1184 jssrcnote *
1185 js_GetSrcNote(JSScript *script, jsbytecode *pc)
1187     jssrcnote *sn;
1188     ptrdiff_t offset, target;
1190     target = PTRDIFF(pc, script->code, jsbytecode);
1191     if ((uint32)target >= script->length)
1192         return NULL;
1193     offset = 0;
1194     for (sn = SCRIPT_NOTES(script); !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn)) {
1195         offset += SN_DELTA(sn);
1196         if (offset == target && SN_IS_GETTABLE(sn))
1197             return sn;
1198     }
1199     return NULL;
1202 uintN
1203 js_PCToLineNumber(JSContext *cx, JSScript *script, jsbytecode *pc)
1205     JSAtom *atom;
1206     JSFunction *fun;
1207     uintN lineno;
1208     ptrdiff_t offset, target;
1209     jssrcnote *sn;
1210     JSSrcNoteType type;
1212     /*
1213      * Special case: function definition needs no line number note because
1214      * the function's script contains its starting line number.
1215      */
1216     if (*pc == JSOP_DEFFUN) {
1217         atom = GET_ATOM(cx, script, pc);
1218         fun = (JSFunction *) JS_GetPrivate(cx, ATOM_TO_OBJECT(atom));
1219         return fun->script->lineno;
1220     }
1222     /*
1223      * General case: walk through source notes accumulating their deltas,
1224      * keeping track of line-number notes, until we pass the note for pc's
1225      * offset within script->code.
1226      */
1227     lineno = script->lineno;
1228     offset = 0;
1229     target = PTRDIFF(pc, script->code, jsbytecode);
1230     for (sn = SCRIPT_NOTES(script); !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn)) {
1231         offset += SN_DELTA(sn);
1232         type = (JSSrcNoteType) SN_TYPE(sn);
1233         if (type == SRC_SETLINE) {
1234             if (offset <= target)
1235                 lineno = (uintN) js_GetSrcNoteOffset(sn, 0);
1236         } else if (type == SRC_NEWLINE) {
1237             if (offset <= target)
1238                 lineno++;
1239         }
1240         if (offset > target)
1241             break;
1242     }
1243     return lineno;
1246 jsbytecode *
1247 js_LineNumberToPC(JSScript *script, uintN target)
1249     ptrdiff_t offset;
1250     uintN lineno;
1251     jssrcnote *sn;
1252     JSSrcNoteType type;
1254     offset = 0;
1255     lineno = script->lineno;
1256     for (sn = SCRIPT_NOTES(script); !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn)) {
1257         if (lineno >= target)
1258             break;
1259         offset += SN_DELTA(sn);
1260         type = (JSSrcNoteType) SN_TYPE(sn);
1261         if (type == SRC_SETLINE) {
1262             lineno = (uintN) js_GetSrcNoteOffset(sn, 0);
1263         } else if (type == SRC_NEWLINE) {
1264             lineno++;
1265         }
1266     }
1267     return script->code + offset;
1270 uintN
1271 js_GetScriptLineExtent(JSScript *script)
1273     uintN lineno;
1274     jssrcnote *sn;
1275     JSSrcNoteType type;
1277     lineno = script->lineno;
1278     for (sn = SCRIPT_NOTES(script); !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn)) {
1279         type = (JSSrcNoteType) SN_TYPE(sn);
1280         if (type == SRC_SETLINE) {
1281             lineno = (uintN) js_GetSrcNoteOffset(sn, 0);
1282         } else if (type == SRC_NEWLINE) {
1283             lineno++;
1284         }
1285     }
1286     return 1 + lineno - script->lineno;