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>
43 #include "sig/parse.hpp"
44 #include "sig/ffi_type.hpp"
46 #include <apr-1/apr_pools.h>
47 #include <apr-1/apr_strings.h>
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreFoundation/CFLogUtilities.h>
54 #include <CFNetwork/CFNetwork.h>
55 #include <Foundation/Foundation.h>
57 #include <JavaScriptCore/JSBase.h>
58 #include <JavaScriptCore/JSValueRef.h>
59 #include <JavaScriptCore/JSObjectRef.h>
60 #include <JavaScriptCore/JSContextRef.h>
61 #include <JavaScriptCore/JSStringRef.h>
62 #include <JavaScriptCore/JSStringRefCF.h>
64 #include <WebKit/WebScriptObject.h>
66 #include <sys/types.h>
67 #include <sys/socket.h>
68 #include <netinet/in.h>
73 /* XXX: bad _assert */
74 #define _assert(test) do { \
76 CFLog(kCFLogLevelNotice, CFSTR("_assert(%s):%u"), #test, __LINE__); \
80 #define _trace() do { \
81 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
84 /* Objective-C Handle<> {{{ */
85 template <typename Type_>
87 typedef _H<Type_> This_;
92 _finline void Retain_() {
97 _finline void Clear_() {
103 _finline _H(const This_ &rhs) :
104 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
108 _finline _H(Type_ *value = NULL, bool mended = false) :
119 _finline operator Type_ *() const {
123 _finline This_ &operator =(Type_ *value) {
124 if (value_ != value) {
135 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
137 static JSContextRef Context_;
139 static JSClassRef ffi_;
140 static JSClassRef joc_;
141 static JSClassRef ptr_;
142 static JSClassRef sel_;
144 static JSObjectRef Array_;
146 static JSStringRef name_;
147 static JSStringRef message_;
148 static JSStringRef length_;
150 static Class NSCFBoolean_;
153 CFHTTPMessageRef message_;
157 @interface NSMethodSignature (Cyrver)
158 - (NSString *) _typeString;
161 @interface NSObject (Cyrver)
162 - (NSString *) cy$toJSON;
163 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
166 @implementation NSObject (Cyrver)
168 - (NSString *) cy$toJSON {
169 return [self description];
172 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
173 return JSObjectMake(context, joc_, [self retain]);
178 @implementation WebUndefined (Cyrver)
180 - (NSString *) cy$toJSON {
184 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
185 return JSValueMakeUndefined(context);
190 @implementation NSArray (Cyrver)
192 - (NSString *) cy$toJSON {
193 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
194 [json appendString:@"["];
197 for (id object in self) {
199 [json appendString:@","];
202 [json appendString:[object cy$toJSON]];
205 [json appendString:@"]"];
211 @implementation NSDictionary (Cyrver)
213 - (NSString *) cy$toJSON {
214 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
215 [json appendString:@"("];
216 [json appendString:@"{"];
219 for (id key in self) {
221 [json appendString:@","];
224 [json appendString:[key cy$toJSON]];
225 [json appendString:@":"];
226 NSObject *object([self objectForKey:key]);
227 [json appendString:[object cy$toJSON]];
230 [json appendString:@"})"];
236 @implementation NSNumber (Cyrver)
238 - (NSString *) cy$toJSON {
239 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
242 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
243 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
248 @implementation NSString (Cyrver)
250 - (NSString *) cy$toJSON {
251 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
253 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
254 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
255 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
256 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
257 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
259 CFStringInsert(json, 0, CFSTR("\""));
260 CFStringAppend(json, CFSTR("\""));
262 return [reinterpret_cast<const NSString *>(json) autorelease];
267 @interface CY$JSObject : NSDictionary {
269 JSContextRef context_;
272 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
274 - (NSUInteger) count;
275 - (id) objectForKey:(id)key;
276 - (NSEnumerator *) keyEnumerator;
277 - (void) setObject:(id)object forKey:(id)key;
278 - (void) removeObjectForKey:(id)key;
282 @interface CY$JSArray : NSArray {
284 JSContextRef context_;
287 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
289 - (NSUInteger) count;
290 - (id) objectAtIndex:(NSUInteger)index;
294 JSContextRef JSGetContext() {
298 void CYThrow(JSContextRef context, JSValueRef value);
300 id JSObjectToNSObject(JSContextRef context, JSObjectRef object) {
301 if (JSValueIsObjectOfClass(context, object, joc_))
302 return reinterpret_cast<id>(JSObjectGetPrivate(object));
303 JSValueRef exception(NULL);
304 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
305 CYThrow(context, exception);
307 return [[[CY$JSArray alloc] initWithJSObject:object inContext:context] autorelease];
308 return [[[CY$JSObject alloc] initWithJSObject:object inContext:context] autorelease];
311 CFStringRef CYCopyCFString(JSStringRef value) {
312 return JSStringCopyCFString(kCFAllocatorDefault, value);
315 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
316 JSValueRef exception(NULL);
317 JSStringRef string(JSValueToStringCopy(context, value, &exception));
318 CYThrow(context, exception);
319 CFStringRef object(CYCopyCFString(string));
320 JSStringRelease(string);
324 NSString *CYCastNSString(JSStringRef value) {
325 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
328 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
329 JSType type(JSValueGetType(context, value));
332 case kJSTypeUndefined:
333 return CFRetain([WebUndefined undefined]);
341 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
344 case kJSTypeNumber: {
345 JSValueRef exception(NULL);
346 double number(JSValueToNumber(context, value, &exception));
347 CYThrow(context, exception);
348 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
352 return CYCopyCFString(context, value);
356 return CFRetain((CFTypeRef) JSObjectToNSObject(context, (JSObjectRef) value));
365 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
366 size_t size(JSPropertyNameArrayGetCount(names));
367 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
368 for (size_t index(0); index != size; ++index)
369 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
373 id CYCastNSObject(JSContextRef context, JSValueRef value) {
374 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
375 return object == nil ? nil : [object autorelease];
378 void CYThrow(JSContextRef context, JSValueRef value) {
381 @throw CYCastNSObject(context, value);
384 JSValueRef CYCastJSValue(JSContextRef context, id value) {
385 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
388 JSStringRef CYCopyJSString(id value) {
389 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
392 JSStringRef CYCopyJSString(const char *value) {
393 return JSStringCreateWithUTF8CString(value);
396 JSStringRef CYCopyJSString(JSStringRef value) {
397 return JSStringRetain(value);
400 // XXX: this is not a safe handle
406 template <typename Type_>
407 CYString(Type_ value) {
408 string_ = CYCopyJSString(value);
412 JSStringRelease(string_);
415 operator JSStringRef() const {
420 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
421 *exception = CYCastJSValue(context, error);
424 @implementation CY$JSObject
426 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
427 if ((self = [super init]) != nil) {
433 - (NSUInteger) count {
434 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
435 size_t size(JSPropertyNameArrayGetCount(names));
436 JSPropertyNameArrayRelease(names);
440 - (id) objectForKey:(id)key {
441 JSValueRef exception(NULL);
442 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
443 CYThrow(context_, exception);
444 return CYCastNSObject(context_, value);
447 - (NSEnumerator *) keyEnumerator {
448 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
449 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
450 JSPropertyNameArrayRelease(names);
454 - (void) setObject:(id)object forKey:(id)key {
455 JSValueRef exception(NULL);
456 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
457 CYThrow(context_, exception);
460 - (void) removeObjectForKey:(id)key {
461 JSValueRef exception(NULL);
462 // XXX: this returns a bool
463 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
464 CYThrow(context_, exception);
469 @implementation CY$JSArray
471 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
472 if ((self = [super init]) != nil) {
478 - (NSUInteger) count {
479 JSValueRef exception(NULL);
480 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
481 CYThrow(context_, exception);
482 double number(JSValueToNumber(context_, value, &exception));
483 CYThrow(context_, exception);
487 - (id) objectAtIndex:(NSUInteger)index {
488 JSValueRef exception(NULL);
489 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
490 CYThrow(context_, exception);
491 id object(CYCastNSObject(context_, value));
492 return object == nil ? [NSNull null] : object;
497 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
498 id object(CYCastNSObject(context, value));
499 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
502 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
504 case kCFSocketDataCallBack:
505 CFDataRef data(reinterpret_cast<CFDataRef>(value));
506 Client *client(reinterpret_cast<Client *>(info));
508 if (client->message_ == NULL)
509 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
511 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
512 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
513 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
514 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
516 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
517 CFRelease(client->message_);
519 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
522 JSStringRef script(JSStringCreateWithCFString(code));
525 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
526 JSStringRelease(script);
528 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
529 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
531 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
532 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
535 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
536 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
539 CFHTTPMessageSetBody(response, body);
542 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
545 CFSocketSendData(socket, NULL, serialized, 0);
546 CFRelease(serialized);
554 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
556 case kCFSocketAcceptCallBack:
557 Client *client(new Client());
559 client->message_ = NULL;
561 CFSocketContext context;
563 context.info = client;
564 context.retain = NULL;
565 context.release = NULL;
566 context.copyDescription = NULL;
568 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
570 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
575 static JSValueRef joc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
585 static void ptr_finalize(JSObjectRef object) {
586 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
590 static void joc_finalize(JSObjectRef object) {
591 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
595 static JSValueRef obc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
596 NSString *name([(NSString *) JSStringCopyCFString(kCFAllocatorDefault, propertyName) autorelease]);
597 if (Class _class = NSClassFromString(name))
598 return JSObjectMake(context, joc_, [_class retain]);
602 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
603 JSValueRef exception(NULL);
604 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
605 CYThrow(context, exception);
612 sig::Signature signature_;
616 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
617 size_t size(JSStringGetMaximumUTF8CStringSize(value));
618 char *string(reinterpret_cast<char *>(apr_palloc(pool, size)));
619 JSStringGetUTF8CString(value, string, size);
620 JSStringRelease(value);
624 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
625 if (JSValueIsNull(context, value))
627 else if (JSValueIsObjectOfClass(context, value, sel_))
628 return reinterpret_cast<SEL>(JSObjectGetPrivate((JSObjectRef) value));
630 JSValueRef exception(NULL);
631 JSStringRef string(JSValueToStringCopy(context, value, &exception));
632 CYThrow(context, exception);
633 size_t size(JSStringGetMaximumUTF8CStringSize(string));
635 JSStringGetUTF8CString(string, utf8, size);
636 JSStringRelease(string);
637 return sel_registerName(utf8);
641 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
642 switch (type->primitive) {
644 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
647 #define CYPoolFFI_(primitive, native) \
648 case sig::primitive ## _P: { \
649 JSValueRef exception(NULL); \
650 double number(JSValueToNumber(context, value, &exception)); \
651 CYThrow(context, exception); \
652 *reinterpret_cast<native *>(data) = number; \
655 CYPoolFFI_(uchar, unsigned char)
656 CYPoolFFI_(char, char)
657 CYPoolFFI_(ushort, unsigned short)
658 CYPoolFFI_(short, short)
659 CYPoolFFI_(ulong, unsigned long)
660 CYPoolFFI_(long, long)
661 CYPoolFFI_(uint, unsigned int)
663 CYPoolFFI_(ulonglong, unsigned long long)
664 CYPoolFFI_(longlong, long long)
665 CYPoolFFI_(float, float)
666 CYPoolFFI_(double, double)
669 case sig::typename_P:
670 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
673 case sig::selector_P:
674 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
677 case sig::pointer_P: {
678 void *&pointer(*reinterpret_cast<void **>(data));
679 if (JSValueIsNull(context, value))
681 else if (JSValueIsObjectOfClass(context, value, ptr_)) {
682 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
683 pointer = data->value_;
685 JSValueRef exception(NULL);
686 double number(JSValueToNumber(context, value, &exception));
687 CYThrow(context, exception);
688 pointer = reinterpret_cast<void *>(static_cast<uintptr_t>(number));
692 case sig::string_P: {
693 JSValueRef exception(NULL);
694 JSStringRef string(JSValueToStringCopy(context, value, &exception));
695 CYThrow(context, exception);
696 size_t size(JSStringGetMaximumUTF8CStringSize(string));
697 char *utf8(reinterpret_cast<char *>(apr_palloc(pool, size)));
698 JSStringGetUTF8CString(string, utf8, size);
699 JSStringRelease(string);
700 *reinterpret_cast<char **>(data) = utf8;
710 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
715 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
718 switch (type->primitive) {
720 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
723 #define CYFromFFI_(primitive, native) \
724 case sig::primitive ## _P: \
725 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
728 CYFromFFI_(uchar, unsigned char)
729 CYFromFFI_(char, char)
730 CYFromFFI_(ushort, unsigned short)
731 CYFromFFI_(short, short)
732 CYFromFFI_(ulong, unsigned long)
733 CYFromFFI_(long, long)
734 CYFromFFI_(uint, unsigned int)
736 CYFromFFI_(ulonglong, unsigned long long)
737 CYFromFFI_(longlong, long long)
738 CYFromFFI_(float, float)
739 CYFromFFI_(double, double)
742 case sig::typename_P: {
743 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
746 case sig::selector_P: {
747 SEL sel(*reinterpret_cast<SEL *>(data));
748 value = sel == NULL ? JSValueMakeNull(context) : JSObjectMake(context, sel_, sel);
751 case sig::pointer_P: {
752 if (void *pointer = *reinterpret_cast<void **>(data)) {
753 ptrData *data(reinterpret_cast<ptrData *>(malloc(sizeof(ptrData))));
754 data->value_ = pointer;
755 value = JSObjectMake(context, ptr_, data);
756 } else value = JSValueMakeNull(context);
759 case sig::string_P: {
760 char *utf8(*reinterpret_cast<char **>(data));
761 value = utf8 == NULL ? JSValueMakeNull(context) : JSValueMakeString(context, CYString(utf8));
772 NSLog(@"CYFromFFI(%c)\n", type->primitive);
785 apr_pool_create(&pool_, NULL);
789 apr_pool_destroy(pool_);
792 operator apr_pool_t *() const {
797 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
799 if (count != signature->count - 1)
800 [NSException raise:NSInvalidArgumentException format:@"incorrect number of arguments to ffi function"];
805 for (unsigned index(0); index != count; ++index) {
806 sig::Element *element(&signature->elements[index + 1]);
807 values[index] = apr_palloc(pool, cif->arg_types[index]->size);
808 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
811 uint8_t value[cif->rtype->size];
812 ffi_call(cif, function, value, values);
814 return CYFromFFI(context, signature->elements[0].type, value);
815 } @catch (id error) {
816 CYThrow(context, error, exception);
821 bool stret(ffi_type *ffi_type) {
822 return ffi_type->type == FFI_TYPE_STRUCT && (
823 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
824 struct_forward_array[ffi_type->size] != 0
828 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
833 [NSException raise:NSInvalidArgumentException format:@"too few arguments to objc_msgSend"];
835 id self(CYCastNSObject(context, arguments[0]));
837 return JSValueMakeNull(context);
839 SEL _cmd(CYCastSEL(context, arguments[1]));
840 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
842 [NSException raise:NSInvalidArgumentException format:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self];
844 type = [[method _typeString] UTF8String];
845 } @catch (id error) {
846 CYThrow(context, error, exception);
852 sig::Signature signature;
853 sig::Parse(pool, &signature, type);
856 sig::sig_ffi_cif(pool, &sig::sig_objc_ffi_type, &signature, &cif);
858 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
859 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
862 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
863 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
864 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, data->function_);
867 static void ffi_finalize(JSObjectRef object) {
868 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
869 apr_pool_destroy(data->pool_);
872 void CYSetFunction(JSContextRef context, JSObjectRef object, const char *name, void (*function)(), const char *type) {
874 apr_pool_create(&pool, NULL);
876 ffiData *data(reinterpret_cast<ffiData *>(apr_palloc(pool, sizeof(ffiData))));
879 data->function_ = function;
880 data->type_ = apr_pstrdup(pool, type);
882 sig::Parse(pool, &data->signature_, type);
883 sig::sig_ffi_cif(pool, &sig::sig_objc_ffi_type, &data->signature_, &data->cif_);
885 JSObjectRef value(JSObjectMake(context, ffi_, data));
886 CYSetProperty(context, object, name, value);
889 JSValueRef ptr_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef *exception) {
890 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
891 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
894 static JSStaticValue ptr_staticValues[2] = {
895 {"value", &ptr_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
896 {NULL, NULL, NULL, 0}
899 MSInitialize { _pooled
902 NSCFBoolean_ = objc_getClass("NSCFBoolean");
906 struct sockaddr_in address;
907 address.sin_len = sizeof(address);
908 address.sin_family = AF_INET;
909 address.sin_addr.s_addr = INADDR_ANY;
910 address.sin_port = htons(10000 + pid);
912 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
914 CFSocketSignature signature;
915 signature.protocolFamily = AF_INET;
916 signature.socketType = SOCK_STREAM;
917 signature.protocol = IPPROTO_TCP;
918 signature.address = data;
920 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
921 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
923 JSClassDefinition definition;
925 definition = kJSClassDefinitionEmpty;
926 definition.getProperty = &obc_getProperty;
927 JSClassRef obc(JSClassCreate(&definition));
929 definition = kJSClassDefinitionEmpty;
930 definition.className = "ffi";
931 definition.callAsFunction = &ffi_callAsFunction;
932 definition.finalize = &ffi_finalize;
933 ffi_ = JSClassCreate(&definition);
935 definition = kJSClassDefinitionEmpty;
936 definition.className = "ptr";
937 definition.staticValues = ptr_staticValues;
938 definition.finalize = &ptr_finalize;
939 ptr_ = JSClassCreate(&definition);
941 definition = kJSClassDefinitionEmpty;
942 definition.className = "sel";
943 sel_ = JSClassCreate(&definition);
945 definition = kJSClassDefinitionEmpty;
946 definition.className = "joc";
947 definition.getProperty = &joc_getProperty;
948 definition.finalize = &joc_finalize;
949 joc_ = JSClassCreate(&definition);
951 JSContextRef context(JSGlobalContextCreate(obc));
954 JSObjectRef global(JSContextGetGlobalObject(context));
956 #define CYSetFunction_(name, type) \
957 CYSetFunction(context, global, #name, reinterpret_cast<void (*)()>(&name), type)
959 CYSetFunction_(class_addIvar, "B#*LC*");
960 CYSetFunction_(class_addMethod, "B#:^?*");
961 CYSetFunction_(class_addProtocol, "B#@");
962 CYSetFunction_(class_conformsToProtocol, "B#@");
963 CYSetFunction_(class_copyIvarList, "^^{objc_ivar=}#^I");
964 CYSetFunction_(class_copyMethodList, "^^{objc_method=}#^I");
965 CYSetFunction_(class_copyPropertyList, "^^{objc_property=}#^I");
966 CYSetFunction_(class_copyProtocolList, "^@#^I");
967 CYSetFunction_(class_createInstance, "@#L");
968 CYSetFunction_(class_getClassMethod, "^{objc_method=}#:");
969 CYSetFunction_(class_getClassVariable, "^{objc_ivar=}#*");
970 CYSetFunction_(class_getInstanceMethod, "^{objc_method=}#:");
971 CYSetFunction_(class_getInstanceSize, "L#");
972 CYSetFunction_(class_getInstanceVariable, "^{objc_ivar=}#*");
973 CYSetFunction_(class_getIvarLayout, "*#");
974 CYSetFunction_(class_getMethodImplementation, "^?#:");
975 CYSetFunction_(class_getMethodImplementation_stret, "^?#:");
976 CYSetFunction_(class_getName, "*#");
977 CYSetFunction_(class_getProperty, "^{objc_property=}#*");
978 CYSetFunction_(class_getSuperclass, "##");
979 CYSetFunction_(class_getVersion, "i#");
980 CYSetFunction_(class_getWeakIvarLayout, "*#");
981 CYSetFunction_(class_isMetaClass, "B#");
982 CYSetFunction_(class_replaceMethod, "^?#:^?*");
983 CYSetFunction_(class_respondsToSelector, "B#:");
984 CYSetFunction_(class_setIvarLayout, "v#*");
985 CYSetFunction_(class_setSuperclass, "###");
986 CYSetFunction_(class_setVersion, "v#i");
987 CYSetFunction_(class_setWeakIvarLayout, "v#*");
988 CYSetFunction_(ivar_getName, "*^{objc_ivar=}");
989 CYSetFunction_(ivar_getOffset, "i^{objc_ivar=}");
990 CYSetFunction_(ivar_getTypeEncoding, "*^{objc_ivar=}");
991 CYSetFunction_(method_copyArgumentType, "^c^{objc_method=}I");
992 CYSetFunction_(method_copyReturnType, "^c^{objc_method=}");
993 CYSetFunction_(method_exchangeImplementations, "v^{objc_method=}^{objc_method=}");
994 CYSetFunction_(method_getArgumentType, "v^{objc_method=}I^cL");
995 CYSetFunction_(method_getImplementation, "^?^{objc_method=}");
996 CYSetFunction_(method_getName, ":^{objc_method=}");
997 CYSetFunction_(method_getNumberOfArguments, "I^{objc_method=}");
998 CYSetFunction_(method_getReturnType, "v^{objc_method=}^cL");
999 CYSetFunction_(method_getTypeEncoding, "*^{objc_method=}");
1000 CYSetFunction_(method_setImplementation, "^?^{objc_method=}^?");
1001 CYSetFunction_(objc_allocateClassPair, "##*L");
1002 CYSetFunction_(objc_copyProtocolList, "^@^I");
1003 CYSetFunction_(objc_duplicateClass, "##*L");
1004 CYSetFunction_(objc_getClass, "#*");
1005 CYSetFunction_(objc_getClassList, "i^#i");
1006 CYSetFunction_(objc_getFutureClass, "#*");
1007 CYSetFunction_(objc_getMetaClass, "@*");
1008 CYSetFunction_(objc_getProtocol, "@*");
1009 CYSetFunction_(objc_getRequiredClass, "@*");
1010 CYSetFunction_(objc_lookUpClass, "@*");
1011 CYSetFunction_(objc_registerClassPair, "v#");
1012 CYSetFunction_(objc_setFutureClass, "v#*");
1013 CYSetFunction_(object_copy, "@@L");
1014 CYSetFunction_(object_dispose, "@@");
1015 CYSetFunction_(object_getClass, "#@");
1016 CYSetFunction_(object_getClassName, "*@");
1017 CYSetFunction_(object_getIndexedIvars, "^v@");
1018 CYSetFunction_(object_getInstanceVariable, "^{objc_ivar=}@*^^v");
1019 CYSetFunction_(object_getIvar, "@@^{objc_ivar=}");
1020 CYSetFunction_(object_setClass, "#@#");
1021 CYSetFunction_(object_setInstanceVariable, "^{objc_ivar=}@*^v");
1022 CYSetFunction_(object_setIvar, "v@^{objc_ivar=}@");
1023 CYSetFunction_(property_getAttributes, "*^{objc_property=}");
1024 CYSetFunction_(property_getName, "*^{objc_property=}");
1025 CYSetFunction_(protocol_conformsToProtocol, "B@@");
1026 CYSetFunction_(protocol_copyMethodDescriptionList, "^{objc_method_description=:*}@BB^I");
1027 CYSetFunction_(protocol_copyPropertyList, "^{objc_property=}@^I");
1028 CYSetFunction_(protocol_copyProtocolList, "^@@^I");
1029 CYSetFunction_(protocol_getMethodDescription, "{objc_method_description=:*}@:BB");
1030 CYSetFunction_(protocol_getName, "*@");
1031 CYSetFunction_(protocol_getProperty, "^{objc_property=}@*BB");
1032 CYSetFunction_(protocol_isEqual, "B@@");
1033 CYSetFunction_(sel_getName, "*:");
1034 CYSetFunction_(sel_getUid, ":*");
1035 CYSetFunction_(sel_isEqual, "B::");
1036 CYSetFunction_(sel_registerName, ":*");
1038 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
1040 CYSetProperty(context, global, "YES", JSValueMakeBoolean(context, true));
1041 CYSetProperty(context, global, "NO", JSValueMakeBoolean(context, false));
1042 CYSetProperty(context, global, "nil", JSValueMakeNull(context));
1044 name_ = JSStringCreateWithUTF8CString("name");
1045 message_ = JSStringCreateWithUTF8CString("message");
1046 length_ = JSStringCreateWithUTF8CString("length");
1048 JSValueRef exception(NULL);
1049 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
1050 CYThrow(context, exception);
1051 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1052 CYThrow(context, exception);