From: Blake Kaplan <mrbkap@gmail.com>
Date: Fri, 28 Oct 2011 13:47:46 -0700
Subject: Fix bug 653926. r=jst a=LegNeato

---
 js/src/xpconnect/loader/Makefile.in              |    2 ++
 js/src/xpconnect/loader/mozJSSubScriptLoader.cpp |   21 +++++++++++++++++++--
 2 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/js/src/xpconnect/loader/Makefile.in b/js/src/xpconnect/loader/Makefile.in
index 3b6837c..7358f16 100644
--- a/js/src/xpconnect/loader/Makefile.in
+++ b/js/src/xpconnect/loader/Makefile.in
@@ -52,8 +52,11 @@ REQUIRES	= xpcom \
 		  js \
 		  caps \
 		  necko \
+		  dom \
 		  $(NULL)
 
+LOCAL_INCLUDES	+= -I$(srcdir)/../src
+
 CPPSRCS		= mozJSComponentLoader.cpp mozJSSubScriptLoader.cpp
 
 EXTRA_JS_MODULES = XPCOMUtils.jsm ISO8601DateUtils.jsm
diff --git a/js/src/xpconnect/loader/mozJSSubScriptLoader.cpp b/js/src/xpconnect/loader/mozJSSubScriptLoader.cpp
index fb04c3c..37b00da 100644
--- a/js/src/xpconnect/loader/mozJSSubScriptLoader.cpp
+++ b/js/src/xpconnect/loader/mozJSSubScriptLoader.cpp
@@ -45,6 +45,7 @@
 
 #include "nsIServiceManager.h"
 #include "nsIXPConnect.h"
+#include "XPCWrapper.h"
 
 #include "nsIURI.h"
 #include "nsIIOService.h"
@@ -155,6 +156,11 @@ mozJSSubScriptLoader::LoadSubScript (const PRUnichar * /*url*/
         return NS_OK;
     }
 
+    nsCOMPtr<nsIPrincipal> principal = mSystemPrincipal;
+    JSObject *result_obj = target_obj;
+
+    target_obj = target_obj ? XPCWrapper::Unwrap(cx, target_obj) : nsnull;
+
     if (!target_obj)
     {
         /* if the user didn't provide an object to eval onto, find the global
@@ -190,7 +196,7 @@ mozJSSubScriptLoader::LoadSubScript (const PRUnichar * /*url*/
         }
 #ifdef DEBUG_rginda
         fprintf (stderr, "\n");
-#endif  
+#endif
     }
 
     // Innerize the target_obj so that we compile the loaded script in the
@@ -209,6 +215,17 @@ mozJSSubScriptLoader::LoadSubScript (const PRUnichar * /*url*/
         }
     }
 
+    if (result_obj &&
+        target_obj != JS_GetGlobalForObject(cx, result_obj)) {
+        nsCOMPtr<nsIScriptSecurityManager> secman =
+            do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
+        if (!secman)
+            return NS_ERROR_FAILURE;
+
+        rv = secman->GetObjectPrincipal(cx, target_obj, getter_AddRefs(principal));
+        NS_ENSURE_SUCCESS(rv, rv);
+    }
+
     /* load up the url.  From here on, failures are reflected as ``custom''
      * js exceptions */
     PRInt32   len = -1;
@@ -332,7 +349,7 @@ mozJSSubScriptLoader::LoadSubScript (const PRUnichar * /*url*/
     /* we can't hold onto jsPrincipals as a module var because the
      * JSPRINCIPALS_DROP macro takes a JSContext, which we won't have in the
      * destructor */
-    rv = mSystemPrincipal->GetJSPrincipals(cx, &jsPrincipals);
+    rv = principal->GetJSPrincipals(cx, &jsPrincipals);
     if (NS_FAILED(rv) || !jsPrincipals) {
         errmsg = JS_NewStringCopyZ (cx, LOAD_ERROR_NOPRINCIPALS);
         goto return_exception;
