1/*
2 * Copyright (C) 2006, 2007 Apple Inc.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27#include "JSClassRef.h"
28
29#include "APICast.h"
30#include "Identifier.h"
31#include "InitializeThreading.h"
32#include "JSCallbackObject.h"
33#include "JSGlobalObject.h"
34#include "JSObjectRef.h"
35#include "ObjectPrototype.h"
36#include "Operations.h"
37#include <wtf/text/StringHash.h>
38#include <wtf/unicode/UTF8.h>
39
40using namespace std;
41using namespace JSC;
42using namespace WTF::Unicode;
43
44const JSClassDefinition kJSClassDefinitionEmpty = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
45
46OpaqueJSClass::OpaqueJSClass(const JSClassDefinition* definition, OpaqueJSClass* protoClass)
47    : parentClass(definition->parentClass)
48    , prototypeClass(0)
49    , initialize(definition->initialize)
50    , finalize(definition->finalize)
51    , hasProperty(definition->hasProperty)
52    , getProperty(definition->getProperty)
53    , setProperty(definition->setProperty)
54    , deleteProperty(definition->deleteProperty)
55    , getPropertyNames(definition->getPropertyNames)
56    , callAsFunction(definition->callAsFunction)
57    , callAsConstructor(definition->callAsConstructor)
58    , hasInstance(definition->hasInstance)
59    , convertToType(definition->convertToType)
60    , m_className(String::fromUTF8(definition->className))
61{
62    initializeThreading();
63
64    if (const JSStaticValue* staticValue = definition->staticValues) {
65        m_staticValues = adoptPtr(new OpaqueJSClassStaticValuesTable);
66        while (staticValue->name) {
67            String valueName = String::fromUTF8(staticValue->name);
68            if (!valueName.isNull())
69                m_staticValues->set(valueName.impl(), adoptPtr(new StaticValueEntry(staticValue->getProperty, staticValue->setProperty, staticValue->attributes)));
70            ++staticValue;
71        }
72    }
73
74    if (const JSStaticFunction* staticFunction = definition->staticFunctions) {
75        m_staticFunctions = adoptPtr(new OpaqueJSClassStaticFunctionsTable);
76        while (staticFunction->name) {
77            String functionName = String::fromUTF8(staticFunction->name);
78            if (!functionName.isNull())
79                m_staticFunctions->set(functionName.impl(), adoptPtr(new StaticFunctionEntry(staticFunction->callAsFunction, staticFunction->attributes)));
80            ++staticFunction;
81        }
82    }
83
84    if (protoClass)
85        prototypeClass = JSClassRetain(protoClass);
86}
87
88OpaqueJSClass::~OpaqueJSClass()
89{
90    // The empty string is shared across threads & is an identifier, in all other cases we should have done a deep copy in className(), below.
91    ASSERT(!m_className.length() || !m_className.impl()->isIdentifier());
92
93#ifndef NDEBUG
94    if (m_staticValues) {
95        OpaqueJSClassStaticValuesTable::const_iterator end = m_staticValues->end();
96        for (OpaqueJSClassStaticValuesTable::const_iterator it = m_staticValues->begin(); it != end; ++it)
97            ASSERT(!it->key->isIdentifier());
98    }
99
100    if (m_staticFunctions) {
101        OpaqueJSClassStaticFunctionsTable::const_iterator end = m_staticFunctions->end();
102        for (OpaqueJSClassStaticFunctionsTable::const_iterator it = m_staticFunctions->begin(); it != end; ++it)
103            ASSERT(!it->key->isIdentifier());
104    }
105#endif
106
107    if (prototypeClass)
108        JSClassRelease(prototypeClass);
109}
110
111PassRefPtr<OpaqueJSClass> OpaqueJSClass::createNoAutomaticPrototype(const JSClassDefinition* definition)
112{
113    return adoptRef(new OpaqueJSClass(definition, 0));
114}
115
116PassRefPtr<OpaqueJSClass> OpaqueJSClass::create(const JSClassDefinition* clientDefinition)
117{
118    JSClassDefinition definition = *clientDefinition; // Avoid modifying client copy.
119
120    JSClassDefinition protoDefinition = kJSClassDefinitionEmpty;
121    protoDefinition.finalize = 0;
122    swap(definition.staticFunctions, protoDefinition.staticFunctions); // Move static functions to the prototype.
123
124    // We are supposed to use JSClassRetain/Release but since we know that we currently have
125    // the only reference to this class object we cheat and use a RefPtr instead.
126    RefPtr<OpaqueJSClass> protoClass = adoptRef(new OpaqueJSClass(&protoDefinition, 0));
127    return adoptRef(new OpaqueJSClass(&definition, protoClass.get()));
128}
129
130OpaqueJSClassContextData::OpaqueJSClassContextData(JSC::VM&, OpaqueJSClass* jsClass)
131    : m_class(jsClass)
132{
133    if (jsClass->m_staticValues) {
134        staticValues = adoptPtr(new OpaqueJSClassStaticValuesTable);
135        OpaqueJSClassStaticValuesTable::const_iterator end = jsClass->m_staticValues->end();
136        for (OpaqueJSClassStaticValuesTable::const_iterator it = jsClass->m_staticValues->begin(); it != end; ++it) {
137            ASSERT(!it->key->isIdentifier());
138            staticValues->add(it->key->isolatedCopy(), adoptPtr(new StaticValueEntry(it->value->getProperty, it->value->setProperty, it->value->attributes)));
139        }
140    }
141
142    if (jsClass->m_staticFunctions) {
143        staticFunctions = adoptPtr(new OpaqueJSClassStaticFunctionsTable);
144        OpaqueJSClassStaticFunctionsTable::const_iterator end = jsClass->m_staticFunctions->end();
145        for (OpaqueJSClassStaticFunctionsTable::const_iterator it = jsClass->m_staticFunctions->begin(); it != end; ++it) {
146            ASSERT(!it->key->isIdentifier());
147            staticFunctions->add(it->key->isolatedCopy(), adoptPtr(new StaticFunctionEntry(it->value->callAsFunction, it->value->attributes)));
148        }
149    }
150}
151
152OpaqueJSClassContextData& OpaqueJSClass::contextData(ExecState* exec)
153{
154    OwnPtr<OpaqueJSClassContextData>& contextData = exec->lexicalGlobalObject()->opaqueJSClassData().add(this, nullptr).iterator->value;
155    if (!contextData)
156        contextData = adoptPtr(new OpaqueJSClassContextData(exec->vm(), this));
157    return *contextData;
158}
159
160String OpaqueJSClass::className()
161{
162    // Make a deep copy, so that the caller has no chance to put the original into IdentifierTable.
163    return m_className.isolatedCopy();
164}
165
166OpaqueJSClassStaticValuesTable* OpaqueJSClass::staticValues(JSC::ExecState* exec)
167{
168    return contextData(exec).staticValues.get();
169}
170
171OpaqueJSClassStaticFunctionsTable* OpaqueJSClass::staticFunctions(JSC::ExecState* exec)
172{
173    return contextData(exec).staticFunctions.get();
174}
175
176/*!
177// Doc here in case we make this public. (Hopefully we won't.)
178@function
179 @abstract Returns the prototype that will be used when constructing an object with a given class.
180 @param ctx The execution context to use.
181 @param jsClass A JSClass whose prototype you want to get.
182 @result The JSObject prototype that was automatically generated for jsClass, or NULL if no prototype was automatically generated. This is the prototype that will be used when constructing an object using jsClass.
183*/
184JSObject* OpaqueJSClass::prototype(ExecState* exec)
185{
186    /* Class (C++) and prototype (JS) inheritance are parallel, so:
187     *     (C++)      |        (JS)
188     *   ParentClass  |   ParentClassPrototype
189     *       ^        |          ^
190     *       |        |          |
191     *  DerivedClass  |  DerivedClassPrototype
192     */
193
194    if (!prototypeClass)
195        return 0;
196
197    OpaqueJSClassContextData& jsClassData = contextData(exec);
198
199    if (JSObject* prototype = jsClassData.cachedPrototype.get())
200        return prototype;
201
202    // Recursive, but should be good enough for our purposes
203    JSObject* prototype = JSCallbackObject<JSDestructibleObject>::create(exec, exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->callbackObjectStructure(), prototypeClass, &jsClassData); // set jsClassData as the object's private data, so it can clear our reference on destruction
204    if (parentClass) {
205        if (JSObject* parentPrototype = parentClass->prototype(exec))
206            prototype->setPrototype(exec->vm(), parentPrototype);
207    }
208
209    jsClassData.cachedPrototype = PassWeak<JSObject>(prototype);
210    return prototype;
211}
212