1 /* Cyrker - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
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
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.
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.
40 #include <substrate.h>
42 #include "sig/parse.hpp"
43 #include "sig/ffi_type.hpp"
45 #include <apr-1/apr_pools.h>
46 #include <apr-1/apr_strings.h>
50 #include <CoreFoundation/CoreFoundation.h>
51 #include <CoreFoundation/CFLogUtilities.h>
53 #include <CFNetwork/CFNetwork.h>
54 #include <Foundation/Foundation.h>
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>
63 #include <WebKit/WebScriptObject.h>
65 #include <sys/types.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
72 /* XXX: bad _assert */
73 #define _assert(test) do { \
75 CFLog(kCFLogLevelNotice, CFSTR("_assert(%s):%u"), #test, __LINE__); \
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
83 /* Objective-C Handle<> {{{ */
84 template <typename Type_>
86 typedef _H<Type_> This_;
91 _finline void Retain_() {
96 _finline void Clear_() {
102 _finline _H(const This_ &rhs) :
103 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
107 _finline _H(Type_ *value = NULL, bool mended = false) :
118 _finline operator Type_ *() const {
122 _finline This_ &operator =(Type_ *value) {
123 if (value_ != value) {
134 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
136 static JSContextRef Context_;
138 static JSClassRef ffi_;
139 static JSClassRef joc_;
140 static JSClassRef ptr_;
141 static JSClassRef sel_;
143 static JSObjectRef Array_;
145 static JSStringRef name_;
146 static JSStringRef message_;
147 static JSStringRef length_;
149 static Class NSCFBoolean_;
152 CFHTTPMessageRef message_;
156 @interface NSMethodSignature (Cyrver)
157 - (NSString *) _typeString;
160 @interface NSObject (Cyrver)
161 - (NSString *) cy$toJSON;
162 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
165 @implementation NSObject (Cyrver)
167 - (NSString *) cy$toJSON {
168 return [self description];
171 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
172 return JSObjectMake(context, joc_, [self retain]);
177 @implementation WebUndefined (Cyrver)
179 - (NSString *) cy$toJSON {
183 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
184 return JSValueMakeUndefined(context);
189 @implementation NSArray (Cyrver)
191 - (NSString *) cy$toJSON {
192 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
193 [json appendString:@"["];
196 for (id object in self) {
198 [json appendString:@","];
201 [json appendString:[object cy$toJSON]];
204 [json appendString:@"]"];
210 @implementation NSDictionary (Cyrver)
212 - (NSString *) cy$toJSON {
213 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
214 [json appendString:@"("];
215 [json appendString:@"{"];
218 for (id key in self) {
220 [json appendString:@","];
223 [json appendString:[key cy$toJSON]];
224 [json appendString:@":"];
225 NSObject *object([self objectForKey:key]);
226 [json appendString:[object cy$toJSON]];
229 [json appendString:@"})"];
235 @implementation NSNumber (Cyrver)
237 - (NSString *) cy$toJSON {
238 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
241 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
242 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
247 @implementation NSString (Cyrver)
249 - (NSString *) cy$toJSON {
250 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
252 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
253 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
254 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
255 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
256 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
258 CFStringInsert(json, 0, CFSTR("\""));
259 CFStringAppend(json, CFSTR("\""));
261 return [reinterpret_cast<const NSString *>(json) autorelease];
266 @interface CY$JSObject : NSDictionary {
268 JSContextRef context_;
271 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
273 - (NSUInteger) count;
274 - (id) objectForKey:(id)key;
275 - (NSEnumerator *) keyEnumerator;
276 - (void) setObject:(id)object forKey:(id)key;
277 - (void) removeObjectForKey:(id)key;
281 @interface CY$JSArray : NSArray {
283 JSContextRef context_;
286 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
288 - (NSUInteger) count;
289 - (id) objectAtIndex:(NSUInteger)index;
293 JSContextRef JSGetContext() {
297 void CYThrow(JSContextRef context, JSValueRef value);
299 id JSObjectToNSObject(JSContextRef context, JSObjectRef object) {
300 if (JSValueIsObjectOfClass(context, object, joc_))
301 return reinterpret_cast<id>(JSObjectGetPrivate(object));
302 JSValueRef exception(NULL);
303 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
304 CYThrow(context, exception);
306 return [[[CY$JSArray alloc] initWithJSObject:object inContext:context] autorelease];
307 return [[[CY$JSObject alloc] initWithJSObject:object inContext:context] autorelease];
310 CFStringRef CYCopyCFString(JSStringRef value) {
311 return JSStringCopyCFString(kCFAllocatorDefault, value);
314 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
315 JSValueRef exception(NULL);
316 JSStringRef string(JSValueToStringCopy(context, value, &exception));
317 CYThrow(context, exception);
318 CFStringRef object(CYCopyCFString(string));
319 JSStringRelease(string);
323 NSString *CYCastNSString(JSStringRef value) {
324 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
327 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
328 JSType type(JSValueGetType(context, value));
331 case kJSTypeUndefined:
332 return CFRetain([WebUndefined undefined]);
340 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
343 case kJSTypeNumber: {
344 JSValueRef exception(NULL);
345 double number(JSValueToNumber(context, value, &exception));
346 CYThrow(context, exception);
347 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
351 return CYCopyCFString(context, value);
355 return CFRetain((CFTypeRef) JSObjectToNSObject(context, (JSObjectRef) value));
364 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
365 size_t size(JSPropertyNameArrayGetCount(names));
366 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
367 for (size_t index(0); index != size; ++index)
368 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
372 id CYCastNSObject(JSContextRef context, JSValueRef value) {
373 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
374 return object == nil ? nil : [object autorelease];
377 void CYThrow(JSContextRef context, JSValueRef value) {
380 @throw CYCastNSObject(context, value);
383 JSValueRef CYCastJSValue(JSContextRef context, id value) {
384 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
387 JSStringRef CYCopyJSString(id value) {
388 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
391 JSStringRef CYCopyJSString(const char *value) {
392 return JSStringCreateWithUTF8CString(value);
395 JSStringRef CYCopyJSString(JSStringRef value) {
396 return JSStringRetain(value);
399 // XXX: this is not a safe handle
405 template <typename Type_>
406 CYString(Type_ value) {
407 string_ = CYCopyJSString(value);
411 JSStringRelease(string_);
414 operator JSStringRef() const {
419 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
420 *exception = CYCastJSValue(context, error);
423 @implementation CY$JSObject
425 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
426 if ((self = [super init]) != nil) {
432 - (NSUInteger) count {
433 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
434 size_t size(JSPropertyNameArrayGetCount(names));
435 JSPropertyNameArrayRelease(names);
439 - (id) objectForKey:(id)key {
440 JSValueRef exception(NULL);
441 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
442 CYThrow(context_, exception);
443 return CYCastNSObject(context_, value);
446 - (NSEnumerator *) keyEnumerator {
447 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
448 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
449 JSPropertyNameArrayRelease(names);
453 - (void) setObject:(id)object forKey:(id)key {
454 JSValueRef exception(NULL);
455 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
456 CYThrow(context_, exception);
459 - (void) removeObjectForKey:(id)key {
460 JSValueRef exception(NULL);
461 // XXX: this returns a bool
462 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
463 CYThrow(context_, exception);
468 @implementation CY$JSArray
470 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
471 if ((self = [super init]) != nil) {
477 - (NSUInteger) count {
478 JSValueRef exception(NULL);
479 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
480 CYThrow(context_, exception);
481 double number(JSValueToNumber(context_, value, &exception));
482 CYThrow(context_, exception);
486 - (id) objectAtIndex:(NSUInteger)index {
487 JSValueRef exception(NULL);
488 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
489 CYThrow(context_, exception);
490 id object(CYCastNSObject(context_, value));
491 return object == nil ? [NSNull null] : object;
496 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
497 id object(CYCastNSObject(context, value));
498 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
501 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
503 case kCFSocketDataCallBack:
504 CFDataRef data(reinterpret_cast<CFDataRef>(value));
505 Client *client(reinterpret_cast<Client *>(info));
507 if (client->message_ == NULL)
508 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
510 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
511 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
512 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
513 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
515 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
516 CFRelease(client->message_);
518 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
521 JSStringRef script(JSStringCreateWithCFString(code));
524 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
525 JSStringRelease(script);
527 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
528 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
530 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
531 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
534 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
535 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
538 CFHTTPMessageSetBody(response, body);
541 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
544 CFSocketSendData(socket, NULL, serialized, 0);
545 CFRelease(serialized);
553 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
555 case kCFSocketAcceptCallBack:
556 Client *client(new Client());
558 client->message_ = NULL;
560 CFSocketContext context;
562 context.info = client;
563 context.retain = NULL;
564 context.release = NULL;
565 context.copyDescription = NULL;
567 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
569 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
574 static JSValueRef joc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
580 static void joc_finalize(JSObjectRef object) {
581 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
585 static JSValueRef obc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
586 NSString *name([(NSString *) JSStringCopyCFString(kCFAllocatorDefault, propertyName) autorelease]);
587 if (Class _class = NSClassFromString(name))
588 return JSObjectMake(context, joc_, [_class retain]);
592 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
593 JSValueRef exception(NULL);
594 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
595 CYThrow(context, exception);
602 sig::Signature signature_;
606 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
607 size_t size(JSStringGetMaximumUTF8CStringSize(value));
608 char *string(reinterpret_cast<char *>(apr_palloc(pool, size)));
609 JSStringGetUTF8CString(value, string, size);
610 JSStringRelease(value);
614 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
615 if (JSValueIsNull(context, value))
617 else if (JSValueIsObjectOfClass(context, value, sel_))
618 return reinterpret_cast<SEL>(JSObjectGetPrivate((JSObjectRef) value));
620 JSValueRef exception(NULL);
621 JSStringRef string(JSValueToStringCopy(context, value, &exception));
622 CYThrow(context, exception);
623 size_t size(JSStringGetMaximumUTF8CStringSize(string));
625 JSStringGetUTF8CString(string, utf8, size);
626 JSStringRelease(string);
627 return sel_registerName(utf8);
631 void CYToFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
632 switch (type->primitive) {
634 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
637 #define CYToFFI_(primitive, native) \
638 case sig::primitive ## _P: { \
639 JSValueRef exception(NULL); \
640 double number(JSValueToNumber(context, value, &exception)); \
641 CYThrow(context, exception); \
642 *reinterpret_cast<native *>(data) = number; \
645 CYToFFI_(uchar, unsigned char)
647 CYToFFI_(ushort, unsigned short)
648 CYToFFI_(short, short)
649 CYToFFI_(ulong, unsigned long)
651 CYToFFI_(uint, unsigned int)
653 CYToFFI_(ulonglong, unsigned long long)
654 CYToFFI_(longlong, long long)
655 CYToFFI_(float, float)
656 CYToFFI_(double, double)
659 case sig::typename_P:
660 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
663 case sig::selector_P:
664 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
667 case sig::pointer_P: {
668 void *&pointer(*reinterpret_cast<void **>(data));
669 if (JSValueIsNull(context, value))
671 else if (JSValueIsObjectOfClass(context, value, ptr_))
672 pointer = JSObjectGetPrivate((JSObjectRef) value);
674 JSValueRef exception(NULL);
675 double number(JSValueToNumber(context, value, &exception));
676 CYThrow(context, exception);
677 pointer = reinterpret_cast<void *>(static_cast<uintptr_t>(number));
681 case sig::string_P: {
682 JSValueRef exception(NULL);
683 JSStringRef string(JSValueToStringCopy(context, value, &exception));
684 CYThrow(context, exception);
685 size_t size(JSStringGetMaximumUTF8CStringSize(string));
686 char *utf8(reinterpret_cast<char *>(apr_palloc(pool, size)));
687 JSStringGetUTF8CString(string, utf8, size);
688 JSStringRelease(string);
689 *reinterpret_cast<char **>(data) = utf8;
699 NSLog(@"CYToFFI(%c)\n", type->primitive);
704 JSValueRef CYFromFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data) {
707 switch (type->primitive) {
709 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
712 #define CYFromFFI_(primitive, native) \
713 case sig::primitive ## _P: \
714 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
717 CYFromFFI_(uchar, unsigned char)
718 CYFromFFI_(char, char)
719 CYFromFFI_(ushort, unsigned short)
720 CYFromFFI_(short, short)
721 CYFromFFI_(ulong, unsigned long)
722 CYFromFFI_(long, long)
723 CYFromFFI_(uint, unsigned int)
725 CYFromFFI_(ulonglong, unsigned long long)
726 CYFromFFI_(longlong, long long)
727 CYFromFFI_(float, float)
728 CYFromFFI_(double, double)
731 case sig::typename_P: {
732 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
735 case sig::selector_P: {
736 SEL sel(*reinterpret_cast<SEL *>(data));
737 value = sel == NULL ? JSValueMakeNull(context) : JSObjectMake(context, sel_, sel);
740 case sig::pointer_P: {
741 void *pointer(*reinterpret_cast<void **>(data));
742 value = pointer == NULL ? JSValueMakeNull(context) : JSObjectMake(context, ptr_, pointer);
745 case sig::string_P: {
746 char *utf8(*reinterpret_cast<char **>(data));
747 value = utf8 == NULL ? JSValueMakeNull(context) : JSValueMakeString(context, CYString(utf8));
758 NSLog(@"CYFromFFI(%c)\n", type->primitive);
771 apr_pool_create(&pool_, NULL);
775 apr_pool_destroy(pool_);
778 operator apr_pool_t *() const {
783 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
785 if (count != signature->count - 1)
786 [NSException raise:NSInvalidArgumentException format:@"incorrect number of arguments to ffi function"];
791 for (unsigned index(0); index != count; ++index) {
792 sig::Element *element(&signature->elements[index + 1]);
793 values[index] = apr_palloc(pool, cif->arg_types[index]->size);
794 CYToFFI(pool, context, element->type, values[index], arguments[index]);
797 uint8_t value[cif->rtype->size];
798 ffi_call(cif, function, value, values);
800 return CYFromFFI(pool, context, signature->elements[0].type, value);
801 } @catch (id error) {
802 CYThrow(context, error, exception);
807 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
812 [NSException raise:NSInvalidArgumentException format:@"too few arguments to objc_msgSend"];
814 id self(CYCastNSObject(context, arguments[0]));
816 return JSValueMakeNull(context);
818 SEL _cmd(CYCastSEL(context, arguments[1]));
819 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
821 [NSException raise:NSInvalidArgumentException format:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self];
823 type = [[method _typeString] UTF8String];
824 } @catch (id error) {
825 CYThrow(context, error, exception);
831 sig::Signature signature;
832 sig::Parse(pool, &signature, type);
834 void (*function)() = reinterpret_cast<void (*)()>(&objc_msgSend);
837 sig::sig_ffi_cif(pool, &sig::sig_objc_ffi_type, &signature, &cif);
839 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
842 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
843 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
844 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, data->function_);
847 static void ffi_finalize(JSObjectRef object) {
848 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
849 apr_pool_destroy(data->pool_);
852 void CYSetFunction(JSContextRef context, JSObjectRef object, const char *name, void (*function)(), const char *type) {
854 apr_pool_create(&pool, NULL);
856 ffiData *data(reinterpret_cast<ffiData *>(apr_palloc(pool, sizeof(ffiData))));
859 data->function_ = function;
860 data->type_ = apr_pstrdup(pool, type);
862 sig::Parse(pool, &data->signature_, type);
863 sig::sig_ffi_cif(pool, &sig::sig_objc_ffi_type, &data->signature_, &data->cif_);
865 JSObjectRef value(JSObjectMake(context, ffi_, data));
866 CYSetProperty(context, object, name, value);
869 MSInitialize { _pooled
872 NSCFBoolean_ = objc_getClass("NSCFBoolean");
876 struct sockaddr_in address;
877 address.sin_len = sizeof(address);
878 address.sin_family = AF_INET;
879 address.sin_addr.s_addr = INADDR_ANY;
880 address.sin_port = htons(10000 + pid);
882 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
884 CFSocketSignature signature;
885 signature.protocolFamily = AF_INET;
886 signature.socketType = SOCK_STREAM;
887 signature.protocol = IPPROTO_TCP;
888 signature.address = data;
890 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
891 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
893 JSClassDefinition definition;
895 definition = kJSClassDefinitionEmpty;
896 definition.getProperty = &obc_getProperty;
897 JSClassRef obc(JSClassCreate(&definition));
899 definition = kJSClassDefinitionEmpty;
900 definition.className = "ffi";
901 definition.callAsFunction = &ffi_callAsFunction;
902 definition.finalize = &ffi_finalize;
903 ffi_ = JSClassCreate(&definition);
905 definition = kJSClassDefinitionEmpty;
906 definition.className = "ptr";
907 ptr_ = JSClassCreate(&definition);
909 definition = kJSClassDefinitionEmpty;
910 definition.className = "sel";
911 sel_ = JSClassCreate(&definition);
913 definition = kJSClassDefinitionEmpty;
914 definition.className = "joc";
915 definition.getProperty = &joc_getProperty;
916 definition.finalize = &joc_finalize;
917 joc_ = JSClassCreate(&definition);
919 JSContextRef context(JSGlobalContextCreate(obc));
922 JSObjectRef global(JSContextGetGlobalObject(context));
924 #define CYSetFunction_(name, type) \
925 CYSetFunction(context, global, #name, reinterpret_cast<void (*)()>(&name), type)
927 CYSetFunction_(class_createInstance, "@#L");
928 CYSetFunction_(class_getInstanceSize, "L#");
929 CYSetFunction_(class_getIvarLayout, "*#");
930 CYSetFunction_(class_getName, "*#");
931 CYSetFunction_(class_getSuperclass, "##");
932 CYSetFunction_(class_getVersion, "i#");
933 CYSetFunction_(class_isMetaClass, "B#");
934 CYSetFunction_(class_respondsToSelector, "B#:");
935 CYSetFunction_(class_setSuperclass, "###");
936 CYSetFunction_(class_setVersion, "v#i");
937 CYSetFunction_(objc_allocateClassPair, "##*L");
938 CYSetFunction_(objc_getClass, "#*");
939 CYSetFunction_(objc_getFutureClass, "#*");
940 CYSetFunction_(objc_getMetaClass, "@*");
941 CYSetFunction_(objc_getRequiredClass, "@*");
942 CYSetFunction_(objc_lookUpClass, "@*");
943 CYSetFunction_(objc_registerClassPair, "v#");
944 CYSetFunction_(objc_setFutureClass, "v#*");
945 CYSetFunction_(object_copy, "@@L");
946 CYSetFunction_(object_dispose, "@@");
947 CYSetFunction_(object_getClass, "#@");
948 CYSetFunction_(object_getClassName, "*@");
949 CYSetFunction_(object_setClass, "#@#");
950 CYSetFunction_(sel_getName, "*:");
951 CYSetFunction_(sel_getUid, ":*");
952 CYSetFunction_(sel_isEqual, "B::");
953 CYSetFunction_(sel_registerName, ":*");
955 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
957 CYSetProperty(context, global, "YES", JSValueMakeBoolean(context, true));
958 CYSetProperty(context, global, "NO", JSValueMakeBoolean(context, false));
959 CYSetProperty(context, global, "nil", JSValueMakeNull(context));
961 name_ = JSStringCreateWithUTF8CString("name");
962 message_ = JSStringCreateWithUTF8CString("message");
963 length_ = JSStringCreateWithUTF8CString("length");
965 JSValueRef exception(NULL);
966 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
967 CYThrow(context, exception);
968 Array_ = JSValueToObject(JSGetContext(), value, &exception);
969 CYThrow(context, exception);