1/*
2 * Copyright (C) 2004, 2006 Apple Computer, Inc.  All rights reserved.
3 * Copyright (C) 2007-2009 Google, Inc.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "config.h"
28
29#include "bindings/core/v8/NPV8Object.h"
30#include "bindings/core/v8/V8NPObject.h"
31#include "bindings/core/v8/npruntime_impl.h"
32#include "bindings/core/v8/npruntime_priv.h"
33
34#include "wtf/Assertions.h"
35#include "wtf/HashMap.h"
36#include "wtf/HashSet.h"
37#include "wtf/HashTableDeletedValueType.h"
38
39#include <stdlib.h>
40
41using namespace blink;
42
43// FIXME: Consider removing locks if we're singlethreaded already.
44// The static initializer here should work okay, but we want to avoid
45// static initialization in general.
46
47namespace npruntime {
48
49// We use StringKey here as the key-type to avoid a string copy to
50// construct the map key and for faster comparisons than strcmp.
51class StringKey {
52public:
53    explicit StringKey(const char* str) : m_string(str), m_length(strlen(str)) { }
54    StringKey() : m_string(0), m_length(0) { }
55    explicit StringKey(WTF::HashTableDeletedValueType) : m_string(hashTableDeletedValue()), m_length(0) { }
56
57    StringKey& operator=(const StringKey& other)
58    {
59        this->m_string = other.m_string;
60        this->m_length = other.m_length;
61        return *this;
62    }
63
64    bool isHashTableDeletedValue() const
65    {
66        return m_string == hashTableDeletedValue();
67    }
68
69    const char* m_string;
70    size_t m_length;
71
72private:
73    const char* hashTableDeletedValue() const
74    {
75        return reinterpret_cast<const char*>(-1);
76    }
77};
78
79inline bool operator==(const StringKey& x, const StringKey& y)
80{
81    if (x.m_length != y.m_length)
82        return false;
83    if (x.m_string == y.m_string)
84        return true;
85
86    ASSERT(!x.isHashTableDeletedValue() && !y.isHashTableDeletedValue());
87    return !memcmp(x.m_string, y.m_string, y.m_length);
88}
89
90// Implement WTF::DefaultHash<StringKey>::Hash interface.
91struct StringKeyHash {
92    static unsigned hash(const StringKey& key)
93    {
94        // Compute string hash.
95        unsigned hash = 0;
96        size_t len = key.m_length;
97        const char* str = key.m_string;
98        for (size_t i = 0; i < len; i++) {
99            char c = str[i];
100            hash += c;
101            hash += (hash << 10);
102            hash ^= (hash >> 6);
103        }
104        hash += (hash << 3);
105        hash ^= (hash >> 11);
106        hash += (hash << 15);
107        if (hash == 0)
108            hash = 27;
109        return hash;
110    }
111
112    static bool equal(const StringKey& x, const StringKey& y)
113    {
114        return x == y;
115    }
116
117    static const bool safeToCompareToEmptyOrDeleted = true;
118};
119
120}  // namespace npruntime
121
122using npruntime::StringKey;
123using npruntime::StringKeyHash;
124
125// Implement HashTraits<StringKey>
126struct StringKeyHashTraits : WTF::GenericHashTraits<StringKey> {
127    static void constructDeletedValue(StringKey& slot, bool)
128    {
129        new (&slot) StringKey(WTF::HashTableDeletedValue);
130    }
131
132    static bool isDeletedValue(const StringKey& value)
133    {
134        return value.isHashTableDeletedValue();
135    }
136};
137
138typedef WTF::HashMap<StringKey, PrivateIdentifier*, StringKeyHash, StringKeyHashTraits> StringIdentifierMap;
139
140static StringIdentifierMap* getStringIdentifierMap()
141{
142    static StringIdentifierMap* stringIdentifierMap = 0;
143    if (!stringIdentifierMap)
144        stringIdentifierMap = new StringIdentifierMap();
145    return stringIdentifierMap;
146}
147
148typedef WTF::HashMap<int, PrivateIdentifier*> IntIdentifierMap;
149
150static IntIdentifierMap* getIntIdentifierMap()
151{
152    static IntIdentifierMap* intIdentifierMap = 0;
153    if (!intIdentifierMap)
154        intIdentifierMap = new IntIdentifierMap();
155    return intIdentifierMap;
156}
157
158extern "C" {
159
160NPIdentifier _NPN_GetStringIdentifier(const NPUTF8* name)
161{
162    ASSERT(name);
163
164    if (name) {
165
166        StringKey key(name);
167        StringIdentifierMap* identMap = getStringIdentifierMap();
168        StringIdentifierMap::iterator iter = identMap->find(key);
169        if (iter != identMap->end())
170            return static_cast<NPIdentifier>(iter->value);
171
172        size_t nameLen = key.m_length;
173
174        // We never release identifiers, so this dictionary will grow.
175        PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(malloc(sizeof(PrivateIdentifier) + nameLen + 1));
176        char* nameStorage = reinterpret_cast<char*>(identifier + 1);
177        memcpy(nameStorage, name, nameLen + 1);
178        identifier->isString = true;
179        identifier->value.string = reinterpret_cast<NPUTF8*>(nameStorage);
180        key.m_string = nameStorage;
181        identMap->set(key, identifier);
182        return (NPIdentifier)identifier;
183    }
184
185    return 0;
186}
187
188void _NPN_GetStringIdentifiers(const NPUTF8** names, int32_t nameCount, NPIdentifier* identifiers)
189{
190    ASSERT(names);
191    ASSERT(identifiers);
192
193    if (names && identifiers) {
194        for (int i = 0; i < nameCount; i++)
195            identifiers[i] = _NPN_GetStringIdentifier(names[i]);
196    }
197}
198
199NPIdentifier _NPN_GetIntIdentifier(int32_t intId)
200{
201    // Special case for -1 and 0, both cannot be used as key in HashMap.
202    if (!intId || intId == -1) {
203        static PrivateIdentifier* minusOneOrZeroIds[2];
204        PrivateIdentifier* id = minusOneOrZeroIds[intId + 1];
205        if (!id) {
206            id = reinterpret_cast<PrivateIdentifier*>(malloc(sizeof(PrivateIdentifier)));
207            id->isString = false;
208            id->value.number = intId;
209            minusOneOrZeroIds[intId + 1] = id;
210        }
211        return (NPIdentifier) id;
212    }
213
214    IntIdentifierMap* identMap = getIntIdentifierMap();
215    IntIdentifierMap::iterator iter = identMap->find(intId);
216    if (iter != identMap->end())
217        return static_cast<NPIdentifier>(iter->value);
218
219    // We never release identifiers, so this dictionary will grow.
220    PrivateIdentifier* identifier = reinterpret_cast<PrivateIdentifier*>(malloc(sizeof(PrivateIdentifier)));
221    identifier->isString = false;
222    identifier->value.number = intId;
223    identMap->set(intId, identifier);
224    return (NPIdentifier)identifier;
225}
226
227bool _NPN_IdentifierIsString(NPIdentifier identifier)
228{
229    PrivateIdentifier* privateIdentifier = reinterpret_cast<PrivateIdentifier*>(identifier);
230    return privateIdentifier->isString;
231}
232
233NPUTF8 *_NPN_UTF8FromIdentifier(NPIdentifier identifier)
234{
235    PrivateIdentifier* privateIdentifier = reinterpret_cast<PrivateIdentifier*>(identifier);
236    if (!privateIdentifier->isString || !privateIdentifier->value.string)
237        return 0;
238
239    return (NPUTF8*) strdup(privateIdentifier->value.string);
240}
241
242int32_t _NPN_IntFromIdentifier(NPIdentifier identifier)
243{
244    PrivateIdentifier* privateIdentifier = reinterpret_cast<PrivateIdentifier*>(identifier);
245    if (privateIdentifier->isString)
246        return 0;
247    return privateIdentifier->value.number;
248}
249
250void _NPN_ReleaseVariantValue(NPVariant* variant)
251{
252    ASSERT(variant);
253
254    if (variant->type == NPVariantType_Object) {
255        _NPN_ReleaseObject(variant->value.objectValue);
256        variant->value.objectValue = 0;
257    } else if (variant->type == NPVariantType_String) {
258        free((void*)variant->value.stringValue.UTF8Characters);
259        variant->value.stringValue.UTF8Characters = 0;
260        variant->value.stringValue.UTF8Length = 0;
261    }
262
263    variant->type = NPVariantType_Void;
264}
265
266NPObject *_NPN_CreateObject(NPP npp, NPClass* npClass)
267{
268    ASSERT(npClass);
269
270    if (npClass) {
271        NPObject* npObject;
272        if (npClass->allocate != 0)
273            npObject = npClass->allocate(npp, npClass);
274        else
275            npObject = reinterpret_cast<NPObject*>(malloc(sizeof(NPObject)));
276
277        npObject->_class = npClass;
278        npObject->referenceCount = 1;
279        return npObject;
280    }
281
282    return 0;
283}
284
285NPObject* _NPN_RetainObject(NPObject* npObject)
286{
287    ASSERT(npObject);
288    ASSERT(npObject->referenceCount > 0);
289
290    if (npObject)
291        npObject->referenceCount++;
292
293    return npObject;
294}
295
296// _NPN_DeallocateObject actually deletes the object.  Technically,
297// callers should use _NPN_ReleaseObject.  Webkit exposes this function
298// to kill objects which plugins may not have properly released.
299void _NPN_DeallocateObject(NPObject* npObject)
300{
301    ASSERT(npObject);
302
303    if (npObject) {
304        // NPObjects that remain in pure C++ may never have wrappers.
305        // Hence, if it's not already alive, don't unregister it.
306        // If it is alive, unregister it as the *last* thing we do
307        // so that it can do as much cleanup as possible on its own.
308        if (_NPN_IsAlive(npObject))
309            _NPN_UnregisterObject(npObject);
310
311        npObject->referenceCount = 0xFFFFFFFF;
312        if (npObject->_class->deallocate)
313            npObject->_class->deallocate(npObject);
314        else
315            free(npObject);
316    }
317}
318
319void _NPN_ReleaseObject(NPObject* npObject)
320{
321    ASSERT(npObject);
322    ASSERT(npObject->referenceCount >= 1);
323
324    if (npObject && npObject->referenceCount >= 1) {
325        if (!--npObject->referenceCount)
326            _NPN_DeallocateObject(npObject);
327    }
328}
329
330void _NPN_InitializeVariantWithStringCopy(NPVariant* variant, const NPString* value)
331{
332    variant->type = NPVariantType_String;
333    variant->value.stringValue.UTF8Length = value->UTF8Length;
334    variant->value.stringValue.UTF8Characters = reinterpret_cast<NPUTF8*>(malloc(sizeof(NPUTF8) * value->UTF8Length));
335    memcpy((void*)variant->value.stringValue.UTF8Characters, value->UTF8Characters, sizeof(NPUTF8) * value->UTF8Length);
336}
337
338} // extern "C"
339
340// NPN_Registry
341//
342// The registry is designed for quick lookup of NPObjects.
343// JS needs to be able to quickly lookup a given NPObject to determine
344// if it is alive or not.
345// The browser needs to be able to quickly lookup all NPObjects which are
346// "owned" by an object.
347//
348// The liveObjectMap is a hash table of all live objects to their owner
349// objects.  Presence in this table is used primarily to determine if
350// objects are live or not.
351//
352// The rootObjectMap is a hash table of root objects to a set of
353// objects that should be deactivated in sync with the root.  A
354// root is defined as a top-level owner object.  This is used on
355// LocalFrame teardown to deactivate all objects associated
356// with a particular plugin.
357
358typedef WTF::HashSet<NPObject*> NPObjectSet;
359typedef WTF::HashMap<NPObject*, NPObject*> NPObjectMap;
360typedef WTF::HashMap<NPObject*, NPObjectSet*> NPRootObjectMap;
361
362// A map of live NPObjects with pointers to their Roots.
363static NPObjectMap& liveObjectMap()
364{
365    DEFINE_STATIC_LOCAL(NPObjectMap, objectMap, ());
366    return objectMap;
367}
368
369// A map of the root objects and the list of NPObjects
370// associated with that object.
371static NPRootObjectMap& rootObjectMap()
372{
373    DEFINE_STATIC_LOCAL(NPRootObjectMap, objectMap, ());
374    return objectMap;
375}
376
377extern "C" {
378
379void _NPN_RegisterObject(NPObject* npObject, NPObject* owner)
380{
381    ASSERT(npObject);
382
383    // Check if already registered.
384    if (liveObjectMap().find(npObject) != liveObjectMap().end())
385        return;
386
387    if (!owner) {
388        // Registering a new owner object.
389        ASSERT(rootObjectMap().find(npObject) == rootObjectMap().end());
390        rootObjectMap().set(npObject, new NPObjectSet());
391    } else {
392        // Always associate this object with it's top-most parent.
393        // Since we always flatten, we only have to look up one level.
394        NPObjectMap::iterator ownerEntry = liveObjectMap().find(owner);
395        NPObject* parent = 0;
396        if (liveObjectMap().end() != ownerEntry)
397            parent = ownerEntry->value;
398
399        if (parent)
400            owner = parent;
401        ASSERT(rootObjectMap().find(npObject) == rootObjectMap().end());
402        if (rootObjectMap().find(owner) != rootObjectMap().end())
403            rootObjectMap().get(owner)->add(npObject);
404    }
405
406    ASSERT(liveObjectMap().find(npObject) == liveObjectMap().end());
407    liveObjectMap().set(npObject, owner);
408}
409
410void _NPN_UnregisterObject(NPObject* npObject)
411{
412    ASSERT(npObject);
413    ASSERT_WITH_SECURITY_IMPLICATION(liveObjectMap().find(npObject) != liveObjectMap().end());
414
415    NPObject* owner = 0;
416    if (liveObjectMap().find(npObject) != liveObjectMap().end())
417        owner = liveObjectMap().find(npObject)->value;
418
419    if (!owner) {
420        // Unregistering a owner object; also unregister it's descendants.
421        ASSERT_WITH_SECURITY_IMPLICATION(rootObjectMap().find(npObject) != rootObjectMap().end());
422        NPObjectSet* set = rootObjectMap().get(npObject);
423        while (set->size() > 0) {
424#if ENABLE(ASSERT)
425            unsigned size = set->size();
426#endif
427            NPObject* sub_object = *(set->begin());
428            // The sub-object should not be a owner!
429            ASSERT(rootObjectMap().find(sub_object) == rootObjectMap().end());
430
431            // First, unregister the object.
432            set->remove(sub_object);
433            liveObjectMap().remove(sub_object);
434
435            // Script objects hold a refernce to their LocalDOMWindow*, which is going away if
436            // we're unregistering the associated owner NPObject. Clear it out.
437            if (V8NPObject* v8npObject = npObjectToV8NPObject(sub_object))
438                v8npObject->rootObject = 0;
439
440            // Remove the JS references to the object.
441            forgetV8ObjectForNPObject(sub_object);
442
443            ASSERT(set->size() < size);
444        }
445        delete set;
446        rootObjectMap().remove(npObject);
447    } else {
448        NPRootObjectMap::iterator ownerEntry = rootObjectMap().find(owner);
449        if (ownerEntry != rootObjectMap().end()) {
450            NPObjectSet* list = ownerEntry->value;
451            ASSERT(list->find(npObject) != list->end());
452            list->remove(npObject);
453        }
454    }
455
456    liveObjectMap().remove(npObject);
457    forgetV8ObjectForNPObject(npObject);
458}
459
460bool _NPN_IsAlive(NPObject* npObject)
461{
462    return liveObjectMap().find(npObject) != liveObjectMap().end();
463}
464
465} // extern "C"
466