Back to index

lightning-sunbird  0.9+nobinonly
mozJSSubScriptLoader.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
00002  * vim: set ts=4 sw=4 et tw=80:
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  *   Robert Ginda <rginda@netscape.com>
00027  *
00028  * Alternatively, the contents of this file may be used under the terms of
00029  * either of the GNU General Public License Version 2 or later (the "GPL"),
00030  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00031  * in which case the provisions of the GPL or the LGPL are applicable instead
00032  * of those above. If you wish to allow use of your version of this file only
00033  * under the terms of either the GPL or the LGPL, and not to allow others to
00034  * use your version of this file under the terms of the MPL, indicate your
00035  * decision by deleting the provisions above and replace them with the notice
00036  * and other provisions required by the GPL or the LGPL. If you do not delete
00037  * the provisions above, a recipient may use your version of this file under
00038  * the terms of any one of the MPL, the GPL or the LGPL.
00039  *
00040  * ***** END LICENSE BLOCK ***** */
00041 
00042 #if !defined(XPCONNECT_STANDALONE) && !defined(NO_SUBSCRIPT_LOADER)
00043 
00044 #include "mozJSSubScriptLoader.h"
00045 
00046 #include "nsIServiceManager.h"
00047 #include "nsIXPConnect.h"
00048 
00049 #include "nsIURI.h"
00050 #include "nsIIOService.h"
00051 #include "nsIChannel.h"
00052 #include "nsIInputStream.h"
00053 #include "nsNetCID.h"
00054 #include "nsDependentString.h"
00055 #include "nsAutoPtr.h"
00056 #include "nsNetUtil.h"
00057 #include "nsIProtocolHandler.h"
00058 #include "nsIFileURL.h"
00059 
00060 #include "jsapi.h"
00061 #include "jsdbgapi.h"
00062 
00063 static NS_DEFINE_CID(kIOServiceCID,              NS_IOSERVICE_CID);
00064 
00065 /* load() error msgs, XXX localize? */
00066 #define LOAD_ERROR_NOSERVICE "Error creating IO Service."
00067 #define LOAD_ERROR_NOURI "Error creating URI (invalid URL scheme?)"
00068 #define LOAD_ERROR_NOSCHEME "Failed to get URI scheme.  This is bad."
00069 #define LOAD_ERROR_URI_NOT_LOCAL "Trying to load a non-local URI."
00070 #define LOAD_ERROR_NOSTREAM  "Error opening input stream (invalid filename?)"
00071 #define LOAD_ERROR_NOCONTENT "ContentLength not available (not a local URL?)"
00072 #define LOAD_ERROR_BADREAD   "File Read Error."
00073 #define LOAD_ERROR_READUNDERFLOW "File Read Error (underflow.)"
00074 #define LOAD_ERROR_NOPRINCIPALS "Failed to get principals."
00075 #define LOAD_ERROR_NOSPEC "Failed to get URI spec.  This is bad."
00076 
00077 // We just use the same reporter as the component loader
00078 extern void JS_DLL_CALLBACK
00079 mozJSLoaderErrorReporter(JSContext *cx, const char *message, JSErrorReport *rep);
00080 
00081 mozJSSubScriptLoader::mozJSSubScriptLoader() : mSystemPrincipal(nsnull)
00082 {
00083 }
00084 
00085 mozJSSubScriptLoader::~mozJSSubScriptLoader()    
00086 {
00087     /* empty */
00088 }
00089 
00090 NS_IMPL_THREADSAFE_ISUPPORTS1(mozJSSubScriptLoader, mozIJSSubScriptLoader)
00091 
00092 NS_IMETHODIMP /* args and return value are delt with using XPConnect and JSAPI */
00093 mozJSSubScriptLoader::LoadSubScript (const PRUnichar * /*url*/
00094                                      /* [, JSObject *target_obj] */)
00095 {
00096     /*
00097      * Loads a local url and evals it into the current cx
00098      * Synchronous (an async version would be cool too.)
00099      *   url: The url to load.  Must be local so that it can be loaded
00100      *        synchronously.
00101      *   target_obj: Optional object to eval the script onto (defaults to context
00102      *               global)
00103      *   returns: Whatever jsval the script pointed to by the url returns.
00104      * Should ONLY (O N L Y !) be called from JavaScript code.
00105      */
00106     
00107     /* gotta define most of this stuff up here because of all the gotos,
00108      * defined the rest up here to be consistent */
00109     nsresult  rv;
00110     JSBool    ok;
00111 
00112     /* get JS things from the CallContext */
00113     nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
00114     if (!xpc) return NS_ERROR_FAILURE;
00115 
00116     nsCOMPtr<nsIXPCNativeCallContext> cc;
00117     rv = xpc->GetCurrentNativeCallContext(getter_AddRefs(cc));
00118     if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
00119 
00120     JSContext *cx;
00121     rv = cc->GetJSContext (&cx);
00122     if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
00123 
00124     PRUint32 argc;
00125     rv = cc->GetArgc (&argc);
00126     if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
00127 
00128     jsval *argv;
00129     rv = cc->GetArgvPtr (&argv);
00130     if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
00131 
00132     jsval *rval;
00133     rv = cc->GetRetValPtr (&rval);
00134     if (NS_FAILED(rv)) return NS_ERROR_FAILURE;    
00135 
00136     /* set mJSPrincipals if it's not here already */
00137     if (!mSystemPrincipal)
00138     {
00139         nsCOMPtr<nsIScriptSecurityManager> secman =
00140             do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
00141         if (!secman)
00142             return rv;
00143 
00144         rv = secman->GetSystemPrincipal(getter_AddRefs(mSystemPrincipal));
00145         if (NS_FAILED(rv) || !mSystemPrincipal)
00146             return rv;
00147     }
00148 
00149     char     *url;
00150     JSObject *target_obj = nsnull;
00151     ok = JS_ConvertArguments (cx, argc, argv, "s / o", &url, &target_obj);
00152     if (!ok)
00153     {
00154         cc->SetExceptionWasThrown (JS_TRUE);
00155         /* let the exception raised by JS_ConvertArguments show through */
00156         return NS_OK;
00157     }
00158 
00159     if (!target_obj)
00160     {
00161         /* if the user didn't provide an object to eval onto, find the global
00162          * object by walking the parent chain of the calling object */
00163 
00164 #ifdef DEBUG_rginda
00165         JSObject *got_glob = JS_GetGlobalObject (cx);
00166         fprintf (stderr, "JS_GetGlobalObject says glob is %p.\n", got_glob);
00167         target_obj = JS_GetPrototype (cx, got_glob);
00168         fprintf (stderr, "That glob's prototype is %p.\n", target_obj);
00169         target_obj = JS_GetParent (cx, got_glob);
00170         fprintf (stderr, "That glob's parent is %p.\n", target_obj);
00171 #endif
00172         
00173         nsCOMPtr<nsIXPConnectWrappedNative> wn;
00174         rv = cc->GetCalleeWrapper (getter_AddRefs(wn));
00175         if (NS_FAILED(rv)) return NS_ERROR_FAILURE;    
00176 
00177         rv = wn->GetJSObject (&target_obj);
00178         if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
00179 
00180 #ifdef DEBUG_rginda
00181         fprintf (stderr, "Parent chain: %p", target_obj);
00182 #endif
00183         JSObject *maybe_glob = JS_GetParent (cx, target_obj);
00184         while (maybe_glob != nsnull)
00185         {
00186 #ifdef DEBUG_rginda
00187             fprintf (stderr, ", %p", maybe_glob);
00188 #endif
00189             target_obj = maybe_glob;
00190             maybe_glob = JS_GetParent (cx, maybe_glob);
00191         }
00192 #ifdef DEBUG_rginda
00193         fprintf (stderr, "\n");
00194 #endif  
00195     }
00196 
00197     // Innerize the target_obj so that we compile the loaded script in the
00198     // correct (inner) scope.
00199     JSClass *target_class = JS_GET_CLASS(cx, target_obj);
00200     if (target_class->flags & JSCLASS_IS_EXTENDED)
00201     {
00202         JSExtendedClass *extended = (JSExtendedClass*)target_class;
00203         if (extended->innerObject)
00204         {
00205             target_obj = extended->innerObject(cx, target_obj);
00206             if (!target_obj) return NS_ERROR_FAILURE;
00207 #ifdef DEBUG_rginda
00208             fprintf (stderr, "Final global: %p\n", target_obj);
00209 #endif
00210         }
00211     }
00212 
00213     /* load up the url.  From here on, failures are reflected as ``custom''
00214      * js exceptions */
00215     PRInt32   len = -1;
00216     PRUint32  readcount;
00217     nsAutoArrayPtr<char> buf;
00218     
00219     JSString        *errmsg;
00220     JSErrorReporter  er;
00221     JSPrincipals    *jsPrincipals;
00222     
00223     nsCOMPtr<nsIChannel>     chan;
00224     nsCOMPtr<nsIInputStream> instream;
00225     nsCOMPtr<nsIURI> uri;
00226     nsCAutoString uriStr;
00227     nsCAutoString scheme;
00228 
00229     JSStackFrame* frame = nsnull;
00230     JSScript* script = nsnull;
00231 
00232     // Figure out who's calling us
00233     do
00234     {
00235         frame = JS_FrameIterator(cx, &frame);
00236 
00237         if (frame)
00238             script = JS_GetFrameScript(cx, frame);
00239     } while (frame && !script);
00240 
00241     if (!script)
00242     {
00243         // No script means we don't know who's calling, bail.
00244 
00245         return NS_ERROR_FAILURE;
00246     }
00247 
00248     nsCOMPtr<nsIIOService> serv = do_GetService(kIOServiceCID);
00249     if (!serv)
00250     {
00251         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOSERVICE);
00252         goto return_exception;
00253     }
00254 
00255     // Make sure to explicitly create the URI, since we'll need the
00256     // canonicalized spec.
00257     rv = NS_NewURI(getter_AddRefs(uri), url, nsnull, serv);
00258     if (NS_FAILED(rv)) {
00259         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOURI);
00260         goto return_exception;
00261     }
00262 
00263     rv = uri->GetSpec(uriStr);
00264     if (NS_FAILED(rv)) {
00265         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOSPEC);
00266         goto return_exception;
00267     }    
00268 
00269     rv = uri->GetScheme(scheme);
00270     if (NS_FAILED(rv))
00271     {
00272         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOSCHEME);
00273         goto return_exception;
00274     }
00275 
00276     if (!scheme.EqualsLiteral("chrome"))
00277     {
00278         // This might be a URI to a local file, though!
00279         nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(uri);
00280         if (!fileURL)
00281         {
00282             errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_URI_NOT_LOCAL);
00283             goto return_exception;
00284         }
00285 
00286         // For file URIs prepend the filename with the filename of the
00287         // calling script, and " -> ". See bug 418356.
00288         nsCAutoString tmp(JS_GetScriptFilename(cx, script));
00289         tmp.AppendLiteral(" -> ");
00290         tmp.Append(uriStr);
00291 
00292         uriStr = tmp;
00293     }        
00294         
00295     rv = NS_OpenURI(getter_AddRefs(instream), uri, serv,
00296                     nsnull, nsnull, nsIRequest::LOAD_NORMAL,
00297                     getter_AddRefs(chan));
00298     if (NS_FAILED(rv))
00299     {
00300         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOSTREAM);
00301         goto return_exception;
00302     }
00303     
00304     rv = chan->GetContentLength (&len);
00305     if (NS_FAILED(rv) || len == -1)
00306     {
00307         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOCONTENT);
00308         goto return_exception;
00309     }
00310 
00311     buf = new char[len + 1];
00312     if (!buf)
00313         return NS_ERROR_OUT_OF_MEMORY;
00314     
00315     rv = instream->Read (buf, len, &readcount);
00316     if (NS_FAILED(rv))
00317     {
00318         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_BADREAD);
00319         goto return_exception;
00320     }
00321     
00322     if (NS_STATIC_CAST(PRUint32, len) != readcount)
00323     {
00324         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_READUNDERFLOW);
00325         goto return_exception;
00326     }
00327 
00328     /* we can't hold onto jsPrincipals as a module var because the
00329      * JSPRINCIPALS_DROP macro takes a JSContext, which we won't have in the
00330      * destructor */
00331     rv = mSystemPrincipal->GetJSPrincipals(cx, &jsPrincipals);
00332     if (NS_FAILED(rv) || !jsPrincipals) {
00333         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOPRINCIPALS);
00334         goto return_exception;
00335     }
00336 
00337     /* set our own error reporter so we can report any bad things as catchable
00338      * exceptions, including the source/line number */
00339     er = JS_SetErrorReporter (cx, mozJSLoaderErrorReporter);
00340 
00341     ok = JS_EvaluateScriptForPrincipals (cx, target_obj, jsPrincipals,
00342                                          buf, len, uriStr.get(), 1, rval);        
00343     /* repent for our evil deeds */
00344     JS_SetErrorReporter (cx, er);
00345 
00346     cc->SetExceptionWasThrown (!ok);
00347     cc->SetReturnValueWasSet (ok);
00348 
00349     JSPRINCIPALS_DROP(cx, jsPrincipals);
00350     return NS_OK;
00351 
00352  return_exception:
00353     JS_SetPendingException (cx, STRING_TO_JSVAL(errmsg));
00354     cc->SetExceptionWasThrown (JS_TRUE);
00355     return NS_OK;
00356 }
00357 
00358 #endif /* NO_SUBSCRIPT_LOADER */