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
17 * The Original Code is Mozilla Communicator client code, released
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.
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"
50 #include "nsIIOService.h"
51 #include "nsIChannel.h"
52 #include "nsIInputStream.h"
54 #include "nsDependentString.h"
55 #include "nsAutoPtr.h"
56 #include "nsNetUtil.h"
57 #include "nsIProtocolHandler.h"
58 #include "nsIFileURL.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
80 mozJSLoaderErrorReporter(JSContext
*cx
, const char *message
, JSErrorReport
*rep
);
82 mozJSSubScriptLoader::mozJSSubScriptLoader() : mSystemPrincipal(nsnull
)
86 mozJSSubScriptLoader::~mozJSSubScriptLoader()
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
102 * target_obj: Optional object to eval the script onto (defaults to context
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 */
113 #ifdef NS_FUNCTION_TIMER
114 NS_TIME_FUNCTION_FMT("%s (line %d) (url: %s)", MOZ_FUNCTION_NAME
,
115 __LINE__
, NS_LossyConvertUTF16toASCII(aURL
).get());
117 (void)aURL
; // prevent compiler warning
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
;
129 rv
= cc
->GetJSContext (&cx
);
130 if (NS_FAILED(rv
)) return NS_ERROR_FAILURE
;
133 rv
= cc
->GetArgc (&argc
);
134 if (NS_FAILED(rv
)) return NS_ERROR_FAILURE
;
137 rv
= cc
->GetArgvPtr (&argv
);
138 if (NS_FAILED(rv
)) return NS_ERROR_FAILURE
;
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
);
152 rv
= secman
->GetSystemPrincipal(getter_AddRefs(mSystemPrincipal
));
153 if (NS_FAILED(rv
) || !mSystemPrincipal
)
157 JSAutoRequest
ar(cx
);
160 JSObject
*target_obj
= nsnull
;
161 ok
= JS_ConvertArguments (cx
, argc
, argv
, "s / o", &url
, &target_obj
);
164 /* let the exception raised by JS_ConvertArguments show through */
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 */
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
);
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
;
190 fprintf (stderr
, "Parent chain: %p", target_obj
);
192 JSObject
*maybe_glob
= JS_GetParent (cx
, target_obj
);
193 while (maybe_glob
!= nsnull
)
196 fprintf (stderr
, ", %p", maybe_glob
);
198 target_obj
= maybe_glob
;
199 maybe_glob
= JS_GetParent (cx
, maybe_glob
);
202 fprintf (stderr
, "\n");
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
;
213 fprintf (stderr
, "Final global: %p\n", target_obj
);
217 /* load up the url. From here on, failures are reflected as ``custom''
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
;
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
);
243 script
= JS_GetFrameScript(cx
, frame
);
244 } while (frame
&& !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
);
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
);
264 errmsg
= JS_NewStringCopyZ (cx
, LOAD_ERROR_NOURI
);
265 goto return_exception
;
268 rv
= uri
->GetSpec(uriStr
);
270 errmsg
= JS_NewStringCopyZ (cx
, LOAD_ERROR_NOSPEC
);
271 goto return_exception
;
274 rv
= uri
->GetScheme(scheme
);
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
);
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(" -> ");
301 rv
= NS_OpenURI(getter_AddRefs(instream
), uri
, serv
,
302 nsnull
, nsnull
, nsIRequest::LOAD_NORMAL
,
303 getter_AddRefs(chan
));
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];
319 return NS_ERROR_OUT_OF_MEMORY
;
323 rv
= instream
->Read (buf
+ readcount
, len
- readcount
, &lastReadCount
);
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
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
);
362 JS_SetPendingException (cx
, STRING_TO_JSVAL(errmsg
));
366 #endif /* NO_SUBSCRIPT_LOADER */