Back to index

lightning-sunbird  0.9+nobinonly
jsexn.c
Go to the documentation of this file.
00001 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
00002  * vim: set ts=8 sw=4 et tw=78:
00003  *
00004  * ***** BEGIN LICENSE BLOCK *****
00005  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00006  *
00007  * The contents of this file are subject to the Mozilla Public License Version
00008  * 1.1 (the "License"); you may not use this file except in compliance with
00009  * the License. You may obtain a copy of the License at
00010  * http://www.mozilla.org/MPL/
00011  *
00012  * Software distributed under the License is distributed on an "AS IS" basis,
00013  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00014  * for the specific language governing rights and limitations under the
00015  * License.
00016  *
00017  * The Original Code is Mozilla Communicator client code, released
00018  * March 31, 1998.
00019  *
00020  * The Initial Developer of the Original Code is
00021  * Netscape Communications Corporation.
00022  * Portions created by the Initial Developer are Copyright (C) 1998
00023  * the Initial Developer. All Rights Reserved.
00024  *
00025  * Contributor(s):
00026  *
00027  * Alternatively, the contents of this file may be used under the terms of
00028  * either of the GNU General Public License Version 2 or later (the "GPL"),
00029  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00030  * in which case the provisions of the GPL or the LGPL are applicable instead
00031  * of those above. If you wish to allow use of your version of this file only
00032  * under the terms of either the GPL or the LGPL, and not to allow others to
00033  * use your version of this file under the terms of the MPL, indicate your
00034  * decision by deleting the provisions above and replace them with the notice
00035  * and other provisions required by the GPL or the LGPL. If you do not delete
00036  * the provisions above, a recipient may use your version of this file under
00037  * the terms of any one of the MPL, the GPL or the LGPL.
00038  *
00039  * ***** END LICENSE BLOCK ***** */
00040 
00041 /*
00042  * JS standard exception implementation.
00043  */
00044 
00045 #include "jsstddef.h"
00046 #include <stdlib.h>
00047 #include <string.h>
00048 #include "jstypes.h"
00049 #include "jsbit.h"
00050 #include "jsutil.h" /* Added by JSIFY */
00051 #include "jsprf.h"
00052 #include "jsapi.h"
00053 #include "jscntxt.h"
00054 #include "jsconfig.h"
00055 #include "jsdbgapi.h"
00056 #include "jsexn.h"
00057 #include "jsfun.h"
00058 #include "jsinterp.h"
00059 #include "jsnum.h"
00060 #include "jsopcode.h"
00061 #include "jsscript.h"
00062 
00063 /* Forward declarations for js_ErrorClass's initializer. */
00064 static JSBool
00065 Exception(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
00066 
00067 static void
00068 exn_finalize(JSContext *cx, JSObject *obj);
00069 
00070 static uint32
00071 exn_mark(JSContext *cx, JSObject *obj, void *arg);
00072 
00073 static void
00074 exn_finalize(JSContext *cx, JSObject *obj);
00075 
00076 static JSBool
00077 exn_enumerate(JSContext *cx, JSObject *obj);
00078 
00079 static JSBool
00080 exn_resolve(JSContext *cx, JSObject *obj, jsval id, uintN flags,
00081             JSObject **objp);
00082 
00083 JSClass js_ErrorClass = {
00084     js_Error_str,
00085     JSCLASS_HAS_PRIVATE | JSCLASS_NEW_RESOLVE |
00086     JSCLASS_HAS_CACHED_PROTO(JSProto_Error),
00087     JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,
00088     exn_enumerate,    (JSResolveOp)exn_resolve, JS_ConvertStub, exn_finalize,
00089     NULL,             NULL,             NULL,             Exception,
00090     NULL,             NULL,             exn_mark,         NULL
00091 };
00092 
00093 typedef struct JSStackTraceElem {
00094     JSString            *funName;
00095     size_t              argc;
00096     const char          *filename;
00097     uintN               ulineno;
00098 } JSStackTraceElem;
00099 
00100 typedef struct JSExnPrivate {
00101     /* A copy of the JSErrorReport originally generated. */
00102     JSErrorReport       *errorReport;
00103     JSString            *message;
00104     JSString            *filename;
00105     uintN               lineno;
00106     size_t              stackDepth;
00107     JSStackTraceElem    stackElems[1];
00108 } JSExnPrivate;
00109 
00110 static JSString *
00111 StackTraceToString(JSContext *cx, JSExnPrivate *priv);
00112 
00113 static JSErrorReport *
00114 CopyErrorReport(JSContext *cx, JSErrorReport *report)
00115 {
00116     /*
00117      * We use a single malloc block to make a deep copy of JSErrorReport with
00118      * the following layout:
00119      *   JSErrorReport
00120      *   array of copies of report->messageArgs
00121      *   jschar array with characters for all messageArgs
00122      *   jschar array with characters for ucmessage
00123      *   jschar array with characters for uclinebuf and uctokenptr
00124      *   char array with characters for linebuf and tokenptr
00125      *   char array with characters for filename
00126      * Such layout together with the properties enforced by the following
00127      * asserts does not need any extra alignment padding.
00128      */
00129     JS_STATIC_ASSERT(sizeof(JSErrorReport) % sizeof(const char *) == 0);
00130     JS_STATIC_ASSERT(sizeof(const char *) % sizeof(jschar) == 0);
00131 
00132     size_t filenameSize;
00133     size_t linebufSize;
00134     size_t uclinebufSize;
00135     size_t ucmessageSize;
00136     size_t i, argsArraySize, argsCopySize, argSize;
00137     size_t mallocSize;
00138     JSErrorReport *copy;
00139     uint8 *cursor;
00140 
00141 #define JS_CHARS_SIZE(jschars) ((js_strlen(jschars) + 1) * sizeof(jschar))
00142 
00143     filenameSize = report->filename ? strlen(report->filename) + 1 : 0;
00144     linebufSize = report->linebuf ? strlen(report->linebuf) + 1 : 0;
00145     uclinebufSize = report->uclinebuf ? JS_CHARS_SIZE(report->uclinebuf) : 0;
00146     ucmessageSize = 0;
00147     argsArraySize = 0;
00148     argsCopySize = 0;
00149     if (report->ucmessage) {
00150         ucmessageSize = JS_CHARS_SIZE(report->ucmessage);
00151         if (report->messageArgs) {
00152             for (i = 0; report->messageArgs[i]; ++i)
00153                 argsCopySize += JS_CHARS_SIZE(report->messageArgs[i]);
00154 
00155             /* Non-null messageArgs should have at least one non-null arg. */
00156             JS_ASSERT(i != 0);
00157             argsArraySize = (i + 1) * sizeof(const jschar *);
00158         }
00159     }
00160 
00161     /*
00162      * The mallocSize can not overflow since it represents the sum of the
00163      * sizes of already allocated objects.
00164      */
00165     mallocSize = sizeof(JSErrorReport) + argsArraySize + argsCopySize +
00166                  ucmessageSize + uclinebufSize + linebufSize + filenameSize;
00167     cursor = (uint8 *)JS_malloc(cx, mallocSize);
00168     if (!cursor)
00169         return NULL;
00170 
00171     copy = (JSErrorReport *)cursor;
00172     memset(cursor, 0, sizeof(JSErrorReport));
00173     cursor += sizeof(JSErrorReport);
00174 
00175     if (argsArraySize != 0) {
00176         copy->messageArgs = (const jschar **)cursor;
00177         cursor += argsArraySize;
00178         for (i = 0; report->messageArgs[i]; ++i) {
00179             copy->messageArgs[i] = (const jschar *)cursor;
00180             argSize = JS_CHARS_SIZE(report->messageArgs[i]);
00181             memcpy(cursor, report->messageArgs[i], argSize);
00182             cursor += argSize;
00183         }
00184         copy->messageArgs[i] = NULL;
00185         JS_ASSERT(cursor == (uint8 *)copy->messageArgs[0] + argsCopySize);
00186     }
00187 
00188     if (report->ucmessage) {
00189         copy->ucmessage = (const jschar *)cursor;
00190         memcpy(cursor, report->ucmessage, ucmessageSize);
00191         cursor += ucmessageSize;
00192     }
00193 
00194     if (report->uclinebuf) {
00195         copy->uclinebuf = (const jschar *)cursor;
00196         memcpy(cursor, report->uclinebuf, uclinebufSize);
00197         cursor += uclinebufSize;
00198         if (report->uctokenptr) {
00199             copy->uctokenptr = copy->uclinebuf + (report->uctokenptr -
00200                                                   report->uclinebuf);
00201         }
00202     }
00203 
00204     if (report->linebuf) {
00205         copy->linebuf = (const char *)cursor;
00206         memcpy(cursor, report->linebuf, linebufSize);
00207         cursor += linebufSize;
00208         if (report->tokenptr) {
00209             copy->tokenptr = copy->linebuf + (report->tokenptr -
00210                                               report->linebuf);
00211         }
00212     }
00213 
00214     if (report->filename) {
00215         copy->filename = (const char *)cursor;
00216         memcpy(cursor, report->filename, filenameSize);
00217     }
00218     JS_ASSERT(cursor + filenameSize == (uint8 *)copy + mallocSize);
00219 
00220     /* Copy non-pointer members. */
00221     copy->lineno = report->lineno;
00222     copy->errorNumber = report->errorNumber;
00223 
00224     /* Note that this is before it gets flagged with JSREPORT_EXCEPTION */
00225     copy->flags = report->flags;
00226 
00227 #undef JS_CHARS_SIZE
00228     return copy;
00229 }
00230 
00231 static jsval *
00232 GetStackTraceValueBuffer(JSExnPrivate *priv)
00233 {
00234     /*
00235      * We use extra memory after JSExnPrivateInfo.stackElems to store jsvals
00236      * that helps to produce more informative stack traces. The following
00237      * assert allows us to assume that no gap after stackElems is necessary to
00238      * align the buffer properly.
00239      */
00240     JS_STATIC_ASSERT(sizeof(JSStackTraceElem) % sizeof(jsval) == 0);
00241 
00242     return (jsval *)(priv->stackElems + priv->stackDepth);
00243 }
00244 
00245 static JSBool
00246 InitExnPrivate(JSContext *cx, JSObject *exnObject, JSString *message,
00247                JSString *filename, uintN lineno, JSErrorReport *report)
00248 {
00249     JSCheckAccessOp checkAccess;
00250     JSErrorReporter older;
00251     JSExceptionState *state;
00252     jsval callerid, v;
00253     JSStackFrame *fp, *fpstop;
00254     size_t stackDepth, valueCount, size;
00255     JSBool overflow;
00256     JSExnPrivate *priv;
00257     JSStackTraceElem *elem;
00258     jsval *values;
00259 
00260     JS_ASSERT(OBJ_GET_CLASS(cx, exnObject) == &js_ErrorClass);
00261 
00262     /*
00263      * Prepare stack trace data.
00264      *
00265      * Set aside any error reporter for cx and save its exception state
00266      * so we can suppress any checkAccess failures.  Such failures should stop
00267      * the backtrace procedure, not result in a failure of this constructor.
00268      */
00269     checkAccess = cx->runtime->checkObjectAccess;
00270     older = JS_SetErrorReporter(cx, NULL);
00271     state = JS_SaveExceptionState(cx);
00272 
00273     callerid = ATOM_KEY(cx->runtime->atomState.callerAtom);
00274     stackDepth = 0;
00275     valueCount = 0;
00276     for (fp = cx->fp; fp; fp = fp->down) {
00277         if (fp->fun && fp->argv) {
00278             if (checkAccess) {
00279                 v = fp->argv[-2];
00280                 if (!JSVAL_IS_PRIMITIVE(v) &&
00281                     !checkAccess(cx, JSVAL_TO_OBJECT(v), callerid,
00282                                  JSACC_READ, &v /* ignored */)) {
00283                     break;
00284                 }
00285             }
00286             valueCount += fp->argc;
00287         }
00288         ++stackDepth;
00289     }
00290     JS_RestoreExceptionState(cx, state);
00291     JS_SetErrorReporter(cx, older);
00292     fpstop = fp;
00293 
00294     size = offsetof(JSExnPrivate, stackElems);
00295     overflow = (stackDepth > ((size_t)-1 - size) / sizeof(JSStackTraceElem));
00296     size += stackDepth * sizeof(JSStackTraceElem);
00297     overflow |= (valueCount > ((size_t)-1 - size) / sizeof(jsval));
00298     size += valueCount * sizeof(jsval);
00299     if (overflow) {
00300         JS_ReportOutOfMemory(cx);
00301         return JS_FALSE;
00302     }
00303     priv = (JSExnPrivate *)JS_malloc(cx, size);
00304     if (!priv)
00305         return JS_FALSE;
00306 
00307     /*
00308      * We initialize errorReport with a copy of report after setting the
00309      * private slot, to prevent GC accessing a junk value we clear the field
00310      * here.
00311      */
00312     priv->errorReport = NULL;
00313     priv->message = message;
00314     priv->filename = filename;
00315     priv->lineno = lineno;
00316     priv->stackDepth = stackDepth;
00317 
00318     values = GetStackTraceValueBuffer(priv);
00319     elem = priv->stackElems;
00320     for (fp = cx->fp; fp != fpstop; fp = fp->down) {
00321         if (!fp->fun) {
00322             elem->funName = NULL;
00323             elem->argc = 0;
00324         } else {
00325             elem->funName = fp->fun->atom
00326                             ? ATOM_TO_STRING(fp->fun->atom)
00327                             : cx->runtime->emptyString;
00328             elem->argc = fp->argc;
00329             memcpy(values, fp->argv, fp->argc * sizeof(jsval));
00330             values += fp->argc;
00331         }
00332         elem->ulineno = 0;
00333         elem->filename = NULL;
00334         if (fp->script) {
00335             elem->filename = fp->script->filename;
00336             if (fp->pc)
00337                 elem->ulineno = js_PCToLineNumber(cx, fp->script, fp->pc);
00338         }
00339         ++elem;
00340     }
00341     JS_ASSERT(priv->stackElems + stackDepth == elem);
00342     JS_ASSERT(GetStackTraceValueBuffer(priv) + valueCount == values);
00343 
00344     OBJ_SET_SLOT(cx, exnObject, JSSLOT_PRIVATE, PRIVATE_TO_JSVAL(priv));
00345 
00346     if (report) {
00347         /*
00348          * Construct a new copy of the error report struct. We can't use the
00349          * error report struct that was passed in, because it's allocated on
00350          * the stack, and also because it may point to transient data in the
00351          * JSTokenStream.
00352          */
00353         priv->errorReport = CopyErrorReport(cx, report);
00354         if (!priv->errorReport) {
00355             /* The finalizer realeases priv since it is in the private slot. */
00356             return JS_FALSE;
00357         }
00358     }
00359 
00360     return JS_TRUE;
00361 }
00362 
00363 static JSExnPrivate *
00364 GetExnPrivate(JSContext *cx, JSObject *obj)
00365 {
00366     jsval privateValue;
00367     JSExnPrivate *priv;
00368 
00369     JS_ASSERT(OBJ_GET_CLASS(cx, obj) == &js_ErrorClass);
00370     privateValue = OBJ_GET_SLOT(cx, obj, JSSLOT_PRIVATE);
00371     if (JSVAL_IS_VOID(privateValue))
00372         return NULL;
00373     priv = (JSExnPrivate *)JSVAL_TO_PRIVATE(privateValue);
00374     JS_ASSERT(priv);
00375     return priv;
00376 }
00377 
00378 static uint32
00379 exn_mark(JSContext *cx, JSObject *obj, void *arg)
00380 {
00381     JSExnPrivate *priv;
00382     JSStackTraceElem *elem;
00383     size_t vcount, i;
00384     jsval *vp, v;
00385 
00386     priv = GetExnPrivate(cx, obj);
00387     if (priv) {
00388         GC_MARK(cx, priv->message, "exception message");
00389         GC_MARK(cx, priv->filename, "exception filename");
00390         elem = priv->stackElems;
00391         for (vcount = i = 0; i != priv->stackDepth; ++i, ++elem) {
00392             if (elem->funName)
00393                 GC_MARK(cx, elem->funName, "stack trace function name");
00394             if (elem->filename)
00395                 js_MarkScriptFilename(elem->filename);
00396             vcount += elem->argc;
00397         }
00398         vp = GetStackTraceValueBuffer(priv);
00399         for (i = 0; i != vcount; ++i, ++vp) {
00400             v = *vp;
00401             if (JSVAL_IS_GCTHING(v))
00402                 GC_MARK(cx, JSVAL_TO_GCTHING(v), "stack trace argument");
00403         }
00404     }
00405     return 0;
00406 }
00407 
00408 static void
00409 exn_finalize(JSContext *cx, JSObject *obj)
00410 {
00411     JSExnPrivate *priv;
00412 
00413     priv = GetExnPrivate(cx, obj);
00414     if (priv) {
00415         if (priv->errorReport)
00416             JS_free(cx, priv->errorReport);
00417         JS_free(cx, priv);
00418     }
00419 }
00420 
00421 static JSBool
00422 exn_enumerate(JSContext *cx, JSObject *obj)
00423 {
00424     JSAtomState *atomState;
00425     uintN i;
00426     JSAtom *atom;
00427     JSObject *pobj;
00428     JSProperty *prop;
00429     
00430     JS_STATIC_ASSERT(sizeof(JSAtomState) <= (size_t)(uint16)-1);
00431     static const uint16 offsets[] = {
00432         (uint16)offsetof(JSAtomState, messageAtom),
00433         (uint16)offsetof(JSAtomState, fileNameAtom),
00434         (uint16)offsetof(JSAtomState, lineNumberAtom),
00435         (uint16)offsetof(JSAtomState, stackAtom),
00436     };
00437 
00438     atomState = &cx->runtime->atomState;
00439     for (i = 0; i != JS_ARRAY_LENGTH(offsets); ++i) {
00440         atom = *(JSAtom **)((uint8 *)atomState + offsets[i]); 
00441         if (!js_LookupProperty(cx, obj, ATOM_TO_JSID(atom), &pobj, &prop))
00442             return JS_FALSE;
00443         if (prop)
00444             OBJ_DROP_PROPERTY(cx, pobj, prop);
00445     }
00446     return JS_TRUE;
00447 }
00448 
00449 static JSBool
00450 exn_resolve(JSContext *cx, JSObject *obj, jsval id, uintN flags,
00451             JSObject **objp)
00452 {
00453     JSExnPrivate *priv;
00454     JSString *str;
00455     JSAtom *atom;
00456     JSString *stack;
00457     const char *prop;
00458     jsval v;
00459 
00460     *objp = NULL;
00461     priv = GetExnPrivate(cx, obj);
00462     if (priv && JSVAL_IS_STRING(id)) {
00463         str = JSVAL_TO_STRING(id);
00464 
00465         atom = cx->runtime->atomState.messageAtom;
00466         if (str == ATOM_TO_STRING(atom)) {
00467             prop = js_message_str;
00468             v = STRING_TO_JSVAL(priv->message);
00469             goto define;
00470         }
00471 
00472         atom = cx->runtime->atomState.fileNameAtom;
00473         if (str == ATOM_TO_STRING(atom)) {
00474             prop = js_fileName_str;
00475             v = STRING_TO_JSVAL(priv->filename);
00476             goto define;
00477         }
00478 
00479         atom = cx->runtime->atomState.lineNumberAtom;
00480         if (str == ATOM_TO_STRING(atom)) {
00481             prop = js_lineNumber_str;
00482             v = INT_TO_JSVAL(priv->lineno);
00483             goto define;
00484         }
00485 
00486         atom = cx->runtime->atomState.stackAtom;
00487         if (str == ATOM_TO_STRING(atom)) {
00488             stack = StackTraceToString(cx, priv);
00489             if (!stack)
00490                 return JS_FALSE;
00491 
00492             /* Allow to GC all things that were used to build stack trace. */
00493             priv->stackDepth = 0;
00494             prop = js_stack_str;
00495             v = STRING_TO_JSVAL(stack);
00496             goto define;
00497         }
00498     }
00499     return JS_TRUE;
00500 
00501   define:
00502     if (!JS_DefineProperty(cx, obj, prop, v, NULL, NULL, JSPROP_ENUMERATE))
00503         return JS_FALSE;
00504     *objp = obj;
00505     return JS_TRUE;
00506 }
00507 
00508 JSErrorReport *
00509 js_ErrorFromException(JSContext *cx, jsval exn)
00510 {
00511     JSObject *obj;
00512     JSExnPrivate *priv;
00513 
00514     if (JSVAL_IS_PRIMITIVE(exn))
00515         return NULL;
00516     obj = JSVAL_TO_OBJECT(exn);
00517     if (OBJ_GET_CLASS(cx, obj) != &js_ErrorClass)
00518         return NULL;
00519     priv = GetExnPrivate(cx, obj);
00520     if (!priv)
00521         return NULL;
00522     return priv->errorReport;
00523 }
00524 
00525 struct JSExnSpec {
00526     int protoIndex;
00527     const char *name;
00528     JSProtoKey key;
00529     JSNative native;
00530 };
00531 
00532 /*
00533  * All *Error constructors share the same JSClass, js_ErrorClass.  But each
00534  * constructor function for an *Error class must have a distinct native 'call'
00535  * function pointer, in order for instanceof to work properly across multiple
00536  * standard class sets.  See jsfun.c:fun_hasInstance.
00537  */
00538 #define MAKE_EXCEPTION_CTOR(name)                                             \
00539 static JSBool                                                                 \
00540 name(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)      \
00541 {                                                                             \
00542     return Exception(cx, obj, argc, argv, rval);                              \
00543 }
00544 
00545 MAKE_EXCEPTION_CTOR(Error)
00546 MAKE_EXCEPTION_CTOR(InternalError)
00547 MAKE_EXCEPTION_CTOR(EvalError)
00548 MAKE_EXCEPTION_CTOR(RangeError)
00549 MAKE_EXCEPTION_CTOR(ReferenceError)
00550 MAKE_EXCEPTION_CTOR(SyntaxError)
00551 MAKE_EXCEPTION_CTOR(TypeError)
00552 MAKE_EXCEPTION_CTOR(URIError)
00553 
00554 #undef MAKE_EXCEPTION_CTOR
00555 
00556 static struct JSExnSpec exceptions[] = {
00557     {JSEXN_NONE, js_Error_str,          JSProto_Error,          Error},
00558     {JSEXN_ERR,  js_InternalError_str,  JSProto_InternalError,  InternalError},
00559     {JSEXN_ERR,  js_EvalError_str,      JSProto_EvalError,      EvalError},
00560     {JSEXN_ERR,  js_RangeError_str,     JSProto_RangeError,     RangeError},
00561     {JSEXN_ERR,  js_ReferenceError_str, JSProto_ReferenceError, ReferenceError},
00562     {JSEXN_ERR,  js_SyntaxError_str,    JSProto_SyntaxError,    SyntaxError},
00563     {JSEXN_ERR,  js_TypeError_str,      JSProto_TypeError,      TypeError},
00564     {JSEXN_ERR,  js_URIError_str,       JSProto_URIError,       URIError},
00565     {0,          NULL,                  JSProto_Null,           NULL}
00566 };
00567 
00568 static JSString *
00569 ValueToShortSource(JSContext *cx, jsval v)
00570 {
00571     JSString *str;
00572 
00573     /* Avoid toSource bloat and fallibility for object types. */
00574     if (JSVAL_IS_PRIMITIVE(v)) {
00575         str = js_ValueToSource(cx, v);
00576     } else if (VALUE_IS_FUNCTION(cx, v)) {
00577         /*
00578          * XXX Avoid function decompilation bloat for now.
00579          */
00580         str = JS_GetFunctionId(JS_ValueToFunction(cx, v));
00581         if (!str && !(str = js_ValueToSource(cx, v))) {
00582             /*
00583              * Continue to soldier on if the function couldn't be
00584              * converted into a string.
00585              */
00586             JS_ClearPendingException(cx);
00587             str = JS_NewStringCopyZ(cx, "[unknown function]");
00588         }
00589     } else {
00590         /*
00591          * XXX Avoid toString on objects, it takes too long and uses too much
00592          * memory, for too many classes (see Mozilla bug 166743).
00593          */
00594         char buf[100];
00595         JS_snprintf(buf, sizeof buf, "[object %s]",
00596                     OBJ_GET_CLASS(cx, JSVAL_TO_OBJECT(v))->name);
00597         str = JS_NewStringCopyZ(cx, buf);
00598     }
00599     return str;
00600 }
00601 
00602 static JSString *
00603 StackTraceToString(JSContext *cx, JSExnPrivate *priv)
00604 {
00605     jschar *stackbuf;
00606     size_t stacklen, stackmax;
00607     JSStackTraceElem *elem, *endElem;
00608     jsval *values;
00609     size_t i;
00610     JSString *str;
00611     const char *cp;
00612     char ulnbuf[11];
00613 
00614     /* After this point, failing control flow must goto bad. */
00615     stackbuf = NULL;
00616     stacklen = stackmax = 0;
00617 
00618 /* Limit the stackbuf length to a reasonable value to avoid overflow checks. */
00619 #define STACK_LENGTH_LIMIT JS_BIT(20)
00620 
00621 #define APPEND_CHAR_TO_STACK(c)                                               \
00622     JS_BEGIN_MACRO                                                            \
00623         if (stacklen == stackmax) {                                           \
00624             void *ptr_;                                                       \
00625             if (stackmax >= STACK_LENGTH_LIMIT)                               \
00626                 goto done;                                                    \
00627             stackmax = stackmax ? 2 * stackmax : 64;                          \
00628             ptr_ = JS_realloc(cx, stackbuf, (stackmax+1) * sizeof(jschar));   \
00629             if (!ptr_)                                                        \
00630                 goto bad;                                                     \
00631             stackbuf = ptr_;                                                  \
00632         }                                                                     \
00633         stackbuf[stacklen++] = (c);                                           \
00634     JS_END_MACRO
00635 
00636 #define APPEND_STRING_TO_STACK(str)                                           \
00637     JS_BEGIN_MACRO                                                            \
00638         JSString *str_ = str;                                                 \
00639         size_t length_ = JSSTRING_LENGTH(str_);                               \
00640         if (length_ > stackmax - stacklen) {                                  \
00641             void *ptr_;                                                       \
00642             if (stackmax >= STACK_LENGTH_LIMIT ||                             \
00643                 length_ >= STACK_LENGTH_LIMIT - stacklen) {                   \
00644                 goto done;                                                    \
00645             }                                                                 \
00646             stackmax = JS_BIT(JS_CeilingLog2(stacklen + length_));            \
00647             ptr_ = JS_realloc(cx, stackbuf, (stackmax+1) * sizeof(jschar));   \
00648             if (!ptr_)                                                        \
00649                 goto bad;                                                     \
00650             stackbuf = ptr_;                                                  \
00651         }                                                                     \
00652         js_strncpy(stackbuf + stacklen, JSSTRING_CHARS(str_), length_);       \
00653         stacklen += length_;                                                  \
00654     JS_END_MACRO
00655 
00656     values = GetStackTraceValueBuffer(priv);
00657     elem = priv->stackElems;
00658     for (endElem = elem + priv->stackDepth; elem != endElem; elem++) {
00659         if (elem->funName) {
00660             APPEND_STRING_TO_STACK(elem->funName);
00661             APPEND_CHAR_TO_STACK('(');
00662             for (i = 0; i != elem->argc; i++, values++) {
00663                 if (i > 0)
00664                     APPEND_CHAR_TO_STACK(',');
00665                 str = ValueToShortSource(cx, *values);
00666                 if (!str)
00667                     goto bad;
00668                 APPEND_STRING_TO_STACK(str);
00669             }
00670             APPEND_CHAR_TO_STACK(')');
00671         }
00672         APPEND_CHAR_TO_STACK('@');
00673         if (elem->filename) {
00674             for (cp = elem->filename; *cp; cp++)
00675                 APPEND_CHAR_TO_STACK(*cp);
00676         }
00677         APPEND_CHAR_TO_STACK(':');
00678         JS_snprintf(ulnbuf, sizeof ulnbuf, "%u", elem->ulineno);
00679         for (cp = ulnbuf; *cp; cp++)
00680             APPEND_CHAR_TO_STACK(*cp);
00681         APPEND_CHAR_TO_STACK('\n');
00682     }
00683 #undef APPEND_CHAR_TO_STACK
00684 #undef APPEND_STRING_TO_STACK
00685 #undef STACK_LENGTH_LIMIT
00686 
00687   done:
00688     if (stacklen == 0) {
00689         JS_ASSERT(!stackbuf);
00690         return cx->runtime->emptyString;
00691     }
00692     if (stacklen < stackmax) {
00693         /*
00694          * Realloc can fail when shrinking on some FreeBSD versions, so
00695          * don't use JS_realloc here; simply let the oversized allocation
00696          * be owned by the string in that rare case.
00697          */
00698         void *shrunk = JS_realloc(cx, stackbuf, (stacklen+1) * sizeof(jschar));
00699         if (shrunk)
00700             stackbuf = shrunk;
00701     }
00702 
00703     stackbuf[stacklen] = 0;
00704     str = js_NewString(cx, stackbuf, stacklen, 0);
00705     if (str)
00706         return str;
00707 
00708   bad:
00709     if (stackbuf)
00710         JS_free(cx, stackbuf);
00711     return NULL;
00712 }
00713 
00714 /* XXXbe Consolidate the ugly truth that we don't treat filename as UTF-8
00715          with these two functions. */
00716 static JSString *
00717 FilenameToString(JSContext *cx, const char *filename)
00718 {
00719     return JS_NewStringCopyZ(cx, filename);
00720 }
00721 
00722 static const char *
00723 StringToFilename(JSContext *cx, JSString *str)
00724 {
00725     return JS_GetStringBytes(str);
00726 }
00727 
00728 static JSBool
00729 Exception(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
00730 {
00731     JSBool ok;
00732     uint32 lineno;
00733     JSString *message, *filename;
00734     JSStackFrame *fp;
00735 
00736     if (cx->creatingException)
00737         return JS_FALSE;
00738     cx->creatingException = JS_TRUE;
00739 
00740     if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) {
00741         /*
00742          * ECMA ed. 3, 15.11.1 requires Error, etc., to construct even when
00743          * called as functions, without operator new.  But as we do not give
00744          * each constructor a distinct JSClass, whose .name member is used by
00745          * js_NewObject to find the class prototype, we must get the class
00746          * prototype ourselves.
00747          */
00748         ok = OBJ_GET_PROPERTY(cx, JSVAL_TO_OBJECT(argv[-2]),
00749                               ATOM_TO_JSID(cx->runtime->atomState
00750                                            .classPrototypeAtom),
00751                               rval);
00752         if (!ok)
00753             goto out;
00754         obj = js_NewObject(cx, &js_ErrorClass, JSVAL_TO_OBJECT(*rval), NULL);
00755         if (!obj) {
00756             ok = JS_FALSE;
00757             goto out;
00758         }
00759         *rval = OBJECT_TO_JSVAL(obj);
00760     }
00761 
00762     /*
00763      * If it's a new object of class Exception, then null out the private
00764      * data so that the finalizer doesn't attempt to free it.
00765      */
00766     if (OBJ_GET_CLASS(cx, obj) == &js_ErrorClass)
00767         OBJ_SET_SLOT(cx, obj, JSSLOT_PRIVATE, JSVAL_VOID);
00768 
00769     /* Set the 'message' property. */
00770     if (argc != 0) {
00771         message = js_ValueToString(cx, argv[0]);
00772         if (!message) {
00773             ok = JS_FALSE;
00774             goto out;
00775         }
00776         argv[0] = STRING_TO_JSVAL(message);
00777     } else {
00778         message = cx->runtime->emptyString;
00779     }
00780 
00781     /* Set the 'fileName' property. */
00782     if (argc > 1) {
00783         filename = js_ValueToString(cx, argv[1]);
00784         if (!filename) {
00785             ok = JS_FALSE;
00786             goto out;
00787         }
00788         argv[1] = STRING_TO_JSVAL(filename);
00789         fp = NULL;
00790     } else {
00791         fp = JS_GetScriptedCaller(cx, NULL);
00792         if (fp) {
00793             filename = FilenameToString(cx, fp->script->filename);
00794             if (!filename) {
00795                 ok = JS_FALSE;
00796                 goto out;
00797             }
00798         } else {
00799             filename = cx->runtime->emptyString;
00800         }
00801     }
00802 
00803     /* Set the 'lineNumber' property. */
00804     if (argc > 2) {
00805         ok = js_ValueToECMAUint32(cx, argv[2], &lineno);
00806         if (!ok)
00807             goto out;
00808     } else {
00809         if (!fp)
00810             fp = JS_GetScriptedCaller(cx, NULL);
00811         lineno = (fp && fp->pc) ? js_PCToLineNumber(cx, fp->script, fp->pc) : 0;
00812     }
00813 
00814     ok = (OBJ_GET_CLASS(cx, obj) != &js_ErrorClass) ||
00815          InitExnPrivate(cx, obj, message, filename, lineno, NULL);
00816 
00817   out:
00818     cx->creatingException = JS_FALSE;
00819     return ok;
00820 }
00821 
00822 /*
00823  * Convert to string.
00824  *
00825  * This method only uses JavaScript-modifiable properties name, message.  It
00826  * is left to the host to check for private data and report filename and line
00827  * number information along with this message.
00828  */
00829 static JSBool
00830 exn_toString(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
00831 {
00832     jsval v;
00833     JSString *name, *message, *result;
00834     jschar *chars, *cp;
00835     size_t name_length, message_length, length;
00836 
00837     if (!OBJ_GET_PROPERTY(cx, obj,
00838                           ATOM_TO_JSID(cx->runtime->atomState.nameAtom),
00839                           &v)) {
00840         return JS_FALSE;
00841     }
00842     name = JSVAL_IS_STRING(v) ? JSVAL_TO_STRING(v) : cx->runtime->emptyString;
00843     *rval = STRING_TO_JSVAL(name);
00844 
00845     if (!JS_GetProperty(cx, obj, js_message_str, &v))
00846         return JS_FALSE;
00847     message = JSVAL_IS_STRING(v) ? JSVAL_TO_STRING(v)
00848                                  : cx->runtime->emptyString;
00849 
00850     if (JSSTRING_LENGTH(message) != 0) {
00851         name_length = JSSTRING_LENGTH(name);
00852         message_length = JSSTRING_LENGTH(message);
00853         length = (name_length ? name_length + 2 : 0) + message_length;
00854         cp = chars = (jschar*) JS_malloc(cx, (length + 1) * sizeof(jschar));
00855         if (!chars)
00856             return JS_FALSE;
00857 
00858         if (name_length) {
00859             js_strncpy(cp, JSSTRING_CHARS(name), name_length);
00860             cp += name_length;
00861             *cp++ = ':'; *cp++ = ' ';
00862         }
00863         js_strncpy(cp, JSSTRING_CHARS(message), message_length);
00864         cp += message_length;
00865         *cp = 0;
00866 
00867         result = js_NewString(cx, chars, length, 0);
00868         if (!result) {
00869             JS_free(cx, chars);
00870             return JS_FALSE;
00871         }
00872     } else {
00873         result = name;
00874     }
00875 
00876     *rval = STRING_TO_JSVAL(result);
00877     return JS_TRUE;
00878 }
00879 
00880 #if JS_HAS_TOSOURCE
00881 /*
00882  * Return a string that may eval to something similar to the original object.
00883  */
00884 static JSBool
00885 exn_toSource(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
00886 {
00887     jsval *vp;
00888     JSString *name, *message, *filename, *lineno_as_str, *result;
00889     uint32 lineno;
00890     size_t lineno_length, name_length, message_length, filename_length, length;
00891     jschar *chars, *cp;
00892 
00893     vp = argv + argc;   /* beginning of explicit local roots */
00894 
00895     if (!OBJ_GET_PROPERTY(cx, obj,
00896                           ATOM_TO_JSID(cx->runtime->atomState.nameAtom),
00897                           rval)) {
00898         return JS_FALSE;
00899     }
00900     name = js_ValueToString(cx, *rval);
00901     if (!name)
00902         return JS_FALSE;
00903     *rval = STRING_TO_JSVAL(name);
00904 
00905     if (!JS_GetProperty(cx, obj, js_message_str, &vp[0]) ||
00906         !(message = js_ValueToSource(cx, vp[0]))) {
00907         return JS_FALSE;
00908     }
00909     vp[0] = STRING_TO_JSVAL(message);
00910 
00911     if (!JS_GetProperty(cx, obj, js_fileName_str, &vp[1]) ||
00912         !(filename = js_ValueToSource(cx, vp[1]))) {
00913         return JS_FALSE;
00914     }
00915     vp[1] = STRING_TO_JSVAL(filename);
00916 
00917     if (!JS_GetProperty(cx, obj, js_lineNumber_str, &vp[2]) ||
00918         !js_ValueToECMAUint32 (cx, vp[2], &lineno)) {
00919         return JS_FALSE;
00920     }
00921 
00922     if (lineno != 0) {
00923         lineno_as_str = js_ValueToString(cx, vp[2]);
00924         if (!lineno_as_str)
00925             return JS_FALSE;
00926         lineno_length = JSSTRING_LENGTH(lineno_as_str);
00927     } else {
00928         lineno_as_str = NULL;
00929         lineno_length = 0;
00930     }
00931 
00932     /* Magic 8, for the characters in ``(new ())''. */
00933     name_length = JSSTRING_LENGTH(name);
00934     message_length = JSSTRING_LENGTH(message);
00935     length = 8 + name_length + message_length;
00936 
00937     filename_length = JSSTRING_LENGTH(filename);
00938     if (filename_length != 0) {
00939         /* append filename as ``, {filename}'' */
00940         length += 2 + filename_length;
00941         if (lineno_as_str) {
00942             /* append lineno as ``, {lineno_as_str}'' */
00943             length += 2 + lineno_length;
00944         }
00945     } else {
00946         if (lineno_as_str) {
00947             /*
00948              * no filename, but have line number,
00949              * need to append ``, "", {lineno_as_str}''
00950              */
00951             length += 6 + lineno_length;
00952         }
00953     }
00954 
00955     cp = chars = (jschar*) JS_malloc(cx, (length + 1) * sizeof(jschar));
00956     if (!chars)
00957         return JS_FALSE;
00958 
00959     *cp++ = '('; *cp++ = 'n'; *cp++ = 'e'; *cp++ = 'w'; *cp++ = ' ';
00960     js_strncpy(cp, JSSTRING_CHARS(name), name_length);
00961     cp += name_length;
00962     *cp++ = '(';
00963     if (message_length != 0) {
00964         js_strncpy(cp, JSSTRING_CHARS(message), message_length);
00965         cp += message_length;
00966     }
00967 
00968     if (filename_length != 0) {
00969         /* append filename as ``, {filename}'' */
00970         *cp++ = ','; *cp++ = ' ';
00971         js_strncpy(cp, JSSTRING_CHARS(filename), filename_length);
00972         cp += filename_length;
00973     } else {
00974         if (lineno_as_str) {
00975             /*
00976              * no filename, but have line number,
00977              * need to append ``, "", {lineno_as_str}''
00978              */
00979             *cp++ = ','; *cp++ = ' '; *cp++ = '"'; *cp++ = '"';
00980         }
00981     }
00982     if (lineno_as_str) {
00983         /* append lineno as ``, {lineno_as_str}'' */
00984         *cp++ = ','; *cp++ = ' ';
00985         js_strncpy(cp, JSSTRING_CHARS(lineno_as_str), lineno_length);
00986         cp += lineno_length;
00987     }
00988 
00989     *cp++ = ')'; *cp++ = ')'; *cp = 0;
00990 
00991     result = js_NewString(cx, chars, length, 0);
00992     if (!result) {
00993         JS_free(cx, chars);
00994         return JS_FALSE;
00995     }
00996     *rval = STRING_TO_JSVAL(result);
00997     return JS_TRUE;
00998 }
00999 #endif
01000 
01001 static JSFunctionSpec exception_methods[] = {
01002 #if JS_HAS_TOSOURCE
01003     {js_toSource_str,   exn_toSource,           0,0,3},
01004 #endif
01005     {js_toString_str,   exn_toString,           0,0,0},
01006     {0,0,0,0,0}
01007 };
01008 
01009 JSObject *
01010 js_InitExceptionClasses(JSContext *cx, JSObject *obj)
01011 {
01012     JSObject *obj_proto, *protos[JSEXN_LIMIT];
01013     int i;
01014 
01015     /*
01016      * If lazy class initialization occurs for any Error subclass, then all
01017      * classes are initialized, starting with Error.  To avoid reentry and
01018      * redundant initialization, we must not pass a null proto parameter to
01019      * js_NewObject below, when called for the Error superclass.  We need to
01020      * ensure that Object.prototype is the proto of Error.prototype.
01021      *
01022      * See the equivalent code to ensure that parent_proto is non-null when
01023      * JS_InitClass calls js_NewObject, in jsapi.c.
01024      */
01025     if (!js_GetClassPrototype(cx, obj, INT_TO_JSID(JSProto_Object),
01026                               &obj_proto)) {
01027         return NULL;
01028     }
01029 
01030     if (!js_EnterLocalRootScope(cx))
01031         return NULL;
01032 
01033     /* Initialize the prototypes first. */
01034     for (i = 0; exceptions[i].name != 0; i++) {
01035         JSAtom *atom;
01036         JSFunction *fun;
01037         JSObject *funobj;
01038         JSString *nameString;
01039         int protoIndex = exceptions[i].protoIndex;
01040 
01041         /* Make the prototype for the current constructor name. */
01042         protos[i] = js_NewObject(cx, &js_ErrorClass,
01043                                  (protoIndex != JSEXN_NONE)
01044                                  ? protos[protoIndex]
01045                                  : obj_proto,
01046                                  obj);
01047         if (!protos[i])
01048             break;
01049 
01050         /* So exn_finalize knows whether to destroy private data. */
01051         OBJ_SET_SLOT(cx, protos[i], JSSLOT_PRIVATE, JSVAL_VOID);
01052 
01053         /* Make a constructor function for the current name. */
01054         atom = cx->runtime->atomState.classAtoms[exceptions[i].key];
01055         fun = js_DefineFunction(cx, obj, atom, exceptions[i].native, 3, 0);
01056         if (!fun)
01057             break;
01058 
01059         /* Make this constructor make objects of class Exception. */
01060         fun->clasp = &js_ErrorClass;
01061 
01062         /* Extract the constructor object. */
01063         funobj = fun->object;
01064 
01065         /* Make the prototype and constructor links. */
01066         if (!js_SetClassPrototype(cx, funobj, protos[i],
01067                                   JSPROP_READONLY | JSPROP_PERMANENT)) {
01068             break;
01069         }
01070 
01071         /* proto bootstrap bit from JS_InitClass omitted. */
01072         nameString = JS_NewStringCopyZ(cx, exceptions[i].name);
01073         if (!nameString)
01074             break;
01075 
01076         /* Add the name property to the prototype. */
01077         if (!JS_DefineProperty(cx, protos[i], js_name_str,
01078                                STRING_TO_JSVAL(nameString),
01079                                NULL, NULL,
01080                                JSPROP_ENUMERATE)) {
01081             break;
01082         }
01083 
01084         /* Finally, stash the constructor for later uses. */
01085         if (!js_SetClassObject(cx, obj, exceptions[i].key, funobj))
01086             break;
01087     }
01088 
01089     js_LeaveLocalRootScope(cx);
01090     if (exceptions[i].name)
01091         return NULL;
01092 
01093     /*
01094      * Add an empty message property.  (To Exception.prototype only,
01095      * because this property will be the same for all the exception
01096      * protos.)
01097      */
01098     if (!JS_DefineProperty(cx, protos[0], js_message_str,
01099                            STRING_TO_JSVAL(cx->runtime->emptyString),
01100                            NULL, NULL, JSPROP_ENUMERATE)) {
01101         return NULL;
01102     }
01103     if (!JS_DefineProperty(cx, protos[0], js_fileName_str,
01104                            STRING_TO_JSVAL(cx->runtime->emptyString),
01105                            NULL, NULL, JSPROP_ENUMERATE)) {
01106         return NULL;
01107     }
01108     if (!JS_DefineProperty(cx, protos[0], js_lineNumber_str,
01109                            INT_TO_JSVAL(0),
01110                            NULL, NULL, JSPROP_ENUMERATE)) {
01111         return NULL;
01112     }
01113 
01114     /*
01115      * Add methods only to Exception.prototype, because ostensibly all
01116      * exception types delegate to that.
01117      */
01118     if (!JS_DefineFunctions(cx, protos[0], exception_methods))
01119         return NULL;
01120 
01121     return protos[0];
01122 }
01123 
01124 const JSErrorFormatString*
01125 js_GetLocalizedErrorMessage(JSContext* cx, void *userRef, const char *locale, const uintN errorNumber)
01126 {
01127     const JSErrorFormatString *errorString = NULL;
01128 
01129     if (cx->localeCallbacks && cx->localeCallbacks->localeGetErrorMessage) {
01130         errorString = cx->localeCallbacks
01131                         ->localeGetErrorMessage(userRef, locale, errorNumber);
01132     }
01133     if (!errorString)
01134         errorString = js_GetErrorMessage(userRef, locale, errorNumber);
01135     return errorString;
01136 }
01137 
01138 #if defined ( DEBUG_mccabe ) && defined ( PRINTNAMES )
01139 /* For use below... get character strings for error name and exception name */
01140 static struct exnname { char *name; char *exception; } errortoexnname[] = {
01141 #define MSG_DEF(name, number, count, exception, format) \
01142     {#name, #exception},
01143 #include "js.msg"
01144 #undef MSG_DEF
01145 };
01146 #endif /* DEBUG */
01147 
01148 JSBool
01149 js_ErrorToException(JSContext *cx, const char *message, JSErrorReport *reportp)
01150 {
01151     JSErrNum errorNumber;
01152     const JSErrorFormatString *errorString;
01153     JSExnType exn;
01154     jsval tv[4];
01155     JSTempValueRooter tvr;
01156     JSBool ok;
01157     JSObject *errProto, *errObject;
01158     JSString *messageStr, *filenameStr;
01159 
01160     /*
01161      * Tell our caller to report immediately if cx has no active frames, or if
01162      * this report is just a warning.
01163      */
01164     JS_ASSERT(reportp);
01165     if (!cx->fp || JSREPORT_IS_WARNING(reportp->flags))
01166         return JS_FALSE;
01167 
01168     /* Find the exception index associated with this error. */
01169     errorNumber = (JSErrNum) reportp->errorNumber;
01170     errorString = js_GetLocalizedErrorMessage(cx, NULL, NULL, errorNumber);
01171     exn = errorString ? errorString->exnType : JSEXN_NONE;
01172     JS_ASSERT(exn < JSEXN_LIMIT);
01173 
01174 #if defined( DEBUG_mccabe ) && defined ( PRINTNAMES )
01175     /* Print the error name and the associated exception name to stderr */
01176     fprintf(stderr, "%s\t%s\n",
01177             errortoexnname[errorNumber].name,
01178             errortoexnname[errorNumber].exception);
01179 #endif
01180 
01181     /*
01182      * Return false (no exception raised) if no exception is associated
01183      * with the given error number.
01184      */
01185     if (exn == JSEXN_NONE)
01186         return JS_FALSE;
01187 
01188     /*
01189      * Prevent runaway recursion, just as the Exception native constructor
01190      * must do, via cx->creatingException.  If an out-of-memory error occurs,
01191      * no exception object will be created, but we don't assume that OOM is
01192      * the only kind of error that subroutines of this function called below
01193      * might raise.
01194      */
01195     if (cx->creatingException)
01196         return JS_FALSE;
01197 
01198     /* After this point the control must flow through the label out. */
01199     cx->creatingException = JS_TRUE;
01200 
01201     /* Protect the newly-created strings below from nesting GCs. */
01202     memset(tv, 0, sizeof tv);
01203     JS_PUSH_TEMP_ROOT(cx, sizeof tv / sizeof tv[0], tv, &tvr);
01204 
01205     /*
01206      * Try to get an appropriate prototype by looking up the corresponding
01207      * exception constructor name in the scope chain of the current context's
01208      * top stack frame, or in the global object if no frame is active.
01209      */
01210     ok = js_GetClassPrototype(cx, NULL, INT_TO_JSID(exceptions[exn].key),
01211                               &errProto);
01212     if (!ok)
01213         goto out;
01214     tv[0] = OBJECT_TO_JSVAL(errProto);
01215 
01216     errObject = js_NewObject(cx, &js_ErrorClass, errProto, NULL);
01217     if (!errObject) {
01218         ok = JS_FALSE;
01219         goto out;
01220     }
01221     tv[1] = OBJECT_TO_JSVAL(errObject);
01222 
01223     messageStr = JS_NewStringCopyZ(cx, message);
01224     if (!messageStr) {
01225         ok = JS_FALSE;
01226         goto out;
01227     }
01228     tv[2] = STRING_TO_JSVAL(messageStr);
01229 
01230     filenameStr = JS_NewStringCopyZ(cx, reportp->filename);
01231     if (!filenameStr) {
01232         ok = JS_FALSE;
01233         goto out;
01234     }
01235     tv[3] = STRING_TO_JSVAL(filenameStr);
01236 
01237     ok = InitExnPrivate(cx, errObject, messageStr, filenameStr,
01238                         reportp->lineno, reportp);
01239     if (!ok)
01240         goto out;
01241 
01242     JS_SetPendingException(cx, OBJECT_TO_JSVAL(errObject));
01243 
01244     /* Flag the error report passed in to indicate an exception was raised. */
01245     reportp->flags |= JSREPORT_EXCEPTION;
01246 
01247 out:
01248     JS_POP_TEMP_ROOT(cx, &tvr);
01249     cx->creatingException = JS_FALSE;
01250     return ok;
01251 }
01252 
01253 JSBool
01254 js_ReportUncaughtException(JSContext *cx)
01255 {
01256     jsval exn;
01257     JSObject *exnObject;
01258     jsval vp[5];
01259     JSTempValueRooter tvr;
01260     JSErrorReport *reportp, report;
01261     JSString *str;
01262     const char *bytes;
01263     JSBool ok;
01264 
01265     if (!JS_IsExceptionPending(cx))
01266         return JS_TRUE;
01267 
01268     if (!JS_GetPendingException(cx, &exn))
01269         return JS_FALSE;
01270 
01271     /*
01272      * Because js_ValueToString below could error and an exception object
01273      * could become unrooted, we must root exnObject.  Later, if exnObject is
01274      * non-null, we need to root other intermediates, so allocate an operand
01275      * stack segment to protect all of these values.
01276      */
01277     if (JSVAL_IS_PRIMITIVE(exn)) {
01278         exnObject = NULL;
01279     } else {
01280         exnObject = JSVAL_TO_OBJECT(exn);
01281         vp[0] = exn;
01282         memset(vp + 1, 0, sizeof vp - sizeof vp[0]);
01283         JS_PUSH_TEMP_ROOT(cx, JS_ARRAY_LENGTH(vp), vp, &tvr);
01284     }
01285 
01286     JS_ClearPendingException(cx);
01287     reportp = js_ErrorFromException(cx, exn);
01288 
01289     /* XXX L10N angels cry once again (see also jsemit.c, /L10N gaffes/) */
01290     str = js_ValueToString(cx, exn);
01291     if (!str) {
01292         bytes = "unknown (can't convert to string)";
01293     } else {
01294         if (exnObject)
01295             vp[1] = STRING_TO_JSVAL(str);
01296         bytes = js_GetStringBytes(cx->runtime, str);
01297     }
01298     ok = JS_TRUE;
01299 
01300     if (!reportp &&
01301         exnObject &&
01302         OBJ_GET_CLASS(cx, exnObject) == &js_ErrorClass) {
01303         const char *filename;
01304         uint32 lineno;
01305 
01306         ok = JS_GetProperty(cx, exnObject, js_message_str, &vp[2]);
01307         if (!ok)
01308             goto out;
01309         if (JSVAL_IS_STRING(vp[2]))
01310             bytes = JS_GetStringBytes(JSVAL_TO_STRING(vp[2]));
01311 
01312         ok = JS_GetProperty(cx, exnObject, js_fileName_str, &vp[3]);
01313         if (!ok)
01314             goto out;
01315         str = js_ValueToString(cx, vp[3]);
01316         if (!str) {
01317             ok = JS_FALSE;
01318             goto out;
01319         }
01320         filename = StringToFilename(cx, str);
01321 
01322         ok = JS_GetProperty(cx, exnObject, js_lineNumber_str, &vp[4]);
01323         if (!ok)
01324             goto out;
01325         ok = js_ValueToECMAUint32 (cx, vp[4], &lineno);
01326         if (!ok)
01327             goto out;
01328 
01329         reportp = &report;
01330         memset(&report, 0, sizeof report);
01331         report.filename = filename;
01332         report.lineno = (uintN) lineno;
01333     }
01334 
01335     if (!reportp) {
01336         JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
01337                              JSMSG_UNCAUGHT_EXCEPTION, bytes);
01338     } else {
01339         /* Flag the error as an exception. */
01340         reportp->flags |= JSREPORT_EXCEPTION;
01341         js_ReportErrorAgain(cx, bytes, reportp);
01342     }
01343 
01344 out:
01345     if (exnObject)
01346         JS_POP_TEMP_ROOT(cx, &tvr);
01347     return ok;
01348 }