npruntime.cpp 14.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*
 * Copyright (C) 2004, 2006 Apple Computer, Inc.  All rights reserved.
 * Copyright (C) 2007-2009 Google, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include "NPV8Object.h"
30
#include "npruntime_impl.h"
31 32 33 34 35 36 37 38 39 40 41
#include "npruntime_priv.h"
#include "V8NPObject.h"

#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/Assertions.h>

// FIXME: Consider removing locks if we're singlethreaded already.
// The static initializer here should work okay, but we want to avoid
// static initialization in general.

42
namespace npruntime {
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

// We use StringKey here as the key-type to avoid a string copy to
// construct the map key and for faster comparisons than strcmp.
class StringKey {
public:
    explicit StringKey(const char* str) : m_string(str), m_length(strlen(str)) { }
    StringKey() : m_string(0), m_length(0) { }
    explicit StringKey(WTF::HashTableDeletedValueType) : m_string(hashTableDeletedValue()), m_length(0) { }

    StringKey& operator=(const StringKey& other)
    {
        this->m_string = other.m_string;
        this->m_length = other.m_length;
        return *this;
    }

    bool isHashTableDeletedValue() const
    {
        return m_string == hashTableDeletedValue();
    }

    const char* m_string;
    size_t m_length;

private:
    const char* hashTableDeletedValue() const
    {
        return reinterpret_cast<const char*>(-1);
    }
};

inline bool operator==(const StringKey& x, const StringKey& y)
{
    if (x.m_length != y.m_length)
        return false;
    if (x.m_string == y.m_string)
        return true;

    ASSERT(!x.isHashTableDeletedValue() && !y.isHashTableDeletedValue());
    return !memcmp(x.m_string, y.m_string, y.m_length);
}

// Implement WTF::DefaultHash<StringKey>::Hash interface.
struct StringKeyHash {
    static unsigned hash(const StringKey& key)
    {
        // Compute string hash.
        unsigned hash = 0;
        size_t len = key.m_length;
        const char* str = key.m_string;
        for (size_t i = 0; i < len; i++) {
            char c = str[i];
            hash += c;
            hash += (hash << 10);
            hash ^= (hash >> 6);
        }
        hash += (hash << 3);
        hash ^= (hash >> 11);
        hash += (hash << 15);
        if (hash == 0)
            hash = 27;
        return hash;
    }

    static bool equal(const StringKey& x, const StringKey& y)
    {
        return x == y;
    }

    static const bool safeToCompareToEmptyOrDeleted = true;
};

115 116 117 118
}  // namespace npruntime

using npruntime::StringKey;
using npruntime::StringKeyHash;
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

// Implement HashTraits<StringKey>
struct StringKeyHashTraits : WTF::GenericHashTraits<StringKey> {
    static void constructDeletedValue(StringKey& slot)
    {
        new (&slot) StringKey(WTF::HashTableDeletedValue);
    }

    static bool isDeletedValue(const StringKey& value)
    {
        return value.isHashTableDeletedValue();
    }
};

typedef WTF::HashMap<StringKey, PrivateIdentifier*, StringKeyHash, StringKeyHashTraits> StringIdentifierMap;

static StringIdentifierMap* getStringIdentifierMap()
{
    static StringIdentifierMap* stringIdentifierMap = 0;
    if (!stringIdentifierMap)
        stringIdentifierMap = new StringIdentifierMap();
    return stringIdentifierMap;
}

typedef WTF::HashMap<int, PrivateIdentifier*> IntIdentifierMap;

static IntIdentifierMap* getIntIdentifierMap()
{
    static IntIdentifierMap* intIdentifierMap = 0;
    if (!intIdentifierMap)
        intIdentifierMap = new IntIdentifierMap();
    return intIdentifierMap;
}

extern "C" {

155
NPIdentifier _NPN_GetStringIdentifier(const NPUTF8* name)
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
{
    ASSERT(name);

    if (name) {

        StringKey key(name);
        StringIdentifierMap* identMap = getStringIdentifierMap();
        StringIdentifierMap::iterator iter = identMap->find(key);
        if (iter != identMap->end())
            return static_cast<NPIdentifier>(iter->second);

        size_t nameLen = key.m_length;

        // We never release identifiers, so this dictionary will grow.
        PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(malloc(sizeof(PrivateIdentifier) + nameLen + 1));
        char* nameStorage = reinterpret_cast<char*>(identifier + 1);
        memcpy(nameStorage, name, nameLen + 1);
        identifier->isString = true;
        identifier->value.string = reinterpret_cast<NPUTF8*>(nameStorage);
        key.m_string = nameStorage;
        identMap->set(key, identifier);
        return (NPIdentifier)identifier;
    }

    return 0;
}

183
void _NPN_GetStringIdentifiers(const NPUTF8** names, int32_t nameCount, NPIdentifier* identifiers)
184 185 186 187 188 189
{
    ASSERT(names);
    ASSERT(identifiers);

    if (names && identifiers) {
        for (int i = 0; i < nameCount; i++)
190
            identifiers[i] = _NPN_GetStringIdentifier(names[i]);
191 192 193
    }
}

194
NPIdentifier _NPN_GetIntIdentifier(int32_t intId)
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
{
    // Special case for -1 and 0, both cannot be used as key in HashMap.
    if (!intId || intId == -1) {
        static PrivateIdentifier* minusOneOrZeroIds[2];
        PrivateIdentifier* id = minusOneOrZeroIds[intId + 1];
        if (!id) {
            id = reinterpret_cast<PrivateIdentifier*>(malloc(sizeof(PrivateIdentifier)));
            id->isString = false;
            id->value.number = intId;
            minusOneOrZeroIds[intId + 1] = id;
        }
        return (NPIdentifier) id;
    }

    IntIdentifierMap* identMap = getIntIdentifierMap();
    IntIdentifierMap::iterator iter = identMap->find(intId);
    if (iter != identMap->end())
        return static_cast<NPIdentifier>(iter->second);

    // We never release identifiers, so this dictionary will grow.
    PrivateIdentifier* identifier = reinterpret_cast<PrivateIdentifier*>(malloc(sizeof(PrivateIdentifier)));
    identifier->isString = false;
    identifier->value.number = intId;
    identMap->set(intId, identifier);
    return (NPIdentifier)identifier;
}

222
bool _NPN_IdentifierIsString(NPIdentifier identifier)
223 224 225 226 227
{
    PrivateIdentifier* privateIdentifier = reinterpret_cast<PrivateIdentifier*>(identifier);
    return privateIdentifier->isString;
}

228
NPUTF8 *_NPN_UTF8FromIdentifier(NPIdentifier identifier)
229 230 231 232 233 234 235 236
{
    PrivateIdentifier* privateIdentifier = reinterpret_cast<PrivateIdentifier*>(identifier);
    if (!privateIdentifier->isString || !privateIdentifier->value.string)
        return 0;

    return (NPUTF8*) strdup(privateIdentifier->value.string);
}

237
int32_t _NPN_IntFromIdentifier(NPIdentifier identifier)
238 239 240 241 242 243 244
{
    PrivateIdentifier* privateIdentifier = reinterpret_cast<PrivateIdentifier*>(identifier);
    if (privateIdentifier->isString)
        return 0;
    return privateIdentifier->value.number;
}

245
void _NPN_ReleaseVariantValue(NPVariant* variant)
246 247 248 249
{
    ASSERT(variant);

    if (variant->type == NPVariantType_Object) {
250
        _NPN_ReleaseObject(variant->value.objectValue);
251 252 253 254 255 256 257 258 259 260
        variant->value.objectValue = 0;
    } else if (variant->type == NPVariantType_String) {
        free((void*)variant->value.stringValue.UTF8Characters);
        variant->value.stringValue.UTF8Characters = 0;
        variant->value.stringValue.UTF8Length = 0;
    }

    variant->type = NPVariantType_Void;
}

261
NPObject *_NPN_CreateObject(NPP npp, NPClass* npClass)
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
{
    ASSERT(npClass);

    if (npClass) {
        NPObject* npObject;
        if (npClass->allocate != 0)
            npObject = npClass->allocate(npp, npClass);
        else
            npObject = reinterpret_cast<NPObject*>(malloc(sizeof(NPObject)));

        npObject->_class = npClass;
        npObject->referenceCount = 1;
        return npObject;
    }

    return 0;
}

280
NPObject* _NPN_RetainObject(NPObject* npObject)
281 282 283 284 285 286 287 288 289 290 291
{
    ASSERT(npObject);
    ASSERT(npObject->referenceCount > 0);

    if (npObject)
        npObject->referenceCount++;

    return npObject;
}

// _NPN_DeallocateObject actually deletes the object.  Technically,
292
// callers should use _NPN_ReleaseObject.  Webkit exposes this function
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
// to kill objects which plugins may not have properly released.
void _NPN_DeallocateObject(NPObject* npObject)
{
    ASSERT(npObject);
    ASSERT(npObject->referenceCount >= 0);

    if (npObject) {
        // NPObjects that remain in pure C++ may never have wrappers.
        // Hence, if it's not already alive, don't unregister it.
        // If it is alive, unregister it as the *last* thing we do
        // so that it can do as much cleanup as possible on its own.
        if (_NPN_IsAlive(npObject))
            _NPN_UnregisterObject(npObject);

        npObject->referenceCount = -1;
        if (npObject->_class->deallocate)
            npObject->_class->deallocate(npObject);
        else
            free(npObject);
    }
}

315
void _NPN_ReleaseObject(NPObject* npObject)
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
{
    ASSERT(npObject);
    ASSERT(npObject->referenceCount >= 1);

    if (npObject && npObject->referenceCount >= 1) {
        if (!--npObject->referenceCount)
            _NPN_DeallocateObject(npObject);
    }
}

void _NPN_InitializeVariantWithStringCopy(NPVariant* variant, const NPString* value)
{
    variant->type = NPVariantType_String;
    variant->value.stringValue.UTF8Length = value->UTF8Length;
    variant->value.stringValue.UTF8Characters = reinterpret_cast<NPUTF8*>(malloc(sizeof(NPUTF8) * value->UTF8Length));
    memcpy((void*)variant->value.stringValue.UTF8Characters, value->UTF8Characters, sizeof(NPUTF8) * value->UTF8Length);
}


// NPN_Registry
//
// The registry is designed for quick lookup of NPObjects.
// JS needs to be able to quickly lookup a given NPObject to determine
// if it is alive or not.
// The browser needs to be able to quickly lookup all NPObjects which are
// "owned" by an object.
//
// The liveObjectMap is a hash table of all live objects to their owner
// objects.  Presence in this table is used primarily to determine if
// objects are live or not.
//
// The rootObjectMap is a hash table of root objects to a set of
// objects that should be deactivated in sync with the root.  A
// root is defined as a top-level owner object.  This is used on
// Frame teardown to deactivate all objects associated
// with a particular plugin.

typedef WTF::HashSet<NPObject*> NPObjectSet;
typedef WTF::HashMap<NPObject*, NPObject*> NPObjectMap;
typedef WTF::HashMap<NPObject*, NPObjectSet*> NPRootObjectMap;

// A map of live NPObjects with pointers to their Roots.
NPObjectMap liveObjectMap;

// A map of the root objects and the list of NPObjects
// associated with that object.
NPRootObjectMap rootObjectMap;

void _NPN_RegisterObject(NPObject* npObject, NPObject* owner)
{
    ASSERT(npObject);

    // Check if already registered.
    if (liveObjectMap.find(npObject) != liveObjectMap.end())
        return;

    if (!owner) {
        // Registering a new owner object.
        ASSERT(rootObjectMap.find(npObject) == rootObjectMap.end());
        rootObjectMap.set(npObject, new NPObjectSet());
    } else {
        // Always associate this object with it's top-most parent.
        // Since we always flatten, we only have to look up one level.
        NPObjectMap::iterator ownerEntry = liveObjectMap.find(owner);
        NPObject* parent = 0;
        if (liveObjectMap.end() != ownerEntry)
            parent = ownerEntry->second;

        if (parent)
            owner = parent;
        ASSERT(rootObjectMap.find(npObject) == rootObjectMap.end());
        if (rootObjectMap.find(owner) != rootObjectMap.end())
            rootObjectMap.get(owner)->add(npObject);
    }

    ASSERT(liveObjectMap.find(npObject) == liveObjectMap.end());
    liveObjectMap.set(npObject, owner);
}

void _NPN_UnregisterObject(NPObject* npObject)
{
    ASSERT(npObject);
    ASSERT(liveObjectMap.find(npObject) != liveObjectMap.end());

    NPObject* owner = 0;
    if (liveObjectMap.find(npObject) != liveObjectMap.end())
        owner = liveObjectMap.find(npObject)->second;

    if (!owner) {
        // Unregistering a owner object; also unregister it's descendants.
        ASSERT(rootObjectMap.find(npObject) != rootObjectMap.end());
        NPObjectSet* set = rootObjectMap.get(npObject);
        while (set->size() > 0) {
#ifndef NDEBUG
            int size = set->size();
#endif
            NPObject* sub_object = *(set->begin());
            // The sub-object should not be a owner!
            ASSERT(rootObjectMap.find(sub_object) == rootObjectMap.end());

            // First, unregister the object.
            set->remove(sub_object);
            liveObjectMap.remove(sub_object);

            // Remove the JS references to the object.
            forgetV8ObjectForNPObject(sub_object);

            ASSERT(set->size() < size);
        }
        delete set;
        rootObjectMap.remove(npObject);
    } else {
        NPRootObjectMap::iterator ownerEntry = rootObjectMap.find(owner);
        if (ownerEntry != rootObjectMap.end()) {
            NPObjectSet* list = ownerEntry->second;
            ASSERT(list->find(npObject) != list->end());
            list->remove(npObject);
        }
    }

    liveObjectMap.remove(npObject);
    forgetV8ObjectForNPObject(npObject);
}

bool _NPN_IsAlive(NPObject* npObject)
{
    return liveObjectMap.find(npObject) != liveObjectMap.end();
}

}  // extern "C"