Code

r11451@tres: ted | 2006-04-17 22:21:33 -0700
[inkscape.git] / src / dom / js / jscntxt.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 execution context.
42  */
43 #include "jsstddef.h"
44 #include <stdarg.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include "jstypes.h"
48 #include "jsarena.h" /* Added by JSIFY */
49 #include "jsutil.h" /* Added by JSIFY */
50 #include "jsclist.h"
51 #include "jsprf.h"
52 #include "jsatom.h"
53 #include "jscntxt.h"
54 #include "jsconfig.h"
55 #include "jsdbgapi.h"
56 #include "jsexn.h"
57 #include "jsgc.h"
58 #include "jslock.h"
59 #include "jsnum.h"
60 #include "jsobj.h"
61 #include "jsopcode.h"
62 #include "jsscan.h"
63 #include "jsscript.h"
64 #include "jsstr.h"
66 JSContext *
67 js_NewContext(JSRuntime *rt, size_t stackChunkSize)
68 {
69     JSContext *cx;
70     JSBool ok, first;
72     cx = (JSContext *) malloc(sizeof *cx);
73     if (!cx)
74         return NULL;
75     memset(cx, 0, sizeof *cx);
77     cx->runtime = rt;
78 #if JS_STACK_GROWTH_DIRECTION > 0
79     cx->stackLimit = (jsuword)-1;
80 #endif
81 #ifdef JS_THREADSAFE
82     js_InitContextForLocking(cx);
83 #endif
85     JS_LOCK_GC(rt);
86     for (;;) {
87         first = (rt->contextList.next == &rt->contextList);
88         if (rt->state == JSRTS_UP) {
89             JS_ASSERT(!first);
90             break;
91         }
92         if (rt->state == JSRTS_DOWN) {
93             JS_ASSERT(first);
94             rt->state = JSRTS_LAUNCHING;
95             break;
96         }
97         JS_WAIT_CONDVAR(rt->stateChange, JS_NO_TIMEOUT);
98     }
99     JS_APPEND_LINK(&cx->links, &rt->contextList);
100     JS_UNLOCK_GC(rt);
102     /*
103      * First we do the infallible, every-time per-context initializations.
104      * Should a later, fallible initialization (js_InitRegExpStatics, e.g.,
105      * or the stuff under 'if (first)' below) fail, at least the version
106      * and arena-pools will be valid and safe to use (say, from the last GC
107      * done by js_DestroyContext).
108      */
109     cx->version = JSVERSION_DEFAULT;
110     cx->jsop_eq = JSOP_EQ;
111     cx->jsop_ne = JSOP_NE;
112     JS_InitArenaPool(&cx->stackPool, "stack", stackChunkSize, sizeof(jsval));
113     JS_InitArenaPool(&cx->tempPool, "temp", 1024, sizeof(jsdouble));
115 #if JS_HAS_REGEXPS
116     if (!js_InitRegExpStatics(cx, &cx->regExpStatics)) {
117         js_DestroyContext(cx, JS_NO_GC);
118         return NULL;
119     }
120 #endif
121 #if JS_HAS_EXCEPTIONS
122     cx->throwing = JS_FALSE;
123 #endif
125     /*
126      * If cx is the first context on this runtime, initialize well-known atoms,
127      * keywords, numbers, and strings.  If one of these steps should fail, the
128      * runtime will be left in a partially initialized state, with zeroes and
129      * nulls stored in the default-initialized remainder of the struct.  We'll
130      * clean the runtime up under js_DestroyContext, because cx will be "last"
131      * as well as "first".
132      */
133     if (first) {
134         ok = (rt->atomState.liveAtoms == 0)
135              ? js_InitAtomState(cx, &rt->atomState)
136              : js_InitPinnedAtoms(cx, &rt->atomState);
137         if (ok)
138             ok = js_InitScanner(cx);
139         if (ok)
140             ok = js_InitRuntimeNumberState(cx);
141         if (ok)
142             ok = js_InitRuntimeScriptState(cx);
143         if (ok)
144             ok = js_InitRuntimeStringState(cx);
145         if (!ok) {
146             js_DestroyContext(cx, JS_NO_GC);
147             return NULL;
148         }
150         JS_LOCK_GC(rt);
151         rt->state = JSRTS_UP;
152         JS_NOTIFY_ALL_CONDVAR(rt->stateChange);
153         JS_UNLOCK_GC(rt);
154     }
156     return cx;
159 void
160 js_DestroyContext(JSContext *cx, JSGCMode gcmode)
162     JSRuntime *rt;
163     JSBool last;
164     JSArgumentFormatMap *map;
165     JSLocalRootStack *lrs;
166     JSLocalRootChunk *lrc;
168     rt = cx->runtime;
170     /* Remove cx from context list first. */
171     JS_LOCK_GC(rt);
172     JS_ASSERT(rt->state == JSRTS_UP || rt->state == JSRTS_LAUNCHING);
173     JS_REMOVE_LINK(&cx->links);
174     last = (rt->contextList.next == &rt->contextList);
175     if (last)
176         rt->state = JSRTS_LANDING;
177     JS_UNLOCK_GC(rt);
179     if (last) {
180 #ifdef JS_THREADSAFE
181         /*
182          * If cx is not in a request already, begin one now so that we wait
183          * for any racing GC started on a not-last context to finish, before
184          * we plow ahead and unpin atoms.  Note that even though we begin a
185          * request here if necessary, we end all requests on cx below before
186          * forcing a final GC.  This lets any not-last context destruction
187          * racing in another thread try to force or maybe run the GC, but by
188          * that point, rt->state will not be JSRTS_UP, and that GC attempt
189          * will return early.
190          */
191         if (cx->requestDepth == 0)
192             JS_BeginRequest(cx);
193 #endif
195         /* Unpin all pinned atoms before final GC. */
196         js_UnpinPinnedAtoms(&rt->atomState);
198         /* Unlock and clear GC things held by runtime pointers. */
199         js_FinishRuntimeNumberState(cx);
200         js_FinishRuntimeStringState(cx);
202         /* Clear debugging state to remove GC roots. */
203         JS_ClearAllTraps(cx);
204         JS_ClearAllWatchPoints(cx);
205     }
207 #if JS_HAS_REGEXPS
208     /*
209      * Remove more GC roots in regExpStatics, then collect garbage.
210      * XXX anti-modularity alert: we rely on the call to js_RemoveRoot within
211      * XXX this function call to wait for any racing GC to complete, in the
212      * XXX case where JS_DestroyContext is called outside of a request on cx
213      */
214     js_FreeRegExpStatics(cx, &cx->regExpStatics);
215 #endif
217 #ifdef JS_THREADSAFE
218     /*
219      * Destroying a context implicitly calls JS_EndRequest().  Also, we must
220      * end our request here in case we are "last" -- in that event, another
221      * js_DestroyContext that was not last might be waiting in the GC for our
222      * request to end.  We'll let it run below, just before we do the truly
223      * final GC and then free atom state.
224      *
225      * At this point, cx must be inaccessible to other threads.  It's off the
226      * rt->contextList, and it should not be reachable via any object private
227      * data structure.
228      */
229     while (cx->requestDepth != 0)
230         JS_EndRequest(cx);
231 #endif
233     if (last) {
234         /* Always force, so we wait for any racing GC to finish. */
235         js_ForceGC(cx, GC_LAST_CONTEXT);
237         /* Iterate until no finalizer removes a GC root or lock. */
238         while (rt->gcPoke)
239             js_GC(cx, GC_LAST_CONTEXT);
241         /* Try to free atom state, now that no unrooted scripts survive. */
242         if (rt->atomState.liveAtoms == 0)
243             js_FreeAtomState(cx, &rt->atomState);
245         /* Now after the last GC can we free the script filename table. */
246         js_FinishRuntimeScriptState(cx);
248         /* Take the runtime down, now that it has no contexts or atoms. */
249         JS_LOCK_GC(rt);
250         rt->state = JSRTS_DOWN;
251         JS_NOTIFY_ALL_CONDVAR(rt->stateChange);
252         JS_UNLOCK_GC(rt);
253     } else {
254         if (gcmode == JS_FORCE_GC)
255             js_ForceGC(cx, 0);
256         else if (gcmode == JS_MAYBE_GC)
257             JS_MaybeGC(cx);
258     }
260     /* Free the stuff hanging off of cx. */
261     JS_FinishArenaPool(&cx->stackPool);
262     JS_FinishArenaPool(&cx->tempPool);
263     if (cx->lastMessage)
264         free(cx->lastMessage);
266     /* Remove any argument formatters. */
267     map = cx->argumentFormatMap;
268     while (map) {
269         JSArgumentFormatMap *temp = map;
270         map = map->next;
271         JS_free(cx, temp);
272     }
274     /* Destroy the resolve recursion damper. */
275     if (cx->resolvingTable) {
276         JS_DHashTableDestroy(cx->resolvingTable);
277         cx->resolvingTable = NULL;
278     }
280     lrs = cx->localRootStack;
281     if (lrs) {
282         while ((lrc = lrs->topChunk) != &lrs->firstChunk) {
283             lrs->topChunk = lrc->down;
284             JS_free(cx, lrc);
285         }
286         JS_free(cx, lrs);
287     }
289     /* Finally, free cx itself. */
290     free(cx);
293 JSBool
294 js_ValidContextPointer(JSRuntime *rt, JSContext *cx)
296     JSCList *cl;
298     for (cl = rt->contextList.next; cl != &rt->contextList; cl = cl->next) {
299         if (cl == &cx->links)
300             return JS_TRUE;
301     }
302     JS_RUNTIME_METER(rt, deadContexts);
303     return JS_FALSE;
306 JSContext *
307 js_ContextIterator(JSRuntime *rt, JSBool unlocked, JSContext **iterp)
309     JSContext *cx = *iterp;
311     if (unlocked)
312         JS_LOCK_GC(rt);
313     if (!cx)
314         cx = (JSContext *)&rt->contextList;
315     cx = (JSContext *)cx->links.next;
316     if (&cx->links == &rt->contextList)
317         cx = NULL;
318     *iterp = cx;
319     if (unlocked)
320         JS_UNLOCK_GC(rt);
321     return cx;
324 JS_STATIC_DLL_CALLBACK(const void *)
325 resolving_GetKey(JSDHashTable *table, JSDHashEntryHdr *hdr)
327     JSResolvingEntry *entry = (JSResolvingEntry *)hdr;
329     return &entry->key;
332 JS_STATIC_DLL_CALLBACK(JSDHashNumber)
333 resolving_HashKey(JSDHashTable *table, const void *ptr)
335     const JSResolvingKey *key = (const JSResolvingKey *)ptr;
337     return ((JSDHashNumber)key->obj >> JSVAL_TAGBITS) ^ key->id;
340 JS_PUBLIC_API(JSBool)
341 resolving_MatchEntry(JSDHashTable *table,
342                      const JSDHashEntryHdr *hdr,
343                      const void *ptr)
345     const JSResolvingEntry *entry = (const JSResolvingEntry *)hdr;
346     const JSResolvingKey *key = (const JSResolvingKey *)ptr;
348     return entry->key.obj == key->obj && entry->key.id == key->id;
351 static const JSDHashTableOps resolving_dhash_ops = {
352     JS_DHashAllocTable,
353     JS_DHashFreeTable,
354     resolving_GetKey,
355     resolving_HashKey,
356     resolving_MatchEntry,
357     JS_DHashMoveEntryStub,
358     JS_DHashClearEntryStub,
359     JS_DHashFinalizeStub,
360     NULL
361 };
363 JSBool
364 js_StartResolving(JSContext *cx, JSResolvingKey *key, uint32 flag,
365                   JSResolvingEntry **entryp)
367     JSDHashTable *table;
368     JSResolvingEntry *entry;
370     table = cx->resolvingTable;
371     if (!table) {
372         table = JS_NewDHashTable(&resolving_dhash_ops, NULL,
373                                  sizeof(JSResolvingEntry),
374                                  JS_DHASH_MIN_SIZE);
375         if (!table)
376             goto outofmem;
377         cx->resolvingTable = table;
378     }
380     entry = (JSResolvingEntry *)
381             JS_DHashTableOperate(table, key, JS_DHASH_ADD);
382     if (!entry)
383         goto outofmem;
385     if (entry->flags & flag) {
386         /* An entry for (key, flag) exists already -- dampen recursion. */
387         entry = NULL;
388     } else {
389         /* Fill in key if we were the first to add entry, then set flag. */
390         if (!entry->key.obj)
391             entry->key = *key;
392         entry->flags |= flag;
393     }
394     *entryp = entry;
395     return JS_TRUE;
397 outofmem:
398     JS_ReportOutOfMemory(cx);
399     return JS_FALSE;
402 void
403 js_StopResolving(JSContext *cx, JSResolvingKey *key, uint32 flag,
404                  JSResolvingEntry *entry, uint32 generation)
406     JSDHashTable *table;
408     /*
409      * Clear flag from entry->flags and return early if other flags remain.
410      * We must take care to re-lookup entry if the table has changed since
411      * it was found by js_StartResolving.
412      */
413     table = cx->resolvingTable;
414     if (!entry || table->generation != generation) {
415         entry = (JSResolvingEntry *)
416                 JS_DHashTableOperate(table, key, JS_DHASH_LOOKUP);
417     }
418     JS_ASSERT(JS_DHASH_ENTRY_IS_BUSY(&entry->hdr));
419     entry->flags &= ~flag;
420     if (entry->flags)
421         return;
423     /*
424      * Do a raw remove only if fewer entries were removed than would cause
425      * alpha to be less than .5 (alpha is at most .75).  Otherwise, we just
426      * call JS_DHashTableOperate to re-lookup the key and remove its entry,
427      * compressing or shrinking the table as needed.
428      */
429     if (table->removedCount < JS_DHASH_TABLE_SIZE(table) >> 2)
430         JS_DHashTableRawRemove(table, &entry->hdr);
431     else
432         JS_DHashTableOperate(table, key, JS_DHASH_REMOVE);
435 JSBool
436 js_EnterLocalRootScope(JSContext *cx)
438     JSLocalRootStack *lrs;
439     int mark;
441     lrs = cx->localRootStack;
442     if (!lrs) {
443         lrs = (JSLocalRootStack *) JS_malloc(cx, sizeof *lrs);
444         if (!lrs)
445             return JS_FALSE;
446         lrs->scopeMark = JSLRS_NULL_MARK;
447         lrs->rootCount = 0;
448         lrs->topChunk = &lrs->firstChunk;
449         lrs->firstChunk.down = NULL;
450         cx->localRootStack = lrs;
451     }
453     /* Push lrs->scopeMark to save it for restore when leaving. */
454     mark = js_PushLocalRoot(cx, lrs, INT_TO_JSVAL(lrs->scopeMark));
455     if (mark < 0)
456         return JS_FALSE;
457     lrs->scopeMark = (uint16) mark;
458     return JS_TRUE;
461 void
462 js_LeaveLocalRootScope(JSContext *cx)
464     JSLocalRootStack *lrs;
465     unsigned mark, m, n;
466     JSLocalRootChunk *lrc;
468     /* Defend against buggy native callers. */
469     lrs = cx->localRootStack;
470     JS_ASSERT(lrs && lrs->rootCount != 0);
471     if (!lrs || lrs->rootCount == 0)
472         return;
474     mark = lrs->scopeMark;
475     JS_ASSERT(mark != JSLRS_NULL_MARK);
476     if (mark == JSLRS_NULL_MARK)
477         return;
479     /* Free any chunks being popped by this leave operation. */
480     m = mark >> JSLRS_CHUNK_SHIFT;
481     n = (lrs->rootCount - 1) >> JSLRS_CHUNK_SHIFT;
482     while (n > m) {
483         lrc = lrs->topChunk;
484         JS_ASSERT(lrc != &lrs->firstChunk);
485         lrs->topChunk = lrc->down;
486         JS_free(cx, lrc);
487         --n;
488     }
490     /* Pop the scope, restoring lrs->scopeMark. */
491     lrc = lrs->topChunk;
492     m = mark & JSLRS_CHUNK_MASK;
493     lrs->scopeMark = JSVAL_TO_INT(lrc->roots[m]);
494     lrc->roots[m] = JSVAL_NULL;
495     lrs->rootCount = (uint16) mark;
497     /*
498      * Free the stack eagerly, risking malloc churn.  The alternative would
499      * require an lrs->entryCount member, maintained by Enter and Leave, and
500      * tested by the GC in addition to the cx->localRootStack non-null test.
501      *
502      * That approach would risk hoarding 264 bytes (net) per context.  Right
503      * now it seems better to give fresh (dirty in CPU write-back cache, and
504      * the data is no longer needed) memory back to the malloc heap.
505      */
506     if (mark == 0) {
507         cx->localRootStack = NULL;
508         JS_free(cx, lrs);
509     } else if (m == 0) {
510         lrs->topChunk = lrc->down;
511         JS_free(cx, lrc);
512     }
515 void
516 js_ForgetLocalRoot(JSContext *cx, jsval v)
518     JSLocalRootStack *lrs;
519     unsigned i, j, m, n, mark;
520     JSLocalRootChunk *lrc, *lrc2;
521     jsval top;
523     lrs = cx->localRootStack;
524     JS_ASSERT(lrs && lrs->rootCount);
525     if (!lrs || lrs->rootCount == 0)
526         return;
528     /* Prepare to pop the top-most value from the stack. */
529     n = lrs->rootCount - 1;
530     m = n & JSLRS_CHUNK_MASK;
531     lrc = lrs->topChunk;
532     top = lrc->roots[m];
534     /* Be paranoid about calls on an empty scope. */
535     mark = lrs->scopeMark;
536     JS_ASSERT(mark < n);
537     if (mark >= n)
538         return;
540     /* If v was not the last root pushed in the top scope, find it. */
541     if (top != v) {
542         /* Search downward in case v was recently pushed. */
543         i = n;
544         j = m;
545         lrc2 = lrc;
546         while (--i > mark) {
547             if (j == 0)
548                 lrc2 = lrc2->down;
549             j = i & JSLRS_CHUNK_MASK;
550             if (lrc2->roots[j] == v)
551                 break;
552         }
554         /* If we didn't find v in this scope, assert and bail out. */
555         JS_ASSERT(i != mark);
556         if (i == mark)
557             return;
559         /* Swap top and v so common tail code can pop v. */
560         lrc2->roots[j] = top;
561     }
563     /* Pop the last value from the stack. */
564     lrc->roots[m] = JSVAL_NULL;
565     lrs->rootCount = n;
566     if (m == 0) {
567         JS_ASSERT(n != 0);
568         JS_ASSERT(lrc != &lrs->firstChunk);
569         lrs->topChunk = lrc->down;
570         JS_free(cx, lrc);
571     }
574 int
575 js_PushLocalRoot(JSContext *cx, JSLocalRootStack *lrs, jsval v)
577     unsigned n, m;
578     JSLocalRootChunk *lrc;
580     n = lrs->rootCount;
581     m = n & JSLRS_CHUNK_MASK;
582     if (n == 0 || m != 0) {
583         /*
584          * At start of first chunk, or not at start of a non-first top chunk.
585          * Check for lrs->rootCount overflow.
586          */
587         if ((uint16)(n + 1) == 0) {
588             JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
589                                  JSMSG_TOO_MANY_LOCAL_ROOTS);
590             return -1;
591         }
592         lrc = lrs->topChunk;
593         JS_ASSERT(n != 0 || lrc == &lrs->firstChunk);
594     } else {
595         /*
596          * After lrs->firstChunk, trying to index at a power-of-two chunk
597          * boundary: need a new chunk.
598          */
599         lrc = (JSLocalRootChunk *) JS_malloc(cx, sizeof *lrc);
600         if (!lrc)
601             return -1;
602         lrc->down = lrs->topChunk;
603         lrs->topChunk = lrc;
604     }
605     lrs->rootCount = n + 1;
606     lrc->roots[m] = v;
607     return (int) m;
610 void
611 js_MarkLocalRoots(JSContext *cx, JSLocalRootStack *lrs)
613     unsigned n, m, mark;
614     JSLocalRootChunk *lrc;
616     n = lrs->rootCount;
617     if (n == 0)
618         return;
620     mark = lrs->scopeMark;
621     lrc = lrs->topChunk;
622     while (--n > mark) {
623 #ifdef GC_MARK_DEBUG
624         char name[22];
625         JS_snprintf(name, sizeof name, "<local root %u>", n);
626 #else
627         const char *name = NULL;
628 #endif
629         m = n & JSLRS_CHUNK_MASK;
630         JS_ASSERT(JSVAL_IS_GCTHING(lrc->roots[m]));
631         JS_MarkGCThing(cx, JSVAL_TO_GCTHING(lrc->roots[m]), name, NULL);
632         if (m == 0)
633             lrc = lrc->down;
634     }
637 static void
638 ReportError(JSContext *cx, const char *message, JSErrorReport *reportp)
640     /*
641      * Check the error report, and set a JavaScript-catchable exception
642      * if the error is defined to have an associated exception.  If an
643      * exception is thrown, then the JSREPORT_EXCEPTION flag will be set
644      * on the error report, and exception-aware hosts should ignore it.
645      */
646     if (reportp && reportp->errorNumber == JSMSG_UNCAUGHT_EXCEPTION)
647         reportp->flags |= JSREPORT_EXCEPTION;
649 #if JS_HAS_ERROR_EXCEPTIONS
650     /*
651      * Call the error reporter only if an exception wasn't raised.
652      *
653      * If an exception was raised, then we call the debugErrorHook
654      * (if present) to give it a chance to see the error before it
655      * propagates out of scope.  This is needed for compatability
656      * with the old scheme.
657      */
658     if (!js_ErrorToException(cx, message, reportp)) {
659         js_ReportErrorAgain(cx, message, reportp);
660     } else if (cx->runtime->debugErrorHook && cx->errorReporter) {
661         JSDebugErrorHook hook = cx->runtime->debugErrorHook;
662         /* test local in case debugErrorHook changed on another thread */
663         if (hook)
664             hook(cx, message, reportp, cx->runtime->debugErrorHookData);
665     }
666 #else
667     js_ReportErrorAgain(cx, message, reportp);
668 #endif
671 /*
672  * We don't post an exception in this case, since doing so runs into
673  * complications of pre-allocating an exception object which required
674  * running the Exception class initializer early etc.
675  * Instead we just invoke the errorReporter with an "Out Of Memory"
676  * type message, and then hope the process ends swiftly.
677  */
678 void
679 js_ReportOutOfMemory(JSContext *cx, JSErrorCallback callback)
681     JSStackFrame *fp;
682     JSErrorReport report;
683     JSErrorReporter onError = cx->errorReporter;
685     /* Get the message for this error, but we won't expand any arguments. */
686     const JSErrorFormatString *efs = callback(NULL, NULL, JSMSG_OUT_OF_MEMORY);
687     const char *msg = efs ? efs->format : "Out of memory";
689     /* Fill out the report, but don't do anything that requires allocation. */
690     memset(&report, 0, sizeof (struct JSErrorReport));
691     report.flags = JSREPORT_ERROR;
692     report.errorNumber = JSMSG_OUT_OF_MEMORY;
694     /*
695      * Walk stack until we find a frame that is associated with some script
696      * rather than a native frame.
697      */
698     for (fp = cx->fp; fp; fp = fp->down) {
699         if (fp->script && fp->pc) {
700             report.filename = fp->script->filename;
701             report.lineno = js_PCToLineNumber(cx, fp->script, fp->pc);
702             break;
703         }
704     }
706     /*
707      * If debugErrorHook is present then we give it a chance to veto
708      * sending the error on to the regular ErrorReporter.
709      */
710     if (onError) {
711         JSDebugErrorHook hook = cx->runtime->debugErrorHook;
712         if (hook &&
713             !hook(cx, msg, &report, cx->runtime->debugErrorHookData)) {
714             onError = NULL;
715         }
716     }
718     if (onError)
719         onError(cx, msg, &report);
722 JSBool
723 js_ReportErrorVA(JSContext *cx, uintN flags, const char *format, va_list ap)
725     char *last;
726     JSStackFrame *fp;
727     JSErrorReport report;
728     JSBool warning;
730     if ((flags & JSREPORT_STRICT) && !JS_HAS_STRICT_OPTION(cx))
731         return JS_TRUE;
733     last = JS_vsmprintf(format, ap);
734     if (!last)
735         return JS_FALSE;
737     memset(&report, 0, sizeof (struct JSErrorReport));
738     report.flags = flags;
740     /* Find the top-most active script frame, for best line number blame. */
741     for (fp = cx->fp; fp; fp = fp->down) {
742         if (fp->script && fp->pc) {
743             report.filename = fp->script->filename;
744             report.lineno = js_PCToLineNumber(cx, fp->script, fp->pc);
745             break;
746         }
747     }
749     warning = JSREPORT_IS_WARNING(report.flags);
750     if (warning && JS_HAS_WERROR_OPTION(cx)) {
751         report.flags &= ~JSREPORT_WARNING;
752         warning = JS_FALSE;
753     }
755     ReportError(cx, last, &report);
756     free(last);
757     return warning;
760 /*
761  * The arguments from ap need to be packaged up into an array and stored
762  * into the report struct.
763  *
764  * The format string addressed by the error number may contain operands
765  * identified by the format {N}, where N is a decimal digit. Each of these
766  * is to be replaced by the Nth argument from the va_list. The complete
767  * message is placed into reportp->ucmessage converted to a JSString.
768  *
769  * Returns true if the expansion succeeds (can fail if out of memory).
770  */
771 JSBool
772 js_ExpandErrorArguments(JSContext *cx, JSErrorCallback callback,
773                         void *userRef, const uintN errorNumber,
774                         char **messagep, JSErrorReport *reportp,
775                         JSBool *warningp, JSBool charArgs, va_list ap)
777     const JSErrorFormatString *efs;
778     int i;
779     int argCount;
781     *warningp = JSREPORT_IS_WARNING(reportp->flags);
782     if (*warningp && JS_HAS_WERROR_OPTION(cx)) {
783         reportp->flags &= ~JSREPORT_WARNING;
784         *warningp = JS_FALSE;
785     }
787     *messagep = NULL;
788     if (callback) {
789         efs = callback(userRef, NULL, errorNumber);
790         if (efs) {
791             size_t totalArgsLength = 0;
792             size_t argLengths[10]; /* only {0} thru {9} supported */
793             argCount = efs->argCount;
794             JS_ASSERT(argCount <= 10);
795             if (argCount > 0) {
796                 /*
797                  * Gather the arguments into an array, and accumulate
798                  * their sizes. We allocate 1 more than necessary and
799                  * null it out to act as the caboose when we free the
800                  * pointers later.
801                  */
802                 reportp->messageArgs = (const jschar **)
803                     JS_malloc(cx, sizeof(jschar *) * (argCount + 1));
804                 if (!reportp->messageArgs)
805                     return JS_FALSE;
806                 reportp->messageArgs[argCount] = NULL;
807                 for (i = 0; i < argCount; i++) {
808                     if (charArgs) {
809                         char *charArg = va_arg(ap, char *);
810                         reportp->messageArgs[i]
811                             = js_InflateString(cx, charArg, strlen(charArg));
812                         if (!reportp->messageArgs[i])
813                             goto error;
814                     }
815                     else
816                         reportp->messageArgs[i] = va_arg(ap, jschar *);
817                     argLengths[i] = js_strlen(reportp->messageArgs[i]);
818                     totalArgsLength += argLengths[i];
819                 }
820                 /* NULL-terminate for easy copying. */
821                 reportp->messageArgs[i] = NULL;
822             }
823             /*
824              * Parse the error format, substituting the argument X
825              * for {X} in the format.
826              */
827             if (argCount > 0) {
828                 if (efs->format) {
829                     const char *fmt;
830                     const jschar *arg;
831                     jschar *out;
832                     int expandedArgs = 0;
833                     size_t expandedLength
834                         = strlen(efs->format)
835                             - (3 * argCount) /* exclude the {n} */
836                             + totalArgsLength;
837                     /*
838                      * Note - the above calculation assumes that each argument
839                      * is used once and only once in the expansion !!!
840                      */
841                     reportp->ucmessage = out = (jschar *)
842                         JS_malloc(cx, (expandedLength + 1) * sizeof(jschar));
843                     if (!out)
844                         goto error;
845                     fmt = efs->format;
846                     while (*fmt) {
847                         if (*fmt == '{') {
848                             if (isdigit(fmt[1])) {
849                                 int d = JS7_UNDEC(fmt[1]);
850                                 JS_ASSERT(expandedArgs < argCount);
851                                 arg = reportp->messageArgs[d];
852                                 js_strncpy(out, arg, argLengths[d]);
853                                 out += argLengths[d];
854                                 fmt += 3;
855                                 expandedArgs++;
856                                 continue;
857                             }
858                         }
859                         /*
860                          * is this kosher?
861                          */
862                         *out++ = (unsigned char)(*fmt++);
863                     }
864                     JS_ASSERT(expandedArgs == argCount);
865                     *out = 0;
866                     *messagep =
867                         js_DeflateString(cx, reportp->ucmessage,
868                                          (size_t)(out - reportp->ucmessage));
869                     if (!*messagep)
870                         goto error;
871                 }
872             } else {
873                 /*
874                  * Zero arguments: the format string (if it exists) is the
875                  * entire message.
876                  */
877                 if (efs->format) {
878                     *messagep = JS_strdup(cx, efs->format);
879                     if (!*messagep)
880                         goto error;
881                     reportp->ucmessage
882                         = js_InflateString(cx, *messagep, strlen(*messagep));
883                     if (!reportp->ucmessage)
884                         goto error;
885                 }
886             }
887         }
888     }
889     if (*messagep == NULL) {
890         /* where's the right place for this ??? */
891         const char *defaultErrorMessage
892             = "No error message available for error number %d";
893         size_t nbytes = strlen(defaultErrorMessage) + 16;
894         *messagep = (char *)JS_malloc(cx, nbytes);
895         if (!*messagep)
896             goto error;
897         JS_snprintf(*messagep, nbytes, defaultErrorMessage, errorNumber);
898     }
899     return JS_TRUE;
901 error:
902     if (reportp->messageArgs) {
903         i = 0;
904         while (reportp->messageArgs[i])
905             JS_free(cx, (void *)reportp->messageArgs[i++]);
906         JS_free(cx, (void *)reportp->messageArgs);
907         reportp->messageArgs = NULL;
908     }
909     if (reportp->ucmessage) {
910         JS_free(cx, (void *)reportp->ucmessage);
911         reportp->ucmessage = NULL;
912     }
913     if (*messagep) {
914         JS_free(cx, (void *)*messagep);
915         *messagep = NULL;
916     }
917     return JS_FALSE;
920 JSBool
921 js_ReportErrorNumberVA(JSContext *cx, uintN flags, JSErrorCallback callback,
922                        void *userRef, const uintN errorNumber,
923                        JSBool charArgs, va_list ap)
925     JSStackFrame *fp;
926     JSErrorReport report;
927     char *message;
928     JSBool warning;
930     if ((flags & JSREPORT_STRICT) && !JS_HAS_STRICT_OPTION(cx))
931         return JS_TRUE;
933     memset(&report, 0, sizeof (struct JSErrorReport));
934     report.flags = flags;
935     report.errorNumber = errorNumber;
937     /*
938      * If we can't find out where the error was based on the current frame,
939      * see if the next frame has a script/pc combo we can use.
940      */
941     for (fp = cx->fp; fp; fp = fp->down) {
942         if (fp->script && fp->pc) {
943             report.filename = fp->script->filename;
944             report.lineno = js_PCToLineNumber(cx, fp->script, fp->pc);
945             break;
946         }
947     }
949     if (!js_ExpandErrorArguments(cx, callback, userRef, errorNumber,
950                                  &message, &report, &warning, charArgs, ap)) {
951         return JS_FALSE;
952     }
954     ReportError(cx, message, &report);
956     if (message)
957         JS_free(cx, message);
958     if (report.messageArgs) {
959         int i = 0;
960         while (report.messageArgs[i])
961             JS_free(cx, (void *)report.messageArgs[i++]);
962         JS_free(cx, (void *)report.messageArgs);
963     }
964     if (report.ucmessage)
965         JS_free(cx, (void *)report.ucmessage);
967     return warning;
970 JS_FRIEND_API(void)
971 js_ReportErrorAgain(JSContext *cx, const char *message, JSErrorReport *reportp)
973     JSErrorReporter onError;
975     if (!message)
976         return;
978     if (cx->lastMessage)
979         free(cx->lastMessage);
980     cx->lastMessage = JS_strdup(cx, message);
981     if (!cx->lastMessage)
982         return;
983     onError = cx->errorReporter;
985     /*
986      * If debugErrorHook is present then we give it a chance to veto
987      * sending the error on to the regular ErrorReporter.
988      */
989     if (onError) {
990         JSDebugErrorHook hook = cx->runtime->debugErrorHook;
991         if (hook &&
992             !hook(cx, cx->lastMessage, reportp,
993                   cx->runtime->debugErrorHookData)) {
994             onError = NULL;
995         }
996     }
997     if (onError)
998         onError(cx, cx->lastMessage, reportp);
1001 void
1002 js_ReportIsNotDefined(JSContext *cx, const char *name)
1004     JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_DEFINED, name);
1007 #if defined DEBUG && defined XP_UNIX
1008 /* For gdb usage. */
1009 void js_traceon(JSContext *cx)  { cx->tracefp = stderr; }
1010 void js_traceoff(JSContext *cx) { cx->tracefp = NULL; }
1011 #endif
1013 JSErrorFormatString js_ErrorFormatString[JSErr_Limit] = {
1014 #if JS_HAS_DFLT_MSG_STRINGS
1015 #define MSG_DEF(name, number, count, exception, format) \
1016     { format, count } ,
1017 #else
1018 #define MSG_DEF(name, number, count, exception, format) \
1019     { NULL, count } ,
1020 #endif
1021 #include "js.msg"
1022 #undef MSG_DEF
1023 };
1025 const JSErrorFormatString *
1026 js_GetErrorMessage(void *userRef, const char *locale, const uintN errorNumber)
1028     if ((errorNumber > 0) && (errorNumber < JSErr_Limit))
1029         return &js_ErrorFormatString[errorNumber];
1030     return NULL;