]> git.saurik.com Git - cycript.git/blob - Tweak.mm
Initial FFI call success.
[cycript.git] / Tweak.mm
1 /* Cyrker - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 #include <substrate.h>
41
42 #include "sig/parse.hpp"
43 #include "sig/ffi_type.hpp"
44
45 #include <apr-1/apr_pools.h>
46 #include <apr-1/apr_strings.h>
47
48 #include <unistd.h>
49
50 #include <CoreFoundation/CoreFoundation.h>
51 #include <CoreFoundation/CFLogUtilities.h>
52
53 #include <CFNetwork/CFNetwork.h>
54 #include <Foundation/Foundation.h>
55
56 #include <JavaScriptCore/JSBase.h>
57 #include <JavaScriptCore/JSValueRef.h>
58 #include <JavaScriptCore/JSObjectRef.h>
59 #include <JavaScriptCore/JSContextRef.h>
60 #include <JavaScriptCore/JSStringRef.h>
61 #include <JavaScriptCore/JSStringRefCF.h>
62
63 #include <WebKit/WebScriptObject.h>
64
65 #include <sys/types.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
68
69 #undef _assert
70 #undef _trace
71
72 /* XXX: bad _assert */
73 #define _assert(test) do { \
74 if ((test)) break; \
75 CFLog(kCFLogLevelNotice, CFSTR("_assert(%s):%u"), #test, __LINE__); \
76 throw; \
77 } while (false)
78
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
81 } while (false)
82
83 static JSContextRef Context_;
84
85 static JSClassRef ffi_;
86 static JSClassRef joc_;
87
88 static JSObjectRef Array_;
89
90 static JSStringRef name_;
91 static JSStringRef message_;
92 static JSStringRef length_;
93
94 static Class NSCFBoolean_;
95
96 struct Client {
97 CFHTTPMessageRef message_;
98 CFSocketRef socket_;
99 };
100
101 @interface NSObject (Cyrver)
102 - (NSString *) cy$toJSON;
103 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
104 @end
105
106 @implementation NSObject (Cyrver)
107
108 - (NSString *) cy$toJSON {
109 return [self description];
110 }
111
112 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
113 return JSObjectMake(context, joc_, [self retain]);
114 }
115
116 @end
117
118 @implementation WebUndefined (Cyrver)
119
120 - (NSString *) cy$toJSON {
121 return @"undefined";
122 }
123
124 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
125 return JSValueMakeUndefined(context);
126 }
127
128 @end
129
130 @implementation NSArray (Cyrver)
131
132 - (NSString *) cy$toJSON {
133 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
134 [json appendString:@"["];
135
136 bool comma(false);
137 for (id object in self) {
138 if (comma)
139 [json appendString:@","];
140 else
141 comma = true;
142 [json appendString:[object cy$toJSON]];
143 }
144
145 [json appendString:@"]"];
146 return json;
147 }
148
149 @end
150
151 @implementation NSDictionary (Cyrver)
152
153 - (NSString *) cy$toJSON {
154 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
155 [json appendString:@"({"];
156
157 bool comma(false);
158 for (id key in self) {
159 if (comma)
160 [json appendString:@","];
161 else
162 comma = true;
163 [json appendString:[key cy$toJSON]];
164 [json appendString:@":"];
165 NSObject *object([self objectForKey:key]);
166 [json appendString:[object cy$toJSON]];
167 }
168
169 [json appendString:@"})"];
170 return json;
171 }
172
173 @end
174
175 @implementation NSNumber (Cyrver)
176
177 - (NSString *) cy$toJSON {
178 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
179 }
180
181 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
182 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
183 }
184
185 @end
186
187 @implementation NSString (Cyrver)
188
189 - (NSString *) cy$toJSON {
190 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
191
192 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
193 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
194 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
195 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
196 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
197
198 CFStringInsert(json, 0, CFSTR("\""));
199 CFStringAppend(json, CFSTR("\""));
200
201 return [reinterpret_cast<const NSString *>(json) autorelease];
202 }
203
204 @end
205
206 @interface CY$JSObject : NSDictionary {
207 JSObjectRef object_;
208 JSContextRef context_;
209 }
210
211 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
212
213 - (NSUInteger) count;
214 - (id) objectForKey:(id)key;
215 - (NSEnumerator *) keyEnumerator;
216 - (void) setObject:(id)object forKey:(id)key;
217 - (void) removeObjectForKey:(id)key;
218
219 @end
220
221 @interface CY$JSArray : NSArray {
222 JSObjectRef object_;
223 JSContextRef context_;
224 }
225
226 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
227
228 - (NSUInteger) count;
229 - (id) objectAtIndex:(NSUInteger)index;
230
231 @end
232
233 JSContextRef JSGetContext() {
234 return Context_;
235 }
236
237 void CYThrow(JSContextRef context, JSValueRef value);
238
239 id JSObjectToNSObject(JSContextRef context, JSObjectRef object) {
240 if (JSValueIsObjectOfClass(context, object, joc_))
241 return reinterpret_cast<id>(JSObjectGetPrivate(object));
242 JSValueRef exception(NULL);
243 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
244 CYThrow(context, exception);
245 if (array)
246 return [[[CY$JSArray alloc] initWithJSObject:object inContext:context] autorelease];
247 return [[[CY$JSObject alloc] initWithJSObject:object inContext:context] autorelease];
248 }
249
250 CFStringRef CYCopyCFString(JSStringRef value) {
251 return JSStringCopyCFString(kCFAllocatorDefault, value);
252 }
253
254 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
255 JSValueRef exception(NULL);
256 JSStringRef string(JSValueToStringCopy(context, value, &exception));
257 CYThrow(context, exception);
258 CFStringRef object(CYCopyCFString(string));
259 JSStringRelease(string);
260 return object;
261 }
262
263 NSString *CYCastNSString(JSStringRef value) {
264 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
265 }
266
267 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
268 JSType type(JSValueGetType(context, value));
269
270 switch (type) {
271 case kJSTypeUndefined:
272 return CFRetain([WebUndefined undefined]);
273 break;
274
275 case kJSTypeNull:
276 return nil;
277 break;
278
279 case kJSTypeBoolean:
280 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
281 break;
282
283 case kJSTypeNumber: {
284 JSValueRef exception(NULL);
285 double number(JSValueToNumber(context, value, &exception));
286 CYThrow(context, exception);
287 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
288 } break;
289
290 case kJSTypeString:
291 return CYCopyCFString(context, value);
292 break;
293
294 case kJSTypeObject:
295 return CFRetain((CFTypeRef) JSObjectToNSObject(context, (JSObjectRef) value));
296 break;
297
298 default:
299 _assert(false);
300 break;
301 }
302 }
303
304 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
305 size_t size(JSPropertyNameArrayGetCount(names));
306 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
307 for (size_t index(0); index != size; ++index)
308 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
309 return array;
310 }
311
312 id CYCastNSObject(JSContextRef context, JSValueRef value) {
313 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
314 return object == nil ? nil : [object autorelease];
315 }
316
317 void CYThrow(JSContextRef context, JSValueRef value) {
318 if (value == NULL)
319 return;
320 @throw CYCastNSObject(context, value);
321 }
322
323 JSValueRef CYCastJSValue(JSContextRef context, id value) {
324 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
325 }
326
327 JSStringRef CYCopyJSString(id value) {
328 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
329 }
330
331 JSStringRef CYCopyJSString(const char *value) {
332 return JSStringCreateWithUTF8CString(value);
333 }
334
335 @implementation CY$JSObject
336
337 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
338 if ((self = [super init]) != nil) {
339 object_ = object;
340 context_ = context;
341 } return self;
342 }
343
344 - (NSUInteger) count {
345 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
346 size_t size(JSPropertyNameArrayGetCount(names));
347 JSPropertyNameArrayRelease(names);
348 return size;
349 }
350
351 - (id) objectForKey:(id)key {
352 JSValueRef exception(NULL);
353 JSStringRef string(CYCopyJSString(key));
354 JSValueRef value(JSObjectGetProperty(context_, object_, string, &exception));
355 JSStringRelease(string);
356 CYThrow(context_, exception);
357 return CYCastNSObject(context_, value);
358 }
359
360 - (NSEnumerator *) keyEnumerator {
361 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
362 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
363 JSPropertyNameArrayRelease(names);
364 return enumerator;
365 }
366
367 - (void) setObject:(id)object forKey:(id)key {
368 JSValueRef exception(NULL);
369 JSStringRef string(CYCopyJSString(key));
370 JSObjectSetProperty(context_, object_, string, CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
371 JSStringRelease(string);
372 CYThrow(context_, exception);
373 }
374
375 - (void) removeObjectForKey:(id)key {
376 JSValueRef exception(NULL);
377 JSStringRef string(CYCopyJSString(key));
378 // XXX: this returns a bool
379 JSObjectDeleteProperty(context_, object_, string, &exception);
380 JSStringRelease(string);
381 CYThrow(context_, exception);
382 }
383
384 @end
385
386 @implementation CY$JSArray
387
388 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
389 if ((self = [super init]) != nil) {
390 object_ = object;
391 context_ = context;
392 } return self;
393 }
394
395 - (NSUInteger) count {
396 JSValueRef exception(NULL);
397 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
398 CYThrow(context_, exception);
399 double number(JSValueToNumber(context_, value, &exception));
400 CYThrow(context_, exception);
401 return number;
402 }
403
404 - (id) objectAtIndex:(NSUInteger)index {
405 JSValueRef exception(NULL);
406 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
407 CYThrow(context_, exception);
408 id object(CYCastNSObject(context_, value));
409 return object == nil ? [NSNull null] : object;
410 }
411
412 @end
413
414 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
415 id object(CYCastNSObject(context, value));
416 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
417 }
418
419 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
420 switch (type) {
421 case kCFSocketDataCallBack:
422 CFDataRef data(reinterpret_cast<CFDataRef>(value));
423 Client *client(reinterpret_cast<Client *>(info));
424
425 if (client->message_ == NULL)
426 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
427
428 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
429 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
430 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
431 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
432 Boolean absolute;
433 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
434 CFRelease(client->message_);
435
436 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
437 CFRelease(path);
438
439 JSStringRef script(JSStringCreateWithCFString(code));
440 CFRelease(code);
441
442 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
443 JSStringRelease(script);
444
445 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
446 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
447
448 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
449 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
450 CFRelease(json);
451
452 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
453 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
454 CFRelease(length);
455
456 CFHTTPMessageSetBody(response, body);
457 CFRelease(body);
458
459 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
460 CFRelease(response);
461
462 CFSocketSendData(socket, NULL, serialized, 0);
463 CFRelease(serialized);
464
465 CFRelease(url);
466 }
467 break;
468 }
469 }
470
471 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
472 switch (type) {
473 case kCFSocketAcceptCallBack:
474 Client *client(new Client());
475
476 client->message_ = NULL;
477
478 CFSocketContext context;
479 context.version = 0;
480 context.info = client;
481 context.retain = NULL;
482 context.release = NULL;
483 context.copyDescription = NULL;
484
485 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
486
487 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
488 break;
489 }
490 }
491
492 static JSValueRef joc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
493 return NULL;
494 }
495
496 typedef id jocData;
497
498 static void joc_finalize(JSObjectRef object) {
499 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
500 [data release];
501 }
502
503 static JSValueRef obc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
504 NSString *name([(NSString *) JSStringCopyCFString(kCFAllocatorDefault, propertyName) autorelease]);
505 if (Class _class = NSClassFromString(name))
506 return JSObjectMake(context, joc_, [_class retain]);
507 return NULL;
508 }
509
510 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
511 JSValueRef exception(NULL);
512 JSStringRef string(CYCopyJSString(name));
513 JSObjectSetProperty(context, object, string, value, kJSPropertyAttributeNone, &exception);
514 JSStringRelease(string);
515 CYThrow(context, exception);
516 }
517
518 struct ffiData {
519 apr_pool_t *pool_;
520 void (*function_)();
521 const char *type_;
522 sig::Signature signature_;
523 ffi_cif cif_;
524 };
525
526 void CYToFFI(apr_pool_t *pool, JSContextRef context, JSValueRef *exception, sig::Type *type, void *data, JSValueRef value) {
527 switch (type->primitive) {
528 case sig::boolean_P:
529 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
530 break;
531
532 #define CYToFFI_(primitive, native) \
533 case sig::primitive ## _P: { \
534 double number(JSValueToNumber(context, value, exception)); \
535 if (exception == NULL) \
536 *reinterpret_cast<native *>(data) = number; \
537 } break;
538
539 CYToFFI_(uchar, unsigned char)
540 CYToFFI_(char, char)
541 CYToFFI_(ushort, unsigned short)
542 CYToFFI_(short, short)
543 CYToFFI_(ulong, unsigned long)
544 CYToFFI_(long, long)
545 CYToFFI_(uint, unsigned int)
546 CYToFFI_(int, int)
547 CYToFFI_(ulonglong, unsigned long long)
548 CYToFFI_(longlong, long long)
549 CYToFFI_(float, float)
550 CYToFFI_(double, double)
551
552 case sig::object_P:
553 case sig::typename_P:
554 case sig::selector_P:
555 case sig::pointer_P:
556 goto fail;
557
558 case sig::string_P: {
559 JSStringRef string(JSValueToStringCopy(context, value, exception));
560 if (exception != NULL) {
561 size_t size(JSStringGetMaximumUTF8CStringSize(string));
562 char *utf8(reinterpret_cast<char *>(apr_palloc(pool, size)));
563 JSStringGetUTF8CString(string, utf8, size);
564 JSStringRelease(string);
565 *reinterpret_cast<char **>(data) = utf8;
566 }
567 } break;
568
569 case sig::struct_P:
570 goto fail;
571
572 case sig::void_P:
573 break;
574
575 default: fail:
576 NSLog(@"CYToFFI(%c)\n", type->primitive);
577 _assert(false);
578 }
579 }
580
581 JSValueRef CYFromFFI(apr_pool_t *pool, JSContextRef context, JSValueRef *exception, sig::Type *type, void *data) {
582 JSValueRef value;
583
584 switch (type->primitive) {
585 case sig::boolean_P:
586 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
587 break;
588
589 #define CYFromFFI_(primitive, native) \
590 case sig::primitive ## _P: \
591 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
592 break;
593
594 CYFromFFI_(uchar, unsigned char)
595 CYFromFFI_(char, char)
596 CYFromFFI_(ushort, unsigned short)
597 CYFromFFI_(short, short)
598 CYFromFFI_(ulong, unsigned long)
599 CYFromFFI_(long, long)
600 CYFromFFI_(uint, unsigned int)
601 CYFromFFI_(int, int)
602 CYFromFFI_(ulonglong, unsigned long long)
603 CYFromFFI_(longlong, long long)
604 CYFromFFI_(float, float)
605 CYFromFFI_(double, double)
606
607 case sig::object_P:
608 case sig::typename_P: {
609 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
610 } break;
611
612 case sig::selector_P:
613 case sig::pointer_P:
614 goto fail;
615
616 case sig::string_P: {
617 char *utf8(*reinterpret_cast<char **>(data));
618 JSStringRef string(JSStringCreateWithUTF8CString(utf8));
619 value = JSValueMakeString(context, string);
620 JSStringRelease(string);
621 } break;
622
623 case sig::struct_P:
624 goto fail;
625
626 case sig::void_P:
627 value = NULL;
628 break;
629
630 default: fail:
631 NSLog(@"CYFromFFI(%c)\n", type->primitive);
632 _assert(false);
633 }
634
635 return value;
636 }
637
638 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
639 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
640
641 if (count != data->signature_.count - 1)
642 _assert(false);
643
644 JSValueRef result(NULL);
645
646 apr_pool_t *pool;
647 apr_pool_create(&pool, NULL);
648
649 void *values[count];
650
651 for (unsigned index(0); index != count; ++index) {
652 sig::Element *element(&data->signature_.elements[index + 1]);
653 values[index] = apr_palloc(pool, data->cif_.arg_types[index]->size);
654 CYToFFI(pool, context, exception, element->type, values[index], arguments[index]);
655 if (*exception != NULL)
656 goto error;
657 }
658
659 uint8_t value[data->cif_.rtype->size];
660
661 @try {
662 ffi_call(&data->cif_, data->function_, value, values);
663 } @catch (id error) {
664 _assert(false);
665 }
666
667 result = CYFromFFI(pool, context, exception, data->signature_.elements[0].type, value);
668
669 error:
670 apr_pool_destroy(pool);
671 return result;
672 }
673
674 static void ffi_finalize(JSObjectRef object) {
675 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
676 apr_pool_destroy(data->pool_);
677 }
678
679 void CYSetFunction(JSContextRef context, JSObjectRef object, const char *name, void (*function)(), const char *type) {
680 apr_pool_t *pool;
681 apr_pool_create(&pool, NULL);
682
683 ffiData *data(reinterpret_cast<ffiData *>(apr_palloc(pool, sizeof(ffiData))));
684
685 data->pool_ = pool;
686 data->function_ = function;
687 data->type_ = apr_pstrdup(pool, type);
688
689 sig::Parse(pool, &data->signature_, type);
690 sig::sig_ffi_cif(pool, &sig::sig_objc_ffi_type, &data->signature_, &data->cif_);
691
692 JSObjectRef value(JSObjectMake(context, ffi_, data));
693 CYSetProperty(context, object, name, value);
694 }
695
696 MSInitialize {
697 apr_initialize();
698
699 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
700
701 NSCFBoolean_ = objc_getClass("NSCFBoolean");
702
703 pid_t pid(getpid());
704
705 struct sockaddr_in address;
706 address.sin_len = sizeof(address);
707 address.sin_family = AF_INET;
708 address.sin_addr.s_addr = INADDR_ANY;
709 address.sin_port = htons(10000 + pid);
710
711 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
712
713 CFSocketSignature signature;
714 signature.protocolFamily = AF_INET;
715 signature.socketType = SOCK_STREAM;
716 signature.protocol = IPPROTO_TCP;
717 signature.address = data;
718
719 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
720 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
721
722 JSClassDefinition definition;
723
724 definition = kJSClassDefinitionEmpty;
725 definition.getProperty = &obc_getProperty;
726 JSClassRef obc(JSClassCreate(&definition));
727
728 definition = kJSClassDefinitionEmpty;
729 definition.callAsFunction = &ffi_callAsFunction;
730 definition.finalize = &ffi_finalize;
731 ffi_ = JSClassCreate(&definition);
732
733 definition = kJSClassDefinitionEmpty;
734 definition.getProperty = &joc_getProperty;
735 definition.finalize = &joc_finalize;
736 joc_ = JSClassCreate(&definition);
737
738 JSContextRef context(JSGlobalContextCreate(obc));
739 Context_ = context;
740
741 JSObjectRef global(JSContextGetGlobalObject(context));
742
743 CYSetFunction(context, global, "objc_getClass", reinterpret_cast<void (*)()>(&objc_getClass), "#*");
744
745 name_ = JSStringCreateWithUTF8CString("name");
746 message_ = JSStringCreateWithUTF8CString("message");
747 length_ = JSStringCreateWithUTF8CString("length");
748
749 JSStringRef name(JSStringCreateWithUTF8CString("Array"));
750 JSValueRef exception(NULL);
751 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, name, &exception));
752 CYThrow(context, exception);
753 JSStringRelease(name);
754 Array_ = JSValueToObject(JSGetContext(), value, &exception);
755 CYThrow(context, exception);
756
757 [pool release];
758 }