]> git.saurik.com Git - cycript.git/blame - Tweak.mm
Initial FFI call success.
[cycript.git] / Tweak.mm
CommitLineData
62ca2b82 1/* Cyrker - Remove Execution Server and Disassembler
c1582939
JF
2 * Copyright (C) 2009 Jay Freeman (saurik)
3*/
4
62ca2b82 5/* Modified BSD License {{{ */
c1582939
JF
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*/
62ca2b82 38/* }}} */
c1582939
JF
39
40#include <substrate.h>
41
ea2d184c
JF
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
c1582939
JF
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
ea2d184c
JF
69#undef _assert
70#undef _trace
71
c1582939
JF
72/* XXX: bad _assert */
73#define _assert(test) do { \
74 if ((test)) break; \
62ca2b82
JF
75 CFLog(kCFLogLevelNotice, CFSTR("_assert(%s):%u"), #test, __LINE__); \
76 throw; \
c1582939
JF
77} while (false)
78
79#define _trace() do { \
62ca2b82 80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
c1582939
JF
81} while (false)
82
ea2d184c
JF
83static JSContextRef Context_;
84
85static JSClassRef ffi_;
c1582939 86static JSClassRef joc_;
ea2d184c 87
c1582939 88static JSObjectRef Array_;
ea2d184c 89
62ca2b82
JF
90static JSStringRef name_;
91static JSStringRef message_;
c1582939 92static JSStringRef length_;
ea2d184c 93
c1582939
JF
94static Class NSCFBoolean_;
95
96struct Client {
97 CFHTTPMessageRef message_;
98 CFSocketRef socket_;
99};
100
101@interface NSObject (Cyrver)
102- (NSString *) cy$toJSON;
ea2d184c 103- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
c1582939
JF
104@end
105
106@implementation NSObject (Cyrver)
62ca2b82 107
c1582939 108- (NSString *) cy$toJSON {
62ca2b82
JF
109 return [self description];
110}
111
ea2d184c
JF
112- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
113 return JSObjectMake(context, joc_, [self retain]);
114}
115
62ca2b82 116@end
c1582939
JF
117
118@implementation WebUndefined (Cyrver)
62ca2b82 119
c1582939
JF
120- (NSString *) cy$toJSON {
121 return @"undefined";
62ca2b82
JF
122}
123
124- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
125 return JSValueMakeUndefined(context);
126}
127
128@end
c1582939
JF
129
130@implementation NSArray (Cyrver)
62ca2b82 131
c1582939
JF
132- (NSString *) cy$toJSON {
133 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
134 [json appendString:@"["];
135
136 bool comma(false);
62ca2b82 137 for (id object in self) {
c1582939
JF
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;
62ca2b82
JF
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
c1582939
JF
174
175@implementation NSNumber (Cyrver)
62ca2b82 176
c1582939
JF
177- (NSString *) cy$toJSON {
178 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
62ca2b82
JF
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
c1582939
JF
186
187@implementation NSString (Cyrver)
62ca2b82 188
c1582939
JF
189- (NSString *) cy$toJSON {
190 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
191
c1582939
JF
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
62ca2b82
JF
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
c1582939
JF
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
62ca2b82 233JSContextRef JSGetContext() {
ea2d184c 234 return Context_;
62ca2b82
JF
235}
236
ea2d184c
JF
237void CYThrow(JSContextRef context, JSValueRef value);
238
239id JSObjectToNSObject(JSContextRef context, JSObjectRef object) {
240 if (JSValueIsObjectOfClass(context, object, joc_))
c1582939 241 return reinterpret_cast<id>(JSObjectGetPrivate(object));
ea2d184c
JF
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];
62ca2b82
JF
248}
249
250CFStringRef CYCopyCFString(JSStringRef value) {
251 return JSStringCopyCFString(kCFAllocatorDefault, value);
252}
253
ea2d184c 254CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
62ca2b82 255 JSValueRef exception(NULL);
ea2d184c
JF
256 JSStringRef string(JSValueToStringCopy(context, value, &exception));
257 CYThrow(context, exception);
62ca2b82
JF
258 CFStringRef object(CYCopyCFString(string));
259 JSStringRelease(string);
260 return object;
c1582939
JF
261}
262
62ca2b82
JF
263NSString *CYCastNSString(JSStringRef value) {
264 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
265}
266
ea2d184c
JF
267CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
268 JSType type(JSValueGetType(context, value));
c1582939
JF
269
270 switch (type) {
271 case kJSTypeUndefined:
62ca2b82 272 return CFRetain([WebUndefined undefined]);
c1582939
JF
273 break;
274
275 case kJSTypeNull:
276 return nil;
277 break;
278
279 case kJSTypeBoolean:
ea2d184c 280 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
c1582939
JF
281 break;
282
283 case kJSTypeNumber: {
62ca2b82 284 JSValueRef exception(NULL);
ea2d184c
JF
285 double number(JSValueToNumber(context, value, &exception));
286 CYThrow(context, exception);
c1582939
JF
287 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
288 } break;
289
62ca2b82 290 case kJSTypeString:
ea2d184c 291 return CYCopyCFString(context, value);
62ca2b82 292 break;
c1582939
JF
293
294 case kJSTypeObject:
ea2d184c 295 return CFRetain((CFTypeRef) JSObjectToNSObject(context, (JSObjectRef) value));
c1582939
JF
296 break;
297
298 default:
299 _assert(false);
c1582939
JF
300 break;
301 }
302}
303
62ca2b82
JF
304NSArray *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
ea2d184c
JF
312id CYCastNSObject(JSContextRef context, JSValueRef value) {
313 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
c1582939
JF
314 return object == nil ? nil : [object autorelease];
315}
316
ea2d184c 317void CYThrow(JSContextRef context, JSValueRef value) {
62ca2b82
JF
318 if (value == NULL)
319 return;
ea2d184c 320 @throw CYCastNSObject(context, value);
62ca2b82
JF
321}
322
ea2d184c
JF
323JSValueRef CYCastJSValue(JSContextRef context, id value) {
324 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
62ca2b82
JF
325}
326
ea2d184c 327JSStringRef CYCopyJSString(id value) {
62ca2b82
JF
328 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
329}
330
ea2d184c
JF
331JSStringRef CYCopyJSString(const char *value) {
332 return JSStringCreateWithUTF8CString(value);
333}
334
62ca2b82
JF
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);
ea2d184c 353 JSStringRef string(CYCopyJSString(key));
62ca2b82
JF
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);
ea2d184c 369 JSStringRef string(CYCopyJSString(key));
62ca2b82
JF
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);
ea2d184c 377 JSStringRef string(CYCopyJSString(key));
62ca2b82
JF
378 // XXX: this returns a bool
379 JSObjectDeleteProperty(context_, object_, string, &exception);
380 JSStringRelease(string);
381 CYThrow(context_, exception);
382}
383
384@end
385
c1582939
JF
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 {
62ca2b82
JF
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;
c1582939
JF
402}
403
404- (id) objectAtIndex:(NSUInteger)index {
62ca2b82
JF
405 JSValueRef exception(NULL);
406 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
407 CYThrow(context_, exception);
408 id object(CYCastNSObject(context_, value));
c1582939
JF
409 return object == nil ? [NSNull null] : object;
410}
411
412@end
413
ea2d184c
JF
414CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
415 id object(CYCastNSObject(context, value));
62ca2b82 416 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
c1582939
JF
417}
418
419static 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
62ca2b82 442 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
c1582939
JF
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
62ca2b82 448 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
c1582939
JF
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
471static 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
ea2d184c 492static JSValueRef joc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
c1582939
JF
493 return NULL;
494}
495
ea2d184c
JF
496typedef id jocData;
497
498static void joc_finalize(JSObjectRef object) {
499 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
500 [data release];
501}
502
503static JSValueRef obc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
c1582939
JF
504 NSString *name([(NSString *) JSStringCopyCFString(kCFAllocatorDefault, propertyName) autorelease]);
505 if (Class _class = NSClassFromString(name))
ea2d184c 506 return JSObjectMake(context, joc_, [_class retain]);
c1582939
JF
507 return NULL;
508}
509
ea2d184c
JF
510void 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
518struct ffiData {
519 apr_pool_t *pool_;
520 void (*function_)();
521 const char *type_;
522 sig::Signature signature_;
523 ffi_cif cif_;
524};
525
526void 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
581JSValueRef 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
638static 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
674static void ffi_finalize(JSObjectRef object) {
675 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
676 apr_pool_destroy(data->pool_);
677}
678
679void 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
62ca2b82 696MSInitialize {
ea2d184c
JF
697 apr_initialize();
698
c1582939
JF
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
ea2d184c
JF
728 definition = kJSClassDefinitionEmpty;
729 definition.callAsFunction = &ffi_callAsFunction;
730 definition.finalize = &ffi_finalize;
731 ffi_ = JSClassCreate(&definition);
732
c1582939
JF
733 definition = kJSClassDefinitionEmpty;
734 definition.getProperty = &joc_getProperty;
ea2d184c 735 definition.finalize = &joc_finalize;
c1582939
JF
736 joc_ = JSClassCreate(&definition);
737
ea2d184c
JF
738 JSContextRef context(JSGlobalContextCreate(obc));
739 Context_ = context;
740
741 JSObjectRef global(JSContextGetGlobalObject(context));
c1582939 742
ea2d184c 743 CYSetFunction(context, global, "objc_getClass", reinterpret_cast<void (*)()>(&objc_getClass), "#*");
c1582939 744
62ca2b82
JF
745 name_ = JSStringCreateWithUTF8CString("name");
746 message_ = JSStringCreateWithUTF8CString("message");
c1582939
JF
747 length_ = JSStringCreateWithUTF8CString("length");
748
749 JSStringRef name(JSStringCreateWithUTF8CString("Array"));
62ca2b82
JF
750 JSValueRef exception(NULL);
751 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, name, &exception));
ea2d184c 752 CYThrow(context, exception);
c1582939 753 JSStringRelease(name);
62ca2b82 754 Array_ = JSValueToObject(JSGetContext(), value, &exception);
ea2d184c 755 CYThrow(context, exception);
c1582939
JF
756
757 [pool release];
758}