Back out b70659aca040, burning XPCShell tests. (no_r=me)
[mozilla-central.git] / js / src / xpconnect / loader / mozJSSubScriptLoader.cpp
blob7c3f145bfed7db0fec77a3829c41dd9b5f7acf53
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=4 sw=4 et tw=80:
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
17 * The Original Code is Mozilla Communicator client code, released
18 * March 31, 1998.
20 * The Initial Developer of the Original Code is
21 * Netscape Communications Corporation.
22 * Portions created by the Initial Developer are Copyright (C) 1998
23 * the Initial Developer. All Rights Reserved.
25 * Contributor(s):
26 * Robert Ginda <rginda@netscape.com>
28 * Alternatively, the contents of this file may be used under the terms of
29 * either of the GNU General Public License Version 2 or later (the "GPL"),
30 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
31 * in which case the provisions of the GPL or the LGPL are applicable instead
32 * of those above. If you wish to allow use of your version of this file only
33 * under the terms of either the GPL or the LGPL, and not to allow others to
34 * use your version of this file under the terms of the MPL, indicate your
35 * decision by deleting the provisions above and replace them with the notice
36 * and other provisions required by the GPL or the LGPL. If you do not delete
37 * the provisions above, a recipient may use your version of this file under
38 * the terms of any one of the MPL, the GPL or the LGPL.
40 * ***** END LICENSE BLOCK ***** */
42 #if !defined(XPCONNECT_STANDALONE) && !defined(NO_SUBSCRIPT_LOADER)
44 #include "mozJSSubScriptLoader.h"
46 #include "nsIServiceManager.h"
47 #include "nsIXPConnect.h"
49 #include "nsIURI.h"
50 #include "nsIIOService.h"
51 #include "nsIChannel.h"
52 #include "nsIInputStream.h"
53 #include "nsNetCID.h"
54 #include "nsDependentString.h"
55 #include "nsAutoPtr.h"
56 #include "nsNetUtil.h"
57 #include "nsIProtocolHandler.h"
58 #include "nsIFileURL.h"
60 #include "jsapi.h"
61 #include "jsdbgapi.h"
62 #include "jsobj.h"
64 #include "mozilla/FunctionTimer.h"
66 /* load() error msgs, XXX localize? */
67 #define LOAD_ERROR_NOSERVICE "Error creating IO Service."
68 #define LOAD_ERROR_NOURI "Error creating URI (invalid URL scheme?)"
69 #define LOAD_ERROR_NOSCHEME "Failed to get URI scheme. This is bad."
70 #define LOAD_ERROR_URI_NOT_LOCAL "Trying to load a non-local URI."
71 #define LOAD_ERROR_NOSTREAM "Error opening input stream (invalid filename?)"
72 #define LOAD_ERROR_NOCONTENT "ContentLength not available (not a local URL?)"
73 #define LOAD_ERROR_BADREAD "File Read Error."
74 #define LOAD_ERROR_READUNDERFLOW "File Read Error (underflow.)"
75 #define LOAD_ERROR_NOPRINCIPALS "Failed to get principals."
76 #define LOAD_ERROR_NOSPEC "Failed to get URI spec. This is bad."
78 // We just use the same reporter as the component loader
79 extern void
80 mozJSLoaderErrorReporter(JSContext *cx, const char *message, JSErrorReport *rep);
82 mozJSSubScriptLoader::mozJSSubScriptLoader() : mSystemPrincipal(nsnull)
86 mozJSSubScriptLoader::~mozJSSubScriptLoader()
88 /* empty */
91 NS_IMPL_THREADSAFE_ISUPPORTS1(mozJSSubScriptLoader, mozIJSSubScriptLoader)
93 NS_IMETHODIMP /* args and return value are delt with using XPConnect and JSAPI */
94 mozJSSubScriptLoader::LoadSubScript (const PRUnichar * aURL
95 /* [, JSObject *target_obj] */)
98 * Loads a local url and evals it into the current cx
99 * Synchronous (an async version would be cool too.)
100 * url: The url to load. Must be local so that it can be loaded
101 * synchronously.
102 * target_obj: Optional object to eval the script onto (defaults to context
103 * global)
104 * returns: Whatever jsval the script pointed to by the url returns.
105 * Should ONLY (O N L Y !) be called from JavaScript code.
108 /* gotta define most of this stuff up here because of all the gotos,
109 * defined the rest up here to be consistent */
110 nsresult rv;
111 JSBool ok;
113 #ifdef NS_FUNCTION_TIMER
114 NS_TIME_FUNCTION_FMT("%s (line %d) (url: %s)", MOZ_FUNCTION_NAME,
115 __LINE__, NS_LossyConvertUTF16toASCII(aURL).get());
116 #else
117 (void)aURL; // prevent compiler warning
118 #endif
120 /* get JS things from the CallContext */
121 nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
122 if (!xpc) return NS_ERROR_FAILURE;
124 nsAXPCNativeCallContext *cc = nsnull;
125 rv = xpc->GetCurrentNativeCallContext(&cc);
126 if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
128 JSContext *cx;
129 rv = cc->GetJSContext (&cx);
130 if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
132 PRUint32 argc;
133 rv = cc->GetArgc (&argc);
134 if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
136 jsval *argv;
137 rv = cc->GetArgvPtr (&argv);
138 if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
140 jsval *rval;
141 rv = cc->GetRetValPtr (&rval);
142 if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
144 /* set mJSPrincipals if it's not here already */
145 if (!mSystemPrincipal)
147 nsCOMPtr<nsIScriptSecurityManager> secman =
148 do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
149 if (!secman)
150 return rv;
152 rv = secman->GetSystemPrincipal(getter_AddRefs(mSystemPrincipal));
153 if (NS_FAILED(rv) || !mSystemPrincipal)
154 return rv;
157 JSAutoRequest ar(cx);
159 char *url;
160 JSObject *target_obj = nsnull;
161 ok = JS_ConvertArguments (cx, argc, argv, "s / o", &url, &target_obj);
162 if (!ok)
164 /* let the exception raised by JS_ConvertArguments show through */
165 return NS_OK;
168 if (!target_obj)
170 /* if the user didn't provide an object to eval onto, find the global
171 * object by walking the parent chain of the calling object */
173 #ifdef DEBUG_rginda
174 JSObject *got_glob = JS_GetGlobalObject (cx);
175 fprintf (stderr, "JS_GetGlobalObject says glob is %p.\n", got_glob);
176 target_obj = JS_GetPrototype (cx, got_glob);
177 fprintf (stderr, "That glob's prototype is %p.\n", target_obj);
178 target_obj = JS_GetParent (cx, got_glob);
179 fprintf (stderr, "That glob's parent is %p.\n", target_obj);
180 #endif
182 nsCOMPtr<nsIXPConnectWrappedNative> wn;
183 rv = cc->GetCalleeWrapper (getter_AddRefs(wn));
184 if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
186 rv = wn->GetJSObject (&target_obj);
187 if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
189 #ifdef DEBUG_rginda
190 fprintf (stderr, "Parent chain: %p", target_obj);
191 #endif
192 JSObject *maybe_glob = JS_GetParent (cx, target_obj);
193 while (maybe_glob != nsnull)
195 #ifdef DEBUG_rginda
196 fprintf (stderr, ", %p", maybe_glob);
197 #endif
198 target_obj = maybe_glob;
199 maybe_glob = JS_GetParent (cx, maybe_glob);
201 #ifdef DEBUG_rginda
202 fprintf (stderr, "\n");
203 #endif
206 // Innerize the target_obj so that we compile the loaded script in the
207 // correct (inner) scope.
208 if (JSObjectOp op = target_obj->getClass()->ext.innerObject)
210 target_obj = op(cx, target_obj);
211 if (!target_obj) return NS_ERROR_FAILURE;
212 #ifdef DEBUG_rginda
213 fprintf (stderr, "Final global: %p\n", target_obj);
214 #endif
217 /* load up the url. From here on, failures are reflected as ``custom''
218 * js exceptions */
219 PRInt32 len = -1;
220 PRUint32 readcount = 0; // Total amount of data read
221 PRUint32 lastReadCount = 0; // Amount of data read in last Read() call
222 nsAutoArrayPtr<char> buf;
224 JSString *errmsg;
225 JSErrorReporter er;
226 JSPrincipals *jsPrincipals;
228 nsCOMPtr<nsIChannel> chan;
229 nsCOMPtr<nsIInputStream> instream;
230 nsCOMPtr<nsIURI> uri;
231 nsCAutoString uriStr;
232 nsCAutoString scheme;
234 JSStackFrame* frame = nsnull;
235 JSScript* script = nsnull;
237 // Figure out who's calling us
240 frame = JS_FrameIterator(cx, &frame);
242 if (frame)
243 script = JS_GetFrameScript(cx, frame);
244 } while (frame && !script);
246 if (!script)
248 // No script means we don't know who's calling, bail.
250 return NS_ERROR_FAILURE;
253 nsCOMPtr<nsIIOService> serv = do_GetService(NS_IOSERVICE_CONTRACTID);
254 if (!serv)
256 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOSERVICE);
257 goto return_exception;
260 // Make sure to explicitly create the URI, since we'll need the
261 // canonicalized spec.
262 rv = NS_NewURI(getter_AddRefs(uri), url, nsnull, serv);
263 if (NS_FAILED(rv)) {
264 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOURI);
265 goto return_exception;
268 rv = uri->GetSpec(uriStr);
269 if (NS_FAILED(rv)) {
270 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOSPEC);
271 goto return_exception;
274 rv = uri->GetScheme(scheme);
275 if (NS_FAILED(rv))
277 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOSCHEME);
278 goto return_exception;
281 if (!scheme.EqualsLiteral("chrome"))
283 // This might be a URI to a local file, though!
284 nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(uri);
285 nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(innerURI);
286 if (!fileURL)
288 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_URI_NOT_LOCAL);
289 goto return_exception;
292 // For file URIs prepend the filename with the filename of the
293 // calling script, and " -> ". See bug 418356.
294 nsCAutoString tmp(JS_GetScriptFilename(cx, script));
295 tmp.AppendLiteral(" -> ");
296 tmp.Append(uriStr);
298 uriStr = tmp;
301 rv = NS_OpenURI(getter_AddRefs(instream), uri, serv,
302 nsnull, nsnull, nsIRequest::LOAD_NORMAL,
303 getter_AddRefs(chan));
304 if (NS_FAILED(rv))
306 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOSTREAM);
307 goto return_exception;
310 rv = chan->GetContentLength (&len);
311 if (NS_FAILED(rv) || len == -1)
313 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOCONTENT);
314 goto return_exception;
317 buf = new char[len + 1];
318 if (!buf)
319 return NS_ERROR_OUT_OF_MEMORY;
320 buf[len] = '\0';
322 do {
323 rv = instream->Read (buf + readcount, len - readcount, &lastReadCount);
324 if (NS_FAILED(rv))
326 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_BADREAD);
327 goto return_exception;
329 readcount += lastReadCount;
330 } while (lastReadCount && readcount != PRUint32(len));
332 if (static_cast<PRUint32>(len) != readcount)
334 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_READUNDERFLOW);
335 goto return_exception;
338 /* we can't hold onto jsPrincipals as a module var because the
339 * JSPRINCIPALS_DROP macro takes a JSContext, which we won't have in the
340 * destructor */
341 rv = mSystemPrincipal->GetJSPrincipals(cx, &jsPrincipals);
342 if (NS_FAILED(rv) || !jsPrincipals) {
343 errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOPRINCIPALS);
344 goto return_exception;
347 /* set our own error reporter so we can report any bad things as catchable
348 * exceptions, including the source/line number */
349 er = JS_SetErrorReporter (cx, mozJSLoaderErrorReporter);
351 ok = JS_EvaluateScriptForPrincipals (cx, target_obj, jsPrincipals,
352 buf, len, uriStr.get(), 1, rval);
353 /* repent for our evil deeds */
354 JS_SetErrorReporter (cx, er);
356 cc->SetReturnValueWasSet (ok);
358 JSPRINCIPALS_DROP(cx, jsPrincipals);
359 return NS_OK;
361 return_exception:
362 JS_SetPendingException (cx, STRING_TO_JSVAL(errmsg));
363 return NS_OK;
366 #endif /* NO_SUBSCRIPT_LOADER */