1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 sw=2 et tw=78: */
3 /* ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
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/
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
16 * The Original Code is mozilla.org code.
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 1998
21 * the Initial Developer. All Rights Reserved.
24 * Mark Hammond <mhammond@skippinet.com.au>
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.
38 * ***** END LICENSE BLOCK ***** */
41 #include "nsJSEnvironment.h"
42 #include "nsIScriptGlobalObject.h"
43 #include "nsIScriptObjectPrincipal.h"
44 #include "nsIDOMChromeWindow.h"
45 #include "nsPIDOMWindow.h"
46 #include "nsIDOMNode.h"
47 #include "nsIDOMElement.h"
48 #include "nsIDOMDocument.h"
49 #include "nsIDOMText.h"
50 #include "nsIDOMAttr.h"
51 #include "nsIDOMNamedNodeMap.h"
52 #include "nsIDOMNodeList.h"
53 #include "nsIDOMKeyEvent.h"
54 #include "nsIDOMHTMLImageElement.h"
55 #include "nsIDOMHTMLOptionElement.h"
56 #include "nsIScriptSecurityManager.h"
58 #include "nsIServiceManager.h"
59 #include "nsIXPConnect.h"
60 #include "nsIJSContextStack.h"
61 #include "nsIJSRuntimeService.h"
63 #include "nsISupportsPrimitives.h"
64 #include "nsReadableUtils.h"
65 #include "nsJSUtils.h"
66 #include "nsIDocShell.h"
67 #include "nsIDocShellTreeItem.h"
68 #include "nsPresContext.h"
69 #include "nsIConsoleService.h"
70 #include "nsIScriptError.h"
71 #include "nsIInterfaceRequestor.h"
72 #include "nsIInterfaceRequestorUtils.h"
73 #include "nsIPrompt.h"
74 #include "nsIObserverService.h"
75 #include "nsGUIEvent.h"
76 #include "nsThreadUtils.h"
79 #include "nsContentUtils.h"
80 #include "nsEventDispatcher.h"
81 #include "nsIContent.h"
82 #include "nsCycleCollector.h"
83 #include "nsNetUtil.h"
84 #include "nsXPCOMCIDInternal.h"
85 #include "nsIXULRuntime.h"
87 // For locale aware string methods
89 #include "nsIPlatformCharset.h"
90 #include "nsICharsetConverterManager.h"
91 #include "nsUnicharUtils.h"
92 #include "nsILocaleService.h"
93 #include "nsICollation.h"
94 #include "nsCollationCID.h"
95 #include "nsDOMClassInfo.h"
97 #include "jsdbgapi.h" // for JS_ClearWatchPointsForObject
100 #include "nsIObjectInputStream.h"
101 #include "nsIObjectOutputStream.h"
102 #include "nsITimelineService.h"
103 #include "nsDOMScriptObjectHolder.h"
105 #include "WrapperFactory.h"
106 #include "nsGlobalWindow.h"
109 // AssertMacros.h defines 'check' and conflicts with AccessCheck.h
112 #include "AccessCheck.h"
114 #ifdef MOZ_JSDEBUGGER
115 #include "jsdIDebuggerService.h"
118 // Force PR_LOGGING so we can get JS strict warnings even in release builds
119 #define FORCE_PR_LOG 1
122 #include "prthread.h"
124 #include "mozilla/FunctionTimer.h"
126 const size_t gStackSize
= 8192;
129 static PRLogModuleInfo
* gJSDiagnostics
;
132 // Thank you Microsoft!
139 // The amount of time we wait between a request to GC (due to leaving
140 // a page) and doing the actual GC.
141 #define NS_GC_DELAY 2000 // ms
143 // The amount of time we wait until we force a GC in case the previous
144 // GC timer happened to fire while we were in the middle of loading a
145 // page (we'll GC once the page is loaded if that happens before this
146 // amount of time has passed).
147 #define NS_LOAD_IN_PROCESS_GC_DELAY 4000 // ms
149 // The amount of time we wait from the first request to GC to actually
150 // doing the first GC.
151 #define NS_FIRST_GC_DELAY 10000 // ms
153 #define JAVASCRIPT nsIProgrammingLanguage::JAVASCRIPT
155 // The max number of delayed cycle collects..
156 #define NS_MAX_DELAYED_CCOLLECT 45
157 // The max number of user interaction notifications in inactive state before
158 // we try to call cycle collector more aggressively.
159 #define NS_CC_SOFT_LIMIT_INACTIVE 6
160 // The max number of user interaction notifications in active state before
161 // we try to call cycle collector more aggressively.
162 #define NS_CC_SOFT_LIMIT_ACTIVE 12
163 // When higher probability MaybeCC is used, the number of sDelayedCCollectCount
164 // is multiplied with this number.
165 #define NS_PROBABILITY_MULTIPLIER 3
166 // Cycle collector is never called more often than every NS_MIN_CC_INTERVAL
167 // milliseconds. Exceptions are low memory situation and memory pressure
169 #define NS_MIN_CC_INTERVAL 10000 // ms
170 // If previous cycle collection collected more than this number of objects,
171 // the next collection will happen somewhat soon.
172 #define NS_COLLECTED_OBJECTS_LIMIT 5000
173 // CC will be called if GC has been called at least this number of times and
174 // there are at least NS_MIN_SUSPECT_CHANGES new suspected objects.
175 #define NS_MAX_GC_COUNT 5
176 #define NS_MIN_SUSPECT_CHANGES 10
177 // CC will be called if there are at least NS_MAX_SUSPECT_CHANGES new suspected
179 #define NS_MAX_SUSPECT_CHANGES 100
181 // if you add statics here, add them to the list in nsJSRuntime::Startup
183 static PRUint32 sDelayedCCollectCount
;
184 static PRUint32 sCCollectCount
;
185 static PRBool sUserIsActive
;
186 static PRTime sPreviousCCTime
;
187 static PRUint32 sCollectedObjectsCounts
;
188 static PRUint32 sSavedGCCount
;
189 static PRUint32 sCCSuspectChanges
;
190 static PRUint32 sCCSuspectedCount
;
191 static nsITimer
*sGCTimer
;
192 static PRBool sReadyForGC
;
194 // The number of currently pending document loads. This count isn't
195 // guaranteed to always reflect reality and can't easily as we don't
196 // have an easy place to know when a load ends or is interrupted in
197 // all cases. This counter also gets reset if we end up GC'ing while
198 // we're waiting for a slow page to load. IOW, this count may be 0
199 // even when there are pending loads.
200 static PRUint32 sPendingLoadCount
;
202 // Boolean that tells us whether or not the current GC timer
203 // (sGCTimer) was scheduled due to a GC timer firing while we were in
204 // the middle of loading a page.
205 static PRBool sLoadInProgressGCTimer
;
207 nsScriptNameSpaceManager
*gNameSpaceManager
;
209 static nsIJSRuntimeService
*sRuntimeService
;
210 JSRuntime
*nsJSRuntime::sRuntime
;
212 static const char kJSRuntimeServiceContractID
[] =
213 "@mozilla.org/js/xpc/RuntimeService;1";
215 static JSGCCallback gOldJSGCCallback
;
217 static PRBool sIsInitialized
;
218 static PRBool sDidShutdown
;
220 static PRInt32 sContextCount
;
222 static PRTime sMaxScriptRunTime
;
223 static PRTime sMaxChromeScriptRunTime
;
225 static nsIScriptSecurityManager
*sSecurityManager
;
227 static nsICollation
*gCollation
;
229 static nsIUnicodeDecoder
*gDecoder
;
231 // nsUserActivityObserver observes user-interaction-active and
232 // user-interaction-inactive notifications. It counts the number of
233 // notifications and if the number is bigger than NS_CC_SOFT_LIMIT_ACTIVE
234 // (in case the current notification is user-interaction-active) or
235 // NS_CC_SOFT_LIMIT_INACTIVE (current notification is user-interaction-inactive)
236 // MaybeCC is called with aHigherParameter set to PR_TRUE, otherwise PR_FALSE.
238 // When moving from active state to inactive, nsJSContext::IntervalCC() is
239 // called unless the timer related to page load is active.
241 class nsUserActivityObserver
: public nsIObserver
244 nsUserActivityObserver()
245 : mUserActivityCounter(0), mOldCCollectCount(0) {}
249 PRUint32 mUserActivityCounter
;
250 PRUint32 mOldCCollectCount
;
253 NS_IMPL_ISUPPORTS1(nsUserActivityObserver
, nsIObserver
)
256 nsUserActivityObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
257 const PRUnichar
* aData
)
259 if (mOldCCollectCount
!= sCCollectCount
) {
260 mOldCCollectCount
= sCCollectCount
;
261 // Cycle collector was called between user interaction notifications, so
262 // we can reset the counter.
263 mUserActivityCounter
= 0;
265 PRBool higherProbability
= PR_FALSE
;
266 ++mUserActivityCounter
;
267 if (!strcmp(aTopic
, "user-interaction-inactive")) {
269 printf("user-interaction-inactive\n");
272 sUserIsActive
= PR_FALSE
;
274 nsJSContext::IntervalCC();
278 higherProbability
= (mUserActivityCounter
> NS_CC_SOFT_LIMIT_INACTIVE
);
279 } else if (!strcmp(aTopic
, "user-interaction-active")) {
281 printf("user-interaction-active\n");
283 sUserIsActive
= PR_TRUE
;
284 higherProbability
= (mUserActivityCounter
> NS_CC_SOFT_LIMIT_ACTIVE
);
285 } else if (!strcmp(aTopic
, "xpcom-shutdown")) {
286 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
288 obs
->RemoveObserver(this, "user-interaction-active");
289 obs
->RemoveObserver(this, "user-interaction-inactive");
290 obs
->RemoveObserver(this, "xpcom-shutdown");
294 nsJSContext::MaybeCC(higherProbability
);
298 // nsCCMemoryPressureObserver observes the memory-pressure notifications
299 // and forces a cycle collection when it happens.
301 class nsCCMemoryPressureObserver
: public nsIObserver
308 NS_IMPL_ISUPPORTS1(nsCCMemoryPressureObserver
, nsIObserver
)
311 nsCCMemoryPressureObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
312 const PRUnichar
* aData
)
314 nsJSContext::CC(nsnull
);
318 /****************************************************************
319 ************************** AutoFree ****************************
320 ****************************************************************/
324 AutoFree(void *aPtr
) : mPtr(aPtr
) {
328 nsMemory::Free(mPtr
);
337 class nsAutoPoolRelease
{
339 nsAutoPoolRelease(JSArenaPool
*p
, void *m
) : mPool(p
), mMark(m
) {}
340 ~nsAutoPoolRelease() { JS_ARENA_RELEASE(mPool
, mMark
); }
346 // A utility function for script languages to call. Although it looks small,
347 // the use of nsIDocShell and nsPresContext triggers a huge number of
348 // dependencies that most languages would not otherwise need.
349 // XXXmarkh - This function is mis-placed!
351 NS_HandleScriptError(nsIScriptGlobalObject
*aScriptGlobal
,
352 nsScriptErrorEvent
*aErrorEvent
,
353 nsEventStatus
*aStatus
)
355 PRBool called
= PR_FALSE
;
356 nsCOMPtr
<nsPIDOMWindow
> win(do_QueryInterface(aScriptGlobal
));
357 nsIDocShell
*docShell
= win
? win
->GetDocShell() : nsnull
;
359 nsRefPtr
<nsPresContext
> presContext
;
360 docShell
->GetPresContext(getter_AddRefs(presContext
));
362 static PRInt32 errorDepth
; // Recursion prevention
365 if (presContext
&& errorDepth
< 2) {
366 // Dispatch() must be synchronous for the recursion block
367 // (errorDepth) to work.
368 nsEventDispatcher::Dispatch(win
, presContext
, aErrorEvent
, nsnull
,
377 class ScriptErrorEvent
: public nsRunnable
380 ScriptErrorEvent(nsIScriptGlobalObject
* aScriptGlobal
,
381 PRUint32 aLineNr
, PRUint32 aColumn
, PRUint32 aFlags
,
382 const nsAString
& aErrorMsg
,
383 const nsAString
& aFileName
,
384 const nsAString
& aSourceLine
,
385 PRBool aDispatchEvent
,
387 : mScriptGlobal(aScriptGlobal
), mLineNr(aLineNr
), mColumn(aColumn
),
388 mFlags(aFlags
), mErrorMsg(aErrorMsg
), mFileName(aFileName
),
389 mSourceLine(aSourceLine
), mDispatchEvent(aDispatchEvent
),
395 nsEventStatus status
= nsEventStatus_eIgnore
;
396 // First, notify the DOM that we have a script error.
397 if (mDispatchEvent
) {
398 nsCOMPtr
<nsPIDOMWindow
> win(do_QueryInterface(mScriptGlobal
));
399 nsIDocShell
* docShell
= win
? win
->GetDocShell() : nsnull
;
401 !JSREPORT_IS_WARNING(mFlags
) &&
402 !sHandlingScriptError
) {
403 sHandlingScriptError
= PR_TRUE
; // Recursion prevention
405 nsRefPtr
<nsPresContext
> presContext
;
406 docShell
->GetPresContext(getter_AddRefs(presContext
));
409 nsScriptErrorEvent
errorevent(PR_TRUE
, NS_LOAD_ERROR
);
411 errorevent
.fileName
= mFileName
.get();
413 nsCOMPtr
<nsIScriptObjectPrincipal
> sop(do_QueryInterface(win
));
414 NS_ENSURE_STATE(sop
);
415 nsIPrincipal
* p
= sop
->GetPrincipal();
418 PRBool sameOrigin
= mFileName
.IsVoid();
420 if (p
&& !sameOrigin
) {
421 nsCOMPtr
<nsIURI
> errorURI
;
422 NS_NewURI(getter_AddRefs(errorURI
), mFileName
);
424 // FIXME: Once error reports contain the origin of the
425 // error (principals) we should change this to do the
426 // security check based on the principals and not
427 // URIs. See bug 387476.
428 sameOrigin
= NS_SUCCEEDED(p
->CheckMayLoad(errorURI
, PR_FALSE
));
432 NS_NAMED_LITERAL_STRING(xoriginMsg
, "Script error.");
434 errorevent
.errorMsg
= mErrorMsg
.get();
435 errorevent
.lineNr
= mLineNr
;
437 NS_WARNING("Not same origin error!");
438 errorevent
.errorMsg
= xoriginMsg
.get();
439 errorevent
.lineNr
= 0;
440 // FIXME: once the principal of the script is not tied to
441 // the filename, we can stop using the post-redirect
442 // filename if we want and remove this line. Note that
443 // apparently we can't handle null filenames in the error
444 // event dispatching code.
445 static PRUnichar nullFilename
[] = { PRUnichar(0) };
446 errorevent
.fileName
= nullFilename
;
449 nsEventDispatcher::Dispatch(win
, presContext
, &errorevent
, nsnull
,
453 sHandlingScriptError
= PR_FALSE
;
457 if (status
!= nsEventStatus_eConsumeNoDefault
) {
458 // Make an nsIScriptError and populate it with information from
460 nsCOMPtr
<nsIScriptError
> errorObject
=
461 do_CreateInstance("@mozilla.org/scripterror;1");
463 if (errorObject
!= nsnull
) {
464 nsresult rv
= NS_ERROR_NOT_AVAILABLE
;
466 // Set category to chrome or content
467 nsCOMPtr
<nsIScriptObjectPrincipal
> scriptPrincipal
=
468 do_QueryInterface(mScriptGlobal
);
469 NS_ASSERTION(scriptPrincipal
, "Global objects must implement "
470 "nsIScriptObjectPrincipal");
471 nsCOMPtr
<nsIPrincipal
> systemPrincipal
;
472 sSecurityManager
->GetSystemPrincipal(getter_AddRefs(systemPrincipal
));
473 const char * category
=
474 scriptPrincipal
->GetPrincipal() == systemPrincipal
475 ? "chrome javascript"
476 : "content javascript";
478 nsCOMPtr
<nsIScriptError2
> error2(do_QueryInterface(errorObject
));
480 rv
= error2
->InitWithWindowID(mErrorMsg
.get(), mFileName
.get(),
482 mLineNr
, mColumn
, mFlags
,
483 category
, mWindowID
);
485 rv
= errorObject
->Init(mErrorMsg
.get(), mFileName
.get(),
487 mLineNr
, mColumn
, mFlags
,
491 if (NS_SUCCEEDED(rv
)) {
492 nsCOMPtr
<nsIConsoleService
> consoleService
=
493 do_GetService(NS_CONSOLESERVICE_CONTRACTID
, &rv
);
494 if (NS_SUCCEEDED(rv
)) {
495 consoleService
->LogMessage(errorObject
);
504 nsCOMPtr
<nsIScriptGlobalObject
> mScriptGlobal
;
510 nsString mSourceLine
;
511 PRBool mDispatchEvent
;
514 static PRBool sHandlingScriptError
;
517 PRBool
ScriptErrorEvent::sHandlingScriptError
= PR_FALSE
;
519 // NOTE: This function could be refactored to use the above. The only reason
520 // it has not been done is that the code below only fills the error event
521 // after it has a good nsPresContext - whereas using the above function
522 // would involve always filling it. Is that a concern?
524 NS_ScriptErrorReporter(JSContext
*cx
,
526 JSErrorReport
*report
)
528 // We don't want to report exceptions too eagerly, but warnings in the
529 // absence of werror are swallowed whole, so report those now.
530 if (!JSREPORT_IS_WARNING(report
->flags
)) {
531 JSStackFrame
* fp
= nsnull
;
532 while ((fp
= JS_FrameIterator(cx
, &fp
))) {
533 if (JS_IsScriptFrame(cx
, fp
)) {
538 nsIXPConnect
* xpc
= nsContentUtils::XPConnect();
540 nsAXPCNativeCallContext
*cc
= nsnull
;
541 xpc
->GetCurrentNativeCallContext(&cc
);
543 nsAXPCNativeCallContext
*prev
= cc
;
544 while (NS_SUCCEEDED(prev
->GetPreviousCallContext(&prev
)) && prev
) {
546 if (NS_SUCCEEDED(prev
->GetLanguage(&lang
)) &&
547 lang
== nsAXPCNativeCallContext::LANG_JS
) {
555 // XXX this means we are not going to get error reports on non DOM contexts
556 nsIScriptContext
*context
= nsJSUtils::GetDynamicScriptContext(cx
);
558 // Note: we must do this before running any more code on cx (if cx is the
559 // dynamic script context).
560 ::JS_ClearPendingException(cx
);
563 nsIScriptGlobalObject
*globalObject
= context
->GetGlobalObject();
566 nsAutoString fileName
, msg
;
567 if (!report
->filename
) {
568 fileName
.SetIsVoid(PR_TRUE
);
570 fileName
.AssignWithConversion(report
->filename
);
573 const PRUnichar
*m
= reinterpret_cast<const PRUnichar
*>
579 if (msg
.IsEmpty() && message
) {
580 msg
.AssignWithConversion(message
);
584 /* We do not try to report Out Of Memory via a dom
585 * event because the dom event handler would encounter
586 * an OOM exception trying to process the event, and
587 * then we'd need to generate a new OOM event for that
588 * new OOM instance -- this isn't pretty.
590 nsAutoString sourceLine
;
591 sourceLine
.Assign(reinterpret_cast<const PRUnichar
*>(report
->uclinebuf
));
592 nsCOMPtr
<nsPIDOMWindow
> win
= do_QueryInterface(globalObject
);
593 PRUint64 windowID
= win
? win
->WindowID() : 0;
594 nsContentUtils::AddScriptRunner(
595 new ScriptErrorEvent(globalObject
, report
->lineno
,
596 report
->uctokenptr
- report
->uclinebuf
,
597 report
->flags
, msg
, fileName
, sourceLine
,
598 report
->errorNumber
!= JSMSG_OUT_OF_MEMORY
,
604 // Print it to stderr as well, for the benefit of those invoking
605 // mozilla with -console.
607 error
.Assign("JavaScript ");
608 if (JSREPORT_IS_STRICT(report
->flags
))
609 error
.Append("strict ");
610 if (JSREPORT_IS_WARNING(report
->flags
))
611 error
.Append("warning: ");
613 error
.Append("error: ");
614 error
.Append(report
->filename
);
615 error
.Append(", line ");
616 error
.AppendInt(report
->lineno
, 10);
618 if (report
->ucmessage
) {
619 AppendUTF16toUTF8(reinterpret_cast<const PRUnichar
*>(report
->ucmessage
),
622 error
.Append(message
);
625 fprintf(stderr
, "%s\n", error
.get());
631 gJSDiagnostics
= PR_NewLogModule("JSDiagnostics");
633 if (gJSDiagnostics
) {
634 PR_LOG(gJSDiagnostics
,
635 JSREPORT_IS_WARNING(report
->flags
) ? PR_LOG_WARNING
: PR_LOG_ERROR
,
636 ("file %s, line %u: %s\n%s%s",
637 report
->filename
, report
->lineno
, message
,
638 report
->linebuf
? report
->linebuf
: "",
640 report
->linebuf
[strlen(report
->linebuf
)-1] != '\n')
648 LocaleToUnicode(JSContext
*cx
, char *src
, jsval
*rval
)
653 // use app default locale
654 nsCOMPtr
<nsILocaleService
> localeService
=
655 do_GetService(NS_LOCALESERVICE_CONTRACTID
, &rv
);
656 if (NS_SUCCEEDED(rv
)) {
657 nsCOMPtr
<nsILocale
> appLocale
;
658 rv
= localeService
->GetApplicationLocale(getter_AddRefs(appLocale
));
659 if (NS_SUCCEEDED(rv
)) {
660 nsAutoString localeStr
;
662 GetCategory(NS_LITERAL_STRING(NSILOCALE_TIME
), localeStr
);
663 NS_ASSERTION(NS_SUCCEEDED(rv
), "failed to get app locale info");
665 nsCOMPtr
<nsIPlatformCharset
> platformCharset
=
666 do_GetService(NS_PLATFORMCHARSET_CONTRACTID
, &rv
);
668 if (NS_SUCCEEDED(rv
)) {
669 nsCAutoString charset
;
670 rv
= platformCharset
->GetDefaultCharsetForLocale(localeStr
, charset
);
671 if (NS_SUCCEEDED(rv
)) {
672 // get/create unicode decoder for charset
673 nsCOMPtr
<nsICharsetConverterManager
> ccm
=
674 do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID
, &rv
);
675 if (NS_SUCCEEDED(rv
))
676 ccm
->GetUnicodeDecoder(charset
.get(), &gDecoder
);
683 JSString
*str
= nsnull
;
684 PRInt32 srcLength
= PL_strlen(src
);
687 PRInt32 unicharLength
= srcLength
;
688 PRUnichar
*unichars
=
689 (PRUnichar
*)JS_malloc(cx
, (srcLength
+ 1) * sizeof(PRUnichar
));
691 rv
= gDecoder
->Convert(src
, &srcLength
, unichars
, &unicharLength
);
692 if (NS_SUCCEEDED(rv
)) {
693 // terminate the returned string
694 unichars
[unicharLength
] = 0;
696 // nsIUnicodeDecoder::Convert may use fewer than srcLength PRUnichars
697 if (unicharLength
+ 1 < srcLength
+ 1) {
698 PRUnichar
*shrunkUnichars
=
699 (PRUnichar
*)JS_realloc(cx
, unichars
,
700 (unicharLength
+ 1) * sizeof(PRUnichar
));
702 unichars
= shrunkUnichars
;
704 str
= JS_NewUCString(cx
,
705 reinterpret_cast<jschar
*>(unichars
),
709 JS_free(cx
, unichars
);
714 nsDOMClassInfo::ThrowJSException(cx
, NS_ERROR_OUT_OF_MEMORY
);
718 *rval
= STRING_TO_JSVAL(str
);
724 ChangeCase(JSContext
*cx
, JSString
*src
, jsval
*rval
,
725 void(* changeCaseFnc
)(const nsAString
&, nsAString
&))
728 changeCaseFnc(nsDependentJSString(src
), result
);
730 JSString
*ucstr
= JS_NewUCStringCopyN(cx
, (jschar
*)result
.get(), result
.Length());
735 *rval
= STRING_TO_JSVAL(ucstr
);
741 LocaleToUpperCase(JSContext
*cx
, JSString
*src
, jsval
*rval
)
743 return ChangeCase(cx
, src
, rval
, ToUpperCase
);
747 LocaleToLowerCase(JSContext
*cx
, JSString
*src
, jsval
*rval
)
749 return ChangeCase(cx
, src
, rval
, ToLowerCase
);
753 LocaleCompare(JSContext
*cx
, JSString
*src1
, JSString
*src2
, jsval
*rval
)
758 nsCOMPtr
<nsILocaleService
> localeService
=
759 do_GetService(NS_LOCALESERVICE_CONTRACTID
, &rv
);
761 if (NS_SUCCEEDED(rv
)) {
762 nsCOMPtr
<nsILocale
> locale
;
763 rv
= localeService
->GetApplicationLocale(getter_AddRefs(locale
));
765 if (NS_SUCCEEDED(rv
)) {
766 nsCOMPtr
<nsICollationFactory
> colFactory
=
767 do_CreateInstance(NS_COLLATIONFACTORY_CONTRACTID
, &rv
);
769 if (NS_SUCCEEDED(rv
)) {
770 rv
= colFactory
->CreateCollation(locale
, &gCollation
);
776 nsDOMClassInfo::ThrowJSException(cx
, rv
);
783 rv
= gCollation
->CompareString(nsICollation::kCollationStrengthDefault
,
784 nsDependentJSString(src1
),
785 nsDependentJSString(src2
),
789 nsDOMClassInfo::ThrowJSException(cx
, rv
);
794 *rval
= INT_TO_JSVAL(result
);
800 // A couple of useful functions to call when you're debugging.
802 JSObject2Win(JSContext
*cx
, JSObject
*obj
)
804 nsIXPConnect
*xpc
= nsContentUtils::XPConnect();
809 nsCOMPtr
<nsIXPConnectWrappedNative
> wrapper
;
810 xpc
->GetWrappedNativeOfJSObject(cx
, obj
, getter_AddRefs(wrapper
));
812 nsCOMPtr
<nsPIDOMWindow
> win
= do_QueryWrappedNative(wrapper
);
814 return static_cast<nsGlobalWindow
*>
815 (static_cast<nsPIDOMWindow
*>(win
));
823 PrintWinURI(nsGlobalWindow
*win
)
826 printf("No window passed in.\n");
830 nsCOMPtr
<nsIDocument
> doc
= do_QueryInterface(win
->GetExtantDocument());
832 printf("No document in the window.\n");
836 nsIURI
*uri
= doc
->GetDocumentURI();
838 printf("Document doesn't have a URI.\n");
844 printf("%s\n", spec
.get());
848 PrintWinCodebase(nsGlobalWindow
*win
)
851 printf("No window passed in.\n");
855 nsIPrincipal
*prin
= win
->GetPrincipal();
857 printf("Window doesn't have principals.\n");
861 nsCOMPtr
<nsIURI
> uri
;
862 prin
->GetURI(getter_AddRefs(uri
));
864 printf("No URI, maybe the system principal.\n");
870 printf("%s\n", spec
.get());
874 DumpString(const nsAString
&str
)
876 printf("%s\n", NS_ConvertUTF16toUTF8(str
).get());
881 MaybeGC(JSContext
*cx
)
883 size_t bytes
= cx
->runtime
->gcBytes
;
884 size_t lastBytes
= cx
->runtime
->gcLastBytes
;
885 if ((bytes
> 8192 && bytes
> lastBytes
* 16)
887 || cx
->runtime
->gcZeal
> 0
894 static already_AddRefed
<nsIPrompt
>
895 GetPromptFromContext(nsJSContext
* ctx
)
897 nsCOMPtr
<nsPIDOMWindow
> win(do_QueryInterface(ctx
->GetGlobalObject()));
898 NS_ENSURE_TRUE(win
, nsnull
);
900 nsIDocShell
*docShell
= win
->GetDocShell();
901 NS_ENSURE_TRUE(docShell
, nsnull
);
903 nsCOMPtr
<nsIInterfaceRequestor
> ireq(do_QueryInterface(docShell
));
904 NS_ENSURE_TRUE(ireq
, nsnull
);
906 // Get the nsIPrompt interface from the docshell
908 ireq
->GetInterface(NS_GET_IID(nsIPrompt
), (void**)&prompt
);
913 nsJSContext::DOMOperationCallback(JSContext
*cx
)
917 // Get the native context
918 nsJSContext
*ctx
= static_cast<nsJSContext
*>(::JS_GetContextPrivate(cx
));
921 // Can happen; see bug 355811
925 // XXX Save the operation callback time so we can restore it after the GC,
926 // because GCing can cause JS to run on our context, causing our
927 // ScriptEvaluated to be called, and clearing our operation callback time.
929 PRTime callbackTime
= ctx
->mOperationCallbackTime
;
930 PRTime modalStateTime
= ctx
->mModalStateTime
;
934 // Now restore the callback time and count, in case they got reset.
935 ctx
->mOperationCallbackTime
= callbackTime
;
936 ctx
->mModalStateTime
= modalStateTime
;
938 PRTime now
= PR_Now();
940 if (callbackTime
== 0) {
941 // Initialize mOperationCallbackTime to start timing how long the
943 ctx
->mOperationCallbackTime
= now
;
947 if (ctx
->mModalStateDepth
) {
948 // We're waiting on a modal dialog, nothing more to do here.
952 PRTime duration
= now
- callbackTime
;
954 // Check the amount of time this script has been running, or if the
955 // dialog is disabled.
956 JSObject
* global
= ::JS_GetGlobalForScopeChain(cx
);
957 PRBool isTrackingChromeCodeTime
=
958 global
&& xpc::AccessCheck::isChrome(global
->getCompartment());
959 if (duration
< (isTrackingChromeCodeTime
?
960 sMaxChromeScriptRunTime
: sMaxScriptRunTime
)) {
964 if (!nsContentUtils::IsSafeToRunScript()) {
965 // If it isn't safe to run script, then it isn't safe to bring up the
966 // prompt (since that will cause the event loop to spin). In this case
967 // (which is rare), we just stop the script... But report a warning so
968 // that developers have some idea of what went wrong.
970 JS_ReportWarning(cx
, "A long running script was terminated");
974 // If we get here we're most likely executing an infinite loop in JS,
975 // we'll tell the user about this and we'll give the user the option
976 // of stopping the execution of the script.
977 nsCOMPtr
<nsIPrompt
> prompt
= GetPromptFromContext(ctx
);
978 NS_ENSURE_TRUE(prompt
, JS_TRUE
);
980 // Check if we should offer the option to debug
981 JSStackFrame
* fp
= ::JS_GetScriptedCaller(cx
, NULL
);
982 PRBool debugPossible
= (fp
!= nsnull
&& cx
->debugHooks
&&
983 cx
->debugHooks
->debuggerHandler
!= nsnull
);
984 #ifdef MOZ_JSDEBUGGER
985 // Get the debugger service if necessary.
987 PRBool jsds_IsOn
= PR_FALSE
;
988 const char jsdServiceCtrID
[] = "@mozilla.org/js/jsd/debugger-service;1";
989 nsCOMPtr
<jsdIExecutionHook
> jsdHook
;
990 nsCOMPtr
<jsdIDebuggerService
> jsds
= do_GetService(jsdServiceCtrID
, &rv
);
992 // Check if there's a user for the debugger service that's 'on' for us
993 if (NS_SUCCEEDED(rv
)) {
994 jsds
->GetDebuggerHook(getter_AddRefs(jsdHook
));
995 jsds
->GetIsOn(&jsds_IsOn
);
996 if (jsds_IsOn
) { // If this is not true, the next call would start jsd...
997 rv
= jsds
->OnForRuntime(cx
->runtime
);
998 jsds_IsOn
= NS_SUCCEEDED(rv
);
1002 // If there is a debug handler registered for this runtime AND
1003 // ((jsd is on AND has a hook) OR (jsd isn't on (something else debugs)))
1004 // then something useful will be done with our request to debug.
1005 debugPossible
= ((jsds_IsOn
&& (jsdHook
!= nsnull
)) || !jsds_IsOn
);
1009 // Get localizable strings
1010 nsXPIDLString title
, msg
, stopButton
, waitButton
, debugButton
, neverShowDlg
;
1012 rv
= nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES
,
1016 rv
|= nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES
,
1020 rv
|= nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES
,
1021 "WaitForScriptButton",
1024 rv
|= nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES
,
1029 if (debugPossible
) {
1030 rv
|= nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES
,
1031 "DebugScriptButton",
1034 rv
|= nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES
,
1035 "KillScriptWithDebugMessage",
1039 rv
|= nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES
,
1040 "KillScriptMessage",
1044 //GetStringFromName can return NS_OK and still give NULL string
1045 if (NS_FAILED(rv
) || !title
|| !msg
|| !stopButton
|| !waitButton
||
1046 (!debugButton
&& debugPossible
) || !neverShowDlg
) {
1047 NS_ERROR("Failed to get localized strings.");
1051 // Append file and line number information, if available
1052 JSScript
*script
= fp
? ::JS_GetFrameScript(cx
, fp
) : nsnull
;
1054 const char *filename
= ::JS_GetScriptFilename(cx
, script
);
1056 nsXPIDLString scriptLocation
;
1057 NS_ConvertUTF8toUTF16
filenameUTF16(filename
);
1058 const PRUnichar
*formatParams
[] = { filenameUTF16
.get() };
1059 rv
= nsContentUtils::FormatLocalizedString(nsContentUtils::eDOM_PROPERTIES
,
1060 "KillScriptLocation",
1064 if (NS_SUCCEEDED(rv
) && scriptLocation
) {
1065 msg
.AppendLiteral("\n\n");
1066 msg
.Append(scriptLocation
);
1068 JSStackFrame
*fp
, *iterator
= nsnull
;
1069 fp
= ::JS_FrameIterator(cx
, &iterator
);
1071 jsbytecode
*pc
= ::JS_GetFramePC(cx
, fp
);
1073 PRUint32 lineno
= ::JS_PCToLineNumber(cx
, script
, pc
);
1075 msg
.AppendInt(lineno
);
1082 PRInt32 buttonPressed
= 0; //In case user exits dialog by clicking X
1083 PRBool neverShowDlgChk
= PR_FALSE
;
1084 PRUint32 buttonFlags
= nsIPrompt::BUTTON_POS_1_DEFAULT
+
1085 (nsIPrompt::BUTTON_TITLE_IS_STRING
*
1086 (nsIPrompt::BUTTON_POS_0
+ nsIPrompt::BUTTON_POS_1
));
1088 // Add a third button if necessary:
1090 buttonFlags
+= nsIPrompt::BUTTON_TITLE_IS_STRING
* nsIPrompt::BUTTON_POS_2
;
1092 // Null out the operation callback while we're re-entering JS here.
1093 ::JS_SetOperationCallback(cx
, nsnull
);
1096 rv
= prompt
->ConfirmEx(title
, msg
, buttonFlags
, waitButton
, stopButton
,
1097 debugButton
, neverShowDlg
, &neverShowDlgChk
,
1100 ::JS_SetOperationCallback(cx
, DOMOperationCallback
);
1102 if (NS_FAILED(rv
) || (buttonPressed
== 0)) {
1103 // Allow the script to continue running
1105 if (neverShowDlgChk
) {
1106 nsIPrefBranch
*prefBranch
= nsContentUtils::GetPrefBranch();
1109 prefBranch
->SetIntPref(isTrackingChromeCodeTime
?
1110 "dom.max_chrome_script_run_time" :
1111 "dom.max_script_run_time", 0);
1115 ctx
->mOperationCallbackTime
= PR_Now();
1118 else if ((buttonPressed
== 2) && debugPossible
) {
1121 switch(cx
->debugHooks
->debuggerHandler(cx
, script
, ::JS_GetFramePC(cx
, fp
),
1124 debuggerHandlerData
)) {
1126 fp
->setReturnValue(js::Valueify(rval
));
1129 cx
->throwing
= JS_FALSE
;
1132 JS_SetPendingException(cx
, rval
);
1134 case JSTRAP_CONTINUE
:
1140 JS_ClearPendingException(cx
);
1145 nsJSContext::EnterModalState()
1147 if (!mModalStateDepth
) {
1148 mModalStateTime
= mOperationCallbackTime
? PR_Now() : 0;
1154 nsJSContext::LeaveModalState()
1156 if (!mModalStateDepth
) {
1157 NS_ERROR("Uh, mismatched LeaveModalState() call!");
1164 // If we're still in a modal dialog, or mOperationCallbackTime is still
1165 // uninitialized, do nothing.
1166 if (mModalStateDepth
|| !mOperationCallbackTime
) {
1170 // If mOperationCallbackTime was set when we entered the first dialog
1171 // (and mModalStateTime is thus non-zero), adjust mOperationCallbackTime
1172 // to account for time spent in the dialog.
1173 // If mOperationCallbackTime got set while the modal dialog was open,
1174 // simply set mOperationCallbackTime to the closing time of the dialog so
1175 // that we never adjust mOperationCallbackTime to be in the future.
1176 if (mModalStateTime
) {
1177 mOperationCallbackTime
+= PR_Now() - mModalStateTime
;
1180 mOperationCallbackTime
= PR_Now();
1184 #define JS_OPTIONS_DOT_STR "javascript.options."
1186 static const char js_options_dot_str
[] = JS_OPTIONS_DOT_STR
;
1187 static const char js_strict_option_str
[] = JS_OPTIONS_DOT_STR
"strict";
1189 static const char js_strict_debug_option_str
[] = JS_OPTIONS_DOT_STR
"strict.debug";
1191 static const char js_werror_option_str
[] = JS_OPTIONS_DOT_STR
"werror";
1192 static const char js_relimit_option_str
[]= JS_OPTIONS_DOT_STR
"relimit";
1194 static const char js_zeal_option_str
[] = JS_OPTIONS_DOT_STR
"gczeal";
1196 static const char js_tracejit_content_str
[] = JS_OPTIONS_DOT_STR
"tracejit.content";
1197 static const char js_tracejit_chrome_str
[] = JS_OPTIONS_DOT_STR
"tracejit.chrome";
1198 static const char js_methodjit_content_str
[] = JS_OPTIONS_DOT_STR
"methodjit.content";
1199 static const char js_methodjit_chrome_str
[] = JS_OPTIONS_DOT_STR
"methodjit.chrome";
1200 static const char js_profiling_content_str
[] = JS_OPTIONS_DOT_STR
"jitprofiling.content";
1201 static const char js_profiling_chrome_str
[] = JS_OPTIONS_DOT_STR
"jitprofiling.chrome";
1204 nsJSContext::JSOptionChangedCallback(const char *pref
, void *data
)
1206 nsJSContext
*context
= reinterpret_cast<nsJSContext
*>(data
);
1207 PRUint32 oldDefaultJSOptions
= context
->mDefaultJSOptions
;
1208 PRUint32 newDefaultJSOptions
= oldDefaultJSOptions
;
1210 PRBool strict
= nsContentUtils::GetBoolPref(js_strict_option_str
);
1212 newDefaultJSOptions
|= JSOPTION_STRICT
;
1214 newDefaultJSOptions
&= ~JSOPTION_STRICT
;
1216 nsIScriptGlobalObject
*global
= context
->GetGlobalObject();
1217 // XXX should we check for sysprin instead of a chrome window, to make
1218 // XXX components be covered by the chrome pref instead of the content one?
1219 nsCOMPtr
<nsIDOMChromeWindow
> chromeWindow(do_QueryInterface(global
));
1221 PRBool useTraceJIT
= nsContentUtils::GetBoolPref(chromeWindow
?
1222 js_tracejit_chrome_str
:
1223 js_tracejit_content_str
);
1224 PRBool useMethodJIT
= nsContentUtils::GetBoolPref(chromeWindow
?
1225 js_methodjit_chrome_str
:
1226 js_methodjit_content_str
);
1227 PRBool useProfiling
= nsContentUtils::GetBoolPref(chromeWindow
?
1228 js_profiling_chrome_str
:
1229 js_profiling_content_str
);
1230 nsCOMPtr
<nsIXULRuntime
> xr
= do_GetService(XULRUNTIME_SERVICE_CONTRACTID
);
1232 PRBool safeMode
= PR_FALSE
;
1233 xr
->GetInSafeMode(&safeMode
);
1235 useTraceJIT
= PR_FALSE
;
1236 useMethodJIT
= PR_FALSE
;
1237 useProfiling
= PR_FALSE
;
1242 newDefaultJSOptions
|= JSOPTION_JIT
;
1244 newDefaultJSOptions
&= ~JSOPTION_JIT
;
1247 newDefaultJSOptions
|= JSOPTION_METHODJIT
;
1249 newDefaultJSOptions
&= ~JSOPTION_METHODJIT
;
1252 newDefaultJSOptions
|= JSOPTION_PROFILING
;
1254 newDefaultJSOptions
&= ~JSOPTION_PROFILING
;
1257 // In debug builds, warnings are enabled in chrome context if javascript.options.strict.debug is true
1258 PRBool strictDebug
= nsContentUtils::GetBoolPref(js_strict_debug_option_str
);
1259 // Note this callback is also called from context's InitClasses thus we don't
1260 // need to enable this directly from InitContext
1261 if (strictDebug
&& (newDefaultJSOptions
& JSOPTION_STRICT
) == 0) {
1263 newDefaultJSOptions
|= JSOPTION_STRICT
;
1267 PRBool werror
= nsContentUtils::GetBoolPref(js_werror_option_str
);
1269 newDefaultJSOptions
|= JSOPTION_WERROR
;
1271 newDefaultJSOptions
&= ~JSOPTION_WERROR
;
1273 PRBool relimit
= nsContentUtils::GetBoolPref(js_relimit_option_str
);
1275 newDefaultJSOptions
|= JSOPTION_RELIMIT
;
1277 newDefaultJSOptions
&= ~JSOPTION_RELIMIT
;
1279 if (newDefaultJSOptions
!= oldDefaultJSOptions
) {
1280 // Set options only if we used the old defaults; otherwise the page has
1281 // customized some via the options object and we defer to its wisdom.
1282 if (::JS_GetOptions(context
->mContext
) == oldDefaultJSOptions
)
1283 ::JS_SetOptions(context
->mContext
, newDefaultJSOptions
);
1285 // Save the new defaults for the next page load (InitContext).
1286 context
->mDefaultJSOptions
= newDefaultJSOptions
;
1290 PRInt32 zeal
= nsContentUtils::GetIntPref(js_zeal_option_str
, -1);
1292 ::JS_SetGCZeal(context
->mContext
, (PRUint8
)zeal
);
1298 nsJSContext::nsJSContext(JSRuntime
*aRuntime
)
1299 : mGCOnDestruction(PR_TRUE
),
1305 mDefaultJSOptions
= JSOPTION_PRIVATE_IS_NSISUPPORTS
| JSOPTION_ANONFUNFIX
;
1307 mContext
= ::JS_NewContext(aRuntime
, gStackSize
);
1309 ::JS_SetContextPrivate(mContext
, static_cast<nsIScriptContext
*>(this));
1311 // Preserve any flags the context callback might have set.
1312 mDefaultJSOptions
|= ::JS_GetOptions(mContext
);
1314 // Make sure the new context gets the default context options
1315 ::JS_SetOptions(mContext
, mDefaultJSOptions
);
1317 // Watch for the JS boolean options
1318 nsContentUtils::RegisterPrefCallback(js_options_dot_str
,
1319 JSOptionChangedCallback
,
1322 ::JS_SetOperationCallback(mContext
, DOMOperationCallback
);
1324 static JSLocaleCallbacks localeCallbacks
=
1332 ::JS_SetLocaleCallbacks(mContext
, &localeCallbacks
);
1334 mIsInitialized
= PR_FALSE
;
1335 mNumEvaluations
= 0;
1336 mTerminations
= nsnull
;
1337 mScriptsEnabled
= PR_TRUE
;
1338 mOperationCallbackTime
= 0;
1339 mModalStateTime
= 0;
1340 mModalStateDepth
= 0;
1341 mProcessingScriptTag
= PR_FALSE
;
1344 nsJSContext::~nsJSContext()
1347 nsCycleCollector_DEBUG_wasFreed(static_cast<nsIScriptContext
*>(this));
1349 NS_PRECONDITION(!mTerminations
, "Shouldn't have termination funcs by now");
1351 mGlobalObjectRef
= nsnull
;
1357 if (!sContextCount
&& sDidShutdown
) {
1358 // The last context is being deleted, and we're already in the
1359 // process of shutting down, release the JS runtime service, and
1360 // the security manager.
1362 NS_IF_RELEASE(sRuntimeService
);
1363 NS_IF_RELEASE(sSecurityManager
);
1364 NS_IF_RELEASE(gCollation
);
1365 NS_IF_RELEASE(gDecoder
);
1370 nsJSContext::DestroyJSContext()
1375 // Clear our entry in the JSContext, bugzilla bug 66413
1376 ::JS_SetContextPrivate(mContext
, nsnull
);
1378 // Unregister our "javascript.options.*" pref-changed callback.
1379 nsContentUtils::UnregisterPrefCallback(js_options_dot_str
,
1380 JSOptionChangedCallback
,
1383 PRBool do_gc
= mGCOnDestruction
&& !sGCTimer
&& sReadyForGC
;
1385 // Let xpconnect destroy the JSContext when it thinks the time is right.
1386 nsIXPConnect
*xpc
= nsContentUtils::XPConnect();
1388 xpc
->ReleaseJSContext(mContext
, !do_gc
);
1390 ::JS_DestroyContext(mContext
);
1392 ::JS_DestroyContextNoGC(mContext
);
1397 // QueryInterface implementation for nsJSContext
1398 NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSContext
)
1399 NS_IMPL_CYCLE_COLLECTION_ROOT_BEGIN(nsJSContext
)
1400 NS_ASSERTION(!tmp
->mContext
|| tmp
->mContext
->outstandingRequests
== 0,
1401 "Trying to unlink a context with outstanding requests.");
1402 tmp
->mIsInitialized
= PR_FALSE
;
1403 tmp
->mGCOnDestruction
= PR_FALSE
;
1404 tmp
->DestroyJSContext();
1405 NS_IMPL_CYCLE_COLLECTION_ROOT_END
1406 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsJSContext
)
1407 NS_IMPL_CYCLE_COLLECTION_TRACE_END
1408 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSContext
)
1409 NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mGlobalObjectRef
)
1410 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
1411 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsJSContext
)
1412 NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsJSContext
, tmp
->GetCCRefcnt())
1413 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mGlobalObjectRef
)
1414 NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb
, "mContext");
1415 nsContentUtils::XPConnect()->NoteJSContext(tmp
->mContext
, cb
);
1416 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
1418 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsJSContext
)
1419 NS_INTERFACE_MAP_ENTRY(nsIScriptContext
)
1420 NS_INTERFACE_MAP_ENTRY(nsIScriptContextPrincipal
)
1421 NS_INTERFACE_MAP_ENTRY(nsIXPCScriptNotify
)
1422 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports
, nsIScriptContext
)
1423 NS_INTERFACE_MAP_END
1426 NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsJSContext
, nsIScriptContext
)
1427 NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsJSContext
, nsIScriptContext
)
1430 nsJSContext::GetCCRefcnt()
1432 nsrefcnt refcnt
= mRefCnt
.get();
1433 if (NS_LIKELY(mContext
))
1434 refcnt
+= mContext
->outstandingRequests
;
1439 nsJSContext::EvaluateStringWithValue(const nsAString
& aScript
,
1441 nsIPrincipal
*aPrincipal
,
1446 PRBool
* aIsUndefined
)
1448 NS_TIME_FUNCTION_MIN_FMT(1.0, "%s (line %d) (url: %s, line: %d)", MOZ_FUNCTION_NAME
,
1449 __LINE__
, aURL
, aLineNo
);
1451 NS_ENSURE_TRUE(mIsInitialized
, NS_ERROR_NOT_INITIALIZED
);
1453 if (!mScriptsEnabled
) {
1455 *aIsUndefined
= PR_TRUE
;
1463 aScopeObject
= ::JS_GetGlobalObject(mContext
);
1465 // Safety first: get an object representing the script's principals, i.e.,
1466 // the entities who signed this script, or the fully-qualified-domain-name
1467 // or "codebase" from which it was loaded.
1468 JSPrincipals
*jsprin
;
1469 nsIPrincipal
*principal
= aPrincipal
;
1471 nsIScriptGlobalObject
*global
= GetGlobalObject();
1473 return NS_ERROR_FAILURE
;
1474 nsCOMPtr
<nsIScriptObjectPrincipal
> objPrincipal
=
1475 do_QueryInterface(global
, &rv
);
1477 return NS_ERROR_FAILURE
;
1478 principal
= objPrincipal
->GetPrincipal();
1480 return NS_ERROR_FAILURE
;
1483 principal
->GetJSPrincipals(mContext
, &jsprin
);
1485 // From here on, we must JSPRINCIPALS_DROP(jsprin) before returning...
1487 PRBool ok
= PR_FALSE
;
1489 rv
= sSecurityManager
->CanExecuteScripts(mContext
, principal
, &ok
);
1490 if (NS_FAILED(rv
)) {
1491 JSPRINCIPALS_DROP(mContext
, jsprin
);
1492 return NS_ERROR_FAILURE
;
1495 // Push our JSContext on the current thread's context stack so JS called
1496 // from native code via XPConnect uses the right context. Do this whether
1497 // or not the SecurityManager said "ok", in order to simplify control flow
1498 // below where we pop before returning.
1499 nsCOMPtr
<nsIJSContextStack
> stack
=
1500 do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv
);
1501 if (NS_FAILED(rv
) || NS_FAILED(stack
->Push(mContext
))) {
1502 JSPRINCIPALS_DROP(mContext
, jsprin
);
1503 return NS_ERROR_FAILURE
;
1508 rv
= sSecurityManager
->PushContextPrincipal(mContext
, nsnull
, principal
);
1509 NS_ENSURE_SUCCESS(rv
, rv
);
1511 nsJSContext::TerminationFuncHolder
holder(this);
1513 // SecurityManager said "ok", but don't compile if aVersion is unknown.
1514 // Since the caller is responsible for parsing the version strings, we just
1515 // check it isn't JSVERSION_UNKNOWN.
1516 if (ok
&& ((JSVersion
)aVersion
) != JSVERSION_UNKNOWN
) {
1518 JSAutoRequest
ar(mContext
);
1520 JSAutoEnterCompartment ac
;
1521 if (!ac
.enter(mContext
, (JSObject
*)aScopeObject
)) {
1522 JSPRINCIPALS_DROP(mContext
, jsprin
);
1524 return NS_ERROR_FAILURE
;
1529 ok
= ::JS_EvaluateUCScriptForPrincipalsVersion(mContext
,
1530 (JSObject
*)aScopeObject
,
1532 (jschar
*)PromiseFlatString(aScript
).get(),
1537 JSVersion(aVersion
));
1542 // Tell XPConnect about any pending exceptions. This is needed
1543 // to avoid dropping JS exceptions in case we got here through
1544 // nested calls through XPConnect.
1546 ReportPendingException();
1550 // Whew! Finally done with these manually ref-counted things.
1551 JSPRINCIPALS_DROP(mContext
, jsprin
);
1553 // If all went well, convert val to a string (XXXbe unless undefined?).
1556 *aIsUndefined
= JSVAL_IS_VOID(val
);
1559 *static_cast<jsval
*>(aRetValue
) = val
;
1560 // XXX - nsScriptObjectHolder should be used once this method moves to
1561 // the new world order. However, use of 'jsval' appears to make this
1566 *aIsUndefined
= PR_TRUE
;
1570 sSecurityManager
->PopContextPrincipal(mContext
);
1572 // Pop here, after JS_ValueToString and any other possible evaluation.
1573 if (NS_FAILED(stack
->Pop(nsnull
)))
1574 rv
= NS_ERROR_FAILURE
;
1576 // ScriptEvaluated needs to come after we pop the stack
1577 ScriptEvaluated(PR_TRUE
);
1583 // Helper function to convert a jsval to an nsAString, and set
1584 // exception flags if the conversion fails.
1586 JSValueToAString(JSContext
*cx
, jsval val
, nsAString
*result
,
1587 PRBool
*isUndefined
)
1590 *isUndefined
= JSVAL_IS_VOID(val
);
1597 JSString
* jsstring
= ::JS_ValueToString(cx
, val
);
1599 result
->Assign(reinterpret_cast<const PRUnichar
*>
1600 (::JS_GetStringChars(jsstring
)),
1601 ::JS_GetStringLength(jsstring
));
1605 // We failed to convert val to a string. We're either OOM, or the
1606 // security manager denied access to .toString(), or somesuch, on
1607 // an object. Treat this case as if the result were undefined.
1610 *isUndefined
= PR_TRUE
;
1613 if (!::JS_IsExceptionPending(cx
)) {
1614 // JS_ValueToString() returned null w/o an exception
1615 // pending. That means we're OOM.
1617 return NS_ERROR_OUT_OF_MEMORY
;
1624 nsIScriptObjectPrincipal
*
1625 nsJSContext::GetObjectPrincipal()
1627 nsCOMPtr
<nsIScriptObjectPrincipal
> prin
= do_QueryInterface(GetGlobalObject());
1632 nsJSContext::EvaluateString(const nsAString
& aScript
,
1634 nsIPrincipal
*aPrincipal
,
1638 nsAString
*aRetValue
,
1639 PRBool
* aIsUndefined
)
1641 NS_TIME_FUNCTION_MIN_FMT(1.0, "%s (line %d) (url: %s, line: %d)", MOZ_FUNCTION_NAME
,
1642 __LINE__
, aURL
, aLineNo
);
1644 NS_ENSURE_TRUE(mIsInitialized
, NS_ERROR_NOT_INITIALIZED
);
1646 if (!mScriptsEnabled
) {
1648 *aIsUndefined
= PR_TRUE
;
1652 aRetValue
->Truncate();
1660 aScopeObject
= ::JS_GetGlobalObject(mContext
);
1662 // Safety first: get an object representing the script's principals, i.e.,
1663 // the entities who signed this script, or the fully-qualified-domain-name
1664 // or "codebase" from which it was loaded.
1665 JSPrincipals
*jsprin
;
1666 nsIPrincipal
*principal
= aPrincipal
;
1668 aPrincipal
->GetJSPrincipals(mContext
, &jsprin
);
1671 nsCOMPtr
<nsIScriptObjectPrincipal
> objPrincipal
=
1672 do_QueryInterface(GetGlobalObject(), &rv
);
1674 return NS_ERROR_FAILURE
;
1675 principal
= objPrincipal
->GetPrincipal();
1677 return NS_ERROR_FAILURE
;
1678 principal
->GetJSPrincipals(mContext
, &jsprin
);
1681 // From here on, we must JSPRINCIPALS_DROP(jsprin) before returning...
1683 PRBool ok
= PR_FALSE
;
1685 rv
= sSecurityManager
->CanExecuteScripts(mContext
, principal
, &ok
);
1686 if (NS_FAILED(rv
)) {
1687 JSPRINCIPALS_DROP(mContext
, jsprin
);
1688 return NS_ERROR_FAILURE
;
1691 // Push our JSContext on the current thread's context stack so JS called
1692 // from native code via XPConnect uses the right context. Do this whether
1693 // or not the SecurityManager said "ok", in order to simplify control flow
1694 // below where we pop before returning.
1695 nsCOMPtr
<nsIJSContextStack
> stack
=
1696 do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv
);
1697 if (NS_FAILED(rv
) || NS_FAILED(stack
->Push(mContext
))) {
1698 JSPRINCIPALS_DROP(mContext
, jsprin
);
1699 return NS_ERROR_FAILURE
;
1702 // The result of evaluation, used only if there were no errors. This need
1703 // not be a GC root currently, provided we run the GC only from the
1704 // operation callback or from ScriptEvaluated.
1705 jsval val
= JSVAL_VOID
;
1706 jsval
* vp
= aRetValue
? &val
: NULL
;
1708 rv
= sSecurityManager
->PushContextPrincipal(mContext
, nsnull
, principal
);
1709 NS_ENSURE_SUCCESS(rv
, rv
);
1711 nsJSContext::TerminationFuncHolder
holder(this);
1715 // SecurityManager said "ok", but don't compile if aVersion is unknown.
1716 // Since the caller is responsible for parsing the version strings, we just
1717 // check it isn't JSVERSION_UNKNOWN.
1718 if (ok
&& ((JSVersion
)aVersion
) != JSVERSION_UNKNOWN
) {
1719 JSAutoRequest
ar(mContext
);
1720 JSAutoEnterCompartment ac
;
1721 if (!ac
.enter(mContext
, (JSObject
*)aScopeObject
)) {
1723 JSPRINCIPALS_DROP(mContext
, jsprin
);
1724 return NS_ERROR_FAILURE
;
1727 ok
= ::JS_EvaluateUCScriptForPrincipalsVersion(mContext
,
1728 (JSObject
*)aScopeObject
,
1730 (jschar
*)PromiseFlatString(aScript
).get(),
1735 JSVersion(aVersion
));
1738 // Tell XPConnect about any pending exceptions. This is needed
1739 // to avoid dropping JS exceptions in case we got here through
1740 // nested calls through XPConnect.
1742 ReportPendingException();
1746 // Whew! Finally done with these manually ref-counted things.
1747 JSPRINCIPALS_DROP(mContext
, jsprin
);
1749 // If all went well, convert val to a string if one is wanted.
1751 JSAutoRequest
ar(mContext
);
1752 JSAutoEnterCompartment ac
;
1753 if (!ac
.enter(mContext
, (JSObject
*)aScopeObject
)) {
1756 rv
= JSValueToAString(mContext
, val
, aRetValue
, aIsUndefined
);
1760 *aIsUndefined
= PR_TRUE
;
1764 aRetValue
->Truncate();
1770 sSecurityManager
->PopContextPrincipal(mContext
);
1772 // Pop here, after JS_ValueToString and any other possible evaluation.
1773 if (NS_FAILED(stack
->Pop(nsnull
)))
1774 rv
= NS_ERROR_FAILURE
;
1776 // ScriptEvaluated needs to come after we pop the stack
1777 ScriptEvaluated(PR_TRUE
);
1783 nsJSContext::CompileScript(const PRUnichar
* aText
,
1784 PRInt32 aTextLength
,
1786 nsIPrincipal
*aPrincipal
,
1790 nsScriptObjectHolder
&aScriptObject
)
1792 NS_ENSURE_TRUE(mIsInitialized
, NS_ERROR_NOT_INITIALIZED
);
1795 NS_ENSURE_ARG_POINTER(aPrincipal
);
1798 aScopeObject
= ::JS_GetGlobalObject(mContext
);
1800 JSPrincipals
*jsprin
;
1801 aPrincipal
->GetJSPrincipals(mContext
, &jsprin
);
1802 // From here on, we must JSPRINCIPALS_DROP(jsprin) before returning...
1804 PRBool ok
= PR_FALSE
;
1806 rv
= sSecurityManager
->CanExecuteScripts(mContext
, aPrincipal
, &ok
);
1807 if (NS_FAILED(rv
)) {
1808 JSPRINCIPALS_DROP(mContext
, jsprin
);
1809 return NS_ERROR_FAILURE
;
1812 aScriptObject
.drop(); // ensure old object not used on failure...
1814 // SecurityManager said "ok", but don't compile if aVersion is unknown.
1815 // Since the caller is responsible for parsing the version strings, we just
1816 // check it isn't JSVERSION_UNKNOWN.
1817 if (ok
&& ((JSVersion
)aVersion
) != JSVERSION_UNKNOWN
) {
1818 JSAutoRequest
ar(mContext
);
1821 ::JS_CompileUCScriptForPrincipalsVersion(mContext
,
1822 (JSObject
*)aScopeObject
,
1828 JSVersion(aVersion
));
1830 JSObject
*scriptObject
= ::JS_NewScriptObject(mContext
, script
);
1832 NS_ASSERTION(aScriptObject
.getScriptTypeID()==JAVASCRIPT
,
1833 "Expecting JS script object holder");
1834 rv
= aScriptObject
.set(scriptObject
);
1836 ::JS_DestroyScript(mContext
, script
);
1840 rv
= NS_ERROR_OUT_OF_MEMORY
;
1844 // Whew! Finally done.
1845 JSPRINCIPALS_DROP(mContext
, jsprin
);
1850 nsJSContext::ExecuteScript(void *aScriptObject
,
1852 nsAString
* aRetValue
,
1853 PRBool
* aIsUndefined
)
1855 NS_ENSURE_TRUE(mIsInitialized
, NS_ERROR_NOT_INITIALIZED
);
1857 if (!mScriptsEnabled
) {
1859 *aIsUndefined
= PR_TRUE
;
1863 aRetValue
->Truncate();
1872 aScopeObject
= ::JS_GetGlobalObject(mContext
);
1874 // Push our JSContext on our thread's context stack, in case native code
1875 // called from JS calls back into JS via XPConnect.
1876 nsCOMPtr
<nsIJSContextStack
> stack
=
1877 do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv
);
1878 if (NS_FAILED(rv
) || NS_FAILED(stack
->Push(mContext
))) {
1879 return NS_ERROR_FAILURE
;
1882 // The result of evaluation, used only if there were no errors. This need
1883 // not be a GC root currently, provided we run the GC only from the
1884 // operation callback or from ScriptEvaluated.
1888 JSObject
*scriptObj
= (JSObject
*)aScriptObject
;
1889 nsCOMPtr
<nsIPrincipal
> principal
;
1891 rv
= sSecurityManager
->GetObjectPrincipal(mContext
, scriptObj
, getter_AddRefs(principal
));
1892 NS_ENSURE_SUCCESS(rv
, rv
);
1894 rv
= sSecurityManager
->PushContextPrincipal(mContext
, nsnull
, principal
);
1895 NS_ENSURE_SUCCESS(rv
, rv
);
1897 nsJSContext::TerminationFuncHolder
holder(this);
1898 JSAutoRequest
ar(mContext
);
1900 ok
= ::JS_ExecuteScript(mContext
,
1901 (JSObject
*)aScopeObject
,
1902 (JSScript
*)::JS_GetPrivate(mContext
, scriptObj
),
1906 // If all went well, convert val to a string (XXXbe unless undefined?).
1907 rv
= JSValueToAString(mContext
, val
, aRetValue
, aIsUndefined
);
1910 *aIsUndefined
= PR_TRUE
;
1914 aRetValue
->Truncate();
1920 sSecurityManager
->PopContextPrincipal(mContext
);
1922 // Pop here, after JS_ValueToString and any other possible evaluation.
1923 if (NS_FAILED(stack
->Pop(nsnull
)))
1924 rv
= NS_ERROR_FAILURE
;
1926 // ScriptEvaluated needs to come after we pop the stack
1927 ScriptEvaluated(PR_TRUE
);
1935 AtomIsEventHandlerName(nsIAtom
*aName
)
1937 const PRUnichar
*name
= aName
->GetUTF16String();
1939 const PRUnichar
*cp
;
1941 for (cp
= name
; *cp
!= '\0'; ++cp
)
1944 if ((c
< 'A' || c
> 'Z') && (c
< 'a' || c
> 'z'))
1952 // Helper function to find the JSObject associated with a (presumably DOM)
1955 nsJSContext::JSObjectFromInterface(nsISupports
* aTarget
, void *aScope
, JSObject
**aRet
)
1957 // It is legal to specify a null target.
1963 // Get the jsobject associated with this target
1964 // We don't wrap here because we trust the JS engine to wrap the target
1968 rv
= nsContentUtils::WrapNative(mContext
, (JSObject
*)aScope
, aTarget
, &v
);
1969 NS_ENSURE_SUCCESS(rv
, rv
);
1972 nsCOMPtr
<nsISupports
> targetSupp
= do_QueryInterface(aTarget
);
1973 nsCOMPtr
<nsISupports
> native
=
1974 nsContentUtils::XPConnect()->GetNativeOfWrapper(mContext
,
1975 JSVAL_TO_OBJECT(v
));
1976 NS_ASSERTION(native
== targetSupp
, "Native should be the target!");
1979 *aRet
= JSVAL_TO_OBJECT(v
);
1986 nsJSContext::CompileEventHandler(nsIAtom
*aName
,
1988 const char** aArgNames
,
1989 const nsAString
& aBody
,
1990 const char *aURL
, PRUint32 aLineNo
,
1992 nsScriptObjectHolder
&aHandler
)
1994 NS_TIME_FUNCTION_MIN_FMT(1.0, "%s (line %d) (url: %s, line: %d)", MOZ_FUNCTION_NAME
,
1995 __LINE__
, aURL
, aLineNo
);
1997 NS_ENSURE_TRUE(mIsInitialized
, NS_ERROR_NOT_INITIALIZED
);
1999 NS_PRECONDITION(AtomIsEventHandlerName(aName
), "Bad event name");
2000 NS_PRECONDITION(!::JS_IsExceptionPending(mContext
),
2001 "Why are we being called with a pending exception?");
2003 if (!sSecurityManager
) {
2004 NS_ERROR("Huh, we need a script security manager to compile "
2005 "an event handler!");
2007 return NS_ERROR_UNEXPECTED
;
2010 // Don't compile if aVersion is unknown. Since the caller is responsible for
2011 // parsing the version strings, we just check it isn't JSVERSION_UNKNOWN.
2012 if ((JSVersion
)aVersion
== JSVERSION_UNKNOWN
) {
2013 return NS_ERROR_ILLEGAL_VALUE
;
2017 JSContext
* top
= nsContentUtils::GetCurrentJSContext();
2018 NS_ASSERTION(mContext
== top
, "Context not properly pushed!");
2021 // Event handlers are always shared, and must be bound before use.
2022 // Therefore we never bother compiling with principals.
2023 // (that probably means we should avoid JS_CompileUCFunctionForPrincipals!)
2024 JSAutoRequest
ar(mContext
);
2027 ::JS_CompileUCFunctionForPrincipalsVersion(mContext
,
2029 nsAtomCString(aName
).get(), aArgCount
, aArgNames
,
2030 (jschar
*)PromiseFlatString(aBody
).get(),
2032 aURL
, aLineNo
, JSVersion(aVersion
));
2035 ReportPendingException();
2036 return NS_ERROR_ILLEGAL_VALUE
;
2039 JSObject
*handler
= ::JS_GetFunctionObject(fun
);
2040 NS_ASSERTION(aHandler
.getScriptTypeID()==JAVASCRIPT
,
2041 "Expecting JS script object holder");
2042 return aHandler
.set((void *)handler
);
2045 // XXX - note that CompileFunction doesn't yet play the nsScriptObjectHolder
2046 // game - caller must still ensure JS GC root.
2048 nsJSContext::CompileFunction(void* aTarget
,
2049 const nsACString
& aName
,
2051 const char** aArgArray
,
2052 const nsAString
& aBody
,
2057 void** aFunctionObject
)
2059 NS_TIME_FUNCTION_FMT(1.0, "%s (line %d) (function: %s, url: %s, line: %d)", MOZ_FUNCTION_NAME
,
2060 __LINE__
, aName
.BeginReading(), aURL
, aLineNo
);
2062 NS_ENSURE_TRUE(mIsInitialized
, NS_ERROR_NOT_INITIALIZED
);
2064 // Don't compile if aVersion is unknown. Since the caller is responsible for
2065 // parsing the version strings, we just check it isn't JSVERSION_UNKNOWN.
2066 if ((JSVersion
)aVersion
== JSVERSION_UNKNOWN
) {
2067 return NS_ERROR_ILLEGAL_VALUE
;
2070 JSPrincipals
*jsprin
= nsnull
;
2072 nsIScriptGlobalObject
*global
= GetGlobalObject();
2074 // XXXbe why the two-step QI? speed up via a new GetGlobalObjectData func?
2075 nsCOMPtr
<nsIScriptObjectPrincipal
> globalData
= do_QueryInterface(global
);
2077 nsIPrincipal
*prin
= globalData
->GetPrincipal();
2079 return NS_ERROR_FAILURE
;
2080 prin
->GetJSPrincipals(mContext
, &jsprin
);
2084 JSObject
*target
= (JSObject
*)aTarget
;
2086 JSAutoRequest
ar(mContext
);
2089 ::JS_CompileUCFunctionForPrincipalsVersion(mContext
,
2090 aShared
? nsnull
: target
, jsprin
,
2091 PromiseFlatCString(aName
).get(),
2092 aArgCount
, aArgArray
,
2093 (jschar
*)PromiseFlatString(aBody
).get(),
2096 JSVersion(aVersion
));
2099 JSPRINCIPALS_DROP(mContext
, jsprin
);
2101 return NS_ERROR_FAILURE
;
2103 JSObject
*handler
= ::JS_GetFunctionObject(fun
);
2104 if (aFunctionObject
)
2105 *aFunctionObject
= (void*) handler
;
2110 nsJSContext::CallEventHandler(nsISupports
* aTarget
, void *aScope
, void *aHandler
,
2111 nsIArray
*aargv
, nsIVariant
**arv
)
2113 NS_ENSURE_TRUE(mIsInitialized
, NS_ERROR_NOT_INITIALIZED
);
2115 if (!mScriptsEnabled
) {
2119 NS_TIME_FUNCTION_FMT(1.0, "%s (line %d) (function: %s)", MOZ_FUNCTION_NAME
,
2120 __LINE__
, JS_GetFunctionName(static_cast<JSFunction
*>(JS_GetPrivate(mContext
, static_cast<JSObject
*>(aHandler
)))));
2123 JSAutoRequest
ar(mContext
);
2124 JSObject
* target
= nsnull
;
2125 nsresult rv
= JSObjectFromInterface(aTarget
, aScope
, &target
);
2126 NS_ENSURE_SUCCESS(rv
, rv
);
2128 js::AutoObjectRooter
targetVal(mContext
, target
);
2129 jsval rval
= JSVAL_VOID
;
2131 // This one's a lot easier than EvaluateString because we don't have to
2132 // hassle with principals: they're already compiled into the JS function.
2133 // xxxmarkh - this comment is no longer true - principals are not used at
2134 // all now, and never were in some cases.
2136 nsCOMPtr
<nsIJSContextStack
> stack
=
2137 do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv
);
2138 if (NS_FAILED(rv
) || NS_FAILED(stack
->Push(mContext
)))
2139 return NS_ERROR_FAILURE
;
2141 // check if the event handler can be run on the object in question
2142 rv
= sSecurityManager
->CheckFunctionAccess(mContext
, aHandler
, target
);
2144 nsJSContext::TerminationFuncHolder
holder(this);
2146 if (NS_SUCCEEDED(rv
)) {
2147 // Convert args to jsvals.
2149 jsval
*argv
= nsnull
;
2151 js::LazilyConstructed
<nsAutoPoolRelease
> poolRelease
;
2152 js::LazilyConstructed
<js::AutoArrayRooter
> tvr
;
2154 // Use |target| as the scope for wrapping the arguments, since aScope is
2155 // the safe scope in many cases, which isn't very useful. Wrapping aTarget
2156 // was OK because those typically have PreCreate methods that give them the
2157 // right scope anyway, and we want to make sure that the arguments end up
2158 // in the same scope as aTarget.
2159 rv
= ConvertSupportsTojsvals(aargv
, target
, &argc
,
2160 &argv
, poolRelease
, tvr
);
2161 if (NS_FAILED(rv
)) {
2166 jsval funval
= OBJECT_TO_JSVAL(static_cast<JSObject
*>(aHandler
));
2167 JSAutoEnterCompartment ac
;
2168 if (!ac
.enter(mContext
, target
)) {
2170 return NS_ERROR_FAILURE
;
2174 PRBool ok
= ::JS_CallFunctionValue(mContext
, target
,
2175 funval
, argc
, argv
, &rval
);
2179 // Tell XPConnect about any pending exceptions. This is needed
2180 // to avoid dropping JS exceptions in case we got here through
2181 // nested calls through XPConnect.
2183 ReportPendingException();
2185 // Don't pass back results from failed calls.
2188 // Tell the caller that the handler threw an error.
2189 rv
= NS_ERROR_FAILURE
;
2193 if (NS_FAILED(stack
->Pop(nsnull
)))
2194 return NS_ERROR_FAILURE
;
2196 // Convert to variant before calling ScriptEvaluated, as it may GC, meaning
2197 // we would need to root rval.
2198 if (NS_SUCCEEDED(rv
)) {
2199 if (rval
== JSVAL_NULL
)
2202 rv
= nsContentUtils::XPConnect()->JSToVariant(mContext
, rval
, arv
);
2205 // ScriptEvaluated needs to come after we pop the stack
2206 ScriptEvaluated(PR_TRUE
);
2212 nsJSContext::BindCompiledEventHandler(nsISupports
* aTarget
, void *aScope
,
2216 NS_ENSURE_ARG(aHandler
);
2217 NS_ENSURE_TRUE(mIsInitialized
, NS_ERROR_NOT_INITIALIZED
);
2219 NS_PRECONDITION(AtomIsEventHandlerName(aName
), "Bad event name");
2222 // Get the jsobject associated with this target
2223 JSObject
*target
= nsnull
;
2224 nsAutoGCRoot
root(&target
, &rv
);
2225 NS_ENSURE_SUCCESS(rv
, rv
);
2226 rv
= JSObjectFromInterface(aTarget
, aScope
, &target
);
2227 NS_ENSURE_SUCCESS(rv
, rv
);
2229 JSObject
*funobj
= (JSObject
*) aHandler
;
2230 JSAutoRequest
ar(mContext
);
2234 JSAutoEnterCompartment ac
;
2235 if (!ac
.enter(mContext
, funobj
)) {
2236 return NS_ERROR_FAILURE
;
2239 NS_ASSERTION(JS_TypeOfValue(mContext
,
2240 OBJECT_TO_JSVAL(funobj
)) == JSTYPE_FUNCTION
,
2241 "Event handler object not a function");
2245 JSAutoEnterCompartment ac
;
2246 if (!ac
.enter(mContext
, target
)) {
2247 return NS_ERROR_FAILURE
;
2250 // Push our JSContext on our thread's context stack, in case native code
2251 // called from JS calls back into JS via XPConnect.
2252 nsCOMPtr
<nsIJSContextStack
> stack
=
2253 do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv
);
2254 if (NS_FAILED(rv
) || NS_FAILED(stack
->Push(mContext
))) {
2255 return NS_ERROR_FAILURE
;
2258 // Make sure the handler function is parented by its event target object
2259 if (funobj
) { // && ::JS_GetParent(mContext, funobj) != target) {
2260 funobj
= ::JS_CloneFunctionObject(mContext
, funobj
, target
);
2262 rv
= NS_ERROR_OUT_OF_MEMORY
;
2265 if (NS_SUCCEEDED(rv
) &&
2266 // Make sure the flags here match those in nsEventReceiverSH::NewResolve
2267 !::JS_DefineProperty(mContext
, target
, nsAtomCString(aName
).get(),
2268 OBJECT_TO_JSVAL(funobj
), nsnull
, nsnull
,
2269 JSPROP_ENUMERATE
| JSPROP_PERMANENT
)) {
2270 ReportPendingException();
2271 rv
= NS_ERROR_FAILURE
;
2274 // XXXmarkh - ideally we should assert that the wrapped native is now
2275 // "long lived" - how to do that?
2277 if (NS_FAILED(stack
->Pop(nsnull
)) && NS_SUCCEEDED(rv
)) {
2278 rv
= NS_ERROR_FAILURE
;
2285 nsJSContext::GetBoundEventHandler(nsISupports
* aTarget
, void *aScope
,
2287 nsScriptObjectHolder
&aHandler
)
2289 NS_PRECONDITION(AtomIsEventHandlerName(aName
), "Bad event name");
2292 JSObject
*obj
= nsnull
;
2293 nsAutoGCRoot
root(&obj
, &rv
);
2294 NS_ENSURE_SUCCESS(rv
, rv
);
2295 JSAutoRequest
ar(mContext
);
2296 rv
= JSObjectFromInterface(aTarget
, aScope
, &obj
);
2297 NS_ENSURE_SUCCESS(rv
, rv
);
2299 JSAutoEnterCompartment ac
;
2300 if (!ac
.enter(mContext
, obj
)) {
2301 return NS_ERROR_FAILURE
;
2305 if (!JS_LookupProperty(mContext
, obj
,
2306 nsAtomCString(aName
).get(), &funval
))
2307 return NS_ERROR_FAILURE
;
2309 if (JS_TypeOfValue(mContext
, funval
) != JSTYPE_FUNCTION
) {
2310 NS_WARNING("Event handler object not a function");
2314 NS_ASSERTION(aHandler
.getScriptTypeID()==JAVASCRIPT
,
2315 "Expecting JS script object holder");
2316 return aHandler
.set(JSVAL_TO_OBJECT(funval
));
2321 nsJSContext::Serialize(nsIObjectOutputStream
* aStream
, void *aScriptObject
)
2323 JSObject
*mJSObject
= (JSObject
*)aScriptObject
;
2325 return NS_ERROR_FAILURE
;
2329 JSContext
* cx
= mContext
;
2330 JSXDRState
*xdr
= ::JS_XDRNewMem(cx
, JSXDR_ENCODE
);
2332 return NS_ERROR_OUT_OF_MEMORY
;
2333 xdr
->userdata
= (void*) aStream
;
2335 JSAutoRequest
ar(cx
);
2336 JSScript
*script
= reinterpret_cast<JSScript
*>
2337 (::JS_GetPrivate(cx
, mJSObject
));
2338 if (! ::JS_XDRScript(xdr
, &script
)) {
2339 rv
= NS_ERROR_FAILURE
; // likely to be a principals serialization error
2341 // Get the encoded JSXDRState data and write it. The JSXDRState owns
2342 // this buffer memory and will free it beneath ::JS_XDRDestroy.
2344 // If an XPCOM object needs to be written in the midst of the JS XDR
2345 // encoding process, the C++ code called back from the JS engine (e.g.,
2346 // nsEncodeJSPrincipals in caps/src/nsJSPrincipals.cpp) will flush data
2347 // from the JSXDRState to aStream, then write the object, then return
2348 // to JS XDR code with xdr reset so new JS data is encoded at the front
2349 // of the xdr's data buffer.
2351 // However many XPCOM objects are interleaved with JS XDR data in the
2352 // stream, when control returns here from ::JS_XDRScript, we'll have
2353 // one last buffer of data to write to aStream.
2356 const char* data
= reinterpret_cast<const char*>
2357 (::JS_XDRMemGetData(xdr
, &size
));
2358 NS_ASSERTION(data
, "no decoded JSXDRState data!");
2360 rv
= aStream
->Write32(size
);
2361 if (NS_SUCCEEDED(rv
))
2362 rv
= aStream
->WriteBytes(data
, size
);
2365 ::JS_XDRDestroy(xdr
);
2366 if (NS_FAILED(rv
)) return rv
;
2372 nsJSContext::Deserialize(nsIObjectInputStream
* aStream
,
2373 nsScriptObjectHolder
&aResult
)
2375 JSObject
*result
= nsnull
;
2378 NS_TIME_FUNCTION_MIN(1.0);
2380 NS_TIMELINE_MARK_FUNCTION("js script deserialize");
2383 rv
= aStream
->Read32(&size
);
2384 if (NS_FAILED(rv
)) return rv
;
2387 rv
= aStream
->ReadBytes(size
, &data
);
2388 if (NS_FAILED(rv
)) return rv
;
2390 JSContext
* cx
= mContext
;
2392 JSXDRState
*xdr
= ::JS_XDRNewMem(cx
, JSXDR_DECODE
);
2394 rv
= NS_ERROR_OUT_OF_MEMORY
;
2396 xdr
->userdata
= (void*) aStream
;
2397 JSAutoRequest
ar(cx
);
2398 ::JS_XDRMemSetData(xdr
, data
, size
);
2400 JSScript
*script
= nsnull
;
2401 if (! ::JS_XDRScript(xdr
, &script
)) {
2402 rv
= NS_ERROR_FAILURE
; // principals deserialization error?
2404 result
= ::JS_NewScriptObject(cx
, script
);
2406 rv
= NS_ERROR_OUT_OF_MEMORY
; // certain error
2407 ::JS_DestroyScript(cx
, script
);
2411 // Update data in case ::JS_XDRScript called back into C++ code to
2412 // read an XPCOM object.
2414 // In that case, the serialization process must have flushed a run
2415 // of counted bytes containing JS data at the point where the XPCOM
2416 // object starts, after which an encoding C++ callback from the JS
2417 // XDR code must have written the XPCOM object directly into the
2418 // nsIObjectOutputStream.
2420 // The deserialization process will XDR-decode counted bytes up to
2421 // but not including the XPCOM object, then call back into C++ to
2422 // read the object, then read more counted bytes and hand them off
2423 // to the JSXDRState, so more JS data can be decoded.
2425 // This interleaving of JS XDR data and XPCOM object data may occur
2426 // several times beneath the call to ::JS_XDRScript, above. At the
2427 // end of the day, we need to free (via nsMemory) the data owned by
2428 // the JSXDRState. So we steal it back, nulling xdr's buffer so it
2429 // doesn't get passed to ::JS_free by ::JS_XDRDestroy.
2432 data
= (char*) ::JS_XDRMemGetData(xdr
, &junk
);
2434 ::JS_XDRMemSetData(xdr
, NULL
, 0);
2435 ::JS_XDRDestroy(xdr
);
2438 // If data is null now, it must have been freed while deserializing an
2439 // XPCOM object (e.g., a principal) beneath ::JS_XDRScript.
2441 nsMemory::Free(data
);
2442 NS_ASSERTION(aResult
.getScriptTypeID()==JAVASCRIPT
,
2443 "Expecting JS script object holder");
2445 // Now that we've cleaned up, handle the case when rv is a failure
2446 // code, which could happen for all sorts of reasons above.
2447 NS_ENSURE_SUCCESS(rv
, rv
);
2449 return aResult
.set(result
);
2453 nsJSContext::SetDefaultLanguageVersion(PRUint32 aVersion
)
2455 ::JS_SetVersion(mContext
, (JSVersion
)aVersion
);
2458 nsIScriptGlobalObject
*
2459 nsJSContext::GetGlobalObject()
2461 JSObject
*global
= ::JS_GetGlobalObject(mContext
);
2467 OBJ_TO_INNER_OBJECT(mContext
, global
);
2472 JSClass
*c
= JS_GET_CLASS(mContext
, global
);
2474 if (!c
|| ((~c
->flags
) & (JSCLASS_HAS_PRIVATE
|
2475 JSCLASS_PRIVATE_IS_NSISUPPORTS
))) {
2479 JSAutoEnterCompartment ac
;
2481 // NB: This AutoCrossCompartmentCall is only here to silence a warning. If
2482 // it fails, nothing bad will happen.
2483 ac
.enterAndIgnoreErrors(mContext
, global
);
2485 nsCOMPtr
<nsIScriptGlobalObject
> sgo
;
2487 (nsISupports
*)::JS_GetPrivate(mContext
, global
);
2489 nsCOMPtr
<nsIXPConnectWrappedNative
> wrapped_native
=
2490 do_QueryInterface(priv
);
2492 if (wrapped_native
) {
2493 // The global object is a XPConnect wrapped native, the native in
2494 // the wrapper might be the nsIScriptGlobalObject
2496 sgo
= do_QueryWrappedNative(wrapped_native
);
2498 sgo
= do_QueryInterface(priv
);
2501 // This'll return a pointer to something we're about to release, but
2502 // that's ok, the JS object will hold it alive long enough.
2503 nsCOMPtr
<nsPIDOMWindow
> pwin(do_QueryInterface(sgo
));
2507 return static_cast<nsGlobalWindow
*>(pwin
->GetOuterWindow());
2511 nsJSContext::GetNativeGlobal()
2513 return ::JS_GetGlobalObject(mContext
);
2517 nsJSContext::CreateNativeGlobalForInner(
2518 nsIScriptGlobalObject
*aNewInner
,
2520 nsIPrincipal
*aPrincipal
,
2521 void **aNativeGlobal
, nsISupports
**aHolder
)
2523 nsIXPConnect
*xpc
= nsContentUtils::XPConnect();
2524 PRUint32 flags
= aIsChrome
? nsIXPConnect::FLAG_SYSTEM_GLOBAL_OBJECT
: 0;
2525 nsCOMPtr
<nsIXPConnectJSObjectHolder
> jsholder
;
2527 nsCOMPtr
<nsIPrincipal
> systemPrincipal
;
2529 nsIScriptSecurityManager
*ssm
= nsContentUtils::GetSecurityManager();
2530 ssm
->GetSystemPrincipal(getter_AddRefs(systemPrincipal
));
2534 InitClassesWithNewWrappedGlobal(mContext
,
2535 aNewInner
, NS_GET_IID(nsISupports
),
2536 aIsChrome
? systemPrincipal
.get() : aPrincipal
,
2537 EmptyCString(), flags
,
2538 getter_AddRefs(jsholder
));
2541 jsholder
->GetJSObject(reinterpret_cast<JSObject
**>(aNativeGlobal
));
2542 *aHolder
= jsholder
.get();
2543 NS_ADDREF(*aHolder
);
2548 nsJSContext::ConnectToInner(nsIScriptGlobalObject
*aNewInner
, void *aOuterGlobal
)
2550 NS_ENSURE_ARG(aNewInner
);
2551 JSObject
*newInnerJSObject
= (JSObject
*)aNewInner
->GetScriptGlobal(JAVASCRIPT
);
2552 JSObject
*outerGlobal
= (JSObject
*)aOuterGlobal
;
2554 // Make the inner and outer window both share the same
2555 // prototype. The prototype we share is the outer window's
2556 // prototype, this way XPConnect can still find the wrapper to
2557 // use when making a call like alert() (w/o qualifying it with
2558 // "window."). XPConnect looks up the wrapper based on the
2559 // function object's parent, which is the object the function
2560 // was called on, and when calling alert() we'll be calling the
2561 // alert() function from the outer window's prototype off of the
2562 // inner window. In this case XPConnect is able to find the
2563 // outer (through the JSExtendedClass hook outerObject), so this
2564 // prototype sharing works.
2566 // Now that we're connecting the outer global to the inner one,
2567 // we must have transplanted it. The JS engine tries to maintain
2568 // the global object's compartment as its default compartment,
2569 // so update that now since it might have changed.
2570 JS_SetGlobalObject(mContext
, outerGlobal
);
2572 // We do *not* want to use anything else out of the outer
2573 // object's prototype chain than the first prototype, which is
2574 // the XPConnect prototype. The rest we want from the inner
2575 // window's prototype, i.e. the global scope polluter and
2576 // Object.prototype. This way the outer also gets the benefits
2577 // of the global scope polluter, and the inner window's
2578 // Object.prototype.
2579 JSObject
*proto
= JS_GetPrototype(mContext
, outerGlobal
);
2580 JSObject
*innerProto
= JS_GetPrototype(mContext
, newInnerJSObject
);
2581 JSObject
*innerProtoProto
= JS_GetPrototype(mContext
, innerProto
);
2583 JS_SetPrototype(mContext
, newInnerJSObject
, proto
);
2584 JS_SetPrototype(mContext
, proto
, innerProtoProto
);
2590 nsJSContext::GetNativeContext()
2596 nsJSContext::InitContext()
2598 // Make sure callers of this use
2599 // WillInitializeContext/DidInitializeContext around this call.
2600 NS_ENSURE_TRUE(!mIsInitialized
, NS_ERROR_ALREADY_INITIALIZED
);
2603 return NS_ERROR_OUT_OF_MEMORY
;
2605 ::JS_SetErrorReporter(mContext
, NS_ScriptErrorReporter
);
2611 nsJSContext::CreateOuterObject(nsIScriptGlobalObject
*aGlobalObject
,
2612 nsIScriptGlobalObject
*aCurrentInner
)
2614 mGlobalObjectRef
= aGlobalObject
;
2616 nsCOMPtr
<nsIDOMChromeWindow
> chromeWindow(do_QueryInterface(aGlobalObject
));
2620 // Flag this window's global object and objects under it as "system",
2621 // for optional automated XPCNativeWrapper construction when chrome JS
2622 // views a content DOM.
2623 flags
= nsIXPConnect::FLAG_SYSTEM_GLOBAL_OBJECT
;
2625 // Always enable E4X for XUL and other chrome content -- there is no
2626 // need to preserve the <!-- script hiding hack from JS-in-HTML daze
2627 // (introduced in 1995 for graceful script degradation in Netscape 1,
2628 // Mosaic, and other pre-JS browsers).
2629 JS_SetOptions(mContext
, JS_GetOptions(mContext
) | JSOPTION_XML
);
2632 nsIXPConnect
*xpc
= nsContentUtils::XPConnect();
2633 nsCOMPtr
<nsIXPConnectJSObjectHolder
> holder
;
2635 nsresult rv
= xpc
->WrapNative(mContext
, aCurrentInner
->GetGlobalJSObject(),
2636 aCurrentInner
, NS_GET_IID(nsISupports
),
2637 getter_AddRefs(holder
));
2638 NS_ENSURE_SUCCESS(rv
, rv
);
2640 nsCOMPtr
<nsIXPConnectWrappedNative
> wrapper(do_QueryInterface(holder
));
2641 NS_ABORT_IF_FALSE(wrapper
, "bad wrapper");
2643 wrapper
->RefreshPrototype();
2646 NS_NewOuterWindowProxy(mContext
, aCurrentInner
->GetGlobalJSObject());
2648 return NS_ERROR_FAILURE
;
2651 return SetOuterObject(outer
);
2655 nsJSContext::SetOuterObject(void *aOuterObject
)
2657 JSObject
*outer
= static_cast<JSObject
*>(aOuterObject
);
2659 // Force our context's global object to be the outer.
2660 JS_SetGlobalObject(mContext
, outer
);
2665 nsJSContext::InitOuterWindow()
2667 JSObject
*global
= JS_GetGlobalObject(mContext
);
2668 OBJ_TO_INNER_OBJECT(mContext
, global
);
2670 nsresult rv
= InitClasses(global
); // this will complete global object initialization
2671 NS_ENSURE_SUCCESS(rv
, rv
);
2677 nsJSContext::InitializeExternalClasses()
2679 nsScriptNameSpaceManager
*nameSpaceManager
= nsJSRuntime::GetNameSpaceManager();
2680 NS_ENSURE_TRUE(nameSpaceManager
, NS_ERROR_NOT_INITIALIZED
);
2682 return nameSpaceManager
->InitForContext(this);
2686 nsJSContext::SetProperty(void *aTarget
, const char *aPropName
, nsISupports
*aArgs
)
2689 jsval
*argv
= nsnull
;
2691 JSAutoRequest
ar(mContext
);
2693 js::LazilyConstructed
<nsAutoPoolRelease
> poolRelease
;
2694 js::LazilyConstructed
<js::AutoArrayRooter
> tvr
;
2697 rv
= ConvertSupportsTojsvals(aArgs
, GetNativeGlobal(), &argc
,
2698 &argv
, poolRelease
, tvr
);
2699 NS_ENSURE_SUCCESS(rv
, rv
);
2703 // got the arguments, now attach them.
2705 // window.dialogArguments is supposed to be an array if a JS array
2706 // was passed to showModalDialog(), deal with that here.
2707 if (strcmp(aPropName
, "dialogArguments") == 0 && argc
<= 1) {
2708 vargs
= argc
? argv
[0] : JSVAL_VOID
;
2710 for (PRUint32 i
= 0; i
< argc
; ++i
) {
2711 if (!JS_WrapValue(mContext
, &argv
[i
])) {
2712 return NS_ERROR_FAILURE
;
2716 JSObject
*args
= ::JS_NewArrayObject(mContext
, argc
, argv
);
2717 vargs
= OBJECT_TO_JSVAL(args
);
2720 // Make sure to use JS_DefineProperty here so that we can override
2721 // readonly XPConnect properties here as well (read dialogArguments).
2722 rv
= ::JS_DefineProperty(mContext
, reinterpret_cast<JSObject
*>(aTarget
),
2723 aPropName
, vargs
, nsnull
, nsnull
, 0) ?
2724 NS_OK
: NS_ERROR_FAILURE
;
2730 nsJSContext::ConvertSupportsTojsvals(nsISupports
*aArgs
,
2734 js::LazilyConstructed
<nsAutoPoolRelease
> &aPoolRelease
,
2735 js::LazilyConstructed
<js::AutoArrayRooter
> &aRooter
)
2737 nsresult rv
= NS_OK
;
2739 // If the array implements nsIJSArgArray, just grab the values directly.
2740 nsCOMPtr
<nsIJSArgArray
> fastArray
= do_QueryInterface(aArgs
);
2741 if (fastArray
!= nsnull
)
2742 return fastArray
->GetArgs(aArgc
, reinterpret_cast<void **>(aArgv
));
2744 // Take the slower path converting each item.
2745 // Handle only nsIArray and nsIVariant. nsIArray is only needed for
2746 // SetProperty('arguments', ...);
2751 nsIXPConnect
*xpc
= nsContentUtils::XPConnect();
2752 NS_ENSURE_TRUE(xpc
, NS_ERROR_UNEXPECTED
);
2756 PRUint32 argCtr
, argCount
;
2757 // This general purpose function may need to convert an arg array
2758 // (window.arguments, event-handler args) and a generic property.
2759 nsCOMPtr
<nsIArray
> argsArray(do_QueryInterface(aArgs
));
2762 rv
= argsArray
->GetLength(&argCount
);
2763 NS_ENSURE_SUCCESS(rv
, rv
);
2767 argCount
= 1; // the nsISupports which is not an array
2770 void *mark
= JS_ARENA_MARK(&mContext
->tempPool
);
2772 size_t nbytes
= argCount
* sizeof(jsval
);
2773 JS_ARENA_ALLOCATE_CAST(argv
, jsval
*, &mContext
->tempPool
, nbytes
);
2774 NS_ENSURE_TRUE(argv
, NS_ERROR_OUT_OF_MEMORY
);
2775 memset(argv
, 0, nbytes
); /* initialize so GC-able */
2777 // Use the caller's auto guards to release and unroot.
2778 aPoolRelease
.construct(&mContext
->tempPool
, mark
);
2779 aRooter
.construct(mContext
, argCount
, argv
);
2782 for (argCtr
= 0; argCtr
< argCount
&& NS_SUCCEEDED(rv
); argCtr
++) {
2783 nsCOMPtr
<nsISupports
> arg
;
2784 jsval
*thisval
= argv
+ argCtr
;
2785 argsArray
->QueryElementAt(argCtr
, NS_GET_IID(nsISupports
),
2786 getter_AddRefs(arg
));
2788 *thisval
= JSVAL_NULL
;
2791 nsCOMPtr
<nsIVariant
> variant(do_QueryInterface(arg
));
2792 if (variant
!= nsnull
) {
2793 rv
= xpc
->VariantToJS(mContext
, (JSObject
*)aScope
, variant
,
2796 // And finally, support the nsISupportsPrimitives supplied
2797 // by the AppShell. It generally will pass only strings, but
2798 // as we have code for handling all, we may as well use it.
2799 rv
= AddSupportsPrimitiveTojsvals(arg
, thisval
);
2800 if (rv
== NS_ERROR_NO_INTERFACE
) {
2801 // something else - probably an event object or similar -
2804 // but first, check its not another nsISupportsPrimitive, as
2805 // these are now deprecated for use with script contexts.
2806 nsCOMPtr
<nsISupportsPrimitive
> prim(do_QueryInterface(arg
));
2807 NS_ASSERTION(prim
== nsnull
,
2808 "Don't pass nsISupportsPrimitives - use nsIVariant!");
2810 nsCOMPtr
<nsIXPConnectJSObjectHolder
> wrapper
;
2812 rv
= nsContentUtils::WrapNative(mContext
, (JSObject
*)aScope
, arg
,
2813 &v
, getter_AddRefs(wrapper
));
2814 if (NS_SUCCEEDED(rv
)) {
2821 nsCOMPtr
<nsIVariant
> variant(do_QueryInterface(aArgs
));
2823 rv
= xpc
->VariantToJS(mContext
, (JSObject
*)aScope
, variant
, argv
);
2825 NS_ERROR("Not an array, not an interface?");
2826 rv
= NS_ERROR_UNEXPECTED
;
2836 // This really should go into xpconnect somewhere...
2838 nsJSContext::AddSupportsPrimitiveTojsvals(nsISupports
*aArg
, jsval
*aArgv
)
2840 NS_PRECONDITION(aArg
, "Empty arg");
2842 nsCOMPtr
<nsISupportsPrimitive
> argPrimitive(do_QueryInterface(aArg
));
2844 return NS_ERROR_NO_INTERFACE
;
2846 JSContext
*cx
= mContext
;
2848 argPrimitive
->GetType(&type
);
2851 case nsISupportsPrimitive::TYPE_CSTRING
: {
2852 nsCOMPtr
<nsISupportsCString
> p(do_QueryInterface(argPrimitive
));
2853 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2860 JSString
*str
= ::JS_NewStringCopyN(cx
, data
.get(), data
.Length());
2861 NS_ENSURE_TRUE(str
, NS_ERROR_OUT_OF_MEMORY
);
2863 *aArgv
= STRING_TO_JSVAL(str
);
2867 case nsISupportsPrimitive::TYPE_STRING
: {
2868 nsCOMPtr
<nsISupportsString
> p(do_QueryInterface(argPrimitive
));
2869 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2875 // cast is probably safe since wchar_t and jschar are expected
2876 // to be equivalent; both unsigned 16-bit entities
2878 ::JS_NewUCStringCopyN(cx
,
2879 reinterpret_cast<const jschar
*>(data
.get()),
2881 NS_ENSURE_TRUE(str
, NS_ERROR_OUT_OF_MEMORY
);
2883 *aArgv
= STRING_TO_JSVAL(str
);
2886 case nsISupportsPrimitive::TYPE_PRBOOL
: {
2887 nsCOMPtr
<nsISupportsPRBool
> p(do_QueryInterface(argPrimitive
));
2888 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2894 *aArgv
= BOOLEAN_TO_JSVAL(data
);
2898 case nsISupportsPrimitive::TYPE_PRUINT8
: {
2899 nsCOMPtr
<nsISupportsPRUint8
> p(do_QueryInterface(argPrimitive
));
2900 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2906 *aArgv
= INT_TO_JSVAL(data
);
2910 case nsISupportsPrimitive::TYPE_PRUINT16
: {
2911 nsCOMPtr
<nsISupportsPRUint16
> p(do_QueryInterface(argPrimitive
));
2912 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2918 *aArgv
= INT_TO_JSVAL(data
);
2922 case nsISupportsPrimitive::TYPE_PRUINT32
: {
2923 nsCOMPtr
<nsISupportsPRUint32
> p(do_QueryInterface(argPrimitive
));
2924 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2930 *aArgv
= INT_TO_JSVAL(data
);
2934 case nsISupportsPrimitive::TYPE_CHAR
: {
2935 nsCOMPtr
<nsISupportsChar
> p(do_QueryInterface(argPrimitive
));
2936 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2942 JSString
*str
= ::JS_NewStringCopyN(cx
, &data
, 1);
2943 NS_ENSURE_TRUE(str
, NS_ERROR_OUT_OF_MEMORY
);
2945 *aArgv
= STRING_TO_JSVAL(str
);
2949 case nsISupportsPrimitive::TYPE_PRINT16
: {
2950 nsCOMPtr
<nsISupportsPRInt16
> p(do_QueryInterface(argPrimitive
));
2951 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2957 *aArgv
= INT_TO_JSVAL(data
);
2961 case nsISupportsPrimitive::TYPE_PRINT32
: {
2962 nsCOMPtr
<nsISupportsPRInt32
> p(do_QueryInterface(argPrimitive
));
2963 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2969 *aArgv
= INT_TO_JSVAL(data
);
2973 case nsISupportsPrimitive::TYPE_FLOAT
: {
2974 nsCOMPtr
<nsISupportsFloat
> p(do_QueryInterface(argPrimitive
));
2975 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2981 JSBool ok
= ::JS_NewNumberValue(cx
, data
, aArgv
);
2982 NS_ENSURE_TRUE(ok
, NS_ERROR_OUT_OF_MEMORY
);
2986 case nsISupportsPrimitive::TYPE_DOUBLE
: {
2987 nsCOMPtr
<nsISupportsDouble
> p(do_QueryInterface(argPrimitive
));
2988 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
2994 JSBool ok
= ::JS_NewNumberValue(cx
, data
, aArgv
);
2995 NS_ENSURE_TRUE(ok
, NS_ERROR_OUT_OF_MEMORY
);
2999 case nsISupportsPrimitive::TYPE_INTERFACE_POINTER
: {
3000 nsCOMPtr
<nsISupportsInterfacePointer
> p(do_QueryInterface(argPrimitive
));
3001 NS_ENSURE_TRUE(p
, NS_ERROR_UNEXPECTED
);
3003 nsCOMPtr
<nsISupports
> data
;
3004 nsIID
*iid
= nsnull
;
3006 p
->GetData(getter_AddRefs(data
));
3007 p
->GetDataIID(&iid
);
3008 NS_ENSURE_TRUE(iid
, NS_ERROR_UNEXPECTED
);
3010 AutoFree
iidGuard(iid
); // Free iid upon destruction.
3012 nsCOMPtr
<nsIXPConnectJSObjectHolder
> wrapper
;
3014 nsresult rv
= nsContentUtils::WrapNative(cx
, ::JS_GetGlobalObject(cx
),
3016 getter_AddRefs(wrapper
));
3017 NS_ENSURE_SUCCESS(rv
, rv
);
3023 case nsISupportsPrimitive::TYPE_ID
:
3024 case nsISupportsPrimitive::TYPE_PRUINT64
:
3025 case nsISupportsPrimitive::TYPE_PRINT64
:
3026 case nsISupportsPrimitive::TYPE_PRTIME
:
3027 case nsISupportsPrimitive::TYPE_VOID
: {
3028 NS_WARNING("Unsupported primitive type used");
3029 *aArgv
= JSVAL_NULL
;
3033 NS_WARNING("Unknown primitive type used");
3034 *aArgv
= JSVAL_NULL
;
3041 static JSPropertySpec OptionsProperties
[] = {
3042 {"strict", (int8
)JSOPTION_STRICT
, JSPROP_ENUMERATE
| JSPROP_PERMANENT
},
3043 {"werror", (int8
)JSOPTION_WERROR
, JSPROP_ENUMERATE
| JSPROP_PERMANENT
},
3044 {"relimit", (int8
)JSOPTION_RELIMIT
, JSPROP_ENUMERATE
| JSPROP_PERMANENT
},
3049 GetOptionsProperty(JSContext
*cx
, JSObject
*obj
, jsid id
, jsval
*vp
)
3051 if (JSID_IS_INT(id
)) {
3052 uint32 optbit
= (uint32
) JSID_TO_INT(id
);
3053 if (((optbit
& (optbit
- 1)) == 0 && optbit
<= JSOPTION_WERROR
) ||
3054 optbit
== JSOPTION_RELIMIT
)
3055 *vp
= (JS_GetOptions(cx
) & optbit
) ? JSVAL_TRUE
: JSVAL_FALSE
;
3061 SetOptionsProperty(JSContext
*cx
, JSObject
*obj
, jsid id
, jsval
*vp
)
3063 if (JSID_IS_INT(id
)) {
3064 uint32 optbit
= (uint32
) JSID_TO_INT(id
);
3066 // Don't let options other than strict, werror, or relimit be set -- it
3067 // would be bad if web page script could clear
3068 // JSOPTION_PRIVATE_IS_NSISUPPORTS!
3069 if (((optbit
& (optbit
- 1)) == 0 && optbit
<= JSOPTION_WERROR
) ||
3070 optbit
== JSOPTION_RELIMIT
) {
3072 JS_ValueToBoolean(cx
, *vp
, &optval
);
3074 uint32 optset
= ::JS_GetOptions(cx
);
3079 ::JS_SetOptions(cx
, optset
);
3085 static JSClass OptionsClass
= {
3088 JS_PropertyStub
, JS_PropertyStub
, GetOptionsProperty
, SetOptionsProperty
,
3089 JS_EnumerateStub
, JS_ResolveStub
, JS_ConvertStub
, nsnull
3092 #ifdef NS_TRACE_MALLOC
3094 #include <errno.h> // XXX assume Linux if NS_TRACE_MALLOC
3102 #include "nsTraceMalloc.h"
3105 CheckUniversalXPConnectForTraceMalloc(JSContext
*cx
)
3107 PRBool hasCap
= PR_FALSE
;
3108 nsresult rv
= nsContentUtils::GetSecurityManager()->
3109 IsCapabilityEnabled("UniversalXPConnect", &hasCap
);
3110 if (NS_SUCCEEDED(rv
) && hasCap
)
3112 JS_ReportError(cx
, "trace-malloc functions require UniversalXPConnect");
3117 TraceMallocDisable(JSContext
*cx
, uintN argc
, jsval
*vp
)
3119 if (!CheckUniversalXPConnectForTraceMalloc(cx
))
3122 NS_TraceMallocDisable();
3123 JS_SET_RVAL(cx
, vp
, JSVAL_VOID
);
3128 TraceMallocEnable(JSContext
*cx
, uintN argc
, jsval
*vp
)
3130 if (!CheckUniversalXPConnectForTraceMalloc(cx
))
3133 NS_TraceMallocEnable();
3134 JS_SET_RVAL(cx
, vp
, JSVAL_VOID
);
3139 TraceMallocOpenLogFile(JSContext
*cx
, uintN argc
, jsval
*vp
)
3145 if (!CheckUniversalXPConnectForTraceMalloc(cx
))
3151 str
= JS_ValueToString(cx
, JS_ARGV(cx
, vp
)[0]);
3154 filename
= JS_GetStringBytes(str
);
3155 fd
= open(filename
, O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
3157 JS_ReportError(cx
, "can't open %s: %s", filename
, strerror(errno
));
3161 JS_SET_RVAL(cx
, vp
, INT_TO_JSVAL(fd
));
3166 TraceMallocChangeLogFD(JSContext
*cx
, uintN argc
, jsval
*vp
)
3170 if (!CheckUniversalXPConnectForTraceMalloc(cx
))
3176 if (!JS_ValueToECMAInt32(cx
, JS_ARGV(cx
, vp
)[0], &fd
))
3178 oldfd
= NS_TraceMallocChangeLogFD(fd
);
3180 JS_ReportOutOfMemory(cx
);
3184 JS_SET_RVAL(cx
, vp
, INT_TO_JSVAL(oldfd
));
3189 TraceMallocCloseLogFD(JSContext
*cx
, uintN argc
, jsval
*vp
)
3193 if (!CheckUniversalXPConnectForTraceMalloc(cx
))
3196 JS_SET_RVAL(cx
, vp
, JSVAL_VOID
);
3199 if (!JS_ValueToECMAInt32(cx
, JS_ARGV(cx
, vp
)[0], &fd
))
3201 NS_TraceMallocCloseLogFD((int) fd
);
3206 TraceMallocLogTimestamp(JSContext
*cx
, uintN argc
, jsval
*vp
)
3209 const char *caption
;
3211 if (!CheckUniversalXPConnectForTraceMalloc(cx
))
3214 str
= JS_ValueToString(cx
, argc
? JS_ARGV(cx
, vp
)[0] : JSVAL_VOID
);
3217 caption
= JS_GetStringBytes(str
);
3218 NS_TraceMallocLogTimestamp(caption
);
3219 JS_SET_RVAL(cx
, vp
, JSVAL_VOID
);
3224 TraceMallocDumpAllocations(JSContext
*cx
, uintN argc
, jsval
*vp
)
3227 const char *pathname
;
3229 if (!CheckUniversalXPConnectForTraceMalloc(cx
))
3232 str
= JS_ValueToString(cx
, argc
? JS_ARGV(cx
, vp
)[0] : JSVAL_VOID
);
3235 pathname
= JS_GetStringBytes(str
);
3236 if (NS_TraceMallocDumpAllocations(pathname
) < 0) {
3237 JS_ReportError(cx
, "can't dump to %s: %s", pathname
, strerror(errno
));
3240 JS_SET_RVAL(cx
, vp
, JSVAL_VOID
);
3244 static JSFunctionSpec TraceMallocFunctions
[] = {
3245 {"TraceMallocDisable", TraceMallocDisable
, 0, 0},
3246 {"TraceMallocEnable", TraceMallocEnable
, 0, 0},
3247 {"TraceMallocOpenLogFile", TraceMallocOpenLogFile
, 1, 0},
3248 {"TraceMallocChangeLogFD", TraceMallocChangeLogFD
, 1, 0},
3249 {"TraceMallocCloseLogFD", TraceMallocCloseLogFD
, 1, 0},
3250 {"TraceMallocLogTimestamp", TraceMallocLogTimestamp
, 1, 0},
3251 {"TraceMallocDumpAllocations", TraceMallocDumpAllocations
, 1, 0},
3252 {nsnull
, nsnull
, 0, 0}
3255 #endif /* NS_TRACE_MALLOC */
3262 IsJProfAction(struct sigaction
*action
)
3264 return (action
->sa_sigaction
&&
3265 action
->sa_flags
== (SA_RESTART
| SA_SIGINFO
));
3268 void NS_JProfStartProfiling();
3269 void NS_JProfStopProfiling();
3272 JProfStartProfilingJS(JSContext
*cx
, uintN argc
, jsval
*vp
)
3274 NS_JProfStartProfiling();
3278 void NS_JProfStartProfiling()
3280 // Figure out whether we're dealing with SIGPROF, SIGALRM, or
3281 // SIGPOLL profiling (SIGALRM for JP_REALTIME, SIGPOLL for
3283 struct sigaction action
;
3285 sigaction(SIGALRM
, nsnull
, &action
);
3286 if (IsJProfAction(&action
)) {
3287 printf("Beginning real-time jprof profiling.\n");
3292 sigaction(SIGPROF
, nsnull
, &action
);
3293 if (IsJProfAction(&action
)) {
3294 printf("Beginning process-time jprof profiling.\n");
3299 sigaction(SIGPOLL
, nsnull
, &action
);
3300 if (IsJProfAction(&action
)) {
3301 printf("Beginning rtc-based jprof profiling.\n");
3306 printf("Could not start jprof-profiling since JPROF_FLAGS was not set.\n");
3310 JProfStopProfilingJS(JSContext
*cx
, uintN argc
, jsval
*vp
)
3312 NS_JProfStopProfiling();
3317 NS_JProfStopProfiling()
3320 printf("Stopped jprof profiling.\n");
3323 static JSFunctionSpec JProfFunctions
[] = {
3324 {"JProfStartProfiling", JProfStartProfilingJS
, 0, 0},
3325 {"JProfStopProfiling", JProfStopProfilingJS
, 0, 0},
3326 {nsnull
, nsnull
, 0, 0}
3329 #endif /* defined(MOZ_JPROF) */
3332 static JSFunctionSpec SharkFunctions
[] = {
3333 {"startShark", js_StartShark
, 0, 0},
3334 {"stopShark", js_StopShark
, 0, 0},
3335 {"connectShark", js_ConnectShark
, 0, 0},
3336 {"disconnectShark", js_DisconnectShark
, 0, 0},
3337 {nsnull
, nsnull
, 0, 0}
3341 #ifdef MOZ_CALLGRIND
3342 static JSFunctionSpec CallgrindFunctions
[] = {
3343 {"startCallgrind", js_StartCallgrind
, 0, 0},
3344 {"stopCallgrind", js_StopCallgrind
, 0, 0},
3345 {"dumpCallgrind", js_DumpCallgrind
, 1, 0},
3346 {nsnull
, nsnull
, 0, 0}
3351 static JSFunctionSpec VtuneFunctions
[] = {
3352 {"startVtune", js_StartVtune
, 1, 0},
3353 {"stopVtune", js_StopVtune
, 0, 0},
3354 {"pauseVtune", js_PauseVtune
, 0, 0},
3355 {"resumeVtune", js_ResumeVtune
, 0, 0},
3356 {nsnull
, nsnull
, 0, 0}
3361 static JSFunctionSpec EthogramFunctions
[] = {
3362 {"initEthogram", js_InitEthogram
, 0, 0},
3363 {"shutdownEthogram", js_ShutdownEthogram
, 0, 0},
3364 {nsnull
, nsnull
, 0, 0}
3369 nsJSContext::InitClasses(void *aGlobalObj
)
3371 nsresult rv
= NS_OK
;
3373 JSObject
*globalObj
= static_cast<JSObject
*>(aGlobalObj
);
3375 rv
= InitializeExternalClasses();
3376 NS_ENSURE_SUCCESS(rv
, rv
);
3378 JSAutoRequest
ar(mContext
);
3380 // Initialize the options object and set default options in mContext
3381 JSObject
*optionsObj
= ::JS_DefineObject(mContext
, globalObj
, "_options",
3382 &OptionsClass
, nsnull
, 0);
3384 ::JS_DefineProperties(mContext
, optionsObj
, OptionsProperties
)) {
3385 ::JS_SetOptions(mContext
, mDefaultJSOptions
);
3387 rv
= NS_ERROR_FAILURE
;
3390 #ifdef NS_TRACE_MALLOC
3391 // Attempt to initialize TraceMalloc functions
3392 ::JS_DefineFunctions(mContext
, globalObj
, TraceMallocFunctions
);
3396 // Attempt to initialize JProf functions
3397 ::JS_DefineFunctions(mContext
, globalObj
, JProfFunctions
);
3401 // Attempt to initialize Shark functions
3402 ::JS_DefineFunctions(mContext
, globalObj
, SharkFunctions
);
3405 #ifdef MOZ_CALLGRIND
3406 // Attempt to initialize Callgrind functions
3407 ::JS_DefineFunctions(mContext
, globalObj
, CallgrindFunctions
);
3411 // Attempt to initialize Vtune functions
3412 ::JS_DefineFunctions(mContext
, globalObj
, VtuneFunctions
);
3416 // Attempt to initialize Ethogram functions
3417 ::JS_DefineFunctions(mContext
, globalObj
, EthogramFunctions
);
3420 JSOptionChangedCallback(js_options_dot_str
, this);
3426 nsJSContext::ClearScope(void *aGlobalObj
, PRBool aClearFromProtoChain
)
3428 // Push our JSContext on our thread's context stack.
3429 nsCOMPtr
<nsIJSContextStack
> stack
=
3430 do_GetService("@mozilla.org/js/xpc/ContextStack;1");
3431 if (stack
&& NS_FAILED(stack
->Push(mContext
))) {
3436 JSObject
*obj
= (JSObject
*)aGlobalObj
;
3437 JSAutoRequest
ar(mContext
);
3439 JSAutoEnterCompartment ac
;
3440 ac
.enterAndIgnoreErrors(mContext
, obj
);
3442 JS_ClearScope(mContext
, obj
);
3443 if (xpc::WrapperFactory::IsXrayWrapper(obj
)) {
3444 JS_ClearScope(mContext
, &obj
->getProxyExtra().toObject());
3446 if (!obj
->getParent()) {
3447 JS_ClearRegExpStatics(mContext
, obj
);
3450 // Always clear watchpoints, to deal with two cases:
3451 // 1. The first document for this window is loading, and a miscreant has
3452 // preset watchpoints on the window object in order to attack the new
3453 // document's privileged information.
3454 // 2. A document loaded and used watchpoints on its own window, leaving
3455 // them set until the next document loads. We must clean up window
3456 // watchpoints here.
3457 // Watchpoints set on document and subordinate objects are all cleared
3458 // when those sub-window objects are finalized, after JS_ClearScope and
3459 // a GC run that finds them to be garbage.
3460 ::JS_ClearWatchPointsForObject(mContext
, obj
);
3462 // Since the prototype chain is shared between inner and outer (and
3463 // stays with the inner), we don't clear things from the prototype
3464 // chain when we're clearing an outer window whose current inner we
3466 if (aClearFromProtoChain
) {
3467 nsWindowSH::InvalidateGlobalScopePolluter(mContext
, obj
);
3469 // Clear up obj's prototype chain, but not Object.prototype.
3470 for (JSObject
*o
= ::JS_GetPrototype(mContext
, obj
), *next
;
3471 o
&& (next
= ::JS_GetPrototype(mContext
, o
)); o
= next
)
3472 ::JS_ClearScope(mContext
, o
);
3482 nsJSContext::WillInitializeContext()
3484 mIsInitialized
= PR_FALSE
;
3488 nsJSContext::DidInitializeContext()
3490 mIsInitialized
= PR_TRUE
;
3494 nsJSContext::IsContextInitialized()
3496 return mIsInitialized
;
3500 nsJSContext::FinalizeContext()
3508 FireGCTimer(PR_FALSE
);
3512 nsJSContext::ScriptEvaluated(PRBool aTerminated
)
3514 if (aTerminated
&& mTerminations
) {
3515 // Make sure to null out mTerminations before doing anything that
3516 // might cause new termination funcs to be added!
3517 nsJSContext::TerminationFuncClosure
* start
= mTerminations
;
3518 mTerminations
= nsnull
;
3520 for (nsJSContext::TerminationFuncClosure
* cur
= start
;
3523 (*(cur
->mTerminationFunc
))(cur
->mTerminationFuncArg
);
3531 if (mContext
->runtime
->gcZeal
>= 2) {
3535 if (mNumEvaluations
> 20) {
3536 mNumEvaluations
= 0;
3541 mOperationCallbackTime
= 0;
3542 mModalStateTime
= 0;
3547 nsJSContext::SetTerminationFunction(nsScriptTerminationFunc aFunc
,
3550 NS_PRECONDITION(JS_IsRunning(mContext
), "should be executing script");
3552 nsJSContext::TerminationFuncClosure
* newClosure
=
3553 new nsJSContext::TerminationFuncClosure(aFunc
, aRef
, mTerminations
);
3555 return NS_ERROR_OUT_OF_MEMORY
;
3558 mTerminations
= newClosure
;
3563 nsJSContext::GetScriptsEnabled()
3565 return mScriptsEnabled
;
3569 nsJSContext::SetScriptsEnabled(PRBool aEnabled
, PRBool aFireTimeouts
)
3571 // eeek - this seems the wrong way around - the global should callback
3572 // into each context, so every language is disabled.
3573 mScriptsEnabled
= aEnabled
;
3575 nsIScriptGlobalObject
*global
= GetGlobalObject();
3578 global
->SetScriptsEnabled(aEnabled
, aFireTimeouts
);
3584 nsJSContext::GetProcessingScriptTag()
3586 return mProcessingScriptTag
;
3590 nsJSContext::SetProcessingScriptTag(PRBool aFlag
)
3592 mProcessingScriptTag
= aFlag
;
3596 nsJSContext::GetExecutingScript()
3598 return JS_IsRunning(mContext
) || mExecuteDepth
> 0;
3602 nsJSContext::SetGCOnDestruction(PRBool aGCOnDestruction
)
3604 mGCOnDestruction
= aGCOnDestruction
;
3608 nsJSContext::ScriptExecuted()
3610 ScriptEvaluated(!::JS_IsRunning(mContext
));
3617 nsJSContext::CC(nsICycleCollectorListener
*aListener
)
3619 NS_TIME_FUNCTION_MIN(1.0);
3623 printf("Will run cycle collector (%i), %lldms since previous.\n",
3624 sCCollectCount
, (PR_Now() - sPreviousCCTime
) / PR_USEC_PER_MSEC
);
3626 sPreviousCCTime
= PR_Now();
3627 sDelayedCCollectCount
= 0;
3628 sCCSuspectChanges
= 0;
3629 // nsCycleCollector_collect() no longer forces a JS garbage collection,
3630 // so we have to do it ourselves here.
3631 nsContentUtils::XPConnect()->GarbageCollect();
3632 sCollectedObjectsCounts
= nsCycleCollector_collect(aListener
);
3633 sCCSuspectedCount
= nsCycleCollector_suspectedCount();
3634 sSavedGCCount
= JS_GetGCParameter(nsJSRuntime::sRuntime
, JSGC_NUMBER
);
3636 printf("Collected %u objects, %u suspected objects, took %lldms\n",
3637 sCollectedObjectsCounts
, sCCSuspectedCount
,
3638 (PR_Now() - sPreviousCCTime
) / PR_USEC_PER_MSEC
);
3642 static inline uint32
3643 GetGCRunsSinceLastCC()
3645 // To avoid crash if nsJSRuntime is not properly initialized.
3646 // See the bug 474586
3647 if (!nsJSRuntime::sRuntime
)
3650 // Since JS_GetGCParameter() and sSavedGCCount are unsigned, the following
3651 // gives the correct result even when the GC counter wraps around
3652 // UINT32_MAX since the last call to JS_GetGCParameter().
3653 return JS_GetGCParameter(nsJSRuntime::sRuntime
, JSGC_NUMBER
) -
3659 nsJSContext::MaybeCC(PRBool aHigherProbability
)
3661 ++sDelayedCCollectCount
;
3663 // Don't check suspected count if CC will be called anyway.
3664 if (sCCSuspectChanges
<= NS_MIN_SUSPECT_CHANGES
||
3665 GetGCRunsSinceLastCC() <= NS_MAX_GC_COUNT
) {
3667 PRTime now
= PR_Now();
3669 PRUint32 suspected
= nsCycleCollector_suspectedCount();
3671 printf("%u suspected objects (%lldms), sCCSuspectedCount %u\n",
3672 suspected
, (PR_Now() - now
) / PR_USEC_PER_MSEC
,
3675 // Update only when suspected count has increased.
3676 if (suspected
> sCCSuspectedCount
) {
3677 sCCSuspectChanges
+= (suspected
- sCCSuspectedCount
);
3678 sCCSuspectedCount
= suspected
;
3682 printf("sCCSuspectChanges %u, GC runs %u\n",
3683 sCCSuspectChanges
, GetGCRunsSinceLastCC());
3686 // Increase the probability also if the previous call to cycle collector
3687 // collected something.
3688 if (aHigherProbability
||
3689 sCollectedObjectsCounts
> NS_COLLECTED_OBJECTS_LIMIT
) {
3690 sDelayedCCollectCount
*= NS_PROBABILITY_MULTIPLIER
;
3694 (sDelayedCCollectCount
> NS_MAX_DELAYED_CCOLLECT
) &&
3695 ((sCCSuspectChanges
> NS_MIN_SUSPECT_CHANGES
&&
3696 GetGCRunsSinceLastCC() > NS_MAX_GC_COUNT
) ||
3697 (sCCSuspectChanges
> NS_MAX_SUSPECT_CHANGES
))) {
3698 return IntervalCC();
3705 nsJSContext::CCIfUserInactive()
3707 if (sUserIsActive
) {
3716 nsJSContext::IntervalCC()
3718 if ((PR_Now() - sPreviousCCTime
) >=
3719 PRTime(NS_MIN_CC_INTERVAL
* PR_USEC_PER_MSEC
)) {
3720 nsJSContext::CC(nsnull
);
3724 printf("Running CC was delayed because of NS_MIN_CC_INTERVAL.\n");
3731 GCTimerFired(nsITimer
*aTimer
, void *aClosure
)
3733 NS_RELEASE(sGCTimer
);
3735 if (sPendingLoadCount
== 0 || sLoadInProgressGCTimer
) {
3736 sLoadInProgressGCTimer
= PR_FALSE
;
3738 // Reset sPendingLoadCount in case the timer that fired was a
3739 // timer we scheduled due to a normal GC timer firing while
3740 // documents were loading. If this happens we're waiting for a
3741 // document that is taking a long time to load, and we effectively
3742 // ignore the fact that the currently loading documents are still
3743 // loading and move on as if they weren't.
3744 sPendingLoadCount
= 0;
3746 nsJSContext::CCIfUserInactive();
3748 nsJSContext::FireGCTimer(PR_TRUE
);
3751 sReadyForGC
= PR_TRUE
;
3756 nsJSContext::LoadStart()
3758 ++sPendingLoadCount
;
3763 nsJSContext::LoadEnd()
3765 // sPendingLoadCount is not a well managed load counter (and doesn't
3766 // need to be), so make sure we don't make it wrap backwards here.
3767 if (sPendingLoadCount
> 0) {
3768 --sPendingLoadCount
;
3771 if (!sPendingLoadCount
&& sLoadInProgressGCTimer
) {
3773 NS_RELEASE(sGCTimer
);
3774 sLoadInProgressGCTimer
= PR_FALSE
;
3782 nsJSContext::FireGCTimer(PRBool aLoadInProgress
)
3785 // There's already a timer for GC'ing, just return
3789 CallCreateInstance("@mozilla.org/timer;1", &sGCTimer
);
3792 NS_WARNING("Failed to create timer");
3794 // Reset sLoadInProgressGCTimer since we're not able to fire the
3796 sLoadInProgressGCTimer
= PR_FALSE
;
3802 static PRBool first
= PR_TRUE
;
3804 sGCTimer
->InitWithFuncCallback(GCTimerFired
, nsnull
,
3805 first
? NS_FIRST_GC_DELAY
:
3806 aLoadInProgress
? NS_LOAD_IN_PROCESS_GC_DELAY
:
3808 nsITimer::TYPE_ONE_SHOT
);
3810 sLoadInProgressGCTimer
= aLoadInProgress
;
3816 DOMGCCallback(JSContext
*cx
, JSGCStatus status
)
3818 JSBool result
= gOldJSGCCallback
? gOldJSGCCallback(cx
, status
) : JS_TRUE
;
3820 if (status
== JSGC_BEGIN
&& !NS_IsMainThread())
3826 // Script object mananagement - note duplicate implementation
3827 // in nsJSRuntime below...
3829 nsJSContext::HoldScriptObject(void* aScriptObject
)
3831 NS_ASSERTION(sIsInitialized
, "runtime not initialized");
3832 if (! nsJSRuntime::sRuntime
) {
3833 NS_NOTREACHED("couldn't add GC root - no runtime");
3834 return NS_ERROR_FAILURE
;
3837 ::JS_LockGCThingRT(nsJSRuntime::sRuntime
, aScriptObject
);
3842 nsJSContext::DropScriptObject(void* aScriptObject
)
3844 NS_ASSERTION(sIsInitialized
, "runtime not initialized");
3845 if (! nsJSRuntime::sRuntime
) {
3846 NS_NOTREACHED("couldn't remove GC root");
3847 return NS_ERROR_FAILURE
;
3850 ::JS_UnlockGCThingRT(nsJSRuntime::sRuntime
, aScriptObject
);
3855 nsJSContext::ReportPendingException()
3857 // set aside the frame chain, since it has nothing to do with the
3858 // exception we're reporting.
3859 if (mIsInitialized
&& ::JS_IsExceptionPending(mContext
)) {
3860 JSStackFrame
* frame
= JS_SaveFrameChain(mContext
);
3861 ::JS_ReportPendingException(mContext
);
3862 JS_RestoreFrameChain(mContext
, frame
);
3866 /**********************************************************************
3867 * nsJSRuntime implementation
3868 *********************************************************************/
3870 // QueryInterface implementation for nsJSRuntime
3871 NS_INTERFACE_MAP_BEGIN(nsJSRuntime
)
3872 NS_INTERFACE_MAP_ENTRY(nsIScriptRuntime
)
3873 NS_INTERFACE_MAP_END
3876 NS_IMPL_ADDREF(nsJSRuntime
)
3877 NS_IMPL_RELEASE(nsJSRuntime
)
3880 nsJSRuntime::CreateContext(nsIScriptContext
**aContext
)
3882 nsCOMPtr
<nsIScriptContext
> scriptContext
;
3884 *aContext
= new nsJSContext(sRuntime
);
3885 NS_ENSURE_TRUE(*aContext
, NS_ERROR_OUT_OF_MEMORY
);
3886 NS_ADDREF(*aContext
);
3891 nsJSRuntime::ParseVersion(const nsString
&aVersionStr
, PRUint32
*flags
)
3893 NS_PRECONDITION(flags
, "Null flags param?");
3894 JSVersion jsVersion
= JSVERSION_UNKNOWN
;
3895 if (aVersionStr
.Length() != 3 || aVersionStr
[0] != '1' || aVersionStr
[1] != '.')
3896 jsVersion
= JSVERSION_UNKNOWN
;
3897 else switch (aVersionStr
[2]) {
3898 case '0': jsVersion
= JSVERSION_1_0
; break;
3899 case '1': jsVersion
= JSVERSION_1_1
; break;
3900 case '2': jsVersion
= JSVERSION_1_2
; break;
3901 case '3': jsVersion
= JSVERSION_1_3
; break;
3902 case '4': jsVersion
= JSVERSION_1_4
; break;
3903 case '5': jsVersion
= JSVERSION_1_5
; break;
3904 case '6': jsVersion
= JSVERSION_1_6
; break;
3905 case '7': jsVersion
= JSVERSION_1_7
; break;
3906 case '8': jsVersion
= JSVERSION_1_8
; break;
3907 default: jsVersion
= JSVERSION_UNKNOWN
;
3909 *flags
= (PRUint32
)jsVersion
;
3915 nsJSRuntime::Startup()
3917 // initialize all our statics, so that we can restart XPCOM
3918 sDelayedCCollectCount
= 0;
3920 sUserIsActive
= PR_FALSE
;
3921 sPreviousCCTime
= 0;
3922 sCollectedObjectsCounts
= 0;
3924 sCCSuspectChanges
= 0;
3925 sCCSuspectedCount
= 0;
3927 sReadyForGC
= PR_FALSE
;
3928 sLoadInProgressGCTimer
= PR_FALSE
;
3929 sPendingLoadCount
= 0;
3930 gNameSpaceManager
= nsnull
;
3931 sRuntimeService
= nsnull
;
3933 gOldJSGCCallback
= nsnull
;
3934 sIsInitialized
= PR_FALSE
;
3935 sDidShutdown
= PR_FALSE
;
3937 sSecurityManager
= nsnull
;
3938 gCollation
= nsnull
;
3942 MaxScriptRunTimePrefChangedCallback(const char *aPrefName
, void *aClosure
)
3944 // Default limit on script run time to 10 seconds. 0 means let
3945 // scripts run forever.
3946 PRBool isChromePref
=
3947 strcmp(aPrefName
, "dom.max_chrome_script_run_time") == 0;
3948 PRInt32 time
= nsContentUtils::GetIntPref(aPrefName
, isChromePref
? 20 : 10);
3952 // Let scripts run for a really, really long time.
3953 t
= LL_INIT(0x40000000, 0);
3955 t
= time
* PR_USEC_PER_SEC
;
3959 sMaxChromeScriptRunTime
= t
;
3961 sMaxScriptRunTime
= t
;
3968 ReportAllJSExceptionsPrefChangedCallback(const char* aPrefName
, void* aClosure
)
3970 PRBool reportAll
= nsContentUtils::GetBoolPref(aPrefName
, PR_FALSE
);
3971 nsContentUtils::XPConnect()->SetReportAllJSExceptions(reportAll
);
3976 SetMemoryHighWaterMarkPrefChangedCallback(const char* aPrefName
, void* aClosure
)
3978 PRInt32 highwatermark
= nsContentUtils::GetIntPref(aPrefName
, 32);
3980 if (highwatermark
>= 32) {
3982 * There are two ways to allocate memory in SpiderMonkey. One is
3983 * to use jsmalloc() and the other is to use GC-owned memory
3984 * (e.g. js_NewGCThing()).
3986 * In the browser, we don't cap the amount of GC-owned memory.
3988 JS_SetGCParameter(nsJSRuntime::sRuntime
, JSGC_MAX_MALLOC_BYTES
,
3989 64L * 1024L * 1024L);
3990 JS_SetGCParameter(nsJSRuntime::sRuntime
, JSGC_MAX_BYTES
,
3993 JS_SetGCParameter(nsJSRuntime::sRuntime
, JSGC_MAX_MALLOC_BYTES
,
3994 highwatermark
* 1024L * 1024L);
3995 JS_SetGCParameter(nsJSRuntime::sRuntime
, JSGC_MAX_BYTES
,
3996 highwatermark
* 1024L * 1024L);
4002 SetMemoryGCFrequencyPrefChangedCallback(const char* aPrefName
, void* aClosure
)
4004 PRInt32 triggerFactor
= nsContentUtils::GetIntPref(aPrefName
, 300);
4005 JS_SetGCParameter(nsJSRuntime::sRuntime
, JSGC_TRIGGER_FACTOR
, triggerFactor
);
4009 static JSPrincipals
*
4010 ObjectPrincipalFinder(JSContext
*cx
, JSObject
*obj
)
4012 if (!sSecurityManager
)
4015 nsCOMPtr
<nsIPrincipal
> principal
;
4017 sSecurityManager
->GetObjectPrincipal(cx
, obj
,
4018 getter_AddRefs(principal
));
4020 if (NS_FAILED(rv
) || !principal
) {
4024 JSPrincipals
*jsPrincipals
= nsnull
;
4025 principal
->GetJSPrincipals(cx
, &jsPrincipals
);
4027 // nsIPrincipal::GetJSPrincipals() returns a strong reference to the
4028 // JS principals, but the caller of this function expects a weak
4029 // reference. So we need to release here.
4031 JSPRINCIPALS_DROP(cx
, jsPrincipals
);
4033 return jsPrincipals
;
4037 DOMReadStructuredClone(JSContext
* cx
,
4038 JSStructuredCloneReader
* reader
,
4042 // We don't currently support any extensions to structured cloning.
4043 nsDOMClassInfo::ThrowJSException(cx
, NS_ERROR_DOM_DATA_CLONE_ERR
);
4048 DOMWriteStructuredClone(JSContext
* cx
,
4049 JSStructuredCloneWriter
* writer
,
4052 // We don't currently support any extensions to structured cloning.
4053 nsDOMClassInfo::ThrowJSException(cx
, NS_ERROR_DOM_DATA_CLONE_ERR
);
4058 DOMStructuredCloneError(JSContext
* cx
,
4061 // We don't currently support any extensions to structured cloning.
4062 nsDOMClassInfo::ThrowJSException(cx
, NS_ERROR_DOM_DATA_CLONE_ERR
);
4069 if (sIsInitialized
) {
4070 if (!nsContentUtils::XPConnect())
4071 return NS_ERROR_NOT_AVAILABLE
;
4076 nsresult rv
= CallGetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID
,
4078 NS_ENSURE_SUCCESS(rv
, rv
);
4080 rv
= CallGetService(kJSRuntimeServiceContractID
, &sRuntimeService
);
4081 // get the JSRuntime from the runtime svc, if possible
4082 NS_ENSURE_SUCCESS(rv
, rv
);
4084 rv
= sRuntimeService
->GetRuntime(&sRuntime
);
4085 NS_ENSURE_SUCCESS(rv
, rv
);
4087 // Let's make sure that our main thread is the same as the xpcom main thread.
4088 NS_ASSERTION(NS_IsMainThread(), "bad");
4090 NS_ASSERTION(!gOldJSGCCallback
,
4091 "nsJSRuntime initialized more than once");
4093 sSavedGCCount
= JS_GetGCParameter(nsJSRuntime::sRuntime
, JSGC_NUMBER
);
4095 // Save the old GC callback to chain to it, for GC-observing generality.
4096 gOldJSGCCallback
= ::JS_SetGCCallbackRT(sRuntime
, DOMGCCallback
);
4098 JSSecurityCallbacks
*callbacks
= JS_GetRuntimeSecurityCallbacks(sRuntime
);
4099 NS_ASSERTION(callbacks
, "SecMan should have set security callbacks!");
4101 callbacks
->findObjectPrincipals
= ObjectPrincipalFinder
;
4103 // Set up the structured clone callbacks.
4104 static JSStructuredCloneCallbacks cloneCallbacks
= {
4105 DOMReadStructuredClone
,
4106 DOMWriteStructuredClone
,
4107 DOMStructuredCloneError
4109 JS_SetStructuredCloneCallbacks(sRuntime
, &cloneCallbacks
);
4111 // Set these global xpconnect options...
4112 nsContentUtils::RegisterPrefCallback("dom.max_script_run_time",
4113 MaxScriptRunTimePrefChangedCallback
,
4115 MaxScriptRunTimePrefChangedCallback("dom.max_script_run_time", nsnull
);
4117 nsContentUtils::RegisterPrefCallback("dom.max_chrome_script_run_time",
4118 MaxScriptRunTimePrefChangedCallback
,
4120 MaxScriptRunTimePrefChangedCallback("dom.max_chrome_script_run_time",
4123 nsContentUtils::RegisterPrefCallback("dom.report_all_js_exceptions",
4124 ReportAllJSExceptionsPrefChangedCallback
,
4126 ReportAllJSExceptionsPrefChangedCallback("dom.report_all_js_exceptions",
4129 nsContentUtils::RegisterPrefCallback("javascript.options.mem.high_water_mark",
4130 SetMemoryHighWaterMarkPrefChangedCallback
,
4132 SetMemoryHighWaterMarkPrefChangedCallback("javascript.options.mem.high_water_mark",
4135 nsContentUtils::RegisterPrefCallback("javascript.options.mem.gc_frequency",
4136 SetMemoryGCFrequencyPrefChangedCallback
,
4138 SetMemoryGCFrequencyPrefChangedCallback("javascript.options.mem.gc_frequency",
4141 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
4143 return NS_ERROR_FAILURE
;
4144 nsIObserver
* activityObserver
= new nsUserActivityObserver();
4145 NS_ENSURE_TRUE(activityObserver
, NS_ERROR_OUT_OF_MEMORY
);
4146 obs
->AddObserver(activityObserver
, "user-interaction-inactive", PR_FALSE
);
4147 obs
->AddObserver(activityObserver
, "user-interaction-active", PR_FALSE
);
4148 obs
->AddObserver(activityObserver
, "xpcom-shutdown", PR_FALSE
);
4150 nsIObserver
* ccMemPressureObserver
= new nsCCMemoryPressureObserver();
4151 NS_ENSURE_TRUE(ccMemPressureObserver
, NS_ERROR_OUT_OF_MEMORY
);
4152 obs
->AddObserver(ccMemPressureObserver
, "memory-pressure", PR_FALSE
);
4154 sIsInitialized
= PR_TRUE
;
4160 nsScriptNameSpaceManager
*
4161 nsJSRuntime::GetNameSpaceManager()
4166 if (!gNameSpaceManager
) {
4167 gNameSpaceManager
= new nsScriptNameSpaceManager
;
4168 NS_ENSURE_TRUE(gNameSpaceManager
, nsnull
);
4170 nsresult rv
= gNameSpaceManager
->Init();
4171 NS_ENSURE_SUCCESS(rv
, nsnull
);
4174 return gNameSpaceManager
;
4179 nsJSRuntime::Shutdown()
4182 // We're being shut down, if we have a GC timer scheduled, cancel
4183 // it. The DOM factory will do one final GC once it's shut down.
4187 NS_RELEASE(sGCTimer
);
4189 sLoadInProgressGCTimer
= PR_FALSE
;
4192 delete gNameSpaceManager
;
4193 gNameSpaceManager
= nsnull
;
4195 if (!sContextCount
) {
4196 // We're being shutdown, and there are no more contexts
4197 // alive, release the JS runtime service and the security manager.
4199 if (sRuntimeService
&& sSecurityManager
) {
4200 JSSecurityCallbacks
*callbacks
= JS_GetRuntimeSecurityCallbacks(sRuntime
);
4202 NS_ASSERTION(callbacks
->findObjectPrincipals
== ObjectPrincipalFinder
,
4203 "Fighting over the findObjectPrincipals callback!");
4204 callbacks
->findObjectPrincipals
= NULL
;
4207 NS_IF_RELEASE(sRuntimeService
);
4208 NS_IF_RELEASE(sSecurityManager
);
4209 NS_IF_RELEASE(gCollation
);
4210 NS_IF_RELEASE(gDecoder
);
4213 sDidShutdown
= PR_TRUE
;
4216 // Script object mananagement - note duplicate implementation
4217 // in nsJSContext above...
4219 nsJSRuntime::HoldScriptObject(void* aScriptObject
)
4221 NS_ASSERTION(sIsInitialized
, "runtime not initialized");
4223 NS_NOTREACHED("couldn't remove GC root - no runtime");
4224 return NS_ERROR_FAILURE
;
4227 ::JS_LockGCThingRT(sRuntime
, aScriptObject
);
4232 nsJSRuntime::DropScriptObject(void* aScriptObject
)
4234 NS_ASSERTION(sIsInitialized
, "runtime not initialized");
4236 NS_NOTREACHED("couldn't remove GC root");
4237 return NS_ERROR_FAILURE
;
4240 ::JS_UnlockGCThingRT(sRuntime
, aScriptObject
);
4244 // A factory for the runtime.
4245 nsresult
NS_CreateJSRuntime(nsIScriptRuntime
**aRuntime
)
4247 nsresult rv
= nsJSRuntime::Init();
4248 NS_ENSURE_SUCCESS(rv
, rv
);
4250 *aRuntime
= new nsJSRuntime();
4251 if (*aRuntime
== nsnull
)
4252 return NS_ERROR_OUT_OF_MEMORY
;
4253 NS_IF_ADDREF(*aRuntime
);
4257 // A fast-array class for JS. This class supports both nsIJSScriptArray and
4258 // nsIArray. If it is JS itself providing and consuming this class, all work
4259 // can be done via nsIJSScriptArray, and avoid the conversion of elements
4260 // to/from nsISupports.
4261 // When consumed by non-JS (eg, another script language), conversion is done
4263 class nsJSArgArray
: public nsIJSArgArray
, public nsIArray
{
4265 nsJSArgArray(JSContext
*aContext
, PRUint32 argc
, jsval
*argv
, nsresult
*prv
);
4268 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
4269 NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(nsJSArgArray
,
4276 nsresult
GetArgs(PRUint32
*argc
, void **argv
);
4278 void ReleaseJSObjects();
4281 JSContext
*mContext
;
4286 nsJSArgArray::nsJSArgArray(JSContext
*aContext
, PRUint32 argc
, jsval
*argv
,
4292 // copy the array - we don't know its lifetime, and ours is tied to xpcom
4293 // refcounting. Alloc zero'd array so cleanup etc is safe.
4295 mArgv
= (jsval
*) PR_CALLOC(argc
* sizeof(jsval
));
4297 *prv
= NS_ERROR_OUT_OF_MEMORY
;
4302 // Callers are allowed to pass in a null argv even for argc > 0. They can
4303 // then use GetArgs to initialize the values.
4305 for (PRUint32 i
= 0; i
< argc
; ++i
)
4309 *prv
= argc
> 0 ? NS_HOLD_JS_OBJECTS(this, nsJSArgArray
) : NS_OK
;
4312 nsJSArgArray::~nsJSArgArray()
4318 nsJSArgArray::ReleaseJSObjects()
4321 NS_DROP_JS_OBJECTS(this, nsJSArgArray
);
4328 // QueryInterface implementation for nsJSArgArray
4329 NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSArgArray
)
4330 NS_IMPL_CYCLE_COLLECTION_ROOT_BEGIN(nsJSArgArray
)
4331 tmp
->ReleaseJSObjects();
4332 NS_IMPL_CYCLE_COLLECTION_ROOT_END
4333 NS_IMPL_CYCLE_COLLECTION_UNLINK_0(nsJSArgArray
)
4334 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsJSArgArray
)
4335 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
4336 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
4338 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsJSArgArray
)
4339 jsval
*argv
= tmp
->mArgv
;
4342 for (end
= argv
+ tmp
->mArgc
; argv
< end
; ++argv
) {
4343 if (JSVAL_IS_GCTHING(*argv
))
4344 NS_IMPL_CYCLE_COLLECTION_TRACE_CALLBACK(JAVASCRIPT
,
4345 JSVAL_TO_GCTHING(*argv
))
4348 NS_IMPL_CYCLE_COLLECTION_TRACE_END
4350 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsJSArgArray
)
4351 NS_INTERFACE_MAP_ENTRY(nsIArray
)
4352 NS_INTERFACE_MAP_ENTRY(nsIJSArgArray
)
4353 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports
, nsIJSArgArray
)
4354 NS_INTERFACE_MAP_END
4356 NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsJSArgArray
, nsIJSArgArray
)
4357 NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsJSArgArray
, nsIJSArgArray
)
4360 nsJSArgArray::GetArgs(PRUint32
*argc
, void **argv
)
4363 NS_WARNING("nsJSArgArray has no argv!");
4364 return NS_ERROR_UNEXPECTED
;
4366 *argv
= (void *)mArgv
;
4372 NS_IMETHODIMP
nsJSArgArray::GetLength(PRUint32
*aLength
)
4378 /* void queryElementAt (in unsigned long index, in nsIIDRef uuid, [iid_is (uuid), retval] out nsQIResult result); */
4379 NS_IMETHODIMP
nsJSArgArray::QueryElementAt(PRUint32 index
, const nsIID
& uuid
, void * *result
)
4383 return NS_ERROR_INVALID_ARG
;
4385 if (uuid
.Equals(NS_GET_IID(nsIVariant
)) || uuid
.Equals(NS_GET_IID(nsISupports
))) {
4386 return nsContentUtils::XPConnect()->JSToVariant(mContext
, mArgv
[index
],
4387 (nsIVariant
**)result
);
4389 NS_WARNING("nsJSArgArray only handles nsIVariant");
4390 return NS_ERROR_NO_INTERFACE
;
4393 /* unsigned long indexOf (in unsigned long startIndex, in nsISupports element); */
4394 NS_IMETHODIMP
nsJSArgArray::IndexOf(PRUint32 startIndex
, nsISupports
*element
, PRUint32
*_retval
)
4396 return NS_ERROR_NOT_IMPLEMENTED
;
4399 /* nsISimpleEnumerator enumerate (); */
4400 NS_IMETHODIMP
nsJSArgArray::Enumerate(nsISimpleEnumerator
**_retval
)
4402 return NS_ERROR_NOT_IMPLEMENTED
;
4405 // The factory function
4406 nsresult
NS_CreateJSArgv(JSContext
*aContext
, PRUint32 argc
, void *argv
,
4410 nsJSArgArray
*ret
= new nsJSArgArray(aContext
, argc
,
4411 static_cast<jsval
*>(argv
), &rv
);
4413 return NS_ERROR_OUT_OF_MEMORY
;
4414 if (NS_FAILED(rv
)) {
4418 return ret
->QueryInterface(NS_GET_IID(nsIArray
), (void **)aArray
);