LCOV - code coverage report
Current view: directory - js/xpconnect/src - XPCWrappedNative.cpp (source / functions) Found Hit Coverage
Test: app.info Lines: 1397 922 66.0 %
Date: 2012-04-21 Functions: 90 61 67.8 %

       1                 : /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
       2                 :  * vim: set ts=8 sw=4 et tw=78:
       3                 :  *
       4                 :  * ***** BEGIN LICENSE BLOCK *****
       5                 :  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
       6                 :  *
       7                 :  * The contents of this file are subject to the Mozilla Public License Version
       8                 :  * 1.1 (the "License"); you may not use this file except in compliance with
       9                 :  * the License. You may obtain a copy of the License at
      10                 :  * http://www.mozilla.org/MPL/
      11                 :  *
      12                 :  * Software distributed under the License is distributed on an "AS IS" basis,
      13                 :  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
      14                 :  * for the specific language governing rights and limitations under the
      15                 :  * License.
      16                 :  *
      17                 :  * The Original Code is Mozilla Communicator client code, released
      18                 :  * March 31, 1998.
      19                 :  *
      20                 :  * The Initial Developer of the Original Code is
      21                 :  * Netscape Communications Corporation.
      22                 :  * Portions created by the Initial Developer are Copyright (C) 1998
      23                 :  * the Initial Developer. All Rights Reserved.
      24                 :  *
      25                 :  * Contributor(s):
      26                 :  *   John Bandhauer <jband@netscape.com> (original author)
      27                 :  *
      28                 :  * Alternatively, the contents of this file may be used under the terms of
      29                 :  * either of the GNU General Public License Version 2 or later (the "GPL"),
      30                 :  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
      31                 :  * in which case the provisions of the GPL or the LGPL are applicable instead
      32                 :  * of those above. If you wish to allow use of your version of this file only
      33                 :  * under the terms of either the GPL or the LGPL, and not to allow others to
      34                 :  * use your version of this file under the terms of the MPL, indicate your
      35                 :  * decision by deleting the provisions above and replace them with the notice
      36                 :  * and other provisions required by the GPL or the LGPL. If you do not delete
      37                 :  * the provisions above, a recipient may use your version of this file under
      38                 :  * the terms of any one of the MPL, the GPL or the LGPL.
      39                 :  *
      40                 :  * ***** END LICENSE BLOCK ***** */
      41                 : 
      42                 : /* Wrapper object for reflecting native xpcom objects into JavaScript. */
      43                 : 
      44                 : #include "xpcprivate.h"
      45                 : #include "nsCRT.h"
      46                 : #include "XPCWrapper.h"
      47                 : #include "nsWrapperCacheInlines.h"
      48                 : #include "XPCLog.h"
      49                 : #include "nsINode.h"
      50                 : #include "XPCQuickStubs.h"
      51                 : #include "jsproxy.h"
      52                 : #include "AccessCheck.h"
      53                 : #include "WrapperFactory.h"
      54                 : #include "dombindings.h"
      55                 : 
      56                 : #include "nsContentUtils.h"
      57                 : 
      58                 : #include "mozilla/Util.h"
      59                 : 
      60                 : bool
      61           18459 : xpc_OkToHandOutWrapper(nsWrapperCache *cache)
      62                 : {
      63           18459 :     NS_ABORT_IF_FALSE(cache->GetWrapper(), "Must have wrapper");
      64           18459 :     NS_ABORT_IF_FALSE(cache->IsProxy() || IS_WN_WRAPPER(cache->GetWrapper()),
      65                 :                       "Must have proxy or XPCWrappedNative wrapper");
      66           18459 :     return cache->IsProxy() ?
      67            3093 :         mozilla::dom::binding::instanceIsProxy(cache->GetWrapper()) :
      68           15366 :         !static_cast<XPCWrappedNative*>(xpc_GetJSPrivate(cache->GetWrapper()))->
      69           36918 :             NeedsSOW();
      70                 : }
      71                 : 
      72                 : /***************************************************************************/
      73                 : 
      74            1396 : NS_IMPL_CYCLE_COLLECTION_CLASS(XPCWrappedNative)
      75                 : 
      76                 : NS_IMETHODIMP
      77             322 : NS_CYCLE_COLLECTION_CLASSNAME(XPCWrappedNative)::Unlink(void *p)
      78                 : {
      79             322 :     XPCWrappedNative *tmp = static_cast<XPCWrappedNative*>(p);
      80             322 :     tmp->ExpireWrapper();
      81             322 :     return NS_OK;
      82                 : }
      83                 : 
      84                 : struct TraverseExpandoObjectClosure
      85                 : {
      86                 :     XPCWrappedNative *wn;
      87                 :     nsCycleCollectionTraversalCallback &cb;
      88                 : };
      89                 : 
      90                 : static PLDHashOperator
      91               0 : TraverseExpandoObjects(xpc::PtrAndPrincipalHashKey *aKey, JSCompartment *compartment, void *aClosure)
      92                 : {
      93               0 :     TraverseExpandoObjectClosure *closure = static_cast<TraverseExpandoObjectClosure*>(aClosure);
      94                 :     xpc::CompartmentPrivate *priv =
      95               0 :         static_cast<xpc::CompartmentPrivate *>(JS_GetCompartmentPrivate(compartment));
      96                 : 
      97               0 :     NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(closure->cb, "XPCWrappedNative expando object");
      98                 :     closure->cb.NoteScriptChild(nsIProgrammingLanguage::JAVASCRIPT,
      99               0 :                                 priv->LookupExpandoObjectPreserveColor(closure->wn));
     100                 : 
     101               0 :     return PL_DHASH_NEXT;
     102                 : }
     103                 : 
     104                 : NS_IMETHODIMP
     105             365 : NS_CYCLE_COLLECTION_CLASSNAME(XPCWrappedNative)::Traverse(void *p,
     106                 :                                                           nsCycleCollectionTraversalCallback &cb)
     107                 : {
     108             365 :     XPCWrappedNative *tmp = static_cast<XPCWrappedNative*>(p);
     109             365 :     if (!tmp->IsValid())
     110               0 :         return NS_OK;
     111                 : 
     112             365 :     if (NS_UNLIKELY(cb.WantDebugInfo())) {
     113                 :         char name[72];
     114               0 :         XPCNativeScriptableInfo* si = tmp->GetScriptableInfo();
     115               0 :         if (si)
     116                 :             JS_snprintf(name, sizeof(name), "XPCWrappedNative (%s)",
     117               0 :                         si->GetJSClass()->name);
     118                 :         else
     119               0 :             JS_snprintf(name, sizeof(name), "XPCWrappedNative");
     120                 : 
     121                 :         cb.DescribeRefCountedNode(tmp->mRefCnt.get(),
     122               0 :                                   sizeof(XPCWrappedNative), name);
     123                 :     } else {
     124             365 :         NS_IMPL_CYCLE_COLLECTION_DESCRIBE(XPCWrappedNative, tmp->mRefCnt.get())
     125                 :     }
     126                 : 
     127             365 :     if (tmp->mRefCnt.get() > 1) {
     128                 : 
     129                 :         // If our refcount is > 1, our reference to the flat JS object is
     130                 :         // considered "strong", and we're going to traverse it.
     131                 :         //
     132                 :         // If our refcount is <= 1, our reference to the flat JS object is
     133                 :         // considered "weak", and we're *not* going to traverse it.
     134                 :         //
     135                 :         // This reasoning is in line with the slightly confusing lifecycle rules
     136                 :         // for XPCWrappedNatives, described in a larger comment below and also
     137                 :         // on our wiki at http://wiki.mozilla.org/XPConnect_object_wrapping
     138                 : 
     139               0 :         JSObject *obj = tmp->GetFlatJSObjectPreserveColor();
     140               0 :         NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mFlatJSObject");
     141               0 :         cb.NoteScriptChild(nsIProgrammingLanguage::JAVASCRIPT, obj);
     142                 :     }
     143                 : 
     144             365 :     if (tmp->MightHaveExpandoObject()) {
     145               0 :         XPCJSRuntime *rt = tmp->GetRuntime();
     146               0 :         TraverseExpandoObjectClosure closure = { tmp, cb };
     147               0 :         rt->GetCompartmentMap().EnumerateRead(TraverseExpandoObjects, &closure);
     148                 :     }
     149                 : 
     150                 :     // XPCWrappedNative keeps its native object alive.
     151             365 :     NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mIdentity");
     152             365 :     cb.NoteXPCOMChild(tmp->GetIdentityObject());
     153                 : 
     154             365 :     tmp->NoteTearoffs(cb);
     155                 : 
     156             365 :     return NS_OK;
     157                 : }
     158                 : 
     159                 : void
     160             365 : XPCWrappedNative::NoteTearoffs(nsCycleCollectionTraversalCallback& cb)
     161                 : {
     162                 :     // Tearoffs hold their native object alive. If their JS object hasn't been
     163                 :     // finalized yet we'll note the edge between the JS object and the native
     164                 :     // (see nsXPConnect::Traverse), but if their JS object has been finalized
     165                 :     // then the tearoff is only reachable through the XPCWrappedNative, so we
     166                 :     // record an edge here.
     167                 :     XPCWrappedNativeTearOffChunk* chunk;
     168             835 :     for (chunk = &mFirstChunk; chunk; chunk = chunk->mNextChunk) {
     169             470 :         XPCWrappedNativeTearOff* to = chunk->mTearOffs;
     170             940 :         for (int i = XPC_WRAPPED_NATIVE_TEAROFFS_PER_CHUNK-1; i >= 0; i--, to++) {
     171             470 :             JSObject* jso = to->GetJSObjectPreserveColor();
     172             470 :             if (!jso) {
     173             470 :                 NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "tearoff's mNative");
     174             470 :                 cb.NoteXPCOMChild(to->GetNative());
     175                 :             }
     176                 :         }
     177                 :     }
     178             365 : }
     179                 : 
     180                 : #ifdef XPC_CHECK_CLASSINFO_CLAIMS
     181                 : static void DEBUG_CheckClassInfoClaims(XPCWrappedNative* wrapper);
     182                 : #else
     183                 : #define DEBUG_CheckClassInfoClaims(wrapper) ((void)0)
     184                 : #endif
     185                 : 
     186                 : #ifdef XPC_TRACK_WRAPPER_STATS
     187                 : static int DEBUG_TotalWrappedNativeCount;
     188                 : static int DEBUG_TotalLiveWrappedNativeCount;
     189                 : static int DEBUG_TotalMaxWrappedNativeCount;
     190                 : static int DEBUG_WrappedNativeWithProtoCount;
     191                 : static int DEBUG_LiveWrappedNativeWithProtoCount;
     192                 : static int DEBUG_MaxWrappedNativeWithProtoCount;
     193                 : static int DEBUG_WrappedNativeNoProtoCount;
     194                 : static int DEBUG_LiveWrappedNativeNoProtoCount;
     195                 : static int DEBUG_MaxWrappedNativeNoProtoCount;
     196                 : static int DEBUG_WrappedNativeTotalCalls;
     197                 : static int DEBUG_WrappedNativeMethodCalls;
     198                 : static int DEBUG_WrappedNativeGetterCalls;
     199                 : static int DEBUG_WrappedNativeSetterCalls;
     200                 : #define DEBUG_CHUNKS_TO_COUNT 4
     201                 : static int DEBUG_WrappedNativeTearOffChunkCounts[DEBUG_CHUNKS_TO_COUNT+1];
     202                 : static bool    DEBUG_DumpedWrapperStats;
     203                 : #endif
     204                 : 
     205                 : #ifdef DEBUG
     206         1242037 : static void DEBUG_TrackNewWrapper(XPCWrappedNative* wrapper)
     207                 : {
     208                 : #ifdef XPC_CHECK_WRAPPERS_AT_SHUTDOWN
     209                 :     if (wrapper->GetRuntime())
     210                 :         wrapper->GetRuntime()->DEBUG_AddWrappedNative(wrapper);
     211                 :     else
     212                 :         NS_ERROR("failed to add wrapper");
     213                 : #endif
     214                 : #ifdef XPC_TRACK_WRAPPER_STATS
     215                 :     DEBUG_TotalWrappedNativeCount++;
     216                 :     DEBUG_TotalLiveWrappedNativeCount++;
     217                 :     if (DEBUG_TotalMaxWrappedNativeCount < DEBUG_TotalLiveWrappedNativeCount)
     218                 :         DEBUG_TotalMaxWrappedNativeCount = DEBUG_TotalLiveWrappedNativeCount;
     219                 : 
     220                 :     if (wrapper->HasProto()) {
     221                 :         DEBUG_WrappedNativeWithProtoCount++;
     222                 :         DEBUG_LiveWrappedNativeWithProtoCount++;
     223                 :         if (DEBUG_MaxWrappedNativeWithProtoCount < DEBUG_LiveWrappedNativeWithProtoCount)
     224                 :             DEBUG_MaxWrappedNativeWithProtoCount = DEBUG_LiveWrappedNativeWithProtoCount;
     225                 :     } else {
     226                 :         DEBUG_WrappedNativeNoProtoCount++;
     227                 :         DEBUG_LiveWrappedNativeNoProtoCount++;
     228                 :         if (DEBUG_MaxWrappedNativeNoProtoCount < DEBUG_LiveWrappedNativeNoProtoCount)
     229                 :             DEBUG_MaxWrappedNativeNoProtoCount = DEBUG_LiveWrappedNativeNoProtoCount;
     230                 :     }
     231                 : #endif
     232         1242037 : }
     233                 : 
     234         1241226 : static void DEBUG_TrackDeleteWrapper(XPCWrappedNative* wrapper)
     235                 : {
     236                 : #ifdef XPC_CHECK_WRAPPERS_AT_SHUTDOWN
     237                 :     nsXPConnect::GetRuntimeInstance()->DEBUG_RemoveWrappedNative(wrapper);
     238                 : #endif
     239                 : #ifdef XPC_TRACK_WRAPPER_STATS
     240                 :     DEBUG_TotalLiveWrappedNativeCount--;
     241                 :     if (wrapper->HasProto())
     242                 :         DEBUG_LiveWrappedNativeWithProtoCount--;
     243                 :     else
     244                 :         DEBUG_LiveWrappedNativeNoProtoCount--;
     245                 : 
     246                 :     int extraChunkCount = wrapper->DEBUG_CountOfTearoffChunks() - 1;
     247                 :     if (extraChunkCount > DEBUG_CHUNKS_TO_COUNT)
     248                 :         extraChunkCount = DEBUG_CHUNKS_TO_COUNT;
     249                 :     DEBUG_WrappedNativeTearOffChunkCounts[extraChunkCount]++;
     250                 : #endif
     251         1241226 : }
     252         7371823 : static void DEBUG_TrackWrapperCall(XPCWrappedNative* wrapper,
     253                 :                                    XPCWrappedNative::CallMode mode)
     254                 : {
     255                 : #ifdef XPC_TRACK_WRAPPER_STATS
     256                 :     DEBUG_WrappedNativeTotalCalls++;
     257                 :     switch (mode) {
     258                 :         case XPCWrappedNative::CALL_METHOD:
     259                 :             DEBUG_WrappedNativeMethodCalls++;
     260                 :             break;
     261                 :         case XPCWrappedNative::CALL_GETTER:
     262                 :             DEBUG_WrappedNativeGetterCalls++;
     263                 :             break;
     264                 :         case XPCWrappedNative::CALL_SETTER:
     265                 :             DEBUG_WrappedNativeSetterCalls++;
     266                 :             break;
     267                 :         default:
     268                 :             NS_ERROR("bad value");
     269                 :     }
     270                 : #endif
     271         7371823 : }
     272                 : 
     273             781 : static void DEBUG_TrackShutdownWrapper(XPCWrappedNative* wrapper)
     274                 : {
     275                 : #ifdef XPC_TRACK_WRAPPER_STATS
     276                 :     if (!DEBUG_DumpedWrapperStats) {
     277                 :         DEBUG_DumpedWrapperStats = true;
     278                 :         printf("%d WrappedNatives were constructed. "
     279                 :                "(%d w/ protos, %d w/o)\n",
     280                 :                DEBUG_TotalWrappedNativeCount,
     281                 :                DEBUG_WrappedNativeWithProtoCount,
     282                 :                DEBUG_WrappedNativeNoProtoCount);
     283                 : 
     284                 :         printf("%d WrappedNatives max alive at one time. "
     285                 :                "(%d w/ protos, %d w/o)\n",
     286                 :                DEBUG_TotalMaxWrappedNativeCount,
     287                 :                DEBUG_MaxWrappedNativeWithProtoCount,
     288                 :                DEBUG_MaxWrappedNativeNoProtoCount);
     289                 : 
     290                 :         printf("%d WrappedNatives alive now. "
     291                 :                "(%d w/ protos, %d w/o)\n",
     292                 :                DEBUG_TotalLiveWrappedNativeCount,
     293                 :                DEBUG_LiveWrappedNativeWithProtoCount,
     294                 :                DEBUG_LiveWrappedNativeNoProtoCount);
     295                 : 
     296                 :         printf("%d calls to WrappedNatives. "
     297                 :                "(%d methods, %d getters, %d setters)\n",
     298                 :                DEBUG_WrappedNativeTotalCalls,
     299                 :                DEBUG_WrappedNativeMethodCalls,
     300                 :                DEBUG_WrappedNativeGetterCalls,
     301                 :                DEBUG_WrappedNativeSetterCalls);
     302                 : 
     303                 :         printf("(wrappers / tearoffs): (");
     304                 :         int i;
     305                 :         for (i = 0; i < DEBUG_CHUNKS_TO_COUNT; i++) {
     306                 :             printf("%d / %d, ",
     307                 :                    DEBUG_WrappedNativeTearOffChunkCounts[i],
     308                 :                    (i+1) * XPC_WRAPPED_NATIVE_TEAROFFS_PER_CHUNK);
     309                 :         }
     310                 :         printf("%d / more)\n", DEBUG_WrappedNativeTearOffChunkCounts[i]);
     311                 :     }
     312                 : #endif
     313             781 : }
     314                 : #else
     315                 : #define DEBUG_TrackNewWrapper(wrapper) ((void)0)
     316                 : #define DEBUG_TrackDeleteWrapper(wrapper) ((void)0)
     317                 : #define DEBUG_TrackWrapperCall(wrapper, mode) ((void)0)
     318                 : #define DEBUG_TrackShutdownWrapper(wrapper) ((void)0)
     319                 : #endif
     320                 : 
     321                 : /***************************************************************************/
     322                 : static nsresult
     323                 : FinishCreate(XPCCallContext& ccx,
     324                 :              XPCWrappedNativeScope* Scope,
     325                 :              XPCNativeInterface* Interface,
     326                 :              nsWrapperCache *cache,
     327                 :              XPCWrappedNative* inWrapper,
     328                 :              XPCWrappedNative** resultWrapper);
     329                 : 
     330                 : // static
     331                 : //
     332                 : // This method handles the special case of wrapping a new global object.
     333                 : //
     334                 : // The normal code path for wrapping natives goes through
     335                 : // XPCConvert::NativeInterface2JSObject, XPCWrappedNative::GetNewOrUsed,
     336                 : // and finally into XPCWrappedNative::Init. Unfortunately, this path assumes
     337                 : // very early on that we have an XPCWrappedNativeScope and corresponding global
     338                 : // JS object, which are the very things we need to create here. So we special-
     339                 : // case the logic and do some things in a different order.
     340                 : nsresult
     341           13172 : XPCWrappedNative::WrapNewGlobal(XPCCallContext &ccx, xpcObjectHelper &nativeHelper,
     342                 :                                 nsIPrincipal *principal, bool initStandardClasses,
     343                 :                                 XPCWrappedNative **wrappedGlobal)
     344                 : {
     345                 :     bool success;
     346                 :     nsresult rv;
     347           13172 :     nsISupports *identity = nativeHelper.GetCanonical();
     348                 : 
     349                 :     // The object should specify that it's meant to be global.
     350           13172 :     MOZ_ASSERT(nativeHelper.GetScriptableFlags() & nsIXPCScriptable::IS_GLOBAL_OBJECT);
     351                 : 
     352                 :     // We shouldn't be reusing globals.
     353           13172 :     MOZ_ASSERT(!nativeHelper.GetWrapperCache() ||
     354           13172 :                !nativeHelper.GetWrapperCache()->GetWrapperPreserveColor());
     355                 : 
     356                 :     // Put together the ScriptableCreateInfo...
     357           26344 :     XPCNativeScriptableCreateInfo sciProto;
     358           26344 :     XPCNativeScriptableCreateInfo sciMaybe;
     359                 :     const XPCNativeScriptableCreateInfo& sciWrapper =
     360                 :         GatherScriptableCreateInfo(identity, nativeHelper.GetClassInfo(),
     361           13172 :                                    sciProto, sciMaybe);
     362                 : 
     363                 :     // ...and then ScriptableInfo. We need all this stuff now because it's going
     364                 :     // to tell us the JSClass of the object we're going to create.
     365           13172 :     XPCNativeScriptableInfo *si = XPCNativeScriptableInfo::Construct(ccx, &sciWrapper);
     366           13172 :     MOZ_ASSERT(si);
     367                 : 
     368                 :     // Finally, we get to the JSClass.
     369           13172 :     JSClass *clasp = si->GetJSClass();
     370           13172 :     MOZ_ASSERT(clasp->flags & JSCLASS_IS_GLOBAL);
     371                 : 
     372                 :     // Create the global.
     373                 :     JSObject *global;
     374                 :     JSCompartment *compartment;
     375                 :     rv = xpc_CreateGlobalObject(ccx, clasp, principal, nsnull, false,
     376           13172 :                                 &global, &compartment);
     377           13172 :     NS_ENSURE_SUCCESS(rv, rv);
     378                 : 
     379                 :     // Immediately enter the global's compartment, so that everything else we
     380                 :     // create ends up there.
     381           26344 :     JSAutoEnterCompartment ac;
     382           13172 :     success = ac.enter(ccx, global);
     383           13172 :     MOZ_ASSERT(success);
     384                 : 
     385                 :     // If requested, immediately initialize the standard classes on the global.
     386                 :     // We need to do this before creating a scope, because
     387                 :     // XPCWrappedNativeScope::SetGlobal resolves |Object| via
     388                 :     // JS_ResolveStandardClass. JS_InitStandardClasses asserts if any of the
     389                 :     // standard classes are already initialized, so this is a problem.
     390           13172 :     if (initStandardClasses && ! JS_InitStandardClasses(ccx, global))
     391               0 :         return NS_ERROR_FAILURE;
     392                 : 
     393                 :     // Create a scope, but don't do any extra stuff like initializing |Components|.
     394                 :     // All of that stuff happens in the caller.
     395           13172 :     XPCWrappedNativeScope *scope = XPCWrappedNativeScope::GetNewOrUsed(ccx, global, identity);
     396           13172 :     MOZ_ASSERT(scope);
     397                 : 
     398                 :     // Make a proto.
     399                 :     XPCWrappedNativeProto *proto =
     400                 :         XPCWrappedNativeProto::GetNewOrUsed(ccx, scope, nativeHelper.GetClassInfo(), &sciProto,
     401           13172 :                                             UNKNOWN_OFFSETS, /* callPostCreatePrototype = */ false);
     402           13172 :     if (!proto)
     403               0 :         return NS_ERROR_FAILURE;
     404           13172 :     proto->CacheOffsets(identity);
     405                 : 
     406                 :     // Set up the prototype on the global.
     407           13172 :     MOZ_ASSERT(proto->GetJSProtoObject());
     408           13172 :     success = JS_SplicePrototype(ccx, global, proto->GetJSProtoObject());
     409           13172 :     if (!success)
     410               0 :         return NS_ERROR_FAILURE;
     411                 : 
     412                 :     // Construct the wrapper.
     413           39516 :     nsRefPtr<XPCWrappedNative> wrapper = new XPCWrappedNative(identity, proto);
     414                 : 
     415                 :     // The wrapper takes over the strong reference to the native object.
     416           13172 :     nativeHelper.forgetCanonical();
     417                 : 
     418                 :     //
     419                 :     // We don't call ::Init() on this wrapper, because our setup requirements
     420                 :     // are different for globals. We do our setup inline here, instead.
     421                 :     //
     422                 : 
     423                 :     // Share mScriptableInfo with the proto.
     424                 :     //
     425                 :     // This is probably more trouble than it's worth, since we've already created
     426                 :     // an XPCNativeScriptableInfo for ourselves. Moreover, most of that class is
     427                 :     // shared internally via XPCNativeScriptableInfoShared, so the memory
     428                 :     // savings are negligible. Nevertheless, this is what ::Init() does, and we
     429                 :     // want to be as consistent as possible with that code.
     430           13172 :     XPCNativeScriptableInfo* siProto = proto->GetScriptableInfo();
     431           13172 :     if (siProto && siProto->GetCallback() == sciWrapper.GetCallback()) {
     432               0 :         wrapper->mScriptableInfo = siProto;
     433               0 :         delete si;
     434                 :     } else {
     435           13172 :         wrapper->mScriptableInfo = si;
     436                 :     }
     437                 : 
     438                 :     // Set the JS object to the global we already created.
     439           13172 :     wrapper->mFlatJSObject = global;
     440                 : 
     441                 :     // Set the private to the XPCWrappedNative.
     442           13172 :     JS_SetPrivate(global, wrapper);
     443                 : 
     444                 :     // There are dire comments elsewhere in the code about how a GC can
     445                 :     // happen somewhere after wrapper initialization but before the wrapper is
     446                 :     // added to the hashtable in FinishCreate(). It's not clear if that can
     447                 :     // happen here, but let's just be safe for now.
     448           26344 :     AutoMarkingWrappedNativePtr wrapperMarker(ccx, wrapper);
     449                 : 
     450                 :     // Call the common Init finish routine. This mainly just does an AddRef
     451                 :     // on behalf of XPConnect (the corresponding Release is in the finalizer
     452                 :     // hook), but it does some other miscellaneous things too, so we don't
     453                 :     // inline it.
     454           13172 :     success = wrapper->FinishInit(ccx);
     455           13172 :     MOZ_ASSERT(success);
     456                 : 
     457                 :     // Go through some extra work to find the tearoff. This is kind of silly
     458                 :     // on a conceptual level: the point of tearoffs is to cache the results
     459                 :     // of QI-ing mIdentity to different interfaces, and we don't need that
     460                 :     // since we're dealing with nsISupports. But lots of code expects tearoffs
     461                 :     // to exist for everything, so we just follow along.
     462           13172 :     XPCNativeInterface* iface = XPCNativeInterface::GetNewOrUsed(ccx, &NS_GET_IID(nsISupports));
     463           13172 :     MOZ_ASSERT(iface);
     464                 :     nsresult status;
     465           13172 :     success = wrapper->FindTearOff(ccx, iface, false, &status);
     466           13172 :     if (!success)
     467               0 :         return status;
     468                 : 
     469                 :     // Call the common creation finish routine. This does all of the bookkeeping
     470                 :     // like inserting the wrapper into the wrapper map and setting up the wrapper
     471                 :     // cache.
     472                 :     return FinishCreate(ccx, scope, iface, nativeHelper.GetWrapperCache(),
     473           13172 :                         wrapper, wrappedGlobal);
     474                 : }
     475                 : 
     476                 : // static
     477                 : nsresult
     478         2089352 : XPCWrappedNative::GetNewOrUsed(XPCCallContext& ccx,
     479                 :                                xpcObjectHelper& helper,
     480                 :                                XPCWrappedNativeScope* Scope,
     481                 :                                XPCNativeInterface* Interface,
     482                 :                                XPCWrappedNative** resultWrapper)
     483                 : {
     484         2089352 :     nsWrapperCache *cache = helper.GetWrapperCache();
     485                 : 
     486         2089352 :     NS_ASSERTION(!cache || !cache->GetWrapperPreserveColor(),
     487                 :                  "We assume the caller already checked if it could get the "
     488                 :                  "wrapper from the cache.");
     489                 : 
     490                 :     nsresult rv;
     491                 : 
     492         2089352 :     NS_ASSERTION(!Scope->GetRuntime()->GetThreadRunningGC(),
     493                 :                  "XPCWrappedNative::GetNewOrUsed called during GC");
     494                 : 
     495         2089352 :     nsISupports *identity = helper.GetCanonical();
     496                 : 
     497         2089352 :     if (!identity) {
     498               0 :         NS_ERROR("This XPCOM object fails in QueryInterface to nsISupports!");
     499               0 :         return NS_ERROR_FAILURE;
     500                 :     }
     501                 : 
     502         2089352 :     XPCLock* mapLock = Scope->GetRuntime()->GetMapLock();
     503                 : 
     504         4178704 :     nsRefPtr<XPCWrappedNative> wrapper;
     505                 : 
     506         2089352 :     Native2WrappedNativeMap* map = Scope->GetWrappedNativeMap();
     507         2089352 :     if (!cache) {
     508                 :         {   // scoped lock
     509         4168766 :             XPCAutoLock lock(mapLock);
     510         2084383 :             wrapper = map->Find(identity);
     511                 :         }
     512                 : 
     513         2084383 :         if (wrapper) {
     514         1731481 :             if (Interface &&
     515          864929 :                 !wrapper->FindTearOff(ccx, Interface, false, &rv)) {
     516               0 :                 NS_ASSERTION(NS_FAILED(rv), "returning NS_OK on failure");
     517               0 :                 return rv;
     518                 :             }
     519          866552 :             DEBUG_CheckWrapperThreadSafety(wrapper);
     520          866552 :             *resultWrapper = wrapper.forget().get();
     521          866552 :             return NS_OK;
     522                 :         }
     523                 :     }
     524                 : #ifdef DEBUG
     525            4969 :     else if (!cache->GetWrapperPreserveColor())
     526                 :     {   // scoped lock
     527            9938 :         XPCAutoLock lock(mapLock);
     528            4969 :         NS_ASSERTION(!map->Find(identity),
     529                 :                      "There's a wrapper in the hashtable but it wasn't cached?");
     530                 :     }
     531                 : #endif
     532                 : 
     533                 :     // There is a chance that the object wants to have the self-same JSObject
     534                 :     // reflection regardless of the scope into which we are reflecting it.
     535                 :     // Many DOM objects require this. The scriptable helper specifies this
     536                 :     // in preCreate by indicating a 'parent' of a particular scope.
     537                 :     //
     538                 :     // To handle this we need to get the scriptable helper early and ask it.
     539                 :     // It is possible that we will then end up forwarding this entire call
     540                 :     // to this same function but with a different scope.
     541                 : 
     542                 :     // If we are making a wrapper for the nsIClassInfo interface then
     543                 :     // We *don't* want to have it use the prototype meant for instances
     544                 :     // of that class.
     545                 :     JSBool isClassInfo = Interface &&
     546         1222800 :                          Interface->GetIID()->Equals(NS_GET_IID(nsIClassInfo));
     547                 : 
     548         1222800 :     nsIClassInfo *info = helper.GetClassInfo();
     549                 : 
     550         2445600 :     XPCNativeScriptableCreateInfo sciProto;
     551         2445600 :     XPCNativeScriptableCreateInfo sci;
     552                 : 
     553                 :     // Gather scriptable create info if we are wrapping something
     554                 :     // other than an nsIClassInfo object. We need to not do this for
     555                 :     // nsIClassInfo objects because often nsIClassInfo implementations
     556                 :     // are also nsIXPCScriptable helper implementations, but the helper
     557                 :     // code is obviously intended for the implementation of the class
     558                 :     // described by the nsIClassInfo, not for the class info object
     559                 :     // itself.
     560                 :     const XPCNativeScriptableCreateInfo& sciWrapper =
     561                 :         isClassInfo ? sci :
     562         1222800 :         GatherScriptableCreateInfo(identity, info, sciProto, sci);
     563                 : 
     564         1222800 :     JSObject* parent = Scope->GetGlobalJSObject();
     565                 : 
     566         1222800 :     jsval newParentVal = JSVAL_NULL;
     567         2445600 :     XPCMarkableJSVal newParentVal_markable(&newParentVal);
     568         2445600 :     AutoMarkingJSVal newParentVal_automarker(ccx, &newParentVal_markable);
     569         1222800 :     JSBool needsSOW = false;
     570         1222800 :     JSBool needsCOW = false;
     571                 : 
     572         2445600 :     JSAutoEnterCompartment ac;
     573                 : 
     574         1222800 :     if (sciWrapper.GetFlags().WantPreCreate()) {
     575           12398 :         JSObject* plannedParent = parent;
     576           12398 :         nsresult rv = sciWrapper.GetCallback()->PreCreate(identity, ccx,
     577           12398 :                                                           parent, &parent);
     578           12398 :         if (NS_FAILED(rv))
     579               0 :             return rv;
     580                 : 
     581           12398 :         if (rv == NS_SUCCESS_CHROME_ACCESS_ONLY)
     582               0 :             needsSOW = true;
     583           12398 :         rv = NS_OK;
     584                 : 
     585           12398 :         NS_ASSERTION(!xpc::WrapperFactory::IsXrayWrapper(parent),
     586                 :                      "Xray wrapper being used to parent XPCWrappedNative?");
     587                 : 
     588           12398 :         if (!ac.enter(ccx, parent))
     589               0 :             return NS_ERROR_FAILURE;
     590                 : 
     591           12398 :         if (parent != plannedParent) {
     592                 :             XPCWrappedNativeScope* betterScope =
     593               0 :                 XPCWrappedNativeScope::FindInJSObjectScope(ccx, parent);
     594               0 :             if (betterScope != Scope)
     595               0 :                 return GetNewOrUsed(ccx, helper, betterScope, Interface, resultWrapper);
     596                 : 
     597               0 :             newParentVal = OBJECT_TO_JSVAL(parent);
     598                 :         }
     599                 : 
     600                 :         // Take the performance hit of checking the hashtable again in case
     601                 :         // the preCreate call caused the wrapper to get created through some
     602                 :         // interesting path (the DOM code tends to make this happen sometimes).
     603                 : 
     604           12398 :         if (cache) {
     605            4969 :             JSObject *cached = cache->GetWrapper();
     606            4969 :             if (cached) {
     607               0 :                 if (IS_SLIM_WRAPPER_OBJECT(cached)) {
     608               0 :                     if (!XPCWrappedNative::Morph(ccx, cached, Interface, cache,
     609               0 :                                                  getter_AddRefs(wrapper)))
     610               0 :                         return NS_ERROR_FAILURE;
     611                 :                 } else {
     612               0 :                     wrapper = static_cast<XPCWrappedNative*>(xpc_GetJSPrivate(cached));
     613                 :                 }
     614                 :             }
     615                 :         } else {
     616                 :             // scoped lock
     617           14858 :             XPCAutoLock lock(mapLock);
     618            7429 :             wrapper = map->Find(identity);
     619                 :         }
     620                 : 
     621           12398 :         if (wrapper) {
     622               0 :             if (Interface && !wrapper->FindTearOff(ccx, Interface, false, &rv)) {
     623               0 :                 NS_ASSERTION(NS_FAILED(rv), "returning NS_OK on failure");
     624               0 :                 return rv;
     625                 :             }
     626               0 :             DEBUG_CheckWrapperThreadSafety(wrapper);
     627               0 :             *resultWrapper = wrapper.forget().get();
     628               0 :             return NS_OK;
     629                 :         }
     630                 :     } else {
     631         1210402 :         if (!ac.enter(ccx, parent))
     632               0 :             return NS_ERROR_FAILURE;
     633                 : 
     634         1210402 :         nsISupports *Object = helper.Object();
     635         1210402 :         if (nsXPCWrappedJSClass::IsWrappedJS(Object)) {
     636           29720 :             nsCOMPtr<nsIXPConnectWrappedJS> wrappedjs(do_QueryInterface(Object));
     637                 :             JSObject *obj;
     638           14860 :             wrappedjs->GetJSObject(&obj);
     639           29720 :             if (xpc::AccessCheck::isChrome(js::GetObjectCompartment(obj)) &&
     640           14860 :                 !xpc::AccessCheck::isChrome(js::GetObjectCompartment(Scope->GetGlobalJSObject()))) {
     641               0 :                 needsCOW = true;
     642                 :             }
     643                 :         }
     644                 :     }
     645                 : 
     646         2445600 :     AutoMarkingWrappedNativeProtoPtr proto(ccx);
     647                 : 
     648                 :     // If there is ClassInfo (and we are not building a wrapper for the
     649                 :     // nsIClassInfo interface) then we use a wrapper that needs a prototype.
     650                 : 
     651                 :     // Note that the security check happens inside FindTearOff - after the
     652                 :     // wrapper is actually created, but before JS code can see it.
     653                 : 
     654         1222800 :     if (info && !isClassInfo) {
     655          355485 :         proto = XPCWrappedNativeProto::GetNewOrUsed(ccx, Scope, info, &sciProto);
     656          355485 :         if (!proto)
     657               0 :             return NS_ERROR_FAILURE;
     658                 : 
     659          355485 :         proto->CacheOffsets(identity);
     660                 : 
     661          710970 :         wrapper = new XPCWrappedNative(identity, proto);
     662          710970 :         if (!wrapper)
     663               0 :             return NS_ERROR_FAILURE;
     664                 :     } else {
     665         1734630 :         AutoMarkingNativeInterfacePtr iface(ccx, Interface);
     666          867315 :         if (!iface)
     667               0 :             iface = XPCNativeInterface::GetISupports(ccx);
     668                 : 
     669         1734630 :         AutoMarkingNativeSetPtr set(ccx);
     670          867315 :         set = XPCNativeSet::GetNewOrUsed(ccx, nsnull, iface, 0);
     671                 : 
     672          867315 :         if (!set)
     673               0 :             return NS_ERROR_FAILURE;
     674                 : 
     675         1734630 :         wrapper = new XPCWrappedNative(identity, Scope, set);
     676          867315 :         if (!wrapper)
     677               0 :             return NS_ERROR_FAILURE;
     678                 : 
     679                 :         DEBUG_ReportShadowedMembers(set, wrapper, nsnull);
     680                 :     }
     681                 : 
     682                 :     // The strong reference was taken over by the wrapper, so make the nsCOMPtr
     683                 :     // forget about it.
     684         1222800 :     helper.forgetCanonical();
     685                 : 
     686         1222800 :     NS_ASSERTION(!xpc::WrapperFactory::IsXrayWrapper(parent),
     687                 :                  "Xray wrapper being used to parent XPCWrappedNative?");
     688                 : 
     689                 :     // We use an AutoMarkingPtr here because it is possible for JS gc to happen
     690                 :     // after we have Init'd the wrapper but *before* we add it to the hashtable.
     691                 :     // This would cause the mSet to get collected and we'd later crash. I've
     692                 :     // *seen* this happen.
     693         2445600 :     AutoMarkingWrappedNativePtr wrapperMarker(ccx, wrapper);
     694                 : 
     695         1222800 :     if (!wrapper->Init(ccx, parent, &sciWrapper))
     696               0 :         return NS_ERROR_FAILURE;
     697                 : 
     698         1222800 :     if (Interface && !wrapper->FindTearOff(ccx, Interface, false, &rv)) {
     699               0 :         NS_ASSERTION(NS_FAILED(rv), "returning NS_OK on failure");
     700               0 :         return rv;
     701                 :     }
     702                 : 
     703         1222800 :     if (needsSOW)
     704               0 :         wrapper->SetNeedsSOW();
     705         1222800 :     if (needsCOW)
     706               0 :         wrapper->SetNeedsCOW();
     707                 : 
     708         1222800 :     return FinishCreate(ccx, Scope, Interface, cache, wrapper, resultWrapper);
     709                 : }
     710                 : 
     711                 : static nsresult
     712         1242037 : FinishCreate(XPCCallContext& ccx,
     713                 :              XPCWrappedNativeScope* Scope,
     714                 :              XPCNativeInterface* Interface,
     715                 :              nsWrapperCache *cache,
     716                 :              XPCWrappedNative* inWrapper,
     717                 :              XPCWrappedNative** resultWrapper)
     718                 : {
     719         1242037 :     MOZ_ASSERT(inWrapper);
     720                 : 
     721                 : #if DEBUG_xpc_leaks
     722                 :     {
     723                 :         char* s = wrapper->ToString(ccx);
     724                 :         NS_ASSERTION(wrapper->IsValid(), "eh?");
     725                 :         printf("Created wrapped native %s, flat JSObject is %p\n",
     726                 :                s, (void*)wrapper->GetFlatJSObjectNoMark());
     727                 :         if (s)
     728                 :             JS_smprintf_free(s);
     729                 :     }
     730                 : #endif
     731                 : 
     732         1242037 :     XPCLock* mapLock = Scope->GetRuntime()->GetMapLock();
     733         1242037 :     Native2WrappedNativeMap* map = Scope->GetWrappedNativeMap();
     734                 : 
     735         2484074 :     nsRefPtr<XPCWrappedNative> wrapper;
     736                 :     {   // scoped lock
     737                 : 
     738                 :         // Deal with the case where the wrapper got created as a side effect
     739                 :         // of one of our calls out of this code (or on another thread). Add()
     740                 :         // returns the (possibly pre-existing) wrapper that ultimately ends up
     741                 :         // in the map, which is what we want.
     742         2484074 :         XPCAutoLock lock(mapLock);
     743         1242037 :         wrapper = map->Add(inWrapper);
     744         1242037 :         if (!wrapper)
     745               0 :             return NS_ERROR_FAILURE;
     746                 :     }
     747                 : 
     748         1242037 :     if (wrapper == inWrapper) {
     749         1242037 :         JSObject *flat = wrapper->GetFlatJSObject();
     750         1242037 :         NS_ASSERTION(!cache || !cache->GetWrapperPreserveColor() ||
     751                 :                      flat == cache->GetWrapperPreserveColor(),
     752                 :                      "This object has a cached wrapper that's different from "
     753                 :                      "the JSObject held by its native wrapper?");
     754                 : 
     755         1242037 :         if (cache && !cache->GetWrapperPreserveColor())
     756            4969 :             cache->SetWrapper(flat);
     757                 : 
     758                 :         // Our newly created wrapper is the one that we just added to the table.
     759                 :         // All is well. Call PostCreate as necessary.
     760         1242037 :         XPCNativeScriptableInfo* si = wrapper->GetScriptableInfo();
     761         1242037 :         if (si && si->GetFlags().WantPostCreate()) {
     762            1161 :             nsresult rv = si->GetCallback()->PostCreate(wrapper, ccx, flat);
     763            1161 :             if (NS_FAILED(rv)) {
     764                 :                 // PostCreate failed and that's Very Bad. We'll remove it from
     765                 :                 // the map and mark it as invalid, but the PostCreate function
     766                 :                 // may have handed the partially-constructed-and-now-invalid
     767                 :                 // wrapper to someone before failing. Or, perhaps worse, the
     768                 :                 // PostCreate call could have triggered code that reentered
     769                 :                 // XPConnect and tried to wrap the same object. In that case
     770                 :                 // *we* hand out the invalid wrapper since it is already in our
     771                 :                 // map :(
     772                 :                 NS_ERROR("PostCreate failed! This is known to cause "
     773                 :                          "inconsistent state for some class types and may even "
     774                 :                          "cause a crash in combination with a JS GC. Fix the "
     775               0 :                          "failing PostCreate ASAP!");
     776                 : 
     777                 :                 {   // scoped lock
     778               0 :                     XPCAutoLock lock(mapLock);
     779               0 :                     map->Remove(wrapper);
     780                 :                 }
     781                 : 
     782                 :                 // This would be a good place to tell the wrapper not to remove
     783                 :                 // itself from the map when it dies... See bug 429442.
     784                 : 
     785               0 :                 if (cache)
     786               0 :                     cache->ClearWrapper();
     787               0 :                 wrapper->Release();
     788               0 :                 return rv;
     789                 :             }
     790                 :         }
     791                 :     }
     792                 : 
     793                 :     DEBUG_CheckClassInfoClaims(wrapper);
     794         1242037 :     *resultWrapper = wrapper.forget().get();
     795         1242037 :     return NS_OK;
     796                 : }
     797                 : 
     798                 : // static
     799                 : nsresult
     800            6065 : XPCWrappedNative::Morph(XPCCallContext& ccx,
     801                 :                         JSObject* existingJSObject,
     802                 :                         XPCNativeInterface* Interface,
     803                 :                         nsWrapperCache *cache,
     804                 :                         XPCWrappedNative** resultWrapper)
     805                 : {
     806            6065 :     NS_ASSERTION(IS_SLIM_WRAPPER(existingJSObject),
     807                 :                  "Trying to morph a JSObject that's not a slim wrapper?");
     808                 : 
     809                 :     nsISupports *identity =
     810            6065 :         static_cast<nsISupports*>(xpc_GetJSPrivate(existingJSObject));
     811            6065 :     XPCWrappedNativeProto *proto = GetSlimWrapperProto(existingJSObject);
     812                 : 
     813                 : #if DEBUG
     814                 :     // FIXME Can't assert this until
     815                 :     //       https://bugzilla.mozilla.org/show_bug.cgi?id=343141 is fixed.
     816                 : #if 0
     817                 :     if (proto->GetScriptableInfo()->GetFlags().WantPreCreate()) {
     818                 :         JSObject* parent = JS_GetParent(existingJSObject);
     819                 :         JSObject* plannedParent = parent;
     820                 :         nsresult rv =
     821                 :             proto->GetScriptableInfo()->GetCallback()->PreCreate(identity, ccx,
     822                 :                                                                  parent,
     823                 :                                                                  &parent);
     824                 :         if (NS_FAILED(rv))
     825                 :             return rv;
     826                 : 
     827                 :         NS_ASSERTION(parent == plannedParent,
     828                 :                      "PreCreate returned a different parent");
     829                 :     }
     830                 : #endif
     831                 : #endif
     832                 : 
     833           18195 :     nsRefPtr<XPCWrappedNative> wrapper = new XPCWrappedNative(dont_AddRef(identity), proto);
     834            6065 :     if (!wrapper)
     835               0 :         return NS_ERROR_FAILURE;
     836                 : 
     837            6065 :     NS_ASSERTION(!xpc::WrapperFactory::IsXrayWrapper(js::GetObjectParent(existingJSObject)),
     838                 :                  "Xray wrapper being used to parent XPCWrappedNative?");
     839                 : 
     840                 :     // We use an AutoMarkingPtr here because it is possible for JS gc to happen
     841                 :     // after we have Init'd the wrapper but *before* we add it to the hashtable.
     842                 :     // This would cause the mSet to get collected and we'd later crash. I've
     843                 :     // *seen* this happen.
     844           12130 :     AutoMarkingWrappedNativePtr wrapperMarker(ccx, wrapper);
     845                 : 
     846           12130 :     JSAutoEnterCompartment ac;
     847            6065 :     if (!ac.enter(ccx, existingJSObject)) {
     848               0 :         wrapper->mIdentity = nsnull;
     849               0 :         return NS_ERROR_FAILURE;
     850                 :     }
     851            6065 :     if (!wrapper->Init(ccx, existingJSObject))
     852               0 :         return NS_ERROR_FAILURE;
     853                 : 
     854                 :     nsresult rv;
     855            6065 :     if (Interface && !wrapper->FindTearOff(ccx, Interface, false, &rv)) {
     856               0 :         NS_ASSERTION(NS_FAILED(rv), "returning NS_OK on failure");
     857               0 :         return rv;
     858                 :     }
     859                 : 
     860            6065 :     return FinishCreate(ccx, wrapper->GetScope(), Interface, cache, wrapper, resultWrapper);
     861                 : }
     862                 : 
     863                 : // static
     864                 : nsresult
     865               0 : XPCWrappedNative::GetUsedOnly(XPCCallContext& ccx,
     866                 :                               nsISupports* Object,
     867                 :                               XPCWrappedNativeScope* Scope,
     868                 :                               XPCNativeInterface* Interface,
     869                 :                               XPCWrappedNative** resultWrapper)
     870                 : {
     871               0 :     NS_ASSERTION(Object, "XPCWrappedNative::GetUsedOnly was called with a null Object");
     872                 : 
     873                 :     XPCWrappedNative* wrapper;
     874               0 :     nsWrapperCache* cache = nsnull;
     875               0 :     CallQueryInterface(Object, &cache);
     876               0 :     if (cache) {
     877               0 :         JSObject *flat = cache->GetWrapper();
     878               0 :         if (flat && IS_SLIM_WRAPPER_OBJECT(flat) && !MorphSlimWrapper(ccx, flat))
     879               0 :            return NS_ERROR_FAILURE;
     880                 : 
     881                 :         wrapper = flat ?
     882               0 :                   static_cast<XPCWrappedNative*>(xpc_GetJSPrivate(flat)) :
     883               0 :                   nsnull;
     884                 : 
     885               0 :         if (!wrapper) {
     886               0 :             *resultWrapper = nsnull;
     887               0 :             return NS_OK;
     888                 :         }
     889               0 :         NS_ADDREF(wrapper);
     890                 :     } else {
     891               0 :         nsCOMPtr<nsISupports> identity = do_QueryInterface(Object);
     892                 : 
     893               0 :         if (!identity) {
     894               0 :             NS_ERROR("This XPCOM object fails in QueryInterface to nsISupports!");
     895               0 :             return NS_ERROR_FAILURE;
     896                 :         }
     897                 : 
     898               0 :         Native2WrappedNativeMap* map = Scope->GetWrappedNativeMap();
     899                 : 
     900                 :         {   // scoped lock
     901               0 :             XPCAutoLock lock(Scope->GetRuntime()->GetMapLock());
     902               0 :             wrapper = map->Find(identity);
     903               0 :             if (!wrapper) {
     904               0 :                 *resultWrapper = nsnull;
     905               0 :                 return NS_OK;
     906                 :             }
     907               0 :             NS_ADDREF(wrapper);
     908                 :         }
     909                 :     }
     910                 : 
     911                 :     nsresult rv;
     912               0 :     if (Interface && !wrapper->FindTearOff(ccx, Interface, false, &rv)) {
     913               0 :         NS_RELEASE(wrapper);
     914               0 :         NS_ASSERTION(NS_FAILED(rv), "returning NS_OK on failure");
     915               0 :         return rv;
     916                 :     }
     917                 : 
     918               0 :     *resultWrapper = wrapper;
     919               0 :     return NS_OK;
     920                 : }
     921                 : 
     922                 : // This ctor is used if this object will have a proto.
     923          374722 : XPCWrappedNative::XPCWrappedNative(already_AddRefed<nsISupports> aIdentity,
     924                 :                                    XPCWrappedNativeProto* aProto)
     925                 :     : mMaybeProto(aProto),
     926          374722 :       mSet(aProto->GetSet()),
     927                 :       mFlatJSObject(INVALID_OBJECT), // non-null to pass IsValid() test
     928                 :       mScriptableInfo(nsnull),
     929                 :       mWrapperWord(0)
     930                 : #ifdef XPC_CHECK_WRAPPER_THREADSAFETY
     931          749444 :     , mThread(PR_GetCurrentThread())
     932                 : #endif
     933                 : {
     934          374722 :     mIdentity = aIdentity.get();
     935                 : 
     936          374722 :     NS_ASSERTION(mMaybeProto, "bad ctor param");
     937          374722 :     NS_ASSERTION(mSet, "bad ctor param");
     938                 : 
     939          374722 :     DEBUG_TrackNewWrapper(this);
     940          374722 : }
     941                 : 
     942                 : // This ctor is used if this object will NOT have a proto.
     943          867315 : XPCWrappedNative::XPCWrappedNative(already_AddRefed<nsISupports> aIdentity,
     944                 :                                    XPCWrappedNativeScope* aScope,
     945                 :                                    XPCNativeSet* aSet)
     946                 : 
     947          867315 :     : mMaybeScope(TagScope(aScope)),
     948                 :       mSet(aSet),
     949                 :       mFlatJSObject(INVALID_OBJECT), // non-null to pass IsValid() test
     950                 :       mScriptableInfo(nsnull),
     951                 :       mWrapperWord(0)
     952                 : #ifdef XPC_CHECK_WRAPPER_THREADSAFETY
     953         1734630 :     , mThread(PR_GetCurrentThread())
     954                 : #endif
     955                 : {
     956          867315 :     mIdentity = aIdentity.get();
     957                 : 
     958          867315 :     NS_ASSERTION(aScope, "bad ctor param");
     959          867315 :     NS_ASSERTION(aSet, "bad ctor param");
     960                 : 
     961          867315 :     DEBUG_TrackNewWrapper(this);
     962          867315 : }
     963                 : 
     964         3723678 : XPCWrappedNative::~XPCWrappedNative()
     965                 : {
     966         1241226 :     DEBUG_TrackDeleteWrapper(this);
     967                 : 
     968         1241226 :     Destroy();
     969         4964904 : }
     970                 : 
     971                 : static const PRWord WRAPPER_WORD_POISON = 0xa8a8a8a8;
     972                 : 
     973                 : void
     974         1241548 : XPCWrappedNative::Destroy()
     975                 : {
     976         1241548 :     XPCWrappedNativeProto* proto = GetProto();
     977                 : 
     978         1808864 :     if (mScriptableInfo &&
     979          297416 :         (!HasProto() ||
     980          269900 :          (proto && proto->GetScriptableInfo() != mScriptableInfo))) {
     981          233545 :         delete mScriptableInfo;
     982          233545 :         mScriptableInfo = nsnull;
     983                 :     }
     984                 : 
     985         1241548 :     XPCWrappedNativeScope *scope = GetScope();
     986         1241548 :     if (scope) {
     987         1241226 :         Native2WrappedNativeMap* map = scope->GetWrappedNativeMap();
     988                 : 
     989                 :         // scoped lock
     990         2482452 :         XPCAutoLock lock(GetRuntime()->GetMapLock());
     991                 : 
     992                 :         // Post-1.9 we should not remove this wrapper from the map if it is
     993                 :         // uninitialized.
     994         1241226 :         map->Remove(this);
     995                 :     }
     996                 : 
     997         1241548 :     if (mIdentity) {
     998         1241226 :         XPCJSRuntime* rt = GetRuntime();
     999         1241226 :         if (rt && rt->GetDoingFinalization()) {
    1000         1241226 :             if (rt->DeferredRelease(mIdentity)) {
    1001         1241226 :                 mIdentity = nsnull;
    1002                 :             } else {
    1003               0 :                 NS_WARNING("Failed to append object for deferred release.");
    1004                 :                 // XXX do we really want to do this???
    1005               0 :                 NS_RELEASE(mIdentity);
    1006                 :             }
    1007                 :         } else {
    1008               0 :             NS_RELEASE(mIdentity);
    1009                 :         }
    1010                 :     }
    1011                 : 
    1012                 :     /*
    1013                 :      * The only time GetRuntime() will be NULL is if Destroy is called a second
    1014                 :      * time on a wrapped native. Since we already unregistered the pointer the
    1015                 :      * first time, there's no need to unregister again. Unregistration is safe
    1016                 :      * the first time because mWrapperWord isn't used afterwards.
    1017                 :      */
    1018         1241548 :     if (XPCJSRuntime *rt = GetRuntime()) {
    1019         1241226 :         if (js::IsIncrementalBarrierNeeded(rt->GetJSRuntime()))
    1020               0 :             js::IncrementalReferenceBarrier(GetWrapperPreserveColor());
    1021         1241226 :         mWrapperWord = WRAPPER_WORD_POISON;
    1022                 :     } else {
    1023             322 :         MOZ_ASSERT(mWrapperWord == WRAPPER_WORD_POISON);
    1024                 :     }
    1025                 : 
    1026         1241548 :     mMaybeScope = nsnull;
    1027         1241548 : }
    1028                 : 
    1029                 : void
    1030               0 : XPCWrappedNative::UpdateScriptableInfo(XPCNativeScriptableInfo *si)
    1031                 : {
    1032               0 :     NS_ASSERTION(mScriptableInfo, "UpdateScriptableInfo expects an existing scriptable info");
    1033                 : 
    1034                 :     // Write barrier for incremental GC.
    1035               0 :     JSRuntime* rt = GetRuntime()->GetJSRuntime();
    1036               0 :     if (js::IsIncrementalBarrierNeeded(rt))
    1037               0 :         mScriptableInfo->Mark();
    1038                 : 
    1039               0 :     mScriptableInfo = si;
    1040               0 : }
    1041                 : 
    1042                 : void
    1043               0 : XPCWrappedNative::SetProto(XPCWrappedNativeProto* p)
    1044                 : {
    1045               0 :     NS_ASSERTION(!IsWrapperExpired(), "bad ptr!");
    1046                 : 
    1047               0 :     MOZ_ASSERT(HasProto());
    1048                 : 
    1049                 :     // Write barrier for incremental GC.
    1050               0 :     JSRuntime* rt = GetRuntime()->GetJSRuntime();
    1051               0 :     GetProto()->WriteBarrierPre(rt);
    1052                 : 
    1053               0 :     mMaybeProto = p;
    1054               0 : }
    1055                 : 
    1056                 : // This is factored out so that it can be called publicly
    1057                 : // static
    1058                 : void
    1059          368657 : XPCWrappedNative::GatherProtoScriptableCreateInfo(nsIClassInfo* classInfo,
    1060                 :                                                   XPCNativeScriptableCreateInfo& sciProto)
    1061                 : {
    1062          368657 :     NS_ASSERTION(classInfo, "bad param");
    1063          368657 :     NS_ASSERTION(!sciProto.GetCallback(), "bad param");
    1064                 : 
    1065          368657 :     nsXPCClassInfo *classInfoHelper = nsnull;
    1066          368657 :     CallQueryInterface(classInfo, &classInfoHelper);
    1067          368657 :     if (classInfoHelper) {
    1068                 :         nsCOMPtr<nsIXPCScriptable> helper =
    1069           24796 :           dont_AddRef(static_cast<nsIXPCScriptable*>(classInfoHelper));
    1070                 :         uint32_t flags;
    1071           12398 :         nsresult rv = classInfoHelper->GetScriptableFlags(&flags);
    1072           12398 :         if (NS_FAILED(rv))
    1073               0 :             flags = 0;
    1074                 : 
    1075           12398 :         sciProto.SetCallback(helper.forget());
    1076           12398 :         sciProto.SetFlags(flags);
    1077           12398 :         sciProto.SetInterfacesBitmap(classInfoHelper->GetInterfacesBitmap());
    1078                 : 
    1079                 :         return;
    1080                 :     }
    1081                 : 
    1082          712518 :     nsCOMPtr<nsISupports> possibleHelper;
    1083                 :     nsresult rv = classInfo->GetHelperForLanguage(nsIProgrammingLanguage::JAVASCRIPT,
    1084          356259 :                                                   getter_AddRefs(possibleHelper));
    1085          356259 :     if (NS_SUCCEEDED(rv) && possibleHelper) {
    1086          272428 :         nsCOMPtr<nsIXPCScriptable> helper(do_QueryInterface(possibleHelper));
    1087          136214 :         if (helper) {
    1088                 :             uint32_t flags;
    1089          136214 :             rv = helper->GetScriptableFlags(&flags);
    1090          136214 :             if (NS_FAILED(rv))
    1091               0 :                 flags = 0;
    1092                 : 
    1093          136214 :             sciProto.SetCallback(helper.forget());
    1094          136214 :             sciProto.SetFlags(flags);
    1095                 :         }
    1096                 :     }
    1097                 : }
    1098                 : 
    1099                 : // static
    1100                 : const XPCNativeScriptableCreateInfo&
    1101         1235968 : XPCWrappedNative::GatherScriptableCreateInfo(nsISupports* obj,
    1102                 :                                              nsIClassInfo* classInfo,
    1103                 :                                              XPCNativeScriptableCreateInfo& sciProto,
    1104                 :                                              XPCNativeScriptableCreateInfo& sciWrapper)
    1105                 : {
    1106         1235968 :     NS_ASSERTION(!sciWrapper.GetCallback(), "bad param");
    1107                 : 
    1108                 :     // Get the class scriptable helper (if present)
    1109         1235968 :     if (classInfo) {
    1110          368657 :         GatherProtoScriptableCreateInfo(classInfo, sciProto);
    1111                 : 
    1112          368657 :         if (sciProto.GetFlags().DontAskInstanceForScriptable())
    1113           12398 :             return sciProto;
    1114                 :     }
    1115                 : 
    1116                 :     // Do the same for the wrapper specific scriptable
    1117         2447140 :     nsCOMPtr<nsIXPCScriptable> helper(do_QueryInterface(obj));
    1118         1223570 :     if (helper) {
    1119                 :         uint32_t flags;
    1120          234306 :         nsresult rv = helper->GetScriptableFlags(&flags);
    1121          234306 :         if (NS_FAILED(rv))
    1122               0 :             flags = 0;
    1123                 : 
    1124          234306 :         sciWrapper.SetCallback(helper.forget());
    1125          234306 :         sciWrapper.SetFlags(flags);
    1126                 : 
    1127                 :         // A whole series of assertions to catch bad uses of scriptable flags on
    1128                 :         // the siWrapper...
    1129                 : 
    1130          234306 :         NS_ASSERTION(!(sciWrapper.GetFlags().WantPreCreate() &&
    1131                 :                        !sciProto.GetFlags().WantPreCreate()),
    1132                 :                      "Can't set WANT_PRECREATE on an instance scriptable "
    1133                 :                      "without also setting it on the class scriptable");
    1134                 : 
    1135          234306 :         NS_ASSERTION(!(sciWrapper.GetFlags().DontEnumStaticProps() &&
    1136                 :                        !sciProto.GetFlags().DontEnumStaticProps() &&
    1137                 :                        sciProto.GetCallback()),
    1138                 :                      "Can't set DONT_ENUM_STATIC_PROPS on an instance scriptable "
    1139                 :                      "without also setting it on the class scriptable (if present and shared)");
    1140                 : 
    1141          234306 :         NS_ASSERTION(!(sciWrapper.GetFlags().DontEnumQueryInterface() &&
    1142                 :                        !sciProto.GetFlags().DontEnumQueryInterface() &&
    1143                 :                        sciProto.GetCallback()),
    1144                 :                      "Can't set DONT_ENUM_QUERY_INTERFACE on an instance scriptable "
    1145                 :                      "without also setting it on the class scriptable (if present and shared)");
    1146                 : 
    1147          234306 :         NS_ASSERTION(!(sciWrapper.GetFlags().DontAskInstanceForScriptable() &&
    1148                 :                        !sciProto.GetFlags().DontAskInstanceForScriptable()),
    1149                 :                      "Can't set DONT_ASK_INSTANCE_FOR_SCRIPTABLE on an instance scriptable "
    1150                 :                      "without also setting it on the class scriptable");
    1151                 : 
    1152          234306 :         NS_ASSERTION(!(sciWrapper.GetFlags().ClassInfoInterfacesOnly() &&
    1153                 :                        !sciProto.GetFlags().ClassInfoInterfacesOnly() &&
    1154                 :                        sciProto.GetCallback()),
    1155                 :                      "Can't set CLASSINFO_INTERFACES_ONLY on an instance scriptable "
    1156                 :                      "without also setting it on the class scriptable (if present and shared)");
    1157                 : 
    1158          234306 :         NS_ASSERTION(!(sciWrapper.GetFlags().AllowPropModsDuringResolve() &&
    1159                 :                        !sciProto.GetFlags().AllowPropModsDuringResolve() &&
    1160                 :                        sciProto.GetCallback()),
    1161                 :                      "Can't set ALLOW_PROP_MODS_DURING_RESOLVE on an instance scriptable "
    1162                 :                      "without also setting it on the class scriptable (if present and shared)");
    1163                 : 
    1164          234306 :         NS_ASSERTION(!(sciWrapper.GetFlags().AllowPropModsToPrototype() &&
    1165                 :                        !sciProto.GetFlags().AllowPropModsToPrototype() &&
    1166                 :                        sciProto.GetCallback()),
    1167                 :                      "Can't set ALLOW_PROP_MODS_TO_PROTOTYPE on an instance scriptable "
    1168                 :                      "without also setting it on the class scriptable (if present and shared)");
    1169                 : 
    1170          234306 :         return sciWrapper;
    1171                 :     }
    1172                 : 
    1173          989264 :     return sciProto;
    1174                 : }
    1175                 : 
    1176                 : #ifdef DEBUG_slimwrappers
    1177                 : static PRUint32 sMorphedSlimWrappers;
    1178                 : #endif
    1179                 : 
    1180                 : JSBool
    1181         1222800 : XPCWrappedNative::Init(XPCCallContext& ccx, JSObject* parent,
    1182                 :                        const XPCNativeScriptableCreateInfo* sci)
    1183                 : {
    1184                 :     // setup our scriptable info...
    1185                 : 
    1186         1222800 :     if (sci->GetCallback()) {
    1187          278771 :         if (HasProto()) {
    1188          251420 :             XPCNativeScriptableInfo* siProto = GetProto()->GetScriptableInfo();
    1189          251420 :             if (siProto && siProto->GetCallback() == sci->GetCallback())
    1190           57637 :                 mScriptableInfo = siProto;
    1191                 :         }
    1192          278771 :         if (!mScriptableInfo) {
    1193                 :             mScriptableInfo =
    1194          221134 :                 XPCNativeScriptableInfo::Construct(ccx, sci);
    1195                 : 
    1196          221134 :             if (!mScriptableInfo)
    1197               0 :                 return false;
    1198                 :         }
    1199                 :     }
    1200         1222800 :     XPCNativeScriptableInfo* si = mScriptableInfo;
    1201                 : 
    1202                 :     // create our flatJSObject
    1203                 : 
    1204         1222800 :     JSClass* jsclazz = si ? si->GetJSClass() : Jsvalify(&XPC_WN_NoHelper_JSClass.base);
    1205                 : 
    1206                 :     // We should have the global jsclass flag if and only if we're a global.
    1207         1222800 :     MOZ_ASSERT_IF(si, !!si->GetFlags().IsGlobalObject() == !!(jsclazz->flags & JSCLASS_IS_GLOBAL));
    1208                 : 
    1209         1222800 :     NS_ASSERTION(jsclazz &&
    1210                 :                  jsclazz->name &&
    1211                 :                  jsclazz->flags &&
    1212                 :                  jsclazz->addProperty &&
    1213                 :                  jsclazz->delProperty &&
    1214                 :                  jsclazz->getProperty &&
    1215                 :                  jsclazz->setProperty &&
    1216                 :                  jsclazz->enumerate &&
    1217                 :                  jsclazz->resolve &&
    1218                 :                  jsclazz->convert &&
    1219                 :                  jsclazz->finalize, "bad class");
    1220                 : 
    1221         1222800 :     JSObject* protoJSObject = HasProto() ?
    1222          355485 :                                 GetProto()->GetJSProtoObject() :
    1223         1578285 :                                 GetScope()->GetPrototypeNoHelper(ccx);
    1224                 : 
    1225         1222800 :     if (!protoJSObject) {
    1226               0 :         return false;
    1227                 :     }
    1228                 : 
    1229         1222800 :     mFlatJSObject = xpc_NewSystemInheritingJSObject(ccx, jsclazz, protoJSObject, false, parent);
    1230         1222800 :     if (!mFlatJSObject)
    1231               0 :         return false;
    1232                 : 
    1233         1222800 :     JS_SetPrivate(mFlatJSObject, this);
    1234                 : 
    1235         1222800 :     return FinishInit(ccx);
    1236                 : }
    1237                 : 
    1238                 : JSBool
    1239            6065 : XPCWrappedNative::Init(XPCCallContext &ccx, JSObject *existingJSObject)
    1240                 : {
    1241            6065 :     JS_SetPrivate(existingJSObject, this);
    1242                 : 
    1243                 :     // Morph the existing object.
    1244            6065 :     JS_SetReservedSlot(existingJSObject, 0, JSVAL_VOID);
    1245                 : 
    1246            6065 :     mScriptableInfo = GetProto()->GetScriptableInfo();
    1247            6065 :     mFlatJSObject = existingJSObject;
    1248                 : 
    1249                 :     SLIM_LOG(("----- %i morphed slim wrapper (mFlatJSObject: %p, %p)\n",
    1250                 :               ++sMorphedSlimWrappers, mFlatJSObject,
    1251                 :               static_cast<nsISupports*>(xpc_GetJSPrivate(mFlatJSObject))));
    1252                 : 
    1253            6065 :     return FinishInit(ccx);
    1254                 : }
    1255                 : 
    1256                 : JSBool
    1257         1242037 : XPCWrappedNative::FinishInit(XPCCallContext &ccx)
    1258                 : {
    1259                 :     // This reference will be released when mFlatJSObject is finalized.
    1260                 :     // Since this reference will push the refcount to 2 it will also root
    1261                 :     // mFlatJSObject;
    1262         1242037 :     NS_ASSERTION(1 == mRefCnt, "unexpected refcount value");
    1263         1242037 :     NS_ADDREF(this);
    1264                 : 
    1265         1242037 :     if (mScriptableInfo && mScriptableInfo->GetFlags().WantCreate() &&
    1266               0 :         NS_FAILED(mScriptableInfo->GetCallback()->Create(this, ccx,
    1267                 :                                                          mFlatJSObject))) {
    1268               0 :         return false;
    1269                 :     }
    1270                 : 
    1271                 : #ifdef XPC_CHECK_WRAPPER_THREADSAFETY
    1272         1242037 :     NS_ASSERTION(mThread, "Should have been set at construction time!");
    1273                 : 
    1274         1242037 :     if (HasProto() && GetProto()->ClassIsMainThreadOnly() && !NS_IsMainThread()) {
    1275                 :         DEBUG_ReportWrapperThreadSafetyError(ccx,
    1276               0 :                                              "MainThread only wrapper created on the wrong thread", this);
    1277               0 :         return false;
    1278                 :     }
    1279                 : #endif
    1280                 : 
    1281                 :     // A hack for bug 517665, increase the probability for GC.
    1282         1242037 :     JS_updateMallocCounter(ccx.GetJSContext(), 2 * sizeof(XPCWrappedNative));
    1283                 : 
    1284         1242037 :     return true;
    1285                 : }
    1286                 : 
    1287                 : 
    1288         2458999 : NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(XPCWrappedNative)
    1289         2458269 :   NS_INTERFACE_MAP_ENTRY(nsIXPConnectWrappedNative)
    1290          552310 :   NS_INTERFACE_MAP_ENTRY(nsIXPConnectJSObjectHolder)
    1291             406 :   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIXPConnectWrappedNative)
    1292             406 : NS_INTERFACE_MAP_END_THREADSAFE
    1293                 : 
    1294         7291712 : NS_IMPL_THREADSAFE_ADDREF(XPCWrappedNative)
    1295         7290901 : NS_IMPL_THREADSAFE_RELEASE(XPCWrappedNative)
    1296                 : 
    1297                 : /*
    1298                 :  *  Wrapped Native lifetime management is messy!
    1299                 :  *
    1300                 :  *  - At creation we push the refcount to 2 (only one of which is owned by
    1301                 :  *    the native caller that caused the wrapper creation).
    1302                 :  *  - During the JS GC Mark phase we mark any wrapper with a refcount > 1.
    1303                 :  *  - The *only* thing that can make the wrapper get destroyed is the
    1304                 :  *    finalization of mFlatJSObject. And *that* should only happen if the only
    1305                 :  *    reference is the single extra (internal) reference we hold.
    1306                 :  *
    1307                 :  *  - The wrapper has a pointer to the nsISupports 'view' of the wrapped native
    1308                 :  *    object i.e... mIdentity. This is held until the wrapper's refcount goes
    1309                 :  *    to zero and the wrapper is released, or until an expired wrapper (i.e.,
    1310                 :  *    one unlinked by the cycle collector) has had its JS object finalized.
    1311                 :  *
    1312                 :  *  - The wrapper also has 'tearoffs'. It has one tearoff for each interface
    1313                 :  *    that is actually used on the native object. 'Used' means we have either
    1314                 :  *    needed to QueryInterface to verify the availability of that interface
    1315                 :  *    of that we've had to QueryInterface in order to actually make a call
    1316                 :  *    into the wrapped object via the pointer for the given interface.
    1317                 :  *
    1318                 :  *  - Each tearoff's 'mNative' member (if non-null) indicates one reference
    1319                 :  *    held by our wrapper on the wrapped native for the given interface
    1320                 :  *    associated with the tearoff. If we release that reference then we set
    1321                 :  *    the tearoff's 'mNative' to null.
    1322                 :  *
    1323                 :  *  - We use the occasion of the JavaScript GCCallback for the JSGC_MARK_END
    1324                 :  *    event to scan the tearoffs of all wrappers for non-null mNative members
    1325                 :  *    that represent unused references. We can tell that a given tearoff's
    1326                 :  *    mNative is unused by noting that no live XPCCallContexts hold a pointer
    1327                 :  *    to the tearoff.
    1328                 :  *
    1329                 :  *  - As a time/space tradeoff we may decide to not do this scanning on
    1330                 :  *    *every* JavaScript GC. We *do* want to do this *sometimes* because
    1331                 :  *    we want to allow for wrapped native's to do their own tearoff patterns.
    1332                 :  *    So, we want to avoid holding references to interfaces that we don't need.
    1333                 :  *    At the same time, we don't want to be bracketing every call into a
    1334                 :  *    wrapped native object with a QueryInterface/Release pair. And we *never*
    1335                 :  *    make a call into the object except via the correct interface for which
    1336                 :  *    we've QI'd.
    1337                 :  *
    1338                 :  *  - Each tearoff *can* have a mJSObject whose lazily resolved properties
    1339                 :  *    represent the methods/attributes/constants of that specific interface.
    1340                 :  *    This is optionally reflected into JavaScript as "foo.nsIFoo" when "foo"
    1341                 :  *    is the name of mFlatJSObject and "nsIFoo" is the name of the given
    1342                 :  *    interface associated with the tearoff. When we create the tearoff's
    1343                 :  *    mJSObject we set it's parent to be mFlatJSObject. This way we know that
    1344                 :  *    when mFlatJSObject get's collected there are no outstanding reachable
    1345                 :  *    tearoff mJSObjects. Note that we must clear the private of any lingering
    1346                 :  *    mJSObjects at this point because we have no guarentee of the *order* of
    1347                 :  *    finalization within a given gc cycle.
    1348                 :  */
    1349                 : 
    1350                 : void
    1351         1241226 : XPCWrappedNative::FlatJSObjectFinalized()
    1352                 : {
    1353         1241226 :     if (!IsValid())
    1354               0 :         return;
    1355                 : 
    1356                 :     // Iterate the tearoffs and null out each of their JSObject's privates.
    1357                 :     // This will keep them from trying to access their pointers to the
    1358                 :     // dying tearoff object. We can safely assume that those remaining
    1359                 :     // JSObjects are about to be finalized too.
    1360                 : 
    1361                 :     XPCWrappedNativeTearOffChunk* chunk;
    1362         2664281 :     for (chunk = &mFirstChunk; chunk; chunk = chunk->mNextChunk) {
    1363         1423055 :         XPCWrappedNativeTearOff* to = chunk->mTearOffs;
    1364         2846110 :         for (int i = XPC_WRAPPED_NATIVE_TEAROFFS_PER_CHUNK-1; i >= 0; i--, to++) {
    1365         1423055 :             JSObject* jso = to->GetJSObjectPreserveColor();
    1366         1423055 :             if (jso) {
    1367              41 :                 NS_ASSERTION(JS_IsAboutToBeFinalized(jso), "bad!");
    1368              41 :                 JS_SetPrivate(jso, nsnull);
    1369              41 :                 to->JSObjectFinalized();
    1370                 :             }
    1371                 : 
    1372                 :             // We also need to release any native pointers held...
    1373         1423055 :             nsISupports* obj = to->GetNative();
    1374         1423055 :             if (obj) {
    1375                 : #ifdef XP_WIN
    1376                 :                 // Try to detect free'd pointer
    1377                 :                 NS_ASSERTION(*(int*)obj != 0xdddddddd, "bad pointer!");
    1378                 :                 NS_ASSERTION(*(int*)obj != 0,          "bad pointer!");
    1379                 : #endif
    1380         1126213 :                 XPCJSRuntime* rt = GetRuntime();
    1381         1126213 :                 if (rt) {
    1382         1126213 :                     if (!rt->DeferredRelease(obj)) {
    1383               0 :                         NS_WARNING("Failed to append object for deferred release.");
    1384                 :                         // XXX do we really want to do this???
    1385               0 :                         obj->Release();
    1386                 :                     }
    1387                 :                 } else {
    1388               0 :                     obj->Release();
    1389                 :                 }
    1390         1126213 :                 to->SetNative(nsnull);
    1391                 :             }
    1392                 : 
    1393         1423055 :             to->SetInterface(nsnull);
    1394                 :         }
    1395                 :     }
    1396                 : 
    1397         1241226 :     nsWrapperCache *cache = nsnull;
    1398         1241226 :     CallQueryInterface(mIdentity, &cache);
    1399         1241226 :     if (cache)
    1400           11030 :         cache->ClearWrapper();
    1401                 : 
    1402                 :     // This makes IsValid return false from now on...
    1403         1241226 :     mFlatJSObject = nsnull;
    1404                 : 
    1405         1241226 :     NS_ASSERTION(mIdentity, "bad pointer!");
    1406                 : #ifdef XP_WIN
    1407                 :     // Try to detect free'd pointer
    1408                 :     NS_ASSERTION(*(int*)mIdentity != 0xdddddddd, "bad pointer!");
    1409                 :     NS_ASSERTION(*(int*)mIdentity != 0,          "bad pointer!");
    1410                 : #endif
    1411                 : 
    1412         1241226 :     if (IsWrapperExpired()) {
    1413             322 :         Destroy();
    1414                 :     }
    1415                 : 
    1416                 :     // Note that it's not safe to touch mNativeWrapper here since it's
    1417                 :     // likely that it has already been finalized.
    1418                 : 
    1419         1241226 :     Release();
    1420                 : }
    1421                 : 
    1422                 : void
    1423             781 : XPCWrappedNative::SystemIsBeingShutDown()
    1424                 : {
    1425                 : #ifdef DEBUG_xpc_hacker
    1426                 :     {
    1427                 :         printf("Removing root for still-live XPCWrappedNative %p wrapping:\n",
    1428                 :                static_cast<void*>(this));
    1429                 :         for (PRUint16 i = 0, i_end = mSet->GetInterfaceCount(); i < i_end; ++i) {
    1430                 :             nsXPIDLCString name;
    1431                 :             mSet->GetInterfaceAt(i)->GetInterfaceInfo()
    1432                 :                 ->GetName(getter_Copies(name));
    1433                 :             printf("  %s\n", name.get());
    1434                 :         }
    1435                 :     }
    1436                 : #endif
    1437             781 :     DEBUG_TrackShutdownWrapper(this);
    1438                 : 
    1439             781 :     if (!IsValid())
    1440               0 :         return;
    1441                 : 
    1442                 :     // The long standing strategy is to leak some objects still held at shutdown.
    1443                 :     // The general problem is that propagating release out of xpconnect at
    1444                 :     // shutdown time causes a world of problems.
    1445                 : 
    1446                 :     // We leak mIdentity (see above).
    1447                 : 
    1448                 :     // short circuit future finalization
    1449             781 :     JS_SetPrivate(mFlatJSObject, nsnull);
    1450             781 :     mFlatJSObject = nsnull; // This makes 'IsValid()' return false.
    1451                 : 
    1452             781 :     XPCWrappedNativeProto* proto = GetProto();
    1453                 : 
    1454             781 :     if (HasProto())
    1455             735 :         proto->SystemIsBeingShutDown();
    1456                 : 
    1457            2250 :     if (mScriptableInfo &&
    1458             738 :         (!HasProto() ||
    1459             731 :          (proto && proto->GetScriptableInfo() != mScriptableInfo))) {
    1460             738 :         delete mScriptableInfo;
    1461                 :     }
    1462                 : 
    1463                 :     // cleanup the tearoffs...
    1464                 : 
    1465                 :     XPCWrappedNativeTearOffChunk* chunk;
    1466            1729 :     for (chunk = &mFirstChunk; chunk; chunk = chunk->mNextChunk) {
    1467             948 :         XPCWrappedNativeTearOff* to = chunk->mTearOffs;
    1468            1896 :         for (int i = XPC_WRAPPED_NATIVE_TEAROFFS_PER_CHUNK-1; i >= 0; i--, to++) {
    1469             948 :             if (JSObject *jso = to->GetJSObjectPreserveColor()) {
    1470               0 :                 JS_SetPrivate(jso, nsnull);
    1471               0 :                 to->SetJSObject(nsnull);
    1472                 :             }
    1473                 :             // We leak the tearoff mNative
    1474                 :             // (for the same reason we leak mIdentity - see above).
    1475             948 :             to->SetNative(nsnull);
    1476             948 :             to->SetInterface(nsnull);
    1477                 :         }
    1478                 :     }
    1479                 : 
    1480             781 :     if (mFirstChunk.mNextChunk) {
    1481             160 :         delete mFirstChunk.mNextChunk;
    1482             160 :         mFirstChunk.mNextChunk = nsnull;
    1483                 :     }
    1484                 : }
    1485                 : 
    1486                 : /***************************************************************************/
    1487                 : 
    1488                 : // If we have to transplant an object across compartments, we need to be
    1489                 : // careful if the underlying object implements nsWrapperCache and is preserving
    1490                 : // the wrapper.
    1491                 : //
    1492                 : // The class brackets a pair of Unpreserve/Preserve calls in the given scope.
    1493                 : //
    1494                 : // This class _must_ live on the stack, in part so that mPreservedWrapper is
    1495                 : // visible to the stack scanner. The caller wants the wrapper to be preserved,
    1496                 : // so we don't want it to get accidentally GCed.
    1497                 : class AutoWrapperChanger NS_STACK_CLASS {
    1498                 : public:
    1499               0 :     AutoWrapperChanger() : mCache(nsnull)
    1500                 :                          , mCOMObj(nsnull)
    1501               0 :                          , mPreservedWrapper(nsnull)
    1502               0 :     {}
    1503                 : 
    1504               0 :     void init(nsISupports* aCOMObj, nsWrapperCache* aWrapperCache) {
    1505               0 :         mCOMObj = aCOMObj;
    1506               0 :         mCache = aWrapperCache;
    1507               0 :         if (mCache->PreservingWrapper()) {
    1508               0 :             mPreservedWrapper = mCache->GetWrapper();
    1509               0 :             MOZ_ASSERT(mPreservedWrapper);
    1510               0 :             nsContentUtils::ReleaseWrapper(mCOMObj, mCache);
    1511                 :         }
    1512               0 :     }
    1513                 : 
    1514               0 :     ~AutoWrapperChanger() {
    1515               0 :         if (mPreservedWrapper)
    1516               0 :             nsContentUtils::PreserveWrapper(mCOMObj, mCache);
    1517               0 :     }
    1518                 : 
    1519                 : private:
    1520                 :     nsWrapperCache* mCache;
    1521                 :     nsISupports* mCOMObj;
    1522                 :     JSObject* mPreservedWrapper;
    1523                 : };
    1524                 : 
    1525                 : // static
    1526                 : nsresult
    1527               0 : XPCWrappedNative::ReparentWrapperIfFound(XPCCallContext& ccx,
    1528                 :                                          XPCWrappedNativeScope* aOldScope,
    1529                 :                                          XPCWrappedNativeScope* aNewScope,
    1530                 :                                          JSObject* aNewParent,
    1531                 :                                          nsISupports* aCOMObj,
    1532                 :                                          XPCWrappedNative** aWrapper)
    1533                 : {
    1534                 :     XPCNativeInterface* iface =
    1535               0 :         XPCNativeInterface::GetISupports(ccx);
    1536                 : 
    1537               0 :     if (!iface)
    1538               0 :         return NS_ERROR_FAILURE;
    1539                 : 
    1540                 :     nsresult rv;
    1541                 : 
    1542               0 :     nsRefPtr<XPCWrappedNative> wrapper;
    1543               0 :     AutoWrapperChanger wrapperChanger;
    1544                 :     JSObject *flat;
    1545               0 :     nsWrapperCache* cache = nsnull;
    1546               0 :     CallQueryInterface(aCOMObj, &cache);
    1547               0 :     if (cache) {
    1548                 : 
    1549                 :         // There's a wrapper cache. Make sure we keep it sane no matter what
    1550                 :         // happens.
    1551               0 :         wrapperChanger.init(aCOMObj, cache);
    1552                 : 
    1553               0 :         flat = cache->GetWrapper();
    1554               0 :         if (flat && !IS_SLIM_WRAPPER_OBJECT(flat)) {
    1555               0 :             wrapper = static_cast<XPCWrappedNative*>(xpc_GetJSPrivate(flat));
    1556               0 :             NS_ASSERTION(wrapper->GetScope() == aOldScope,
    1557                 :                          "Incorrect scope passed");
    1558                 :         }
    1559                 :     } else {
    1560                 :         rv = XPCWrappedNative::GetUsedOnly(ccx, aCOMObj, aOldScope, iface,
    1561               0 :                                            getter_AddRefs(wrapper));
    1562               0 :         if (NS_FAILED(rv))
    1563               0 :             return rv;
    1564                 : 
    1565               0 :         flat = wrapper->GetFlatJSObject();
    1566                 :     }
    1567                 : 
    1568               0 :     if (!flat) {
    1569               0 :         *aWrapper = nsnull;
    1570               0 :         return NS_OK;
    1571                 :     }
    1572                 : 
    1573               0 :     bool crosscompartment = js::GetObjectCompartment(aOldScope->GetGlobalJSObject()) !=
    1574               0 :                             js::GetObjectCompartment(aNewScope->GetGlobalJSObject());
    1575                 : #ifdef DEBUG
    1576               0 :     if (crosscompartment) {
    1577               0 :         NS_ASSERTION(aNewParent, "won't be able to find the new parent");
    1578               0 :         NS_ASSERTION(wrapper, "can't transplant slim wrappers");
    1579                 :     }
    1580                 : #endif
    1581                 : 
    1582                 :     // ReparentWrapperIfFound is really only meant to be called from DOM code
    1583                 :     // which must happen only on the main thread. Bail if we're on some other
    1584                 :     // thread or have a non-main-thread-only wrapper.
    1585               0 :     if (!XPCPerThreadData::IsMainThread(ccx) ||
    1586                 :         (wrapper &&
    1587               0 :          wrapper->GetProto() &&
    1588               0 :          !wrapper->GetProto()->ClassIsMainThreadOnly())) {
    1589               0 :         return NS_ERROR_FAILURE;
    1590                 :     }
    1591                 : 
    1592               0 :     JSAutoEnterCompartment ac;
    1593               0 :     if (!ac.enter(ccx, aNewScope->GetGlobalJSObject()))
    1594               0 :         return NS_ERROR_FAILURE;
    1595                 : 
    1596               0 :     if (aOldScope != aNewScope) {
    1597                 :         // Oh, so now we need to move the wrapper to a different scope.
    1598               0 :         AutoMarkingWrappedNativeProtoPtr oldProto(ccx);
    1599               0 :         AutoMarkingWrappedNativeProtoPtr newProto(ccx);
    1600                 : 
    1601               0 :         if (!wrapper)
    1602               0 :             oldProto = GetSlimWrapperProto(flat);
    1603               0 :         else if (wrapper->HasProto())
    1604               0 :             oldProto = wrapper->GetProto();
    1605                 : 
    1606               0 :         if (oldProto) {
    1607               0 :             XPCNativeScriptableInfo *info = oldProto->GetScriptableInfo();
    1608               0 :             XPCNativeScriptableCreateInfo ci(*info);
    1609                 :             newProto =
    1610                 :                 XPCWrappedNativeProto::GetNewOrUsed(ccx, aNewScope,
    1611                 :                                                     oldProto->GetClassInfo(),
    1612               0 :                                                     &ci, oldProto->GetOffsetsMasked());
    1613               0 :             if (!newProto) {
    1614               0 :                 return NS_ERROR_FAILURE;
    1615                 :             }
    1616                 :         }
    1617                 : 
    1618               0 :         if (wrapper) {
    1619               0 :             Native2WrappedNativeMap* oldMap = aOldScope->GetWrappedNativeMap();
    1620               0 :             Native2WrappedNativeMap* newMap = aNewScope->GetWrappedNativeMap();
    1621                 : 
    1622                 :             {   // scoped lock
    1623               0 :                 XPCAutoLock lock(aOldScope->GetRuntime()->GetMapLock());
    1624                 : 
    1625               0 :                 oldMap->Remove(wrapper);
    1626                 : 
    1627               0 :                 if (wrapper->HasProto())
    1628               0 :                     wrapper->SetProto(newProto);
    1629                 : 
    1630                 :                 // If the wrapper has no scriptable or it has a non-shared
    1631                 :                 // scriptable, then we don't need to mess with it.
    1632                 :                 // Otherwise...
    1633                 : 
    1634               0 :                 if (wrapper->mScriptableInfo &&
    1635               0 :                     wrapper->mScriptableInfo == oldProto->GetScriptableInfo()) {
    1636                 :                     // The new proto had better have the same JSClass stuff as
    1637                 :                     // the old one! We maintain a runtime wide unique map of
    1638                 :                     // this stuff. So, if these don't match then the caller is
    1639                 :                     // doing something bad here.
    1640                 : 
    1641               0 :                     NS_ASSERTION(oldProto->GetScriptableInfo()->GetScriptableShared() ==
    1642                 :                                  newProto->GetScriptableInfo()->GetScriptableShared(),
    1643                 :                                  "Changing proto is also changing JSObject Classname or "
    1644                 :                                  "helper's nsIXPScriptable flags. This is not allowed!");
    1645                 : 
    1646               0 :                     wrapper->UpdateScriptableInfo(newProto->GetScriptableInfo());
    1647                 :                 }
    1648                 : 
    1649               0 :                 NS_ASSERTION(!newMap->Find(wrapper->GetIdentityObject()),
    1650                 :                              "wrapper already in new scope!");
    1651                 : 
    1652               0 :                 (void) newMap->Add(wrapper);
    1653                 :             }
    1654                 : 
    1655                 :             // We only try to fixup the __proto__ JSObject if the wrapper
    1656                 :             // is directly using that of its XPCWrappedNativeProto.
    1657                 : 
    1658               0 :             if (crosscompartment) {
    1659                 :                 JSObject *newobj = JS_CloneObject(ccx, flat,
    1660                 :                                                   newProto->GetJSProtoObject(),
    1661               0 :                                                   aNewParent);
    1662               0 :                 if (!newobj)
    1663               0 :                     return NS_ERROR_FAILURE;
    1664                 : 
    1665               0 :                 JS_SetPrivate(flat, nsnull);
    1666                 : 
    1667                 :                 JSObject *propertyHolder =
    1668               0 :                     JS_NewObjectWithGivenProto(ccx, NULL, NULL, aNewParent);
    1669               0 :                 if (!propertyHolder || !JS_CopyPropertiesFrom(ccx, propertyHolder, flat))
    1670               0 :                     return NS_ERROR_OUT_OF_MEMORY;
    1671                 : 
    1672               0 :                 JSObject *ww = wrapper->GetWrapper();
    1673               0 :                 if (ww) {
    1674                 :                     JSObject *newwrapper;
    1675               0 :                     if (xpc::WrapperFactory::IsLocationObject(flat)) {
    1676               0 :                         newwrapper = xpc::WrapperFactory::WrapLocationObject(ccx, newobj);
    1677               0 :                         if (!newwrapper)
    1678               0 :                             return NS_ERROR_FAILURE;
    1679                 :                     } else {
    1680               0 :                         NS_ASSERTION(wrapper->NeedsSOW(), "weird wrapper wrapper");
    1681               0 :                         newwrapper = xpc::WrapperFactory::WrapSOWObject(ccx, newobj);
    1682               0 :                         if (!newwrapper)
    1683               0 :                             return NS_ERROR_FAILURE;
    1684                 :                     }
    1685                 : 
    1686                 :                     ww = js_TransplantObjectWithWrapper(ccx, flat, ww, newobj,
    1687               0 :                                                         newwrapper);
    1688               0 :                     if (!ww)
    1689               0 :                         return NS_ERROR_FAILURE;
    1690               0 :                     flat = newobj;
    1691               0 :                     wrapper->SetWrapper(ww);
    1692                 :                 } else {
    1693               0 :                     flat = JS_TransplantObject(ccx, flat, newobj);
    1694               0 :                     if (!flat)
    1695               0 :                         return NS_ERROR_FAILURE;
    1696                 :                 }
    1697                 : 
    1698               0 :                 wrapper->mFlatJSObject = flat;
    1699               0 :                 if (cache)
    1700               0 :                     cache->SetWrapper(flat);
    1701               0 :                 if (!JS_CopyPropertiesFrom(ccx, flat, propertyHolder))
    1702               0 :                     return NS_ERROR_FAILURE;
    1703                 :             } else {
    1704               0 :                 if (wrapper->HasProto() &&
    1705               0 :                     js::GetObjectProto(flat) == oldProto->GetJSProtoObject()) {
    1706               0 :                     if (!JS_SetPrototype(ccx, flat, newProto->GetJSProtoObject())) {
    1707                 :                         // this is bad, very bad
    1708               0 :                         NS_ERROR("JS_SetPrototype failed");
    1709               0 :                         return NS_ERROR_FAILURE;
    1710                 :                     }
    1711                 :                 } else {
    1712                 :                     NS_WARNING("Moving XPConnect wrappedNative to new scope, "
    1713               0 :                                "but can't fixup __proto__");
    1714                 :                 }
    1715                 :             }
    1716                 :         } else {
    1717                 :             JS_SetReservedSlot(flat, 0,
    1718               0 :                                PRIVATE_TO_JSVAL(newProto.get()));
    1719               0 :             if (!JS_SetPrototype(ccx, flat, newProto->GetJSProtoObject())) {
    1720                 :                 // this is bad, very bad
    1721               0 :                 JS_SetReservedSlot(flat, 0, JSVAL_NULL);
    1722               0 :                 NS_ERROR("JS_SetPrototype failed");
    1723               0 :                 return NS_ERROR_FAILURE;
    1724                 :             }
    1725                 :         }
    1726                 :     }
    1727                 : 
    1728                 :     // Now we can just fix up the parent and return the wrapper
    1729                 : 
    1730               0 :     if (aNewParent) {
    1731               0 :         if (!JS_SetParent(ccx, flat, aNewParent))
    1732               0 :             return NS_ERROR_FAILURE;
    1733                 : 
    1734                 :         JSObject *nw;
    1735               0 :         if (wrapper &&
    1736               0 :             (nw = wrapper->GetWrapper()) &&
    1737               0 :             !JS_SetParent(ccx, nw, JS_GetGlobalForObject(ccx, aNewParent))) {
    1738               0 :             return NS_ERROR_FAILURE;
    1739                 :         }
    1740                 :     }
    1741                 : 
    1742               0 :     *aWrapper = nsnull;
    1743               0 :     wrapper.swap(*aWrapper);
    1744                 : 
    1745               0 :     return NS_OK;
    1746                 : }
    1747                 : 
    1748                 : #define IS_TEAROFF_CLASS(clazz)                                               \
    1749                 :           ((clazz) == &XPC_WN_Tearoff_JSClass)
    1750                 : 
    1751                 : // static
    1752                 : XPCWrappedNative*
    1753        16800957 : XPCWrappedNative::GetWrappedNativeOfJSObject(JSContext* cx,
    1754                 :                                              JSObject* obj,
    1755                 :                                              JSObject* funobj,
    1756                 :                                              JSObject** pobj2,
    1757                 :                                              XPCWrappedNativeTearOff** pTearOff)
    1758                 : {
    1759        16800957 :     NS_PRECONDITION(obj, "bad param");
    1760                 : 
    1761                 :     // fubobj must be null if called without cx.
    1762        16800957 :     NS_PRECONDITION(cx || !funobj, "bad param");
    1763                 : 
    1764                 :     // *pTeaorOff must be null if pTearOff is given
    1765        16800957 :     NS_PRECONDITION(!pTearOff || !*pTearOff, "bad param");
    1766                 : 
    1767                 :     JSObject* cur;
    1768                 : 
    1769        16800957 :     XPCWrappedNativeProto* proto = nsnull;
    1770        16800957 :     nsIClassInfo* protoClassInfo = nsnull;
    1771                 : 
    1772                 :     // If we were passed a function object then we need to find the correct
    1773                 :     // wrapper out of those that might be in the callee obj's proto chain.
    1774                 : 
    1775        16800957 :     if (funobj) {
    1776         7351529 :         JSObject* funObjParent = js::UnwrapObject(js::GetObjectParent(funobj));
    1777         7351529 :         funObjParent = JS_ObjectToInnerObject(cx, funObjParent);
    1778         7351529 :         NS_ASSERTION(funObjParent, "funobj has no parent");
    1779                 : 
    1780         7351529 :         js::Class* funObjParentClass = js::GetObjectClass(funObjParent);
    1781                 : 
    1782         7351529 :         if (IS_PROTO_CLASS(funObjParentClass)) {
    1783         1848702 :             NS_ASSERTION(js::GetObjectParent(funObjParent), "funobj's parent (proto) is global");
    1784         1848702 :             proto = (XPCWrappedNativeProto*) js::GetObjectPrivate(funObjParent);
    1785         1848702 :             if (proto)
    1786         1848702 :                 protoClassInfo = proto->GetClassInfo();
    1787         5502827 :         } else if (IS_WRAPPER_CLASS(funObjParentClass)) {
    1788         5502737 :             cur = funObjParent;
    1789         5502737 :             goto return_wrapper;
    1790              90 :         } else if (IS_TEAROFF_CLASS(funObjParentClass)) {
    1791              90 :             NS_ASSERTION(js::GetObjectParent(funObjParent), "funobj's parent (tearoff) is global");
    1792              90 :             cur = funObjParent;
    1793              90 :             goto return_tearoff;
    1794                 :         } else {
    1795               0 :             NS_ERROR("function object has parent of unknown class!");
    1796               0 :             return nsnull;
    1797                 :         }
    1798                 :     }
    1799                 : 
    1800                 :   restart:
    1801        11721052 :     for (cur = obj; cur; cur = js::GetObjectProto(cur)) {
    1802                 :         // this is on two lines to make the compiler happy given the goto.
    1803                 :         js::Class* clazz;
    1804        11554512 :         clazz = js::GetObjectClass(cur);
    1805                 : 
    1806        11554512 :         if (IS_WRAPPER_CLASS(clazz)) {
    1807                 : return_wrapper:
    1808        16634169 :             JSBool isWN = IS_WN_WRAPPER_OBJECT(cur);
    1809                 :             XPCWrappedNative* wrapper =
    1810        16634169 :                 isWN ? (XPCWrappedNative*) js::GetObjectPrivate(cur) : nsnull;
    1811        16634169 :             if (proto) {
    1812                 :                 XPCWrappedNativeProto* wrapper_proto =
    1813         1848702 :                     isWN ? wrapper->GetProto() : GetSlimWrapperProto(cur);
    1814         1848702 :                 if (proto != wrapper_proto &&
    1815                 :                     (!protoClassInfo || !wrapper_proto ||
    1816               0 :                      protoClassInfo != wrapper_proto->GetClassInfo()))
    1817               0 :                     continue;
    1818                 :             }
    1819        16634169 :             if (pobj2)
    1820        15017356 :                 *pobj2 = isWN ? nsnull : cur;
    1821        16634169 :             return wrapper;
    1822                 :         }
    1823                 : 
    1824          423080 :         if (IS_TEAROFF_CLASS(clazz)) {
    1825                 : return_tearoff:
    1826                 :             XPCWrappedNative* wrapper =
    1827             248 :                 (XPCWrappedNative*) js::GetObjectPrivate(js::GetObjectParent(cur));
    1828             248 :             if (proto && proto != wrapper->GetProto() &&
    1829               0 :                 (proto->GetScope() != wrapper->GetScope() ||
    1830               0 :                  !protoClassInfo || !wrapper->GetProto() ||
    1831               0 :                  protoClassInfo != wrapper->GetProto()->GetClassInfo()))
    1832               0 :                 continue;
    1833             248 :             if (pobj2)
    1834             248 :                 *pobj2 = nsnull;
    1835             248 :             XPCWrappedNativeTearOff* to = (XPCWrappedNativeTearOff*) js::GetObjectPrivate(cur);
    1836             248 :             if (!to)
    1837               0 :                 return nsnull;
    1838             248 :             if (pTearOff)
    1839             248 :                 *pTearOff = to;
    1840             248 :             return wrapper;
    1841                 :         }
    1842                 : 
    1843                 :         // Unwrap any wrapper wrappers.
    1844                 :         JSObject *unsafeObj = cx
    1845                 :                               ? XPCWrapper::Unwrap(cx, cur)
    1846          422922 :                               : XPCWrapper::UnsafeUnwrapSecurityWrapper(cur);
    1847          422922 :         if (unsafeObj) {
    1848               0 :             obj = unsafeObj;
    1849               0 :             goto restart;
    1850                 :         }
    1851                 :     }
    1852                 : 
    1853          166540 :     if (pobj2)
    1854            5963 :         *pobj2 = nsnull;
    1855          166540 :     return nsnull;
    1856                 : }
    1857                 : 
    1858                 : JSBool
    1859          141059 : XPCWrappedNative::ExtendSet(XPCCallContext& ccx, XPCNativeInterface* aInterface)
    1860                 : {
    1861                 :     // This is only called while locked (during XPCWrappedNative::FindTearOff).
    1862                 : 
    1863          141059 :     if (!mSet->HasInterface(aInterface)) {
    1864          282118 :         AutoMarkingNativeSetPtr newSet(ccx);
    1865                 :         newSet = XPCNativeSet::GetNewOrUsed(ccx, mSet, aInterface,
    1866          141059 :                                             mSet->GetInterfaceCount());
    1867          141059 :         if (!newSet)
    1868               0 :             return false;
    1869                 : 
    1870          282118 :         mSet = newSet;
    1871                 : 
    1872                 :         DEBUG_ReportShadowedMembers(newSet, this, GetProto());
    1873                 :     }
    1874          141059 :     return true;
    1875                 : }
    1876                 : 
    1877                 : XPCWrappedNativeTearOff*
    1878               0 : XPCWrappedNative::LocateTearOff(XPCCallContext& ccx,
    1879                 :                                 XPCNativeInterface* aInterface)
    1880                 : {
    1881               0 :     XPCAutoLock al(GetLock()); // hold the lock throughout
    1882                 : 
    1883               0 :     for (XPCWrappedNativeTearOffChunk* chunk = &mFirstChunk;
    1884                 :          chunk != nsnull;
    1885                 :          chunk = chunk->mNextChunk) {
    1886               0 :         XPCWrappedNativeTearOff* tearOff = chunk->mTearOffs;
    1887                 :         XPCWrappedNativeTearOff* const end = tearOff +
    1888               0 :             XPC_WRAPPED_NATIVE_TEAROFFS_PER_CHUNK;
    1889               0 :         for (tearOff = chunk->mTearOffs;
    1890                 :              tearOff < end;
    1891                 :              tearOff++) {
    1892               0 :             if (tearOff->GetInterface() == aInterface) {
    1893               0 :                 return tearOff;
    1894                 :             }
    1895                 :         }
    1896                 :     }
    1897               0 :     return nsnull;
    1898                 : }
    1899                 : 
    1900                 : XPCWrappedNativeTearOff*
    1901         9499507 : XPCWrappedNative::FindTearOff(XPCCallContext& ccx,
    1902                 :                               XPCNativeInterface* aInterface,
    1903                 :                               JSBool needJSObject /* = false */,
    1904                 :                               nsresult* pError /* = nsnull */)
    1905                 : {
    1906        18999014 :     XPCAutoLock al(GetLock()); // hold the lock throughout
    1907                 : 
    1908         9499507 :     nsresult rv = NS_OK;
    1909                 :     XPCWrappedNativeTearOff* to;
    1910         9499507 :     XPCWrappedNativeTearOff* firstAvailable = nsnull;
    1911                 : 
    1912                 :     XPCWrappedNativeTearOffChunk* lastChunk;
    1913                 :     XPCWrappedNativeTearOffChunk* chunk;
    1914        11736285 :     for (lastChunk = chunk = &mFirstChunk;
    1915                 :          chunk;
    1916                 :          lastChunk = chunk, chunk = chunk->mNextChunk) {
    1917        10226428 :         to = chunk->mTearOffs;
    1918                 :         XPCWrappedNativeTearOff* const end = chunk->mTearOffs +
    1919        10226428 :             XPC_WRAPPED_NATIVE_TEAROFFS_PER_CHUNK;
    1920        12463206 :         for (to = chunk->mTearOffs;
    1921                 :              to < end;
    1922                 :              to++) {
    1923        10226428 :             if (to->GetInterface() == aInterface) {
    1924         7989650 :                 if (needJSObject && !to->GetJSObjectPreserveColor()) {
    1925              42 :                     AutoMarkingWrappedNativeTearOffPtr tearoff(ccx, to);
    1926              21 :                     JSBool ok = InitTearOffJSObject(ccx, to);
    1927                 :                     // During shutdown, we don't sweep tearoffs.  So make sure
    1928                 :                     // to unmark manually in case the auto-marker marked us.
    1929                 :                     // We shouldn't ever be getting here _during_ our
    1930                 :                     // Mark/Sweep cycle, so this should be safe.
    1931              21 :                     to->Unmark();
    1932              21 :                     if (!ok) {
    1933               0 :                         to = nsnull;
    1934               0 :                         rv = NS_ERROR_OUT_OF_MEMORY;
    1935                 :                     }
    1936                 :                 }
    1937         7989650 :                 goto return_result;
    1938                 :             }
    1939         2236778 :             if (!firstAvailable && to->IsAvailable())
    1940         1327890 :                 firstAvailable = to;
    1941                 :         }
    1942                 :     }
    1943                 : 
    1944         1509857 :     to = firstAvailable;
    1945                 : 
    1946         1509857 :     if (!to) {
    1947                 :         XPCWrappedNativeTearOffChunk* newChunk =
    1948          181999 :             new XPCWrappedNativeTearOffChunk();
    1949          181999 :         if (!newChunk) {
    1950               0 :             rv = NS_ERROR_OUT_OF_MEMORY;
    1951               0 :             goto return_result;
    1952                 :         }
    1953          181999 :         lastChunk->mNextChunk = newChunk;
    1954          181999 :         to = newChunk->mTearOffs;
    1955                 :     }
    1956                 : 
    1957                 :     {
    1958                 :         // Scope keeps |tearoff| from leaking across the return_result: label
    1959         3019714 :         AutoMarkingWrappedNativeTearOffPtr tearoff(ccx, to);
    1960         1509857 :         rv = InitTearOff(ccx, to, aInterface, needJSObject);
    1961                 :         // During shutdown, we don't sweep tearoffs.  So make sure to unmark
    1962                 :         // manually in case the auto-marker marked us.  We shouldn't ever be
    1963                 :         // getting here _during_ our Mark/Sweep cycle, so this should be safe.
    1964         1509857 :         to->Unmark();
    1965         1509857 :         if (NS_FAILED(rv))
    1966            6160 :             to = nsnull;
    1967                 :     }
    1968                 : 
    1969                 : return_result:
    1970                 : 
    1971         9499507 :     if (pError)
    1972         9499486 :         *pError = rv;
    1973         9499507 :     return to;
    1974                 : }
    1975                 : 
    1976                 : nsresult
    1977         1509857 : XPCWrappedNative::InitTearOff(XPCCallContext& ccx,
    1978                 :                               XPCWrappedNativeTearOff* aTearOff,
    1979                 :                               XPCNativeInterface* aInterface,
    1980                 :                               JSBool needJSObject)
    1981                 : {
    1982                 :     // This is only called while locked (during XPCWrappedNative::FindTearOff).
    1983                 : 
    1984                 :     // Determine if the object really does this interface...
    1985                 : 
    1986         1509857 :     const nsIID* iid = aInterface->GetIID();
    1987         1509857 :     nsISupports* identity = GetIdentityObject();
    1988                 :     nsISupports* obj;
    1989                 : 
    1990                 :     // If the scriptable helper forbids us from reflecting additional
    1991                 :     // interfaces, then don't even try the QI, just fail.
    1992         1909435 :     if (mScriptableInfo &&
    1993          373902 :         mScriptableInfo->GetFlags().ClassInfoInterfacesOnly() &&
    1994           20600 :         !mSet->HasInterface(aInterface) &&
    1995            5076 :         !mSet->HasInterfaceWithAncestor(aInterface)) {
    1996            4999 :         return NS_ERROR_NO_INTERFACE;
    1997                 :     }
    1998                 : 
    1999                 :     // We are about to call out to unlock and other code.
    2000                 :     // So protect our intended tearoff.
    2001                 : 
    2002         1504858 :     aTearOff->SetReserved();
    2003                 : 
    2004                 :     {   // scoped *un*lock
    2005         3009716 :         XPCAutoUnlock unlock(GetLock());
    2006                 : 
    2007         1504858 :         if (NS_FAILED(identity->QueryInterface(*iid, (void**)&obj)) || !obj) {
    2008            1160 :             aTearOff->SetInterface(nsnull);
    2009            1160 :             return NS_ERROR_NO_INTERFACE;
    2010                 :         }
    2011                 : 
    2012                 :         // Guard against trying to build a tearoff for a shared nsIClassInfo.
    2013         1503698 :         if (iid->Equals(NS_GET_IID(nsIClassInfo))) {
    2014              36 :             nsCOMPtr<nsISupports> alternate_identity(do_QueryInterface(obj));
    2015              18 :             if (alternate_identity.get() != identity) {
    2016               0 :                 NS_RELEASE(obj);
    2017               0 :                 aTearOff->SetInterface(nsnull);
    2018               0 :                 return NS_ERROR_NO_INTERFACE;
    2019                 :             }
    2020                 :         }
    2021                 : 
    2022                 :         // Guard against trying to build a tearoff for an interface that is
    2023                 :         // aggregated and is implemented as a nsIXPConnectWrappedJS using this
    2024                 :         // self-same JSObject. The XBL system does this. If we mutate the set
    2025                 :         // of this wrapper then we will shadow the method that XBL has added to
    2026                 :         // the JSObject that it has inserted in the JS proto chain between our
    2027                 :         // JSObject and our XPCWrappedNativeProto's JSObject. If we let this
    2028                 :         // set mutation happen then the interface's methods will be added to
    2029                 :         // our JSObject, but calls on those methods will get routed up to
    2030                 :         // native code and into the wrappedJS - which will do a method lookup
    2031                 :         // on *our* JSObject and find the same method and make another call
    2032                 :         // into an infinite loop.
    2033                 :         // see: http://bugzilla.mozilla.org/show_bug.cgi?id=96725
    2034                 : 
    2035                 :         // The code in this block also does a check for the double wrapped
    2036                 :         // nsIPropertyBag case.
    2037                 : 
    2038         3007396 :         nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS(do_QueryInterface(obj));
    2039         1503698 :         if (wrappedJS) {
    2040           23845 :             JSObject* jso = nsnull;
    2041           23845 :             if (NS_SUCCEEDED(wrappedJS->GetJSObject(&jso)) &&
    2042                 :                 jso == mFlatJSObject) {
    2043                 :                 // The implementing JSObject is the same as ours! Just say OK
    2044                 :                 // without actually extending the set.
    2045                 :                 //
    2046                 :                 // XXX It is a little cheesy to have FindTearOff return an
    2047                 :                 // 'empty' tearoff. But this is the centralized place to do the
    2048                 :                 // QI activities on the underlying object. *And* most caller to
    2049                 :                 // FindTearOff only look for a non-null result and ignore the
    2050                 :                 // actual tearoff returned. The only callers that do use the
    2051                 :                 // returned tearoff make sure to check for either a non-null
    2052                 :                 // JSObject or a matching Interface before proceeding.
    2053                 :                 // I think we can get away with this bit of ugliness.
    2054                 : 
    2055                 : #ifdef DEBUG_xpc_hacker
    2056                 :                 {
    2057                 :                     // I want to make sure this only happens in xbl-like cases.
    2058                 :                     // So, some debug code to verify that there is at least
    2059                 :                     // *some* object between our JSObject and its inital proto.
    2060                 :                     // XXX This is a pretty funky test. Someone might hack it
    2061                 :                     // a bit if false positives start showing up. Note that
    2062                 :                     // this is only going to run for the few people in the
    2063                 :                     // DEBUG_xpc_hacker list.
    2064                 :                     if (HasProto()) {
    2065                 :                         JSObject* proto  = nsnull;
    2066                 :                         JSObject* our_proto = GetProto()->GetJSProtoObject();
    2067                 : 
    2068                 :                         proto = jso->getProto();
    2069                 : 
    2070                 :                         NS_ASSERTION(proto && proto != our_proto,
    2071                 :                                      "!!! xpconnect/xbl check - wrapper has no special proto");
    2072                 : 
    2073                 :                         bool found_our_proto = false;
    2074                 :                         while (proto && !found_our_proto) {
    2075                 :                             proto = proto->getProto();
    2076                 : 
    2077                 :                             found_our_proto = proto == our_proto;
    2078                 :                         }
    2079                 : 
    2080                 :                         NS_ASSERTION(found_our_proto,
    2081                 :                                      "!!! xpconnect/xbl check - wrapper has extra proto");
    2082                 :                     } else {
    2083                 :                         NS_WARNING("!!! xpconnect/xbl check - wrapper has no proto");
    2084                 :                     }
    2085                 :                 }
    2086                 : #endif
    2087               0 :                 NS_RELEASE(obj);
    2088               0 :                 aTearOff->SetInterface(nsnull);
    2089               0 :                 return NS_OK;
    2090                 :             }
    2091                 : 
    2092                 :             // Decide whether or not to expose nsIPropertyBag to calling
    2093                 :             // JS code in the double wrapped case.
    2094                 :             //
    2095                 :             // Our rule here is that when JSObjects are double wrapped and
    2096                 :             // exposed to other JSObjects then the nsIPropertyBag interface
    2097                 :             // is only exposed on an 'opt-in' basis; i.e. if the underlying
    2098                 :             // JSObject wants other JSObjects to be able to see this interface
    2099                 :             // then it must implement QueryInterface and not throw an exception
    2100                 :             // when asked for nsIPropertyBag. It need not actually *implement*
    2101                 :             // nsIPropertyBag - xpconnect will do that work.
    2102                 : 
    2103                 :             nsXPCWrappedJSClass* clazz;
    2104           23849 :             if (iid->Equals(NS_GET_IID(nsIPropertyBag)) && jso &&
    2105               4 :                 NS_SUCCEEDED(nsXPCWrappedJSClass::GetNewOrUsed(ccx,*iid,&clazz))&&
    2106                 :                 clazz) {
    2107                 :                 JSObject* answer =
    2108               4 :                     clazz->CallQueryInterfaceOnJSObject(ccx, jso, *iid);
    2109               4 :                 NS_RELEASE(clazz);
    2110               4 :                 if (!answer) {
    2111               1 :                     NS_RELEASE(obj);
    2112               1 :                     aTearOff->SetInterface(nsnull);
    2113               1 :                     return NS_ERROR_NO_INTERFACE;
    2114                 :                 }
    2115                 :             }
    2116                 :         }
    2117                 : 
    2118                 :         nsIXPCSecurityManager* sm;
    2119         1503697 :            sm = ccx.GetXPCContext()->GetAppropriateSecurityManager(nsIXPCSecurityManager::HOOK_CREATE_WRAPPER);
    2120         1503697 :         if (sm && NS_FAILED(sm->
    2121                 :                             CanCreateWrapper(ccx, *iid, identity,
    2122                 :                                              GetClassInfo(), GetSecurityInfoAddr()))) {
    2123                 :             // the security manager vetoed. It should have set an exception.
    2124               0 :             NS_RELEASE(obj);
    2125               0 :             aTearOff->SetInterface(nsnull);
    2126               0 :             return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
    2127                 :         }
    2128                 :     }
    2129                 :     // We are relocked from here on...
    2130                 : 
    2131                 :     // If this is not already in our set we need to extend our set.
    2132                 :     // Note: we do not cache the result of the previous call to HasInterface()
    2133                 :     // because we unlocked and called out in the interim and the result of the
    2134                 :     // previous call might not be correct anymore.
    2135                 : 
    2136         1503697 :     if (!mSet->HasInterface(aInterface) && !ExtendSet(ccx, aInterface)) {
    2137               0 :         NS_RELEASE(obj);
    2138               0 :         aTearOff->SetInterface(nsnull);
    2139               0 :         return NS_ERROR_NO_INTERFACE;
    2140                 :     }
    2141                 : 
    2142         1503697 :     aTearOff->SetInterface(aInterface);
    2143         1503697 :     aTearOff->SetNative(obj);
    2144         1503697 :     if (needJSObject && !InitTearOffJSObject(ccx, aTearOff))
    2145               0 :         return NS_ERROR_OUT_OF_MEMORY;
    2146                 : 
    2147         1503697 :     return NS_OK;
    2148                 : }
    2149                 : 
    2150                 : JSBool
    2151              60 : XPCWrappedNative::InitTearOffJSObject(XPCCallContext& ccx,
    2152                 :                                       XPCWrappedNativeTearOff* to)
    2153                 : {
    2154                 :     // This is only called while locked (during XPCWrappedNative::FindTearOff).
    2155                 : 
    2156                 :     JSObject* obj =
    2157                 :         xpc_NewSystemInheritingJSObject(ccx, Jsvalify(&XPC_WN_Tearoff_JSClass),
    2158                 :                                         GetScope()->GetPrototypeJSObject(),
    2159              60 :                                         false, mFlatJSObject);
    2160                 : 
    2161              60 :     if (!obj)
    2162               0 :         return false;
    2163                 : 
    2164              60 :     JS_SetPrivate(obj, to);
    2165              60 :     to->SetJSObject(obj);
    2166              60 :     return true;
    2167                 : }
    2168                 : 
    2169                 : /***************************************************************************/
    2170                 : 
    2171               3 : static JSBool Throw(unsigned errNum, XPCCallContext& ccx)
    2172                 : {
    2173               3 :     XPCThrower::Throw(errNum, ccx);
    2174               3 :     return false;
    2175                 : }
    2176                 : 
    2177                 : /***************************************************************************/
    2178                 : 
    2179                 : class CallMethodHelper
    2180                 : {
    2181                 :     XPCCallContext& mCallContext;
    2182                 :     nsIInterfaceInfo* const mIFaceInfo;
    2183                 :     const nsXPTMethodInfo* mMethodInfo;
    2184                 :     nsISupports* const mCallee;
    2185                 :     const uint16_t mVTableIndex;
    2186                 :     const jsid mIdxValueId;
    2187                 : 
    2188                 :     nsAutoTArray<nsXPTCVariant, 8> mDispatchParams;
    2189                 :     uint8_t mJSContextIndex; // TODO make const
    2190                 :     uint8_t mOptArgcIndex; // TODO make const
    2191                 : 
    2192                 :     jsval* const mArgv;
    2193                 :     const PRUint32 mArgc;
    2194                 : 
    2195                 :     JS_ALWAYS_INLINE JSBool
    2196                 :     GetArraySizeFromParam(uint8_t paramIndex, uint32_t* result) const;
    2197                 : 
    2198                 :     JS_ALWAYS_INLINE JSBool
    2199                 :     GetInterfaceTypeFromParam(uint8_t paramIndex,
    2200                 :                               const nsXPTType& datum_type,
    2201                 :                               nsID* result) const;
    2202                 : 
    2203                 :     JS_ALWAYS_INLINE JSBool
    2204                 :     GetOutParamSource(uint8_t paramIndex, jsval* srcp) const;
    2205                 : 
    2206                 :     JS_ALWAYS_INLINE JSBool
    2207                 :     GatherAndConvertResults();
    2208                 : 
    2209                 :     JS_ALWAYS_INLINE JSBool
    2210                 :     QueryInterfaceFastPath() const;
    2211                 : 
    2212                 :     nsXPTCVariant*
    2213        29584757 :     GetDispatchParam(uint8_t paramIndex)
    2214                 :     {
    2215        29584757 :         if (paramIndex >= mJSContextIndex)
    2216          718514 :             paramIndex += 1;
    2217        29584757 :         if (paramIndex >= mOptArgcIndex)
    2218          698326 :             paramIndex += 1;
    2219        29584757 :         return &mDispatchParams[paramIndex];
    2220                 :     }
    2221                 :     const nsXPTCVariant*
    2222          101714 :     GetDispatchParam(uint8_t paramIndex) const
    2223                 :     {
    2224          101714 :         return const_cast<CallMethodHelper*>(this)->GetDispatchParam(paramIndex);
    2225                 :     }
    2226                 : 
    2227                 :     JS_ALWAYS_INLINE JSBool InitializeDispatchParams();
    2228                 : 
    2229                 :     JS_ALWAYS_INLINE JSBool ConvertIndependentParams(JSBool* foundDependentParam);
    2230                 :     JS_ALWAYS_INLINE JSBool ConvertIndependentParam(uint8_t i);
    2231                 :     JS_ALWAYS_INLINE JSBool ConvertDependentParams();
    2232                 :     JS_ALWAYS_INLINE JSBool ConvertDependentParam(uint8_t i);
    2233                 : 
    2234                 :     JS_ALWAYS_INLINE void CleanupParam(nsXPTCMiniVariant& param, nsXPTType& type);
    2235                 : 
    2236                 :     JS_ALWAYS_INLINE JSBool HandleDipperParam(nsXPTCVariant* dp,
    2237                 :                                               const nsXPTParamInfo& paramInfo);
    2238                 : 
    2239                 :     JS_ALWAYS_INLINE nsresult Invoke();
    2240                 : 
    2241                 : public:
    2242                 : 
    2243         7371823 :     CallMethodHelper(XPCCallContext& ccx)
    2244                 :         : mCallContext(ccx)
    2245         7371823 :         , mIFaceInfo(ccx.GetInterface()->GetInterfaceInfo())
    2246                 :         , mMethodInfo(nsnull)
    2247         7371823 :         , mCallee(ccx.GetTearOff()->GetNative())
    2248         7371823 :         , mVTableIndex(ccx.GetMethodIndex())
    2249         7371823 :         , mIdxValueId(ccx.GetRuntime()->GetStringID(XPCJSRuntime::IDX_VALUE))
    2250                 :         , mJSContextIndex(PR_UINT8_MAX)
    2251                 :         , mOptArgcIndex(PR_UINT8_MAX)
    2252         7371823 :         , mArgv(ccx.GetArgv())
    2253        44230938 :         , mArgc(ccx.GetArgc())
    2254                 : 
    2255                 :     {
    2256                 :         // Success checked later.
    2257         7371823 :         mIFaceInfo->GetMethodInfo(mVTableIndex, &mMethodInfo);
    2258         7371823 :     }
    2259                 : 
    2260                 :     ~CallMethodHelper();
    2261                 : 
    2262                 :     JS_ALWAYS_INLINE JSBool Call();
    2263                 : 
    2264                 : };
    2265                 : 
    2266                 : // static
    2267                 : NS_SUPPRESS_STACK_CHECK JSBool
    2268         7371823 : XPCWrappedNative::CallMethod(XPCCallContext& ccx,
    2269                 :                              CallMode mode /*= CALL_METHOD */)
    2270                 : {
    2271         7371823 :     XPCContext* xpcc = ccx.GetXPCContext();
    2272         7371823 :     NS_ASSERTION(xpcc->CallerTypeIsJavaScript(),
    2273                 :                  "Native caller for XPCWrappedNative::CallMethod?");
    2274                 : 
    2275         7371823 :     nsresult rv = ccx.CanCallNow();
    2276         7371823 :     if (NS_FAILED(rv)) {
    2277                 :         // If the security manager is complaining then this is not really an
    2278                 :         // internal error in xpconnect. So, no reason to botch the assertion.
    2279               0 :         NS_ASSERTION(rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO,
    2280                 :                      "hmm? CanCallNow failed in XPCWrappedNative::CallMethod. "
    2281                 :                      "We are finding out about this late!");
    2282               0 :         return Throw(rv, ccx);
    2283                 :     }
    2284                 : 
    2285         7371823 :     DEBUG_TrackWrapperCall(ccx.GetWrapper(), mode);
    2286                 : 
    2287                 :     // set up the method index and do the security check if needed
    2288                 : 
    2289                 :     PRUint32 secFlag;
    2290                 :     PRUint32 secAction;
    2291                 : 
    2292         7371823 :     switch (mode) {
    2293                 :         case CALL_METHOD:
    2294         4944344 :             secFlag   = nsIXPCSecurityManager::HOOK_CALL_METHOD;
    2295         4944344 :             secAction = nsIXPCSecurityManager::ACCESS_CALL_METHOD;
    2296         4944344 :             break;
    2297                 :         case CALL_GETTER:
    2298         2331607 :             secFlag   = nsIXPCSecurityManager::HOOK_GET_PROPERTY;
    2299         2331607 :             secAction = nsIXPCSecurityManager::ACCESS_GET_PROPERTY;
    2300         2331607 :             break;
    2301                 :         case CALL_SETTER:
    2302           95872 :             secFlag   = nsIXPCSecurityManager::HOOK_SET_PROPERTY;
    2303           95872 :             secAction = nsIXPCSecurityManager::ACCESS_SET_PROPERTY;
    2304           95872 :             break;
    2305                 :         default:
    2306               0 :             NS_ERROR("bad value");
    2307               0 :             return false;
    2308                 :     }
    2309                 : 
    2310                 :     nsIXPCSecurityManager* sm =
    2311         7371823 :         xpcc->GetAppropriateSecurityManager(secFlag);
    2312         7371823 :     if (sm && NS_FAILED(sm->CanAccess(secAction, &ccx, ccx,
    2313                 :                                       ccx.GetFlattenedJSObject(),
    2314                 :                                       ccx.GetWrapper()->GetIdentityObject(),
    2315                 :                                       ccx.GetWrapper()->GetClassInfo(),
    2316                 :                                       ccx.GetMember()->GetName(),
    2317                 :                                       ccx.GetWrapper()->GetSecurityInfoAddr()))) {
    2318                 :         // the security manager vetoed. It should have set an exception.
    2319               0 :         return false;
    2320                 :     }
    2321                 : 
    2322         7371823 :     return CallMethodHelper(ccx).Call();
    2323                 : }
    2324                 : 
    2325                 : JSBool
    2326         7371823 : CallMethodHelper::Call()
    2327                 : {
    2328         7371823 :     mCallContext.SetRetVal(JSVAL_VOID);
    2329                 : 
    2330         7371823 :     mCallContext.GetThreadData()->SetException(nsnull);
    2331         7371823 :     mCallContext.GetXPCContext()->SetLastResult(NS_ERROR_UNEXPECTED);
    2332                 : 
    2333         7371823 :     if (mVTableIndex == 0) {
    2334           78890 :         return QueryInterfaceFastPath();
    2335                 :     }
    2336                 : 
    2337         7292933 :     if (!mMethodInfo) {
    2338               0 :         Throw(NS_ERROR_XPC_CANT_GET_METHOD_INFO, mCallContext);
    2339               0 :         return false;
    2340                 :     }
    2341                 : 
    2342         7292933 :     if (!InitializeDispatchParams())
    2343               3 :         return false;
    2344                 : 
    2345                 :     // Iterate through the params doing conversions of independent params only.
    2346                 :     // When we later convert the dependent params (if any) we will know that
    2347                 :     // the params upon which they depend will have already been converted -
    2348                 :     // regardless of ordering.
    2349         7292930 :     JSBool foundDependentParam = false;
    2350         7292930 :     if (!ConvertIndependentParams(&foundDependentParam))
    2351              18 :         return false;
    2352                 : 
    2353         7292912 :     if (foundDependentParam && !ConvertDependentParams())
    2354               7 :         return false;
    2355                 : 
    2356         7292905 :     nsresult invokeResult = Invoke();
    2357                 : 
    2358         7292905 :     mCallContext.GetXPCContext()->SetLastResult(invokeResult);
    2359                 : 
    2360         7292905 :     if (NS_FAILED(invokeResult)) {
    2361           18763 :         ThrowBadResult(invokeResult, mCallContext);
    2362           18763 :         return false;
    2363                 :     }
    2364                 : 
    2365         7274142 :     if (JS_IsExceptionPending(mCallContext)) {
    2366             171 :         return false;
    2367                 :     }
    2368                 : 
    2369         7273971 :     return GatherAndConvertResults();
    2370                 : }
    2371                 : 
    2372        14743646 : CallMethodHelper::~CallMethodHelper()
    2373                 : {
    2374         7371823 :     uint8_t paramCount = mMethodInfo->GetParamCount();
    2375         7371823 :     if (mDispatchParams.Length()) {
    2376        18550830 :         for (uint8_t i = 0; i < paramCount; i++) {
    2377        11406929 :             nsXPTCVariant* dp = GetDispatchParam(i);
    2378        11406929 :             const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
    2379                 : 
    2380        11406929 :             if (paramInfo.GetType().IsArray()) {
    2381           67688 :                 void* p = dp->val.p;
    2382           67688 :                 if (!p)
    2383           18898 :                     continue;
    2384                 : 
    2385                 :                 // Clean up the array contents if necessary.
    2386           48790 :                 if (dp->DoesValNeedCleanup()) {
    2387                 :                     // We need some basic information to properly destroy the array.
    2388            8147 :                     uint32_t array_count = 0;
    2389            8147 :                     nsXPTType datum_type;
    2390           16294 :                     if (!GetArraySizeFromParam(i, &array_count) ||
    2391            8147 :                         !NS_SUCCEEDED(mIFaceInfo->GetTypeForParam(mVTableIndex,
    2392                 :                                                                   &paramInfo,
    2393                 :                                                                   1, &datum_type))) {
    2394                 :                         // XXXbholley - I'm not convinced that the above calls will
    2395                 :                         // ever fail.
    2396               0 :                         NS_ERROR("failed to get array information, we'll leak here");
    2397               0 :                         continue;
    2398                 :                     }
    2399                 : 
    2400                 :                     // Loop over the array contents. For each one, we create a
    2401                 :                     // dummy 'val' and pass it to the cleanup helper.
    2402           63007 :                     for (uint32_t k = 0; k < array_count; k++) {
    2403                 :                         nsXPTCMiniVariant v;
    2404           54860 :                         v.val.p = static_cast<void**>(p)[k];
    2405           54860 :                         CleanupParam(v, datum_type);
    2406                 :                     }
    2407                 :                 }
    2408                 : 
    2409                 :                 // always free the array itself
    2410           48790 :                 nsMemory::Free(p);
    2411                 :             } else {
    2412                 :                 // Clean up single parameters (if requested).
    2413        11339241 :                 if (dp->DoesValNeedCleanup())
    2414         7501649 :                     CleanupParam(*dp, dp->type);
    2415                 :             }
    2416                 :         }
    2417                 :     }
    2418                 : 
    2419         7371823 : }
    2420                 : 
    2421                 : JSBool
    2422           76473 : CallMethodHelper::GetArraySizeFromParam(uint8_t paramIndex,
    2423                 :                                         uint32_t* result) const
    2424                 : {
    2425                 :     nsresult rv;
    2426           76473 :     const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(paramIndex);
    2427                 : 
    2428                 :     // TODO fixup the various exceptions that are thrown
    2429                 : 
    2430           76473 :     rv = mIFaceInfo->GetSizeIsArgNumberForParam(mVTableIndex, &paramInfo, 0, &paramIndex);
    2431           76473 :     if (NS_FAILED(rv))
    2432               0 :         return Throw(NS_ERROR_XPC_CANT_GET_ARRAY_INFO, mCallContext);
    2433                 : 
    2434           76473 :     *result = GetDispatchParam(paramIndex)->val.u32;
    2435                 : 
    2436           76473 :     return true;
    2437                 : }
    2438                 : 
    2439                 : JSBool
    2440         1187549 : CallMethodHelper::GetInterfaceTypeFromParam(uint8_t paramIndex,
    2441                 :                                             const nsXPTType& datum_type,
    2442                 :                                             nsID* result) const
    2443                 : {
    2444                 :     nsresult rv;
    2445         1187549 :     const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(paramIndex);
    2446         1187549 :     uint8_t tag = datum_type.TagPart();
    2447                 : 
    2448                 :     // TODO fixup the various exceptions that are thrown
    2449                 : 
    2450         1187549 :     if (tag == nsXPTType::T_INTERFACE) {
    2451         1162308 :         rv = mIFaceInfo->GetIIDForParamNoAlloc(mVTableIndex, &paramInfo, result);
    2452         1162308 :         if (NS_FAILED(rv))
    2453                 :             return ThrowBadParam(NS_ERROR_XPC_CANT_GET_PARAM_IFACE_INFO,
    2454               0 :                                  paramIndex, mCallContext);
    2455           25241 :     } else if (tag == nsXPTType::T_INTERFACE_IS) {
    2456                 :         rv = mIFaceInfo->GetInterfaceIsArgNumberForParam(mVTableIndex, &paramInfo,
    2457           25241 :                                                          &paramIndex);
    2458           25241 :         if (NS_FAILED(rv))
    2459               0 :             return Throw(NS_ERROR_XPC_CANT_GET_ARRAY_INFO, mCallContext);
    2460                 : 
    2461           25241 :         nsID* p = (nsID*) GetDispatchParam(paramIndex)->val.p;
    2462           25241 :         if (!p)
    2463                 :             return ThrowBadParam(NS_ERROR_XPC_CANT_GET_PARAM_IFACE_INFO,
    2464               0 :                                  paramIndex, mCallContext);
    2465           25241 :         *result = *p;
    2466                 :     }
    2467         1187549 :     return true;
    2468                 : }
    2469                 : 
    2470                 : JSBool
    2471         9291111 : CallMethodHelper::GetOutParamSource(uint8_t paramIndex, jsval* srcp) const
    2472                 : {
    2473         9291111 :     const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(paramIndex);
    2474                 : 
    2475        13862293 :     if ((paramInfo.IsOut() || paramInfo.IsDipper()) &&
    2476         4571182 :         !paramInfo.IsRetval()) {
    2477           33469 :         NS_ASSERTION(paramIndex < mArgc || paramInfo.IsOptional(),
    2478                 :                      "Expected either enough arguments or an optional argument");
    2479           33469 :         jsval arg = paramIndex < mArgc ? mArgv[paramIndex] : JSVAL_NULL;
    2480           62821 :         if (paramIndex < mArgc &&
    2481           14686 :             (JSVAL_IS_PRIMITIVE(arg) ||
    2482                 :              !JS_GetPropertyById(mCallContext,
    2483                 :                                  JSVAL_TO_OBJECT(arg),
    2484                 :                                  mIdxValueId,
    2485           14666 :                                  srcp))) {
    2486                 :             // Explicitly passed in unusable value for out param.  Note
    2487                 :             // that if i >= mArgc we already know that |arg| is JSVAL_NULL,
    2488                 :             // and that's ok.
    2489                 :             ThrowBadParam(NS_ERROR_XPC_NEED_OUT_OBJECT, paramIndex,
    2490              20 :                           mCallContext);
    2491              20 :             return false;
    2492                 :         }
    2493                 :     }
    2494                 : 
    2495         9291091 :     return true;
    2496                 : }
    2497                 : 
    2498                 : JSBool
    2499         7273971 : CallMethodHelper::GatherAndConvertResults()
    2500                 : {
    2501                 :     // now we iterate through the native params to gather and convert results
    2502         7273971 :     uint8_t paramCount = mMethodInfo->GetParamCount();
    2503        18644702 :     for (uint8_t i = 0; i < paramCount; i++) {
    2504        11370731 :         const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
    2505        11370731 :         if (!paramInfo.IsOut() && !paramInfo.IsDipper())
    2506         4701514 :             continue;
    2507                 : 
    2508         6669217 :         const nsXPTType& type = paramInfo.GetType();
    2509         6669217 :         nsXPTCVariant* dp = GetDispatchParam(i);
    2510         6669217 :         jsval v = JSVAL_NULL;
    2511        13338434 :         AUTO_MARK_JSVAL(mCallContext, &v);
    2512         6669217 :         uint32_t array_count = 0;
    2513         6669217 :         nsXPTType datum_type;
    2514         6669217 :         bool isArray = type.IsArray();
    2515                 :         bool isSizedString = isArray ?
    2516                 :                 false :
    2517         6630320 :                 type.TagPart() == nsXPTType::T_PSTRING_SIZE_IS ||
    2518        13299537 :                 type.TagPart() == nsXPTType::T_PWSTRING_SIZE_IS;
    2519                 : 
    2520         6669217 :         if (isArray) {
    2521           38897 :             if (NS_FAILED(mIFaceInfo->GetTypeForParam(mVTableIndex, &paramInfo, 1,
    2522                 :                                                       &datum_type))) {
    2523               0 :                 Throw(NS_ERROR_XPC_CANT_GET_ARRAY_INFO, mCallContext);
    2524               0 :                 return false;
    2525                 :             }
    2526                 :         } else
    2527         6630320 :             datum_type = type;
    2528                 : 
    2529         6669217 :         if (isArray || isSizedString) {
    2530           39549 :             if (!GetArraySizeFromParam(i, &array_count))
    2531               0 :                 return false;
    2532                 :         }
    2533                 : 
    2534                 :         nsID param_iid;
    2535         7853370 :         if (datum_type.IsInterfacePointer() &&
    2536         1184153 :             !GetInterfaceTypeFromParam(i, datum_type, &param_iid))
    2537               0 :             return false;
    2538                 : 
    2539                 :         nsresult err;
    2540         6669217 :         if (isArray) {
    2541           77794 :             XPCLazyCallContext lccx(mCallContext);
    2542           38897 :             if (!XPCConvert::NativeArray2JS(lccx, &v, (const void**)&dp->val,
    2543                 :                                             datum_type, &param_iid,
    2544           38897 :                                             array_count, &err)) {
    2545                 :                 // XXX need exception scheme for arrays to indicate bad element
    2546               0 :                 ThrowBadParam(err, i, mCallContext);
    2547               0 :                 return false;
    2548                 :             }
    2549         6630320 :         } else if (isSizedString) {
    2550             652 :             if (!XPCConvert::NativeStringWithSize2JS(mCallContext, &v,
    2551                 :                                                      (const void*)&dp->val,
    2552                 :                                                      datum_type,
    2553             652 :                                                      array_count, &err)) {
    2554               0 :                 ThrowBadParam(err, i, mCallContext);
    2555               0 :                 return false;
    2556                 :             }
    2557                 :         } else {
    2558         6629668 :             if (!XPCConvert::NativeData2JS(mCallContext, &v, &dp->val, datum_type,
    2559         6629668 :                                            &param_iid, &err)) {
    2560               0 :                 ThrowBadParam(err, i, mCallContext);
    2561               0 :                 return false;
    2562                 :             }
    2563                 :         }
    2564                 : 
    2565         6669217 :         if (paramInfo.IsRetval()) {
    2566         6615883 :             mCallContext.SetRetVal(v);
    2567           53334 :         } else if (i < mArgc) {
    2568                 :             // we actually assured this before doing the invoke
    2569           34552 :             NS_ASSERTION(JSVAL_IS_OBJECT(mArgv[i]), "out var is not object");
    2570           34552 :             if (!JS_SetPropertyById(mCallContext,
    2571           34552 :                                     JSVAL_TO_OBJECT(mArgv[i]),
    2572           34552 :                                     mIdxValueId, &v)) {
    2573               0 :                 ThrowBadParam(NS_ERROR_XPC_CANT_SET_OUT_VAL, i, mCallContext);
    2574               0 :                 return false;
    2575                 :             }
    2576                 :         } else {
    2577           18782 :             NS_ASSERTION(paramInfo.IsOptional(),
    2578                 :                          "Expected either enough arguments or an optional argument");
    2579                 :         }
    2580                 :     }
    2581                 : 
    2582         7273971 :     return true;
    2583                 : }
    2584                 : 
    2585                 : JSBool
    2586           78890 : CallMethodHelper::QueryInterfaceFastPath() const
    2587                 : {
    2588           78890 :     NS_ASSERTION(mVTableIndex == 0,
    2589                 :                  "Using the QI fast-path for a method other than QueryInterface");
    2590                 : 
    2591           78890 :     if (mArgc < 1) {
    2592               0 :         Throw(NS_ERROR_XPC_NOT_ENOUGH_ARGS, mCallContext);
    2593               0 :         return false;
    2594                 :     }
    2595                 :     const nsID* iid;
    2596                 :     JSObject* obj;
    2597          236670 :     if (!JSVAL_IS_OBJECT(mArgv[0]) ||
    2598           78890 :         (!(obj = JSVAL_TO_OBJECT(mArgv[0]))) ||
    2599           78890 :         (!(iid = xpc_JSObjectToID(mCallContext, obj)))) {
    2600               0 :         ThrowBadParam(NS_ERROR_XPC_BAD_CONVERT_JS, 0, mCallContext);
    2601               0 :         return false;
    2602                 :     }
    2603                 : 
    2604                 :     nsresult invokeResult;
    2605           78890 :     nsISupports* qiresult = nsnull;
    2606           78890 :     if (XPCPerThreadData::IsMainThread(mCallContext)) {
    2607           78890 :         invokeResult = mCallee->QueryInterface(*iid, (void**) &qiresult);
    2608                 :     } else {
    2609               0 :         JSAutoSuspendRequest suspended(mCallContext);
    2610               0 :         invokeResult = mCallee->QueryInterface(*iid, (void**) &qiresult);
    2611                 :     }
    2612                 : 
    2613           78890 :     mCallContext.GetXPCContext()->SetLastResult(invokeResult);
    2614                 : 
    2615           78890 :     if (NS_FAILED(invokeResult)) {
    2616               3 :         ThrowBadResult(invokeResult, mCallContext);
    2617               3 :         return false;
    2618                 :     }
    2619                 : 
    2620           78887 :     jsval v = JSVAL_NULL;
    2621                 :     unsigned err;
    2622                 :     JSBool success =
    2623                 :         XPCConvert::NativeData2JS(mCallContext, &v, &qiresult,
    2624                 :                                   nsXPTType::T_INTERFACE_IS,
    2625           78887 :                                   iid, &err);
    2626           78887 :     NS_IF_RELEASE(qiresult);
    2627                 : 
    2628           78887 :     if (!success) {
    2629               0 :         ThrowBadParam(err, 0, mCallContext);
    2630               0 :         return false;
    2631                 :     }
    2632                 : 
    2633           78887 :     mCallContext.SetRetVal(v);
    2634           78887 :     return true;
    2635                 : }
    2636                 : 
    2637                 : JSBool
    2638         7292933 : CallMethodHelper::InitializeDispatchParams()
    2639                 : {
    2640         7292933 :     const uint8_t wantsOptArgc = mMethodInfo->WantsOptArgc() ? 1 : 0;
    2641         7292933 :     const uint8_t wantsJSContext = mMethodInfo->WantsContext() ? 1 : 0;
    2642         7292933 :     const uint8_t paramCount = mMethodInfo->GetParamCount();
    2643         7292933 :     uint8_t requiredArgs = paramCount;
    2644         7292933 :     uint8_t hasRetval = 0;
    2645                 : 
    2646                 :     // XXX ASSUMES that retval is last arg. The xpidl compiler ensures this.
    2647         7292933 :     if (paramCount && mMethodInfo->GetParam(paramCount-1).IsRetval()) {
    2648         6633506 :         hasRetval = 1;
    2649         6633506 :         requiredArgs--;
    2650                 :     }
    2651                 : 
    2652         7292933 :     if (mArgc < requiredArgs || wantsOptArgc) {
    2653          261833 :         if (wantsOptArgc)
    2654          233372 :             mOptArgcIndex = requiredArgs;
    2655                 : 
    2656                 :         // skip over any optional arguments
    2657          795708 :         while (requiredArgs && mMethodInfo->GetParam(requiredArgs-1).IsOptional())
    2658          272042 :             requiredArgs--;
    2659                 : 
    2660          261833 :         if (mArgc < requiredArgs) {
    2661               3 :             Throw(NS_ERROR_XPC_NOT_ENOUGH_ARGS, mCallContext);
    2662               3 :             return false;
    2663                 :         }
    2664                 :     }
    2665                 : 
    2666         7292930 :     if (wantsJSContext) {
    2667          240483 :         if (wantsOptArgc)
    2668                 :             // Need to bump mOptArgcIndex up one here.
    2669          233307 :             mJSContextIndex = mOptArgcIndex++;
    2670            7176 :         else if (mMethodInfo->IsSetter() || mMethodInfo->IsGetter())
    2671                 :             // For attributes, we always put the JSContext* first.
    2672              65 :             mJSContextIndex = 0;
    2673                 :         else
    2674            7111 :             mJSContextIndex = paramCount - hasRetval;
    2675                 :     }
    2676                 : 
    2677                 :     // iterate through the params to clear flags (for safe cleanup later)
    2678        19173714 :     for (uint8_t i = 0; i < paramCount + wantsJSContext + wantsOptArgc; i++) {
    2679        11880784 :         nsXPTCVariant* dp = mDispatchParams.AppendElement();
    2680        11880784 :         dp->ClearFlags();
    2681        11880784 :         dp->val.p = nsnull;
    2682                 :     }
    2683                 : 
    2684                 :     // Fill in the JSContext argument
    2685         7292930 :     if (wantsJSContext) {
    2686          240483 :         nsXPTCVariant* dp = &mDispatchParams[mJSContextIndex];
    2687          240483 :         dp->type = nsXPTType::T_VOID;
    2688          240483 :         dp->val.p = mCallContext;
    2689                 :     }
    2690                 : 
    2691                 :     // Fill in the optional_argc argument
    2692         7292930 :     if (wantsOptArgc) {
    2693          233372 :         nsXPTCVariant* dp = &mDispatchParams[mOptArgcIndex];
    2694          233372 :         dp->type = nsXPTType::T_U8;
    2695          233372 :         dp->val.u8 = NS_MIN<PRUint32>(mArgc, paramCount) - requiredArgs;
    2696                 :     }
    2697                 : 
    2698         7292930 :     return true;
    2699                 : }
    2700                 : 
    2701                 : JSBool
    2702         7292930 : CallMethodHelper::ConvertIndependentParams(JSBool* foundDependentParam)
    2703                 : {
    2704         7292930 :     const uint8_t paramCount = mMethodInfo->GetParamCount();
    2705        18699821 :     for (uint8_t i = 0; i < paramCount; i++) {
    2706        11406909 :         const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
    2707                 : 
    2708        11406909 :         if (paramInfo.GetType().IsDependent())
    2709           95092 :             *foundDependentParam = true;
    2710        11311817 :         else if (!ConvertIndependentParam(i))
    2711              18 :             return false;
    2712                 : 
    2713                 :     }
    2714                 : 
    2715         7292912 :     return true;
    2716                 : }
    2717                 : 
    2718                 : JSBool
    2719        11311817 : CallMethodHelper::ConvertIndependentParam(uint8_t i)
    2720                 : {
    2721        11311817 :     const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
    2722        11311817 :     const nsXPTType& type = paramInfo.GetType();
    2723        11311817 :     uint8_t type_tag = type.TagPart();
    2724        11311817 :     nsXPTCVariant* dp = GetDispatchParam(i);
    2725        11311817 :     dp->type = type;
    2726        11311817 :     NS_ABORT_IF_FALSE(!paramInfo.IsShared(), "[shared] implies [noscript]!");
    2727                 : 
    2728                 :     // Handle dipper types separately.
    2729        11311817 :     if (paramInfo.IsDipper())
    2730         2115786 :         return HandleDipperParam(dp, paramInfo);
    2731                 : 
    2732                 :     // Specify the correct storage/calling semantics.
    2733         9196031 :     if (paramInfo.IsIndirect())
    2734         4744156 :         dp->SetIndirect();
    2735                 : 
    2736                 :     // The JSVal proper is always stored within the 'val' union and passed
    2737                 :     // indirectly, regardless of in/out-ness.
    2738         9196031 :     if (type_tag == nsXPTType::T_JSVAL) {
    2739                 :         // Root the value.
    2740          475333 :         dp->val.j = JSVAL_VOID;
    2741          475333 :         if (!JS_AddValueRoot(mCallContext, &dp->val.j))
    2742               0 :             return false;
    2743                 :     }
    2744                 : 
    2745                 :     // Flag cleanup for anything that isn't self-contained.
    2746         9196031 :     if (!type.IsArithmetic())
    2747         5358452 :         dp->SetValNeedsCleanup();
    2748                 : 
    2749                 :     // Even if there's nothing to convert, we still need to examine the
    2750                 :     // JSObject container for out-params. If it's null or otherwise invalid,
    2751                 :     // we want to know before the call, rather than after.
    2752                 :     //
    2753                 :     // This is a no-op for 'in' params.
    2754                 :     jsval src;
    2755         9196031 :     if (!GetOutParamSource(i, &src))
    2756              17 :         return false;
    2757                 : 
    2758                 :     // All that's left to do is value conversion. Bail early if we don't need
    2759                 :     // to do that.
    2760         9196014 :     if (!paramInfo.IsIn())
    2761         4502618 :         return true;
    2762                 : 
    2763                 :     // We're definitely some variety of 'in' now, so there's something to
    2764                 :     // convert. The source value for conversion depends on whether we're
    2765                 :     // dealing with an 'in' or an 'inout' parameter. 'inout' was handled above,
    2766                 :     // so all that's left is 'in'.
    2767         4693396 :     if (!paramInfo.IsOut()) {
    2768                 :         // Handle the 'in' case.
    2769         4691170 :         NS_ASSERTION(i < mArgc || paramInfo.IsOptional(),
    2770                 :                      "Expected either enough arguments or an optional argument");
    2771         4691170 :         if (i < mArgc)
    2772         4623136 :             src = mArgv[i];
    2773           68034 :         else if (type_tag == nsXPTType::T_JSVAL)
    2774           50063 :             src = JSVAL_VOID;
    2775                 :         else
    2776           17971 :             src = JSVAL_NULL;
    2777                 :     }
    2778                 : 
    2779                 :     nsID param_iid;
    2780         5910049 :     if (type_tag == nsXPTType::T_INTERFACE &&
    2781         1216653 :         NS_FAILED(mIFaceInfo->GetIIDForParamNoAlloc(mVTableIndex, &paramInfo,
    2782                 :                                                     &param_iid))) {
    2783               0 :         ThrowBadParam(NS_ERROR_XPC_CANT_GET_PARAM_IFACE_INFO, i, mCallContext);
    2784               0 :         return false;
    2785                 :     }
    2786                 : 
    2787                 :     unsigned err;
    2788         4693396 :     if (!XPCConvert::JSData2Native(mCallContext, &dp->val, src, type,
    2789         4693396 :                                    true, &param_iid, &err)) {
    2790               1 :         ThrowBadParam(err, i, mCallContext);
    2791               1 :         return false;
    2792                 :     }
    2793                 : 
    2794         4693395 :     return true;
    2795                 : }
    2796                 : 
    2797                 : JSBool
    2798           95036 : CallMethodHelper::ConvertDependentParams()
    2799                 : {
    2800           95036 :     const uint8_t paramCount = mMethodInfo->GetParamCount();
    2801          330815 :     for (uint8_t i = 0; i < paramCount; i++) {
    2802          235786 :         const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
    2803                 : 
    2804          235786 :         if (!paramInfo.GetType().IsDependent())
    2805          140706 :             continue;
    2806           95080 :         if (!ConvertDependentParam(i))
    2807               7 :             return false;
    2808                 :     }
    2809                 : 
    2810           95029 :     return true;
    2811                 : }
    2812                 : 
    2813                 : JSBool
    2814           95080 : CallMethodHelper::ConvertDependentParam(uint8_t i)
    2815                 : {
    2816           95080 :     const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
    2817           95080 :     const nsXPTType& type = paramInfo.GetType();
    2818           95080 :     nsXPTType datum_type;
    2819           95080 :     uint32_t array_count = 0;
    2820           95080 :     bool isArray = type.IsArray();
    2821                 : 
    2822                 :     bool isSizedString = isArray ?
    2823                 :         false :
    2824           27411 :         type.TagPart() == nsXPTType::T_PSTRING_SIZE_IS ||
    2825          122491 :         type.TagPart() == nsXPTType::T_PWSTRING_SIZE_IS;
    2826                 : 
    2827           95080 :     nsXPTCVariant* dp = GetDispatchParam(i);
    2828           95080 :     dp->type = type;
    2829                 : 
    2830           95080 :     if (isArray) {
    2831           67669 :         if (NS_FAILED(mIFaceInfo->GetTypeForParam(mVTableIndex, &paramInfo, 1,
    2832                 :                                                   &datum_type))) {
    2833               0 :             Throw(NS_ERROR_XPC_CANT_GET_ARRAY_INFO, mCallContext);
    2834               0 :             return false;
    2835                 :         }
    2836           67669 :         NS_ABORT_IF_FALSE(datum_type.TagPart() != nsXPTType::T_JSVAL,
    2837                 :                           "Arrays of JSVals not currently supported - "
    2838                 :                           "see bug 693337.");
    2839                 :     } else {
    2840           27411 :         datum_type = type;
    2841                 :     }
    2842                 : 
    2843                 :     // Specify the correct storage/calling semantics.
    2844           95080 :     if (paramInfo.IsIndirect())
    2845           66321 :         dp->SetIndirect();
    2846                 : 
    2847                 :     // We have 3 possible type of dependent parameters: Arrays, Sized Strings,
    2848                 :     // and iid_is Interface pointers. The latter two always need cleanup, and
    2849                 :     // arrays need cleanup for all non-arithmetic types. Since the latter two
    2850                 :     // cases also happen to be non-arithmetic, we can just inspect datum_type
    2851                 :     // here.
    2852           95080 :     if (!datum_type.IsArithmetic())
    2853           38945 :         dp->SetValNeedsCleanup();
    2854                 : 
    2855                 :     // Even if there's nothing to convert, we still need to examine the
    2856                 :     // JSObject container for out-params. If it's null or otherwise invalid,
    2857                 :     // we want to know before the call, rather than after.
    2858                 :     //
    2859                 :     // This is a no-op for 'in' params.
    2860                 :     jsval src;
    2861           95080 :     if (!GetOutParamSource(i, &src))
    2862               3 :         return false;
    2863                 : 
    2864                 :     // All that's left to do is value conversion. Bail early if we don't need
    2865                 :     // to do that.
    2866           95077 :     if (!paramInfo.IsIn())
    2867           66296 :         return true;
    2868                 : 
    2869                 :     // We're definitely some variety of 'in' now, so there's something to
    2870                 :     // convert. The source value for conversion depends on whether we're
    2871                 :     // dealing with an 'in' or an 'inout' parameter. 'inout' was handled above,
    2872                 :     // so all that's left is 'in'.
    2873           28781 :     if (!paramInfo.IsOut()) {
    2874                 :         // Handle the 'in' case.
    2875           28759 :         NS_ASSERTION(i < mArgc || paramInfo.IsOptional(),
    2876                 :                      "Expected either enough arguments or an optional argument");
    2877           28759 :         src = i < mArgc ? mArgv[i] : JSVAL_NULL;
    2878                 :     }
    2879                 : 
    2880                 :     nsID param_iid;
    2881           32177 :     if (datum_type.IsInterfacePointer() &&
    2882            3396 :         !GetInterfaceTypeFromParam(i, datum_type, &param_iid))
    2883               0 :         return false;
    2884                 : 
    2885                 :     unsigned err;
    2886                 : 
    2887           28781 :     if (isArray || isSizedString) {
    2888           28777 :         if (!GetArraySizeFromParam(i, &array_count))
    2889               0 :             return false;
    2890                 : 
    2891           57550 :         if (isArray) {
    2892           56388 :             if (array_count &&
    2893                 :                 !XPCConvert::JSArray2Native(mCallContext, (void**)&dp->val, src,
    2894                 :                                             array_count, datum_type, &param_iid,
    2895           27621 :                                             &err)) {
    2896                 :                 // XXX need exception scheme for arrays to indicate bad element
    2897               4 :                 ThrowBadParam(err, i, mCallContext);
    2898               4 :                 return false;
    2899                 :             }
    2900                 :         } else // if (isSizedString)
    2901                 :         {
    2902              10 :             if (!XPCConvert::JSStringWithSize2Native(mCallContext,
    2903                 :                                                      (void*)&dp->val,
    2904                 :                                                      src, array_count,
    2905              10 :                                                      datum_type, &err)) {
    2906               0 :                 ThrowBadParam(err, i, mCallContext);
    2907               0 :                 return false;
    2908                 :             }
    2909                 :         }
    2910                 :     } else {
    2911               4 :         if (!XPCConvert::JSData2Native(mCallContext, &dp->val, src, type,
    2912               4 :                                        true, &param_iid, &err)) {
    2913               0 :             ThrowBadParam(err, i, mCallContext);
    2914               0 :             return false;
    2915                 :         }
    2916                 :     }
    2917                 : 
    2918           28777 :     return true;
    2919                 : }
    2920                 : 
    2921                 : // Performs all necessary teardown on a parameter after method invocation.
    2922                 : //
    2923                 : // This method should only be called if the value in question was flagged
    2924                 : // for cleanup (ie, if dp->DoesValNeedCleanup()).
    2925                 : void
    2926         7556509 : CallMethodHelper::CleanupParam(nsXPTCMiniVariant& param, nsXPTType& type)
    2927                 : {
    2928                 :     // We handle array elements, but not the arrays themselves.
    2929         7556509 :     NS_ABORT_IF_FALSE(type.TagPart() != nsXPTType::T_ARRAY, "Can't handle arrays.");
    2930                 : 
    2931                 :     // Pointers may sometimes be null even if cleanup was requested. Combine
    2932                 :     // the null checking for all the different types into one check here.
    2933         7556509 :     if (type.TagPart() != nsXPTType::T_JSVAL && param.val.p == nsnull)
    2934          226116 :         return;
    2935                 : 
    2936         7330393 :     switch (type.TagPart()) {
    2937                 :         case nsXPTType::T_JSVAL:
    2938          475333 :             JS_RemoveValueRoot(mCallContext, (jsval*)&param.val);
    2939          475333 :             break;
    2940                 :         case nsXPTType::T_INTERFACE:
    2941                 :         case nsXPTType::T_INTERFACE_IS:
    2942         2271649 :             ((nsISupports*)param.val.p)->Release();
    2943         2271649 :             break;
    2944                 :         case nsXPTType::T_ASTRING:
    2945                 :         case nsXPTType::T_DOMSTRING:
    2946         1554216 :             mCallContext.DeleteString((nsAString*)param.val.p);
    2947         1554216 :             break;
    2948                 :         case nsXPTType::T_UTF8STRING:
    2949                 :         case nsXPTType::T_CSTRING:
    2950         1826352 :             delete (nsCString*) param.val.p;
    2951         1826352 :             break;
    2952                 :         default:
    2953         1202843 :             NS_ABORT_IF_FALSE(!type.IsArithmetic(),
    2954                 :                               "Cleanup requested on unexpected type.");
    2955         1202843 :             nsMemory::Free(param.val.p);
    2956         1202843 :             break;
    2957                 :     }
    2958                 : }
    2959                 : 
    2960                 : // Handle parameters with dipper types.
    2961                 : //
    2962                 : // Dipper types are one of the more inscrutable aspects of xpidl. In a
    2963                 : // nutshell, dippers are empty container objects, created and passed by
    2964                 : // the caller, and filled by the callee. The callee receives a
    2965                 : // fully-formed object, and thus does not have to construct anything. But
    2966                 : // the object is functionally empty, and the callee is responsible for
    2967                 : // putting something useful inside of it.
    2968                 : //
    2969                 : // XPIDL decides which types to make dippers. The list of these types
    2970                 : // is given in the isDipperType() function in typelib.py, and is currently
    2971                 : // limited to 4 string types.
    2972                 : //
    2973                 : // When a dipper type is declared as an 'out' parameter, xpidl internally
    2974                 : // converts it to an 'in', and sets the XPT_PD_DIPPER flag on it. For this
    2975                 : // reason, dipper types are sometimes referred to as 'out parameters
    2976                 : // masquerading as in'. The burden of maintaining this illusion falls mostly
    2977                 : // on XPConnect - we create the empty containers, and harvest the results
    2978                 : // after the call.
    2979                 : //
    2980                 : // This method creates these empty containers.
    2981                 : JSBool
    2982         2115786 : CallMethodHelper::HandleDipperParam(nsXPTCVariant* dp,
    2983                 :                                     const nsXPTParamInfo& paramInfo)
    2984                 : {
    2985                 :     // Get something we can make comparisons with.
    2986         2115786 :     uint8_t type_tag = paramInfo.GetType().TagPart();
    2987                 : 
    2988                 :     // Dippers always have the 'in' and 'dipper' flags set. Never 'out'.
    2989         2115786 :     NS_ABORT_IF_FALSE(!paramInfo.IsOut(), "Dipper has unexpected flags.");
    2990                 : 
    2991                 :     // xpidl.h specifies that dipper types will be used in exactly four
    2992                 :     // cases, all strings. Verify that here.
    2993         2115786 :     NS_ABORT_IF_FALSE(type_tag == nsXPTType::T_ASTRING ||
    2994                 :                       type_tag == nsXPTType::T_DOMSTRING ||
    2995                 :                       type_tag == nsXPTType::T_UTF8STRING ||
    2996                 :                       type_tag == nsXPTType::T_CSTRING,
    2997                 :                       "Unexpected dipper type!");
    2998                 : 
    2999                 :     // ASTRING and DOMSTRING are very similar, and both use nsAutoString.
    3000                 :     // UTF8_STRING and CSTRING are also quite similar, and both use nsCString.
    3001         2115786 :     if (type_tag == nsXPTType::T_ASTRING || type_tag == nsXPTType::T_DOMSTRING)
    3002         1302037 :         dp->val.p = new nsAutoString();
    3003                 :     else
    3004          813749 :         dp->val.p = new nsCString();
    3005                 : 
    3006                 :     // Check for OOM, in either case.
    3007         2115786 :     if (!dp->val.p) {
    3008               0 :         JS_ReportOutOfMemory(mCallContext);
    3009               0 :         return false;
    3010                 :     }
    3011                 : 
    3012                 :     // We allocated, so we need to deallocate after the method call completes.
    3013         2115786 :     dp->SetValNeedsCleanup();
    3014                 : 
    3015         2115786 :     return true;
    3016                 : }
    3017                 : 
    3018                 : nsresult
    3019         7292905 : CallMethodHelper::Invoke()
    3020                 : {
    3021         7292905 :     PRUint32 argc = mDispatchParams.Length();
    3022         7292905 :     nsXPTCVariant* argv = mDispatchParams.Elements();
    3023                 : 
    3024         7292905 :     if (XPCPerThreadData::IsMainThread(mCallContext))
    3025         7292905 :         return NS_InvokeByIndex(mCallee, mVTableIndex, argc, argv);
    3026                 : 
    3027               0 :     JSAutoSuspendRequest suspended(mCallContext);
    3028               0 :     return NS_InvokeByIndex(mCallee, mVTableIndex, argc, argv);
    3029                 : }
    3030                 : 
    3031                 : /***************************************************************************/
    3032                 : // interface methods
    3033                 : 
    3034                 : /* readonly attribute JSObjectPtr JSObject; */
    3035          883124 : NS_IMETHODIMP XPCWrappedNative::GetJSObject(JSObject * *aJSObject)
    3036                 : {
    3037          883124 :     *aJSObject = GetFlatJSObject();
    3038          883124 :     return NS_OK;
    3039                 : }
    3040                 : 
    3041                 : /* readonly attribute nsISupports Native; */
    3042               0 : NS_IMETHODIMP XPCWrappedNative::GetNative(nsISupports * *aNative)
    3043                 : {
    3044                 :     // No need to QI here, we already have the correct nsISupports
    3045                 :     // vtable.
    3046               0 :     *aNative = mIdentity;
    3047               0 :     NS_ADDREF(*aNative);
    3048               0 :     return NS_OK;
    3049                 : }
    3050                 : 
    3051                 : /* reaonly attribute JSObjectPtr JSObjectPrototype; */
    3052               0 : NS_IMETHODIMP XPCWrappedNative::GetJSObjectPrototype(JSObject * *aJSObjectPrototype)
    3053                 : {
    3054               0 :     *aJSObjectPrototype = HasProto() ?
    3055               0 :                 GetProto()->GetJSProtoObject() : GetFlatJSObject();
    3056               0 :     return NS_OK;
    3057                 : }
    3058                 : 
    3059                 : nsIPrincipal*
    3060         2194253 : XPCWrappedNative::GetObjectPrincipal() const
    3061                 : {
    3062         2194253 :     nsIPrincipal* principal = GetScope()->GetPrincipal();
    3063                 : #ifdef DEBUG
    3064                 :     // Because of inner window reuse, we can have objects with one principal
    3065                 :     // living in a scope with a different (but same-origin) principal. So
    3066                 :     // just check same-origin here.
    3067         4388506 :     nsCOMPtr<nsIScriptObjectPrincipal> objPrin(do_QueryInterface(mIdentity));
    3068         2194253 :     if (objPrin) {
    3069                 :         bool equal;
    3070         2194253 :         if (!principal)
    3071               0 :             equal = !objPrin->GetPrincipal();
    3072                 :         else
    3073         2194253 :             principal->Equals(objPrin->GetPrincipal(), &equal);
    3074         2194253 :         NS_ASSERTION(equal, "Principal mismatch.  Expect bad things to happen");
    3075                 :     }
    3076                 : #endif
    3077         2194253 :     return principal;
    3078                 : }
    3079                 : 
    3080                 : /* readonly attribute nsIXPConnect XPConnect; */
    3081          133363 : NS_IMETHODIMP XPCWrappedNative::GetXPConnect(nsIXPConnect * *aXPConnect)
    3082                 : {
    3083          133363 :     if (IsValid()) {
    3084          133363 :         nsIXPConnect* temp = GetRuntime()->GetXPConnect();
    3085          133363 :         NS_IF_ADDREF(temp);
    3086          133363 :         *aXPConnect = temp;
    3087                 :     } else
    3088               0 :         *aXPConnect = nsnull;
    3089          133363 :     return NS_OK;
    3090                 : }
    3091                 : 
    3092                 : /* XPCNativeInterface FindInterfaceWithMember (in jsval name); */
    3093               0 : NS_IMETHODIMP XPCWrappedNative::FindInterfaceWithMember(jsid name, nsIInterfaceInfo * *_retval)
    3094                 : {
    3095                 :     XPCNativeInterface* iface;
    3096                 :     XPCNativeMember*  member;
    3097                 : 
    3098               0 :     if (GetSet()->FindMember(name, &member, &iface) && iface) {
    3099               0 :         nsIInterfaceInfo* temp = iface->GetInterfaceInfo();
    3100               0 :         NS_IF_ADDREF(temp);
    3101               0 :         *_retval = temp;
    3102                 :     } else
    3103               0 :         *_retval = nsnull;
    3104               0 :     return NS_OK;
    3105                 : }
    3106                 : 
    3107                 : /* XPCNativeInterface FindInterfaceWithName (in jsval name); */
    3108               0 : NS_IMETHODIMP XPCWrappedNative::FindInterfaceWithName(jsid name, nsIInterfaceInfo * *_retval)
    3109                 : {
    3110               0 :     XPCNativeInterface* iface = GetSet()->FindNamedInterface(name);
    3111               0 :     if (iface) {
    3112               0 :         nsIInterfaceInfo* temp = iface->GetInterfaceInfo();
    3113               0 :         NS_IF_ADDREF(temp);
    3114               0 :         *_retval = temp;
    3115                 :     } else
    3116               0 :         *_retval = nsnull;
    3117               0 :     return NS_OK;
    3118                 : }
    3119                 : 
    3120               0 : inline nsresult UnexpectedFailure(nsresult rv)
    3121                 : {
    3122               0 :     NS_ERROR("This is not supposed to fail!");
    3123               0 :     return rv;
    3124                 : }
    3125                 : 
    3126                 : /* void finishInitForWrappedGlobal (); */
    3127               0 : NS_IMETHODIMP XPCWrappedNative::FinishInitForWrappedGlobal()
    3128                 : {
    3129                 :     // We can only be called under certain conditions.
    3130               0 :     MOZ_ASSERT(mScriptableInfo);
    3131               0 :     MOZ_ASSERT(mScriptableInfo->GetFlags().IsGlobalObject());
    3132               0 :     MOZ_ASSERT(HasProto());
    3133                 : 
    3134                 :     // Build a CCX.
    3135               0 :     XPCCallContext ccx(NATIVE_CALLER);
    3136               0 :     if (!ccx.IsValid())
    3137               0 :         return UnexpectedFailure(NS_ERROR_FAILURE);
    3138                 : 
    3139                 :     // Call PostCreateProrotype.
    3140               0 :     bool success = GetProto()->CallPostCreatePrototype(ccx);
    3141               0 :     if (!success)
    3142               0 :         return NS_ERROR_FAILURE;
    3143                 : 
    3144               0 :     return NS_OK;
    3145                 : }
    3146                 : 
    3147               0 : NS_IMETHODIMP XPCWrappedNative::GetSecurityInfoAddress(void*** securityInfoAddrPtr)
    3148                 : {
    3149               0 :     NS_ENSURE_ARG_POINTER(securityInfoAddrPtr);
    3150               0 :     *securityInfoAddrPtr = GetSecurityInfoAddr();
    3151               0 :     return NS_OK;
    3152                 : }
    3153                 : 
    3154                 : /* void debugDump (in short depth); */
    3155               0 : NS_IMETHODIMP XPCWrappedNative::DebugDump(PRInt16 depth)
    3156                 : {
    3157                 : #ifdef DEBUG
    3158               0 :     depth-- ;
    3159               0 :     XPC_LOG_ALWAYS(("XPCWrappedNative @ %x with mRefCnt = %d", this, mRefCnt.get()));
    3160               0 :     XPC_LOG_INDENT();
    3161                 : 
    3162               0 :         if (HasProto()) {
    3163               0 :             XPCWrappedNativeProto* proto = GetProto();
    3164               0 :             if (depth && proto)
    3165               0 :                 proto->DebugDump(depth);
    3166                 :             else
    3167               0 :                 XPC_LOG_ALWAYS(("mMaybeProto @ %x", proto));
    3168                 :         } else
    3169               0 :             XPC_LOG_ALWAYS(("Scope @ %x", GetScope()));
    3170                 : 
    3171               0 :         if (depth && mSet)
    3172               0 :             mSet->DebugDump(depth);
    3173                 :         else
    3174               0 :             XPC_LOG_ALWAYS(("mSet @ %x", mSet));
    3175                 : 
    3176               0 :         XPC_LOG_ALWAYS(("mFlatJSObject of %x", mFlatJSObject));
    3177               0 :         XPC_LOG_ALWAYS(("mIdentity of %x", mIdentity));
    3178               0 :         XPC_LOG_ALWAYS(("mScriptableInfo @ %x", mScriptableInfo));
    3179                 : 
    3180               0 :         if (depth && mScriptableInfo) {
    3181               0 :             XPC_LOG_INDENT();
    3182               0 :             XPC_LOG_ALWAYS(("mScriptable @ %x", mScriptableInfo->GetCallback()));
    3183               0 :             XPC_LOG_ALWAYS(("mFlags of %x", (PRUint32)mScriptableInfo->GetFlags()));
    3184               0 :             XPC_LOG_ALWAYS(("mJSClass @ %x", mScriptableInfo->GetJSClass()));
    3185               0 :             XPC_LOG_OUTDENT();
    3186                 :         }
    3187               0 :     XPC_LOG_OUTDENT();
    3188                 : #endif
    3189               0 :     return NS_OK;
    3190                 : }
    3191                 : 
    3192                 : /***************************************************************************/
    3193                 : 
    3194                 : char*
    3195           18713 : XPCWrappedNative::ToString(XPCCallContext& ccx,
    3196                 :                            XPCWrappedNativeTearOff* to /* = nsnull */ ) const
    3197                 : {
    3198                 : #ifdef DEBUG
    3199                 : #  define FMT_ADDR " @ 0x%p"
    3200                 : #  define FMT_STR(str) str
    3201                 : #  define PARAM_ADDR(w) , w
    3202                 : #else
    3203                 : #  define FMT_ADDR ""
    3204                 : #  define FMT_STR(str)
    3205                 : #  define PARAM_ADDR(w)
    3206                 : #endif
    3207                 : 
    3208           18713 :     char* sz = nsnull;
    3209           18713 :     char* name = nsnull;
    3210                 : 
    3211           18713 :     XPCNativeScriptableInfo* si = GetScriptableInfo();
    3212           18713 :     if (si)
    3213             301 :         name = JS_smprintf("%s", si->GetJSClass()->name);
    3214           18713 :     if (to) {
    3215               0 :         const char* fmt = name ? " (%s)" : "%s";
    3216                 :         name = JS_sprintf_append(name, fmt,
    3217               0 :                                  to->GetInterface()->GetNameString());
    3218           18713 :     } else if (!name) {
    3219           18412 :         XPCNativeSet* set = GetSet();
    3220           18412 :         XPCNativeInterface** array = set->GetInterfaceArray();
    3221           18412 :         PRUint16 count = set->GetInterfaceCount();
    3222                 : 
    3223           18412 :         if (count == 1)
    3224              12 :             name = JS_sprintf_append(name, "%s", array[0]->GetNameString());
    3225           22858 :         else if (count == 2 &&
    3226            4458 :                  array[0] == XPCNativeInterface::GetISupports(ccx)) {
    3227            4458 :             name = JS_sprintf_append(name, "%s", array[1]->GetNameString());
    3228                 :         } else {
    3229           78072 :             for (PRUint16 i = 0; i < count; i++) {
    3230                 :                 const char* fmt = (i == 0) ?
    3231                 :                                     "(%s" : (i == count-1) ?
    3232           64130 :                                         ", %s)" : ", %s";
    3233                 :                 name = JS_sprintf_append(name, fmt,
    3234           64130 :                                          array[i]->GetNameString());
    3235                 :             }
    3236                 :         }
    3237                 :     }
    3238                 : 
    3239           18713 :     if (!name) {
    3240               0 :         return nsnull;
    3241                 :     }
    3242                 :     const char* fmt = "[xpconnect wrapped %s" FMT_ADDR FMT_STR(" (native")
    3243           18713 :         FMT_ADDR FMT_STR(")") "]";
    3244           18713 :     if (si) {
    3245             301 :         fmt = "[object %s" FMT_ADDR FMT_STR(" (native") FMT_ADDR FMT_STR(")") "]";
    3246                 :     }
    3247           18713 :     sz = JS_smprintf(fmt, name PARAM_ADDR(this) PARAM_ADDR(mIdentity));
    3248                 : 
    3249           18713 :     JS_smprintf_free(name);
    3250                 : 
    3251                 : 
    3252           18713 :     return sz;
    3253                 : 
    3254                 : #undef FMT_ADDR
    3255                 : #undef PARAM_ADDR
    3256                 : }
    3257                 : 
    3258                 : /***************************************************************************/
    3259                 : 
    3260                 : #ifdef XPC_CHECK_CLASSINFO_CLAIMS
    3261                 : static void DEBUG_CheckClassInfoClaims(XPCWrappedNative* wrapper)
    3262                 : {
    3263                 :     if (!wrapper || !wrapper->GetClassInfo())
    3264                 :         return;
    3265                 : 
    3266                 :     nsISupports* obj = wrapper->GetIdentityObject();
    3267                 :     XPCNativeSet* set = wrapper->GetSet();
    3268                 :     PRUint16 count = set->GetInterfaceCount();
    3269                 :     for (PRUint16 i = 0; i < count; i++) {
    3270                 :         nsIClassInfo* clsInfo = wrapper->GetClassInfo();
    3271                 :         XPCNativeInterface* iface = set->GetInterfaceAt(i);
    3272                 :         nsIInterfaceInfo* info = iface->GetInterfaceInfo();
    3273                 :         const nsIID* iid;
    3274                 :         nsISupports* ptr;
    3275                 : 
    3276                 :         info->GetIIDShared(&iid);
    3277                 :         nsresult rv = obj->QueryInterface(*iid, (void**)&ptr);
    3278                 :         if (NS_SUCCEEDED(rv)) {
    3279                 :             NS_RELEASE(ptr);
    3280                 :             continue;
    3281                 :         }
    3282                 :         if (rv == NS_ERROR_OUT_OF_MEMORY)
    3283                 :             continue;
    3284                 : 
    3285                 :         // Houston, We have a problem...
    3286                 : 
    3287                 :         char* className = nsnull;
    3288                 :         char* contractID = nsnull;
    3289                 :         const char* interfaceName;
    3290                 : 
    3291                 :         info->GetNameShared(&interfaceName);
    3292                 :         clsInfo->GetContractID(&contractID);
    3293                 :         if (wrapper->GetScriptableInfo()) {
    3294                 :             wrapper->GetScriptableInfo()->GetCallback()->
    3295                 :                 GetClassName(&className);
    3296                 :         }
    3297                 : 
    3298                 : 
    3299                 :         printf("\n!!! Object's nsIClassInfo lies about its interfaces!!!\n"
    3300                 :                "   classname: %s \n"
    3301                 :                "   contractid: %s \n"
    3302                 :                "   unimplemented interface name: %s\n\n",
    3303                 :                className ? className : "<unknown>",
    3304                 :                contractID ? contractID : "<unknown>",
    3305                 :                interfaceName);
    3306                 : 
    3307                 : #ifdef XPC_ASSERT_CLASSINFO_CLAIMS
    3308                 :         NS_ERROR("Fix this QueryInterface or nsIClassInfo");
    3309                 : #endif
    3310                 : 
    3311                 :         if (className)
    3312                 :             nsMemory::Free(className);
    3313                 :         if (contractID)
    3314                 :             nsMemory::Free(contractID);
    3315                 :     }
    3316                 : }
    3317                 : #endif
    3318                 : 
    3319                 : #ifdef XPC_REPORT_SHADOWED_WRAPPED_NATIVE_MEMBERS
    3320                 : static void DEBUG_PrintShadowObjectInfo(const char* header,
    3321                 :                                         XPCNativeSet* set,
    3322                 :                                         XPCWrappedNative* wrapper,
    3323                 :                                         XPCWrappedNativeProto* proto)
    3324                 : 
    3325                 : {
    3326                 :     if (header)
    3327                 :         printf("%s\n", header);
    3328                 : 
    3329                 :     printf("   XPCNativeSet @ 0x%p for the class:\n", (void*)set);
    3330                 : 
    3331                 :     char* className = nsnull;
    3332                 :     char* contractID = nsnull;
    3333                 : 
    3334                 :     nsIClassInfo* clsInfo = proto ? proto->GetClassInfo() : nsnull;
    3335                 :     if (clsInfo)
    3336                 :         clsInfo->GetContractID(&contractID);
    3337                 : 
    3338                 :     XPCNativeScriptableInfo* si = wrapper ?
    3339                 :             wrapper->GetScriptableInfo() :
    3340                 :             proto->GetScriptableInfo();
    3341                 :     if (si)
    3342                 :         si->GetCallback()->GetClassName(&className);
    3343                 : 
    3344                 :     printf("   classname: %s \n"
    3345                 :            "   contractid: %s \n",
    3346                 :            className ? className : "<unknown>",
    3347                 :            contractID ? contractID : "<unknown>");
    3348                 : 
    3349                 :     if (className)
    3350                 :         nsMemory::Free(className);
    3351                 :     if (contractID)
    3352                 :         nsMemory::Free(contractID);
    3353                 : 
    3354                 :     printf("   claims to implement interfaces:\n");
    3355                 : 
    3356                 :     PRUint16 count = set->GetInterfaceCount();
    3357                 :     for (PRUint16 i = 0; i < count; i++) {
    3358                 :         XPCNativeInterface* iface = set->GetInterfaceAt(i);
    3359                 :         nsIInterfaceInfo* info = iface->GetInterfaceInfo();
    3360                 :         const char* interfaceName;
    3361                 :         info->GetNameShared(&interfaceName);
    3362                 :         printf("      %s\n", interfaceName);
    3363                 :     }
    3364                 : }
    3365                 : 
    3366                 : static void ReportSingleMember(jsval ifaceName,
    3367                 :                                jsval memberName)
    3368                 : {
    3369                 :     JS_FileEscapedString(stdout, ifaceName, 0);
    3370                 :     if (JSVAL_IS_STRING(memberName)) {
    3371                 :         fputs("::", stdout);
    3372                 :         JS_FileEscapedString(stdout, memberName, 0);
    3373                 :     }
    3374                 : }
    3375                 : 
    3376                 : static void ShowHeader(JSBool* printedHeader,
    3377                 :                        const char* header,
    3378                 :                        XPCNativeSet* set,
    3379                 :                        XPCWrappedNative* wrapper,
    3380                 :                        XPCWrappedNativeProto* proto)
    3381                 : {
    3382                 :     if (!*printedHeader) {
    3383                 :         DEBUG_PrintShadowObjectInfo(header, set, wrapper, proto);
    3384                 :         *printedHeader = true;
    3385                 :     }
    3386                 : 
    3387                 : }
    3388                 : 
    3389                 : static void ShowOneShadow(jsval ifaceName1,
    3390                 :                           jsval memberName1,
    3391                 :                           jsval ifaceName2,
    3392                 :                           jsval memberName2)
    3393                 : {
    3394                 :     ReportSingleMember(ifaceName1, memberName1);
    3395                 :     printf(" shadows ");
    3396                 :     ReportSingleMember(ifaceName2, memberName2);
    3397                 :     printf("\n");
    3398                 : }
    3399                 : 
    3400                 : static void ShowDuplicateInterface(jsval ifaceName)
    3401                 : {
    3402                 :     fputs(" ! ", stdout);
    3403                 :     JS_FileEscapedString(stdout, ifaceName, 0);
    3404                 :     fputs(" appears twice in the nsIClassInfo interface set!\n", stdout);
    3405                 : }
    3406                 : 
    3407                 : static JSBool InterfacesAreRelated(XPCNativeInterface* iface1,
    3408                 :                                    XPCNativeInterface* iface2)
    3409                 : {
    3410                 :     nsIInterfaceInfo* info1 = iface1->GetInterfaceInfo();
    3411                 :     nsIInterfaceInfo* info2 = iface2->GetInterfaceInfo();
    3412                 : 
    3413                 :     NS_ASSERTION(info1 != info2, "should not have different iface!");
    3414                 : 
    3415                 :     bool match;
    3416                 : 
    3417                 :     return
    3418                 :         (NS_SUCCEEDED(info1->HasAncestor(iface2->GetIID(), &match)) && match) ||
    3419                 :         (NS_SUCCEEDED(info2->HasAncestor(iface1->GetIID(), &match)) && match);
    3420                 : }
    3421                 : 
    3422                 : static JSBool MembersAreTheSame(XPCNativeInterface* iface1,
    3423                 :                                 PRUint16 memberIndex1,
    3424                 :                                 XPCNativeInterface* iface2,
    3425                 :                                 PRUint16 memberIndex2)
    3426                 : {
    3427                 :     nsIInterfaceInfo* info1 = iface1->GetInterfaceInfo();
    3428                 :     nsIInterfaceInfo* info2 = iface2->GetInterfaceInfo();
    3429                 : 
    3430                 :     XPCNativeMember* member1 = iface1->GetMemberAt(memberIndex1);
    3431                 :     XPCNativeMember* member2 = iface2->GetMemberAt(memberIndex2);
    3432                 : 
    3433                 :     PRUint16 index1 = member1->GetIndex();
    3434                 :     PRUint16 index2 = member2->GetIndex();
    3435                 : 
    3436                 :     // If they are both constants, then we'll just be sure that they are equivalent.
    3437                 : 
    3438                 :     if (member1->IsConstant()) {
    3439                 :         if (!member2->IsConstant())
    3440                 :             return false;
    3441                 : 
    3442                 :         const nsXPTConstant* constant1;
    3443                 :         const nsXPTConstant* constant2;
    3444                 : 
    3445                 :         return NS_SUCCEEDED(info1->GetConstant(index1, &constant1)) &&
    3446                 :                NS_SUCCEEDED(info2->GetConstant(index2, &constant2)) &&
    3447                 :                constant1->GetType() == constant2->GetType() &&
    3448                 :                constant1->GetValue() == constant2->GetValue();
    3449                 :     }
    3450                 : 
    3451                 :     // Else we make sure they are of the same 'type' and return true only if
    3452                 :     // they are inherited from the same interface.
    3453                 : 
    3454                 :     if (member1->IsMethod() != member2->IsMethod() ||
    3455                 :         member1->IsWritableAttribute() != member2->IsWritableAttribute() ||
    3456                 :         member1->IsReadOnlyAttribute() != member2->IsReadOnlyAttribute()) {
    3457                 :         return false;
    3458                 :     }
    3459                 : 
    3460                 :     const nsXPTMethodInfo* mi1;
    3461                 :     const nsXPTMethodInfo* mi2;
    3462                 : 
    3463                 :     return NS_SUCCEEDED(info1->GetMethodInfo(index1, &mi1)) &&
    3464                 :            NS_SUCCEEDED(info2->GetMethodInfo(index2, &mi2)) &&
    3465                 :            mi1 == mi2;
    3466                 : }
    3467                 : 
    3468                 : void DEBUG_ReportShadowedMembers(XPCNativeSet* set,
    3469                 :                                  XPCWrappedNative* wrapper,
    3470                 :                                  XPCWrappedNativeProto* proto)
    3471                 : {
    3472                 :     // NOTE: Either wrapper or proto could be null...
    3473                 : 
    3474                 :     if (!(proto || wrapper) || !set || set->GetInterfaceCount() < 2)
    3475                 :         return;
    3476                 : 
    3477                 :     NS_ASSERTION(proto || wrapper, "bad param!");
    3478                 :     XPCJSRuntime* rt = proto ? proto->GetRuntime() : wrapper->GetRuntime();
    3479                 : 
    3480                 :     // a quicky hack to avoid reporting info for the same set too often
    3481                 :     static int nextSeenSet = 0;
    3482                 :     static const int MAX_SEEN_SETS = 128;
    3483                 :     static XPCNativeSet* SeenSets[MAX_SEEN_SETS];
    3484                 :     for (int seen = 0; seen < MAX_SEEN_SETS; seen++)
    3485                 :         if (set == SeenSets[seen])
    3486                 :             return;
    3487                 :     SeenSets[nextSeenSet] = set;
    3488                 : 
    3489                 : #ifdef off_DEBUG_jband
    3490                 :     static int seenCount = 0;
    3491                 :     printf("--- adding SeenSets[%d] = 0x%p\n", nextSeenSet, set);
    3492                 :     DEBUG_PrintShadowObjectInfo(nsnull, set, wrapper, proto);
    3493                 : #endif
    3494                 :     int localNext = nextSeenSet+1;
    3495                 :     nextSeenSet = localNext < MAX_SEEN_SETS ? localNext : 0;
    3496                 : 
    3497                 :     XPCNativeScriptableInfo* si = wrapper ?
    3498                 :             wrapper->GetScriptableInfo() :
    3499                 :             proto->GetScriptableInfo();
    3500                 : 
    3501                 :     // We just want to skip some classes...
    3502                 :     if (si) {
    3503                 :         // Add any classnames to skip to this (null terminated) array...
    3504                 :         static const char* skipClasses[] = {
    3505                 :             "Window",
    3506                 :             "HTMLDocument",
    3507                 :             "HTMLCollection",
    3508                 :             "Event",
    3509                 :             "ChromeWindow",
    3510                 :             nsnull
    3511                 :         };
    3512                 : 
    3513                 :         static bool warned = false;
    3514                 :         if (!warned) {
    3515                 :             printf("!!! XPConnect won't warn about Shadowed Members of...\n  ");
    3516                 :             for (const char** name = skipClasses; *name; name++)
    3517                 :                 printf("%s %s", name == skipClasses ? "" : ",", *name);
    3518                 :              printf("\n");
    3519                 :             warned = true;
    3520                 :         }
    3521                 : 
    3522                 :         bool quit = false;
    3523                 :         char* className = nsnull;
    3524                 :         si->GetCallback()->GetClassName(&className);
    3525                 :         if (className) {
    3526                 :             for (const char** name = skipClasses; *name; name++) {
    3527                 :                 if (!strcmp(*name, className)) {
    3528                 :                     quit = true;
    3529                 :                     break;
    3530                 :                 }
    3531                 :             }
    3532                 :             nsMemory::Free(className);
    3533                 :         }
    3534                 :         if (quit)
    3535                 :             return;
    3536                 :     }
    3537                 : 
    3538                 :     const char header[] =
    3539                 :         "!!!Object wrapped by XPConnect has members whose names shadow each other!!!";
    3540                 : 
    3541                 :     JSBool printedHeader = false;
    3542                 : 
    3543                 :     jsval QIName = rt->GetStringJSVal(XPCJSRuntime::IDX_QUERY_INTERFACE);
    3544                 : 
    3545                 :     PRUint16 ifaceCount = set->GetInterfaceCount();
    3546                 :     PRUint16 i, j, k, m;
    3547                 : 
    3548                 :     // First look for duplicate interface entries
    3549                 : 
    3550                 :     for (i = 0; i < ifaceCount; i++) {
    3551                 :         XPCNativeInterface* ifaceOuter = set->GetInterfaceAt(i);
    3552                 :         for (k = i+1; k < ifaceCount; k++) {
    3553                 :             XPCNativeInterface* ifaceInner = set->GetInterfaceAt(k);
    3554                 :             if (ifaceInner == ifaceOuter) {
    3555                 :                 ShowHeader(&printedHeader, header, set, wrapper, proto);
    3556                 :                 ShowDuplicateInterface(ifaceOuter->GetName());
    3557                 :             }
    3558                 :         }
    3559                 :     }
    3560                 : 
    3561                 :     // Now scan for shadowing names
    3562                 : 
    3563                 :     for (i = 0; i < ifaceCount; i++) {
    3564                 :         XPCNativeInterface* ifaceOuter = set->GetInterfaceAt(i);
    3565                 :         jsval ifaceOuterName = ifaceOuter->GetName();
    3566                 : 
    3567                 :         PRUint16 memberCountOuter = ifaceOuter->GetMemberCount();
    3568                 :         for (j = 0; j < memberCountOuter; j++) {
    3569                 :             XPCNativeMember* memberOuter = ifaceOuter->GetMemberAt(j);
    3570                 :             jsval memberOuterName = memberOuter->GetName();
    3571                 : 
    3572                 :             if (memberOuterName == QIName)
    3573                 :                 continue;
    3574                 : 
    3575                 :             for (k = i+1; k < ifaceCount; k++) {
    3576                 :                 XPCNativeInterface* ifaceInner = set->GetInterfaceAt(k);
    3577                 :                 jsval ifaceInnerName = ifaceInner->GetName();
    3578                 : 
    3579                 :                 // Reported elsewhere.
    3580                 :                 if (ifaceInner == ifaceOuter)
    3581                 :                     continue;
    3582                 : 
    3583                 :                 // We consider this not worth reporting because callers will
    3584                 :                 // almost certainly be getting what they expect.
    3585                 :                 if (InterfacesAreRelated(ifaceInner, ifaceOuter))
    3586                 :                     continue;
    3587                 : 
    3588                 :                 if (ifaceInnerName == memberOuterName) {
    3589                 :                     ShowHeader(&printedHeader, header, set, wrapper, proto);
    3590                 :                     ShowOneShadow(ifaceInnerName, JSVAL_NULL,
    3591                 :                                   ifaceOuterName, memberOuterName);
    3592                 :                 }
    3593                 : 
    3594                 :                 PRUint16 memberCountInner = ifaceInner->GetMemberCount();
    3595                 : 
    3596                 :                 for (m = 0; m < memberCountInner; m++) {
    3597                 :                     XPCNativeMember* memberInner = ifaceInner->GetMemberAt(m);
    3598                 :                     jsval memberInnerName = memberInner->GetName();
    3599                 : 
    3600                 :                     if (memberInnerName == QIName)
    3601                 :                         continue;
    3602                 : 
    3603                 :                     if (memberOuterName == memberInnerName &&
    3604                 :                         !MembersAreTheSame(ifaceOuter, j, ifaceInner, m))
    3605                 : 
    3606                 :                     {
    3607                 :                         ShowHeader(&printedHeader, header, set, wrapper, proto);
    3608                 :                         ShowOneShadow(ifaceOuterName, memberOuterName,
    3609                 :                                       ifaceInnerName, memberInnerName);
    3610                 :                     }
    3611                 :                 }
    3612                 :             }
    3613                 :         }
    3614                 :     }
    3615                 : }
    3616                 : #endif
    3617                 : 
    3618                 : #ifdef XPC_CHECK_WRAPPER_THREADSAFETY
    3619               0 : void DEBUG_ReportWrapperThreadSafetyError(XPCCallContext& ccx,
    3620                 :                                           const char* msg,
    3621                 :                                           const XPCWrappedNative* wrapper)
    3622                 : {
    3623               0 :     XPCPerThreadData* tls = ccx.GetThreadData();
    3624               0 :     if (1 != tls->IncrementWrappedNativeThreadsafetyReportDepth())
    3625               0 :         return;
    3626                 : 
    3627               0 :     printf("---------------------------------------------------------------\n");
    3628               0 :     printf("!!!!! XPConnect wrapper thread use error...\n");
    3629                 : 
    3630               0 :     char* wrapperDump = wrapper->ToString(ccx);
    3631               0 :     if (wrapperDump) {
    3632               0 :         printf("  %s\n  wrapper: %s\n", msg, wrapperDump);
    3633               0 :         JS_smprintf_free(wrapperDump);
    3634                 :     } else
    3635               0 :         printf("  %s\n  wrapper @ 0x%p\n", msg, (void *)wrapper);
    3636                 : 
    3637               0 :     printf("  JS call stack...\n");
    3638               0 :     xpc_DumpJSStack(ccx, true, true, true);
    3639               0 :     printf("---------------------------------------------------------------\n");
    3640                 : 
    3641               0 :     tls->ClearWrappedNativeThreadsafetyReportDepth();
    3642                 : }
    3643                 : 
    3644        13310858 : void DEBUG_CheckWrapperThreadSafety(const XPCWrappedNative* wrapper)
    3645                 : {
    3646        13310858 :     XPCWrappedNativeProto* proto = wrapper->GetProto();
    3647        13310858 :     if (proto && proto->ClassIsThreadSafe())
    3648         3746104 :         return;
    3649                 : 
    3650         9564754 :     if (proto && proto->ClassIsMainThreadOnly()) {
    3651                 :         // NS_IsMainThread is safe to call even after we've started shutting
    3652                 :         // down.
    3653          195860 :         if (!NS_IsMainThread()) {
    3654               0 :             XPCCallContext ccx(NATIVE_CALLER);
    3655                 :             DEBUG_ReportWrapperThreadSafetyError(ccx,
    3656               0 :                                                  "Main Thread Only wrapper accessed on another thread", wrapper);
    3657                 :         }
    3658         9368894 :     } else if (PR_GetCurrentThread() != wrapper->mThread) {
    3659               0 :         XPCCallContext ccx(NATIVE_CALLER);
    3660                 :         DEBUG_ReportWrapperThreadSafetyError(ccx,
    3661                 :                                              "XPConnect WrappedNative is being accessed on multiple threads but "
    3662                 :                                              "the underlying native xpcom object does not have a "
    3663               0 :                                              "nsIClassInfo with the 'THREADSAFE' flag set", wrapper);
    3664                 :     }
    3665                 : }
    3666                 : #endif
    3667                 : 
    3668               0 : NS_IMPL_THREADSAFE_ISUPPORTS1(XPCJSObjectHolder, nsIXPConnectJSObjectHolder)
    3669                 : 
    3670                 : NS_IMETHODIMP
    3671               0 : XPCJSObjectHolder::GetJSObject(JSObject** aJSObj)
    3672                 : {
    3673               0 :     NS_PRECONDITION(aJSObj, "bad param");
    3674               0 :     NS_PRECONDITION(mJSObj, "bad object state");
    3675               0 :     *aJSObj = mJSObj;
    3676               0 :     return NS_OK;
    3677                 : }
    3678                 : 
    3679               0 : XPCJSObjectHolder::XPCJSObjectHolder(XPCCallContext& ccx, JSObject* obj)
    3680               0 :     : mJSObj(obj)
    3681                 : {
    3682               0 :     ccx.GetRuntime()->AddObjectHolderRoot(this);
    3683               0 : }
    3684                 : 
    3685               0 : XPCJSObjectHolder::~XPCJSObjectHolder()
    3686                 : {
    3687               0 :     RemoveFromRootSet(nsXPConnect::GetRuntimeInstance()->GetMapLock());
    3688               0 : }
    3689                 : 
    3690                 : void
    3691               0 : XPCJSObjectHolder::TraceJS(JSTracer *trc)
    3692                 : {
    3693               0 :     JS_SET_TRACING_DETAILS(trc, PrintTraceName, this, 0);
    3694               0 :     JS_CallTracer(trc, mJSObj, JSTRACE_OBJECT);
    3695               0 : }
    3696                 : 
    3697                 : #ifdef DEBUG
    3698                 : // static
    3699                 : void
    3700               0 : XPCJSObjectHolder::PrintTraceName(JSTracer* trc, char *buf, size_t bufsize)
    3701                 : {
    3702                 :     JS_snprintf(buf, bufsize, "XPCJSObjectHolder[0x%p].mJSObj",
    3703               0 :                 trc->debugPrintArg);
    3704               0 : }
    3705                 : #endif
    3706                 : 
    3707                 : // static
    3708                 : XPCJSObjectHolder*
    3709               0 : XPCJSObjectHolder::newHolder(XPCCallContext& ccx, JSObject* obj)
    3710                 : {
    3711               0 :     if (!obj) {
    3712               0 :         NS_ERROR("bad param");
    3713               0 :         return nsnull;
    3714                 :     }
    3715               0 :     return new XPCJSObjectHolder(ccx, obj);
    3716                 : }
    3717                 : 
    3718                 : JSBool
    3719            6065 : MorphSlimWrapper(JSContext *cx, JSObject *obj)
    3720                 : {
    3721                 :     SLIM_LOG(("***** morphing from MorphSlimToWrapper (%p, %p)\n",
    3722                 :               obj, static_cast<nsISupports*>(xpc_GetJSPrivate(obj))));
    3723                 : 
    3724           12130 :     XPCCallContext ccx(JS_CALLER, cx);
    3725                 : 
    3726            6065 :     nsISupports* object = static_cast<nsISupports*>(xpc_GetJSPrivate(obj));
    3727            6065 :     nsWrapperCache *cache = nsnull;
    3728            6065 :     CallQueryInterface(object, &cache);
    3729           12130 :     nsRefPtr<XPCWrappedNative> wn;
    3730                 :     nsresult rv = XPCWrappedNative::Morph(ccx, obj, nsnull, cache,
    3731            6065 :                                           getter_AddRefs(wn));
    3732            6065 :     return NS_SUCCEEDED(rv);
    3733                 : }
    3734                 : 
    3735                 : #ifdef DEBUG_slimwrappers
    3736                 : static PRUint32 sSlimWrappers;
    3737                 : #endif
    3738                 : 
    3739                 : JSBool
    3740           20112 : ConstructSlimWrapper(XPCCallContext &ccx,
    3741                 :                      xpcObjectHelper &aHelper,
    3742                 :                      XPCWrappedNativeScope* xpcScope, jsval *rval)
    3743                 : {
    3744           20112 :     nsISupports *identityObj = aHelper.GetCanonical();
    3745           20112 :     nsXPCClassInfo *classInfoHelper = aHelper.GetXPCClassInfo();
    3746                 : 
    3747                 :     uint32_t flagsInt;
    3748           20112 :     nsresult rv = classInfoHelper->GetScriptableFlags(&flagsInt);
    3749           20112 :     if (NS_FAILED(rv))
    3750               0 :         flagsInt = 0;
    3751                 : 
    3752           20112 :     XPCNativeScriptableFlags flags(flagsInt);
    3753                 : 
    3754           20112 :     NS_ASSERTION(flags.DontAskInstanceForScriptable(),
    3755                 :                  "Not supported for cached wrappers!");
    3756                 : 
    3757           20112 :     JSObject* parent = xpcScope->GetGlobalJSObject();
    3758           20112 :     if (!flags.WantPreCreate()) {
    3759                 :         SLIM_LOG_NOT_CREATED(ccx, identityObj,
    3760                 :                              "scriptable helper has no PreCreate hook");
    3761                 : 
    3762               0 :         return false;
    3763                 :     }
    3764                 : 
    3765           20112 :     JSObject* plannedParent = parent;
    3766           20112 :     rv = classInfoHelper->PreCreate(identityObj, ccx, parent, &parent);
    3767           20112 :     if (rv != NS_SUCCESS_ALLOW_SLIM_WRAPPERS) {
    3768                 :         SLIM_LOG_NOT_CREATED(ccx, identityObj, "PreCreate hook refused");
    3769                 : 
    3770            4969 :         return false;
    3771                 :     }
    3772                 : 
    3773           15143 :     if (!js::IsObjectInContextCompartment(parent, ccx.GetJSContext())) {
    3774                 :         SLIM_LOG_NOT_CREATED(ccx, identityObj, "wrong compartment");
    3775                 : 
    3776               0 :         return false;
    3777                 :     }
    3778                 : 
    3779           30286 :     JSAutoEnterCompartment ac;
    3780           15143 :     if (!ac.enter(ccx, parent)) {
    3781                 :         SLIM_LOG_NOT_CREATED(ccx, identityObj, "unable to enter compartment");
    3782                 : 
    3783               0 :         return false;
    3784                 :     }
    3785                 : 
    3786           15143 :     if (parent != plannedParent) {
    3787                 :         XPCWrappedNativeScope *newXpcScope =
    3788           15143 :             XPCWrappedNativeScope::FindInJSObjectScope(ccx, parent);
    3789           15143 :         if (newXpcScope != xpcScope) {
    3790                 :             SLIM_LOG_NOT_CREATED(ccx, identityObj, "crossing origins");
    3791                 : 
    3792               0 :             return false;
    3793                 :         }
    3794                 :     }
    3795                 : 
    3796                 :     // The PreCreate hook could have forced the creation of a wrapper, need
    3797                 :     // to check for that here and return early.
    3798           15143 :     nsWrapperCache *cache = aHelper.GetWrapperCache();
    3799           15143 :     JSObject* wrapper = cache->GetWrapper();
    3800           15143 :     if (wrapper) {
    3801               0 :         *rval = OBJECT_TO_JSVAL(wrapper);
    3802                 : 
    3803               0 :         return true;
    3804                 :     }
    3805                 : 
    3806           15143 :     PRUint32 interfacesBitmap = classInfoHelper->GetInterfacesBitmap();
    3807                 :     XPCNativeScriptableCreateInfo
    3808           30286 :         sciProto(aHelper.forgetXPCClassInfo(), flags, interfacesBitmap);
    3809                 : 
    3810           30286 :     AutoMarkingWrappedNativeProtoPtr xpcproto(ccx);
    3811                 :     xpcproto = XPCWrappedNativeProto::GetNewOrUsed(ccx, xpcScope,
    3812           15143 :                                                    classInfoHelper, &sciProto);
    3813           15143 :     if (!xpcproto)
    3814               0 :         return false;
    3815                 : 
    3816           15143 :     xpcproto->CacheOffsets(identityObj);
    3817                 : 
    3818           15143 :     XPCNativeScriptableInfo* si = xpcproto->GetScriptableInfo();
    3819           15143 :     JSClass* jsclazz = si->GetSlimJSClass();
    3820           15143 :     if (!jsclazz)
    3821               0 :         return false;
    3822                 : 
    3823                 :     wrapper = xpc_NewSystemInheritingJSObject(ccx, jsclazz,
    3824                 :                                               xpcproto->GetJSProtoObject(),
    3825           15143 :                                               false, parent);
    3826           15143 :     if (!wrapper)
    3827               0 :         return false;
    3828                 : 
    3829           15143 :     JS_SetPrivate(wrapper, identityObj);
    3830           15143 :     JS_SetReservedSlot(wrapper, 0, PRIVATE_TO_JSVAL(xpcproto.get()));
    3831                 : 
    3832                 :     // Transfer ownership to the wrapper's private.
    3833           15143 :     aHelper.forgetCanonical();
    3834                 : 
    3835           15143 :     cache->SetWrapper(wrapper);
    3836                 : 
    3837                 :     SLIM_LOG(("+++++ %i created slim wrapper (%p, %p, %p)\n", ++sSlimWrappers,
    3838                 :               wrapper, p, xpcScope));
    3839                 : 
    3840           15143 :     *rval = OBJECT_TO_JSVAL(wrapper);
    3841                 : 
    3842           15143 :     return true;
    3843            4188 : }

Generated by: LCOV version 1.7