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
30
31
32
33
34
35
36
37
38
39
40
41
42
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
115
116
117
118
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
155
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
183
184
185
186
187
188
189
190
191
192
193
194
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
|
/*
* Copyright (C) 2004, 2008, 2009 Apple 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.
*/
#import "config.h"
#import "objc_instance.h"
#import "runtime_method.h"
#import "JSDOMBinding.h"
#import "ObjCRuntimeObject.h"
#import "WebScriptObject.h"
#import <objc/objc-auto.h>
#import <runtime/Error.h>
#import <runtime/JSLock.h>
#import "runtime/FunctionPrototype.h"
#import <wtf/Assertions.h>
#ifdef NDEBUG
#define OBJC_LOG(formatAndArgs...) ((void)0)
#else
#define OBJC_LOG(formatAndArgs...) { \
fprintf (stderr, "%s:%d -- %s: ", __FILE__, __LINE__, __FUNCTION__); \
fprintf(stderr, formatAndArgs); \
}
#endif
using namespace JSC::Bindings;
using namespace JSC;
static NSString *s_exception;
static JSGlobalObject* s_exceptionEnvironment; // No need to protect this value, since we just use it for a pointer comparison.
static NSMapTable *s_instanceWrapperCache;
static NSMapTable *createInstanceWrapperCache()
{
#ifdef BUILDING_ON_TIGER
return NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks, NSNonOwnedPointerMapValueCallBacks, 0);
#else
// NSMapTable with zeroing weak pointers is the recommended way to build caches like this under garbage collection.
NSPointerFunctionsOptions keyOptions = NSPointerFunctionsZeroingWeakMemory | NSPointerFunctionsOpaquePersonality;
NSPointerFunctionsOptions valueOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality;
return [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:valueOptions capacity:0];
#endif
}
RuntimeObject* ObjcInstance::newRuntimeObject(ExecState* exec)
{
return new (exec) ObjCRuntimeObject(exec, exec->lexicalGlobalObject(), this);
}
void ObjcInstance::setGlobalException(NSString* exception, JSGlobalObject* exceptionEnvironment)
{
NSString *oldException = s_exception;
s_exception = [exception copy];
[oldException release];
s_exceptionEnvironment = exceptionEnvironment;
}
void ObjcInstance::moveGlobalExceptionToExecState(ExecState* exec)
{
if (!s_exception) {
ASSERT(!s_exceptionEnvironment);
return;
}
if (!s_exceptionEnvironment || s_exceptionEnvironment == exec->dynamicGlobalObject()) {
JSLock lock(SilenceAssertionsOnly);
throwError(exec, s_exception);
}
[s_exception release];
s_exception = nil;
s_exceptionEnvironment = 0;
}
ObjcInstance::ObjcInstance(id instance, PassRefPtr<RootObject> rootObject)
: Instance(rootObject)
, _instance(instance)
, _class(0)
, _pool(0)
, _beginCount(0)
{
}
PassRefPtr<ObjcInstance> ObjcInstance::create(id instance, PassRefPtr<RootObject> rootObject)
{
if (!s_instanceWrapperCache)
s_instanceWrapperCache = createInstanceWrapperCache();
if (void* existingWrapper = NSMapGet(s_instanceWrapperCache, instance))
return static_cast<ObjcInstance*>(existingWrapper);
RefPtr<ObjcInstance> wrapper = adoptRef(new ObjcInstance(instance, rootObject));
NSMapInsert(s_instanceWrapperCache, instance, wrapper.get());
return wrapper.release();
}
ObjcInstance::~ObjcInstance()
{
// Both -finalizeForWebScript and -dealloc/-finalize of _instance may require autorelease pools.
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
ASSERT(s_instanceWrapperCache);
ASSERT(_instance);
NSMapRemove(s_instanceWrapperCache, _instance.get());
if ([_instance.get() respondsToSelector:@selector(finalizeForWebScript)])
[_instance.get() performSelector:@selector(finalizeForWebScript)];
_instance = 0;
[pool drain];
}
static NSAutoreleasePool* allocateAutoReleasePool()
{
#if defined(OBJC_API_VERSION) && OBJC_API_VERSION >= 2
// If GC is enabled an autorelease pool is unnecessary, and the
// pool cannot be protected from GC so may be collected leading
// to a crash when we try to drain the release pool.
if (objc_collectingEnabled())
return nil;
#endif
return [[NSAutoreleasePool alloc] init];
}
void ObjcInstance::virtualBegin()
{
if (!_pool)
_pool = allocateAutoReleasePool();
_beginCount++;
}
void ObjcInstance::virtualEnd()
{
_beginCount--;
ASSERT(_beginCount >= 0);
if (!_beginCount) {
[_pool drain];
_pool = 0;
}
}
Bindings::Class* ObjcInstance::getClass() const
{
if (!_instance)
return 0;
if (!_class)
_class = ObjcClass::classForIsA(_instance->isa);
return static_cast<Bindings::Class*>(_class);
}
bool ObjcInstance::supportsInvokeDefaultMethod() const
{
return [_instance.get() respondsToSelector:@selector(invokeDefaultMethodWithArguments:)];
}
class ObjCRuntimeMethod : public RuntimeMethod {
public:
ObjCRuntimeMethod(ExecState* exec, JSGlobalObject* globalObject, const Identifier& name, Bindings::MethodList& list)
// FIXME: deprecatedGetDOMStructure uses the prototype off of the wrong global object
// We need to pass in the right global object for "i".
: RuntimeMethod(exec, globalObject, WebCore::deprecatedGetDOMStructure<ObjCRuntimeMethod>(exec), name, list)
{
ASSERT(inherits(&s_info));
}
static PassRefPtr<Structure> createStructure(JSGlobalData& globalData, JSValue prototype)
{
return Structure::create(globalData, prototype, TypeInfo(ObjectType, StructureFlags), AnonymousSlotCount, &s_info);
}
static const ClassInfo s_info;
};
const ClassInfo ObjCRuntimeMethod::s_info = { "ObjCRuntimeMethod", &RuntimeMethod::s_info, 0, 0 };
JSValue ObjcInstance::getMethod(ExecState* exec, const Identifier& propertyName)
{
MethodList methodList = getClass()->methodsNamed(propertyName, this);
return new (exec) ObjCRuntimeMethod(exec, exec->lexicalGlobalObject(), propertyName, methodList);
}
JSValue ObjcInstance::invokeMethod(ExecState* exec, RuntimeMethod* runtimeMethod)
{
if (!asObject(runtimeMethod)->inherits(&ObjCRuntimeMethod::s_info))
return throwError(exec, createTypeError(exec, "Attempt to invoke non-plug-in method on plug-in object."));
const MethodList& methodList = *runtimeMethod->methods();
// Overloading methods is not allowed in ObjectiveC. Should only be one
// name match for a particular method.
ASSERT(methodList.size() == 1);
return invokeObjcMethod(exec, static_cast<ObjcMethod*>(methodList[0]));
}
JSValue ObjcInstance::invokeObjcMethod(ExecState* exec, ObjcMethod* method)
{
JSValue result = jsUndefined();
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly); // Can't put this inside the @try scope because it unwinds incorrectly.
setGlobalException(nil);
@try {
NSMethodSignature* signature = method->getMethodSignature();
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:method->selector()];
[invocation setTarget:_instance.get()];
if (method->isFallbackMethod()) {
if (objcValueTypeForType([signature methodReturnType]) != ObjcObjectType) {
NSLog(@"Incorrect signature for invokeUndefinedMethodFromWebScript:withArguments: -- return type must be object.");
return result;
}
// Invoke invokeUndefinedMethodFromWebScript:withArguments:, pass JavaScript function
// name as first (actually at 2) argument and array of args as second.
NSString* jsName = (NSString* )method->javaScriptName();
[invocation setArgument:&jsName atIndex:2];
NSMutableArray* objcArgs = [NSMutableArray array];
int count = exec->argumentCount();
for (int i = 0; i < count; i++) {
ObjcValue value = convertValueToObjcValue(exec, exec->argument(i), ObjcObjectType);
[objcArgs addObject:value.objectValue];
}
[invocation setArgument:&objcArgs atIndex:3];
} else {
unsigned count = [signature numberOfArguments];
for (unsigned i = 2; i < count ; i++) {
const char* type = [signature getArgumentTypeAtIndex:i];
ObjcValueType objcValueType = objcValueTypeForType(type);
// Must have a valid argument type. This method signature should have
// been filtered already to ensure that it has acceptable argument
// types.
ASSERT(objcValueType != ObjcInvalidType && objcValueType != ObjcVoidType);
ObjcValue value = convertValueToObjcValue(exec, exec->argument(i-2), objcValueType);
switch (objcValueType) {
case ObjcObjectType:
[invocation setArgument:&value.objectValue atIndex:i];
break;
case ObjcCharType:
case ObjcUnsignedCharType:
[invocation setArgument:&value.charValue atIndex:i];
break;
case ObjcShortType:
case ObjcUnsignedShortType:
[invocation setArgument:&value.shortValue atIndex:i];
break;
case ObjcIntType:
case ObjcUnsignedIntType:
[invocation setArgument:&value.intValue atIndex:i];
break;
case ObjcLongType:
case ObjcUnsignedLongType:
[invocation setArgument:&value.longValue atIndex:i];
break;
case ObjcLongLongType:
case ObjcUnsignedLongLongType:
[invocation setArgument:&value.longLongValue atIndex:i];
break;
case ObjcFloatType:
[invocation setArgument:&value.floatValue atIndex:i];
break;
case ObjcDoubleType:
[invocation setArgument:&value.doubleValue atIndex:i];
break;
default:
// Should never get here. Argument types are filtered (and
// the assert above should have fired in the impossible case
// of an invalid type anyway).
fprintf(stderr, "%s: invalid type (%d)\n", __PRETTY_FUNCTION__, (int)objcValueType);
ASSERT(false);
}
}
}
[invocation invoke];
// Get the return value type.
const char* type = [signature methodReturnType];
ObjcValueType objcValueType = objcValueTypeForType(type);
// Must have a valid return type. This method signature should have
// been filtered already to ensure that it have an acceptable return
// type.
ASSERT(objcValueType != ObjcInvalidType);
// Get the return value and convert it to a JavaScript value. Length
// of return value will never exceed the size of largest scalar
// or a pointer.
char buffer[1024];
ASSERT([signature methodReturnLength] < 1024);
if (*type != 'v') {
[invocation getReturnValue:buffer];
result = convertObjcValueToValue(exec, buffer, objcValueType, m_rootObject.get());
}
} @catch(NSException* localException) {
}
moveGlobalExceptionToExecState(exec);
// Work around problem in some versions of GCC where result gets marked volatile and
// it can't handle copying from a volatile to non-volatile.
return const_cast<JSValue&>(result);
}
JSValue ObjcInstance::invokeDefaultMethod(ExecState* exec)
{
JSValue result = jsUndefined();
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly); // Can't put this inside the @try scope because it unwinds incorrectly.
setGlobalException(nil);
@try {
if (![_instance.get() respondsToSelector:@selector(invokeDefaultMethodWithArguments:)])
return result;
NSMethodSignature* signature = [_instance.get() methodSignatureForSelector:@selector(invokeDefaultMethodWithArguments:)];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:@selector(invokeDefaultMethodWithArguments:)];
[invocation setTarget:_instance.get()];
if (objcValueTypeForType([signature methodReturnType]) != ObjcObjectType) {
NSLog(@"Incorrect signature for invokeDefaultMethodWithArguments: -- return type must be object.");
return result;
}
NSMutableArray* objcArgs = [NSMutableArray array];
unsigned count = exec->argumentCount();
for (unsigned i = 0; i < count; i++) {
ObjcValue value = convertValueToObjcValue(exec, exec->argument(i), ObjcObjectType);
[objcArgs addObject:value.objectValue];
}
[invocation setArgument:&objcArgs atIndex:2];
[invocation invoke];
// Get the return value type, should always be "@" because of
// check above.
const char* type = [signature methodReturnType];
ObjcValueType objcValueType = objcValueTypeForType(type);
// Get the return value and convert it to a JavaScript value. Length
// of return value will never exceed the size of a pointer, so we're
// OK with 32 here.
char buffer[32];
[invocation getReturnValue:buffer];
result = convertObjcValueToValue(exec, buffer, objcValueType, m_rootObject.get());
} @catch(NSException* localException) {
}
moveGlobalExceptionToExecState(exec);
// Work around problem in some versions of GCC where result gets marked volatile and
// it can't handle copying from a volatile to non-volatile.
return const_cast<JSValue&>(result);
}
bool ObjcInstance::setValueOfUndefinedField(ExecState* exec, const Identifier& property, JSValue aValue)
{
id targetObject = getObject();
if (![targetObject respondsToSelector:@selector(setValue:forUndefinedKey:)])
return false;
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly); // Can't put this inside the @try scope because it unwinds incorrectly.
// This check is not really necessary because NSObject implements
// setValue:forUndefinedKey:, and unfortunately the default implementation
// throws an exception.
if ([targetObject respondsToSelector:@selector(setValue:forUndefinedKey:)]){
setGlobalException(nil);
ObjcValue objcValue = convertValueToObjcValue(exec, aValue, ObjcObjectType);
@try {
[targetObject setValue:objcValue.objectValue forUndefinedKey:[NSString stringWithCString:property.ascii().data() encoding:NSASCIIStringEncoding]];
} @catch(NSException* localException) {
// Do nothing. Class did not override valueForUndefinedKey:.
}
moveGlobalExceptionToExecState(exec);
}
return true;
}
JSValue ObjcInstance::getValueOfUndefinedField(ExecState* exec, const Identifier& property) const
{
JSValue result = jsUndefined();
id targetObject = getObject();
JSLock::DropAllLocks dropAllLocks(SilenceAssertionsOnly); // Can't put this inside the @try scope because it unwinds incorrectly.
// This check is not really necessary because NSObject implements
// valueForUndefinedKey:, and unfortunately the default implementation
// throws an exception.
if ([targetObject respondsToSelector:@selector(valueForUndefinedKey:)]){
setGlobalException(nil);
@try {
id objcValue = [targetObject valueForUndefinedKey:[NSString stringWithCString:property.ascii().data() encoding:NSASCIIStringEncoding]];
result = convertObjcValueToValue(exec, &objcValue, ObjcObjectType, m_rootObject.get());
} @catch(NSException* localException) {
// Do nothing. Class did not override valueForUndefinedKey:.
}
moveGlobalExceptionToExecState(exec);
}
// Work around problem in some versions of GCC where result gets marked volatile and
// it can't handle copying from a volatile to non-volatile.
return const_cast<JSValue&>(result);
}
JSValue ObjcInstance::defaultValue(ExecState* exec, PreferredPrimitiveType hint) const
{
if (hint == PreferString)
return stringValue(exec);
if (hint == PreferNumber)
return numberValue(exec);
if ([_instance.get() isKindOfClass:[NSString class]])
return stringValue(exec);
if ([_instance.get() isKindOfClass:[NSNumber class]])
return numberValue(exec);
return valueOf(exec);
}
JSValue ObjcInstance::stringValue(ExecState* exec) const
{
return convertNSStringToString(exec, [getObject() description]);
}
JSValue ObjcInstance::numberValue(ExecState*) const
{
// FIXME: Implement something sensible
return jsNumber(0);
}
JSValue ObjcInstance::booleanValue() const
{
// FIXME: Implement something sensible
return jsBoolean(false);
}
JSValue ObjcInstance::valueOf(ExecState* exec) const
{
return stringValue(exec);
}
|