forked from pmougin/F-Script
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFSMethod.m
558 lines (466 loc) · 17.9 KB
/
FSMethod.m
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/* FSMethod.m Copyright (c) 2007-2009 Philippe Mougin. */
/* This software is open source. See the license. */
#import "FSMethod.h"
#import <objc/message.h>
#import "FSBlock.h"
#import "FSSymbolTable.h"
#import "FScriptFunctions.h"
#import "FSCompiler.h"
#import "FSClassDefinition.h"
#include <sys/mman.h>
#import "FSExecEngine.h"
#import "FSMiscTools.h"
#import "FScriptFunctions.h"
#import "FSReturnSignal.h"
#import "FSSymbolTable.h"
@class FSMethodHolder;
//static NSMutableDictionary *classes;
static NSMapTable *classes;
static NSMapTable *instances;
@interface FSMethodHolder : NSObject
{
@package
FSMethod *method;
}
- (void *) dispatcher;
- (id)initWithMethod:(FSMethod *)theMethod;
- (void)setMethod:(FSMethod *)theMethod;
@end
void __attribute__ ((constructor)) initializeFScriptClassSystem(void)
{
// We use the folowing NSMapTable (instead of an NSMutableDictionary) because we don't want our keys to be sent messages when inserted
// or looked up in the table, as they might not be yet functional (i.e., not yet registered with objc_registerClassPair())
// Note that NSMapTableZeroingWeakMemory is used only to avoid receiving retain messages when not running under GC
classes = [[NSMapTable alloc] initWithKeyOptions:NSMapTableZeroingWeakMemory | NSMapTableObjectPointerPersonality valueOptions:NSMapTableStrongMemory capacity:0];
// We use the folowing NSMapTable because we need to have zeroing weak references to our keys as well as an object pointer personality
instances = [[NSMapTable alloc] initWithKeyOptions:NSMapTableZeroingWeakMemory | NSMapTableObjectPointerPersonality valueOptions:NSMapTableStrongMemory capacity:0];
}
static id executeMethod(FSMethod *method, FSSymbolTable *symbolTable, id receiver)
{
NSInteger errorFirstCharIndex, errorLastCharIndex; // Not currently used. TODO: make use of the information available in these variables
id result;
@try
{
result = execute_rec(method->code, symbolTable, &errorFirstCharIndex, &errorLastCharIndex);
}
@catch (FSReturnSignal *returnSignal)
{
FSSymbolTable *signalSymbolTable = [returnSignal symbolTable];
while (signalSymbolTable != nil && signalSymbolTable != symbolTable)
signalSymbolTable = [signalSymbolTable parent];
if (signalSymbolTable != nil) result = [returnSignal result];
else
{
@throw;
assert(0); return nil;
}
}
@finally
{
if (method->selector == @selector(dealloc))
{
// The receiver has been deallocated. Therefore, we must ensure that when symbolTable gets deallocated, it does not send a release message to this deallocated object.
symbolTable->locals[0].value = nil;
}
else if (! symbolTable->receiverRetained)
{
[symbolTable->locals[0].value retain];
symbolTable->receiverRetained = YES;
}
}
if (method->selector == @selector(dealloc))
{
@synchronized(instances)
{
[instances removeObjectForKey:receiver];
}
}
return result;
}
static void dispatch(ffi_cif *cif, void *result, void **args, void *userdata)
{
id receiver = *(id *)args[0];
SEL selector = *(SEL *)args[1];
FSMethod *method = ((FSMethodHolder *)userdata)->method;
FSSymbolTable *symbolTable = [[method->symbolTable copyWithZone:NULL] autorelease];
symbolTable->locals[0].value = receiver;
symbolTable->receiverRetained = NO;
symbolTable->locals[0].status = DEFINED;
for (NSUInteger i = 2; i < method->argumentCount; i++)
{
char fsEncodedType = method->fsEncodedTypes[i+1];
if (fsEncodedType == '@')
symbolTable->locals[i-1].value = *(id *)args[i];
else
symbolTable->locals[i-1].value = FSMapToObject(args[i], 0, fsEncodedType, method->typesByArgument[i], nil, nil);
[symbolTable->locals[i-1].value retain];
symbolTable->locals[i-1].status = DEFINED;
}
char returnType = method->fsEncodedTypes[0];
switch (returnType)
{
case 'v' : executeMethod(method, symbolTable, receiver); break;
case '@' : *(id *)result = executeMethod(method, symbolTable, receiver); break;
default : FSMapFromObject(result, 0, returnType, executeMethod(method, symbolTable, receiver), FSMapReturnValue, 0, selector, nil, NULL);
}
}
id fscript_dynamicIvarValue(id instance, NSString *ivarName, BOOL *found)
{
FSSymbolTable *dynamicIvars;
id value;
@synchronized(instances)
{
dynamicIvars = [instances objectForKey:instance];
if (dynamicIvars)
{
value = [dynamicIvars objectForSymbol:ivarName found:found];
if (*found) return value;
}
}
@synchronized(classes)
{
Class class = object_getClass(instance);
while (class)
{
FSClassDefinition *classDefinition = [classes objectForKey:class];
if (!classDefinition) break;
else if ([[classDefinition ivarNames] containsObject:ivarName])
{
*found = YES;
return nil;
}
class = [class superclass];
}
}
*found = NO;
return nil;
}
NSSet *fscript_dynamicIvarNames(Class class)
{
// Note: do not return the names of inherited dynamic ivars, only the names of dynamic ivar directly defined by the class
NSSet *result; // We use this temp because ObjC emits wacky warnings ("control reaching end of non void function")
// if we simply return from the @synchonized block (GCC 4.2)
@synchronized(classes)
{
FSClassDefinition *classDefinition = [classes objectForKey:class];
if (classDefinition) result = [classDefinition ivarNames];
else result = [NSSet set];
}
return result;
}
BOOL fscript_isFScriptClass(Class class)
{
BOOL r;
@synchronized(classes)
{
r = [classes objectForKey:class] != nil;
}
return r;
}
void fscript_registerFScriptClassPair(Class class)
{
@synchronized(classes)
{
if ([classes objectForKey:class] == nil)
{
[classes setObject:[FSClassDefinition classDefinition] forKey:class];
}
if ([classes objectForKey:object_getClass(class)] == nil)
{
[classes setObject:[FSClassDefinition classDefinition] forKey:object_getClass(class)];
}
}
}
BOOL fscript_setDynamicIvarValue(id instance, NSString *ivarName, id value)
{
FSSymbolTable *dynamicIvars;
BOOL found = NO;
@synchronized(instances)
{
dynamicIvars = [instances objectForKey:instance];
if (!dynamicIvars)
{
dynamicIvars = [FSSymbolTable symbolTable];
[instances setObject:dynamicIvars forKey:instance];
}
struct FSContextIndex locationInContext = [dynamicIvars indexOfSymbol:ivarName];
if (locationInContext.index != -1)
{
found = YES;
[dynamicIvars setObject:value forIndex:locationInContext];
}
else
{
Class class = [instance classOrMetaclass];
@synchronized(classes)
{
while (class != nil && !found)
{
FSClassDefinition *classDefinition = [classes objectForKey:class];
if ([[classDefinition ivarNames] containsObject:ivarName])
{
found = YES;
[dynamicIvars setObject:value forSymbol:ivarName];
}
else
{
class = [class superclass];
}
}
}
}
}
return found;
}
void fscript_setDynamicIvarNames(Class class, NSSet *ivarNames)
{
// precondition: class must be a registered F-Script class
@synchronized(classes)
{
FSClassDefinition *classDefinition = [classes objectForKey:class];
if (classDefinition)
{
[classDefinition setIvarNames:ivarNames];
}
else FSExecError(@"F-Script internal error in fscript_setDynamicIvarNames(): class definition not found");
}
}
@implementation FSMethodHolder
- (id)initWithMethod:(FSMethod *)theMethod
{
self = [super init];
if (self != nil)
{
method = [theMethod retain];
}
return self;
}
- (void *) dispatcher
{
ffi_status status;
ffi_type **ffiTypesByArgument;
ffi_cif *cif;
ffi_closure *closure;
ffi_type *returnType = ffiTypeFromFSEncodedType(method->fsEncodedTypes[0]);
size_t size = sizeof(ffi_type *) * method->argumentCount;
ffiTypesByArgument = malloc(size);
ffiTypesByArgument[0] = ffiTypeFromFSEncodedType(method->fsEncodedTypes[1]);
ffiTypesByArgument[1] = ffiTypeFromFSEncodedType(method->fsEncodedTypes[2]);
for (NSUInteger i = 2; i < method->argumentCount; i++)
ffiTypesByArgument[i] = ffiTypeFromFSEncodedType(method->fsEncodedTypes[i+1]);
// Prepare the ffi_cif structure.
cif = malloc(sizeof(ffi_cif));
if ((status = ffi_prep_cif(cif, FFI_DEFAULT_ABI, method->argumentCount, returnType, ffiTypesByArgument)) != FFI_OK)
{
free(ffiTypesByArgument);
free(cif);
FSExecError(@"F-Script internal error: can't prepare the ffi_cif structure");
}
// Allocate a page to hold the closure with read and write permissions.
if ((closure = mmap(NULL, sizeof(ffi_closure), PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0)) == (void*)-1)
{
free(ffiTypesByArgument);
free(cif);
FSExecError(@"F-Script internal error: can't allocate memory for the ffi_closure structure");
}
if ((status = ffi_prep_closure(closure, cif, dispatch, self)) != FFI_OK)
{
free(ffiTypesByArgument);
free(cif);
if (munmap(closure, sizeof(closure)) == -1)
{
FSExecError(@"F-Script internal error: can't free the memory associated with the ffi_closure");
}
FSExecError(@"F-Script internal error: can't prepare the ffi_closure structure");
}
// Ensure that the closure will execute on all architectures.
if (mprotect(closure, sizeof(closure), PROT_READ | PROT_EXEC) == -1)
{
free(ffiTypesByArgument);
free(cif);
if (munmap(closure, sizeof(closure)) == -1)
{
FSExecError(@"F-Script internal error: can't free the memory associated with the ffi_closure");
}
FSExecError(@"F-Script internal error: can't mprotect() the ffi closure memory");
}
return closure;
// Note: once the closure is returned (and then installed in the run-time), we don't attempt to ever free it
// (neither the associated structures: ffiTypesByArgument and cif) as it might become referenced from other parts
// of the system (e.g. KVO's dynamicaly generated classes like to reference existing IMPs)
}
- (void)setMethod:(FSMethod *)theMethod
{
[theMethod retain];
[method release];
method = theMethod;
}
@end
@implementation FSMethod
- (BOOL) addToClass:(Class)class
{
// NSLog(@"Trying to add method %@ with types %@ and FSEncoded types %@ to class %@", NSStringFromSelector(selector), [NSString stringWithUTF8String:types], [NSString stringWithUTF8String:fsEncodedTypes], class);
if (FSIsIgnoredSelector(selector))
{
// We are in presence of a method with an "ignored selector"
// Under GC, selectors for retain, release, autorelease, retainCount and dealloc are all represented by the same special non-functional "ignored" selector
// Since the method we try to add will never get called, we don't add it and we just return (adding it would cause problems because of the special selector)
return YES;
}
@synchronized(classes)
{
if (![classes objectForKey:class]) [classes setObject:[FSClassDefinition classDefinition] forKey:class];
}
unsigned int methodCount, i;
Method *methods = class_copyMethodList(class, &methodCount);
for (i = 0; i < methodCount && method_getName(methods[i]) != selector ; i++);
if (i < methodCount)
{
// A method with the same selector is already defined in this class
if (strcmp(method_getTypeEncoding(methods[i]), types) == 0)
{
@synchronized(classes)
{
NSMutableArray *methodHolders = [[classes objectForKey:class] methodHolders];
unsigned int j = 0;
for (FSMethodHolder *holder in methodHolders)
{
if (holder->method->selector == selector) break;
j++;
}
if (j < [methodHolders count])
[[methodHolders objectAtIndex:j] setMethod:self];
else
{
FSMethodHolder *holder = [[[FSMethodHolder alloc] initWithMethod:self] autorelease];
method_setImplementation(methods[i], [holder dispatcher]);
[methodHolders addObject:holder];
}
}
free(methods);
return YES;
}
else
{
free(methods);
FSExecError([NSString stringWithFormat:@"can't modify the signature of method \"%@\" in class %@. When redefining an existing method, the new one and the original must have the same signature.", NSStringFromSelector(selector), NSStringFromClass(class)]);
}
}
else
{
// This is a new method for this class
BOOL done;
free(methods);
@synchronized(classes)
{
FSMethodHolder *holder = [[[FSMethodHolder alloc] initWithMethod:self] autorelease];
done = class_addMethod(class, selector, [holder dispatcher], types);
if (done) [[[classes objectForKey:class] methodHolders] addObject:holder];
}
return done;
}
}
- (void) dealloc
{
[code release];
[symbolTable release];
free(types);
free(fsEncodedTypes);
for (NSUInteger i = 0; i < argumentCount; i++)
{
free(typesByArgument[i]);
}
free(typesByArgument);
[super dealloc];
}
/*
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:NSStringFromSelector(selector) forKey:@"selectorString"];
[coder encodeObject:symbolTable forKey:@"symbolTable"];
[coder encodeObject:code forKey:@"code"];
[coder encodeInt32:argumentCount forKey:@"argumentCount"];
[coder encodeObject:[NSString stringWithCString:fsEncodedTypes encoding:NSUTF8StringEncoding] forKey:@"fsEncodedTypes"];
[coder encodeObject:[NSString stringWithCString:types encoding:NSUTF8StringEncoding] forKey:@"types"];
NSMutableArray *typesByArgumentNSArray = [NSMutableArray array];
for (NSUInteger i = 0; i < argumentCount; i++)
{
[typesByArgumentNSArray addObject:[NSString stringWithCString:typesByArgument[i] encoding:NSUTF8StringEncoding]];
}
[coder encodeObject:typesByArgumentNSArray forKey:@"typesByArgument"];
}
- (id)initWithCoder:(NSCoder *)coder
{
self = [super init];
selector = NSSelectorFromString([coder decodeObjectForKey:@"selector"]);
symbolTable = [[coder decodeObjectForKey:@"symbolTable"] retain];
code = [[coder decodeObjectForKey:@"code"] retain];
argumentCount = [coder decodeInt32ForKey:@"argumentCount"];
NSString *fsEncodedTypesNSString = [coder decodeObjectForKey:@"fsEncodedTypes"];
NSUInteger fsEncodedTypesLength = [fsEncodedTypesNSString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]+1;
fsEncodedTypes = NSAllocateCollectable(fsEncodedTypesLength, 0);
[fsEncodedTypesNSString getCString:fsEncodedTypes maxLength:fsEncodedTypesLength encoding:NSUTF8StringEncoding];
NSString *typesNSString = [coder decodeObjectForKey:@"types"];
NSUInteger typesLength = [typesNSString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]+1;
types = NSAllocateCollectable(typesLength, 0);
[typesNSString getCString:types maxLength:typesLength encoding:NSUTF8StringEncoding];
NSArray *typesByArgumentNSArray= [coder decodeObjectForKey:@"typesByArgument"];
typesByArgument = NSAllocateCollectable(argumentCount * sizeof(char *), NSScannedOption);
for (NSUInteger i = 0; i < argumentCount; i++)
{
NSString *type = [typesByArgumentNSArray objectAtIndex:i];
NSUInteger typeLength = [type lengthOfBytesUsingEncoding:NSUTF8StringEncoding]+1;
typesByArgument[i] = NSAllocateCollectable(typeLength, 0);
[type getCString:typesByArgument[i] maxLength:typeLength encoding:NSUTF8StringEncoding];
}
return self;
}
*/
- (id) initWithSelector:(SEL)theSelector fsEncodedTypesPtr:(char *)theFSEncodedTypes typesPtr:(char *)theTypes typesByArgumentPtr:(char **)theTypesByArgument argumentCount:(NSUInteger)theArgumentCount code:(FSCNBase *)theCode symbolTable:(FSSymbolTable *)theSymbolTable
{
self = [super init];
if (self != nil)
{
selector = theSelector;
fsEncodedTypes = theFSEncodedTypes;
types = theTypes;
typesByArgument = theTypesByArgument;
argumentCount = theArgumentCount;
code = [theCode retain];
symbolTable = [theSymbolTable retain];
}
return self;
}
- (id) initWithSelector:(SEL)theSelector fsEncodedTypes:(NSString *)theFSEncodedTypes types:(NSString *)theTypes typesByArgument:(NSArray *)theTypesByArgument argumentCount:(NSUInteger)theArgumentCount code:(FSCNBase *)theCode symbolTable:(FSSymbolTable *)theSymbolTable
{
selector = theSelector;
argumentCount = theArgumentCount;
code = [theCode retain];
symbolTable = [theSymbolTable retain];
NSUInteger fsEncodedTypesLength = [theFSEncodedTypes lengthOfBytesUsingEncoding:NSUTF8StringEncoding]+1;
fsEncodedTypes = NSAllocateCollectable(fsEncodedTypesLength, 0);
if (fsEncodedTypes == NULL)
{
[super dealloc];
return nil;
}
[theFSEncodedTypes getCString:fsEncodedTypes maxLength:fsEncodedTypesLength encoding:NSUTF8StringEncoding];
NSUInteger typesLength = [theTypes lengthOfBytesUsingEncoding:NSUTF8StringEncoding]+1;
types = NSAllocateCollectable(typesLength, 0);
if (types == NULL)
{
[super dealloc];
return nil;
}
[theTypes getCString:types maxLength:typesLength encoding:NSUTF8StringEncoding];
typesByArgument = NSAllocateCollectable(argumentCount * sizeof(char *), NSScannedOption);
for (NSUInteger i = 0; i < argumentCount; i++)
{
NSString *type = [theTypesByArgument objectAtIndex:i];
NSUInteger typeLength = [type lengthOfBytesUsingEncoding:NSUTF8StringEncoding]+1;
typesByArgument[i] = NSAllocateCollectable(typeLength, 0);
[type getCString:typesByArgument[i] maxLength:typeLength encoding:NSUTF8StringEncoding];
}
return self;
}
@end