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 void *operator new(size_t size, apr_pool_t *pool) {
138 return apr_palloc(pool, size);
141 void *operator new [](size_t size, apr_pool_t *pool) {
142 return apr_palloc(pool, size);
145 static JSContextRef Context_;
147 static JSClassRef Functor_;
148 static JSClassRef Instance_;
149 static JSClassRef Pointer_;
150 static JSClassRef Selector_;
152 static JSObjectRef Array_;
154 static JSStringRef name_;
155 static JSStringRef message_;
156 static JSStringRef length_;
158 static Class NSCFBoolean_;
160 static NSMutableDictionary *Bridge_;
163 CFHTTPMessageRef message_;
167 JSObjectRef CYMakeObject(JSContextRef context, id object) {
168 return JSObjectMake(context, Instance_, [object retain]);
171 @interface NSMethodSignature (Cyrver)
172 - (NSString *) _typeString;
175 @interface NSObject (Cyrver)
176 - (NSString *) cy$toJSON;
177 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
180 @interface NSString (Cyrver)
181 - (void *) cy$symbol;
184 @interface NSNumber (Cyrver)
185 - (void *) cy$symbol;
188 @implementation NSObject (Cyrver)
190 - (NSString *) cy$toJSON {
191 return [self description];
194 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
195 return CYMakeObject(context, self);
200 @implementation WebUndefined (Cyrver)
202 - (NSString *) cy$toJSON {
206 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
207 return JSValueMakeUndefined(context);
212 @implementation NSArray (Cyrver)
214 - (NSString *) cy$toJSON {
215 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
216 [json appendString:@"["];
219 for (id object in self) {
221 [json appendString:@","];
224 [json appendString:[object cy$toJSON]];
227 [json appendString:@"]"];
233 @implementation NSDictionary (Cyrver)
235 - (NSString *) cy$toJSON {
236 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
237 [json appendString:@"("];
238 [json appendString:@"{"];
241 for (id key in self) {
243 [json appendString:@","];
246 [json appendString:[key cy$toJSON]];
247 [json appendString:@":"];
248 NSObject *object([self objectForKey:key]);
249 [json appendString:[object cy$toJSON]];
252 [json appendString:@"})"];
258 @implementation NSNumber (Cyrver)
260 - (NSString *) cy$toJSON {
261 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
264 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
265 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
268 - (void *) cy$symbol {
269 return [self pointerValue];
274 @implementation NSString (Cyrver)
276 - (NSString *) cy$toJSON {
277 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
279 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
280 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
281 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
282 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
283 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
285 CFStringInsert(json, 0, CFSTR("\""));
286 CFStringAppend(json, CFSTR("\""));
288 return [reinterpret_cast<const NSString *>(json) autorelease];
291 - (void *) cy$symbol {
292 return dlsym(RTLD_DEFAULT, [self UTF8String]);
297 @interface CYJSObject : NSDictionary {
299 JSContextRef context_;
302 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
304 - (NSUInteger) count;
305 - (id) objectForKey:(id)key;
306 - (NSEnumerator *) keyEnumerator;
307 - (void) setObject:(id)object forKey:(id)key;
308 - (void) removeObjectForKey:(id)key;
312 @interface CYJSArray : NSArray {
314 JSContextRef context_;
317 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
319 - (NSUInteger) count;
320 - (id) objectAtIndex:(NSUInteger)index;
324 JSContextRef JSGetContext() {
329 @catch (id error) { \
330 CYThrow(context, error, exception); \
334 void CYThrow(JSContextRef context, JSValueRef value);
336 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
337 if (JSValueIsObjectOfClass(context, object, Instance_))
338 return reinterpret_cast<id>(JSObjectGetPrivate(object));
339 JSValueRef exception(NULL);
340 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
341 CYThrow(context, exception);
343 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
344 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
347 JSStringRef CYCopyJSString(id value) {
348 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
351 JSStringRef CYCopyJSString(const char *value) {
352 return JSStringCreateWithUTF8CString(value);
355 JSStringRef CYCopyJSString(JSStringRef value) {
356 return JSStringRetain(value);
359 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
360 JSValueRef exception(NULL);
361 JSStringRef string(JSValueToStringCopy(context, value, &exception));
362 CYThrow(context, exception);
366 // XXX: this is not a safe handle
372 template <typename Arg0_>
373 CYString(Arg0_ arg0) {
374 string_ = CYCopyJSString(arg0);
377 template <typename Arg0_, typename Arg1_>
378 CYString(Arg0_ arg0, Arg1_ arg1) {
379 string_ = CYCopyJSString(arg0, arg1);
383 JSStringRelease(string_);
386 operator JSStringRef() const {
391 CFStringRef CYCopyCFString(JSStringRef value) {
392 return JSStringCopyCFString(kCFAllocatorDefault, value);
395 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
396 return CYCopyCFString(CYString(context, value));
399 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
400 JSValueRef exception(NULL);
401 double number(JSValueToNumber(context, value, &exception));
402 CYThrow(context, exception);
403 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
406 NSString *CYCastNSString(JSStringRef value) {
407 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
410 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
411 switch (JSValueGetType(context, value)) {
412 case kJSTypeUndefined:
413 return CFRetain([WebUndefined undefined]);
417 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
419 return CYCopyCFNumber(context, value);
421 return CYCopyCFString(context, value);
423 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
429 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
430 size_t size(JSPropertyNameArrayGetCount(names));
431 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
432 for (size_t index(0); index != size; ++index)
433 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
437 id CYCastNSObject(JSContextRef context, JSValueRef value) {
438 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
439 return object == nil ? nil : [object autorelease];
442 void CYThrow(JSContextRef context, JSValueRef value) {
445 @throw CYCastNSObject(context, value);
448 JSValueRef CYCastJSValue(JSContextRef context, id value) {
449 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
452 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
453 *exception = CYCastJSValue(context, error);
456 @implementation CYJSObject
458 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
459 if ((self = [super init]) != nil) {
465 - (NSUInteger) count {
466 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
467 size_t size(JSPropertyNameArrayGetCount(names));
468 JSPropertyNameArrayRelease(names);
472 - (id) objectForKey:(id)key {
473 JSValueRef exception(NULL);
474 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
475 CYThrow(context_, exception);
476 return CYCastNSObject(context_, value);
479 - (NSEnumerator *) keyEnumerator {
480 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
481 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
482 JSPropertyNameArrayRelease(names);
486 - (void) setObject:(id)object forKey:(id)key {
487 JSValueRef exception(NULL);
488 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
489 CYThrow(context_, exception);
492 - (void) removeObjectForKey:(id)key {
493 JSValueRef exception(NULL);
494 // XXX: this returns a bool
495 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
496 CYThrow(context_, exception);
501 @implementation CYJSArray
503 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
504 if ((self = [super init]) != nil) {
510 - (NSUInteger) count {
511 JSValueRef exception(NULL);
512 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
513 CYThrow(context_, exception);
514 double number(JSValueToNumber(context_, value, &exception));
515 CYThrow(context_, exception);
519 - (id) objectAtIndex:(NSUInteger)index {
520 JSValueRef exception(NULL);
521 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
522 CYThrow(context_, exception);
523 id object(CYCastNSObject(context_, value));
524 return object == nil ? [NSNull null] : object;
529 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
530 id object(CYCastNSObject(context, value));
531 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
534 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
536 case kCFSocketDataCallBack:
537 CFDataRef data(reinterpret_cast<CFDataRef>(value));
538 Client *client(reinterpret_cast<Client *>(info));
540 if (client->message_ == NULL)
541 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
543 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
544 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
545 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
546 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
548 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
549 CFRelease(client->message_);
551 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
554 JSStringRef script(JSStringCreateWithCFString(code));
557 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
558 JSStringRelease(script);
560 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
561 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
563 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
564 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
567 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
568 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
571 CFHTTPMessageSetBody(response, body);
574 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
577 CFSocketSendData(socket, NULL, serialized, 0);
578 CFRelease(serialized);
586 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
588 case kCFSocketAcceptCallBack:
589 Client *client(new Client());
591 client->message_ = NULL;
593 CFSocketContext context;
595 context.info = client;
596 context.retain = NULL;
597 context.release = NULL;
598 context.copyDescription = NULL;
600 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
602 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
607 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
613 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
615 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
616 return CYMakeObject(context, [[data alloc] autorelease]);
625 void *operator new(size_t size) {
627 apr_pool_create(&pool, NULL);
628 void *data(apr_palloc(pool, size));
629 reinterpret_cast<ptrData *>(data)->pool_ = pool;
633 ptrData(void *value) :
639 struct ffiData : ptrData {
640 sig::Signature signature_;
643 ffiData(void (*value)(), const char *type) :
644 ptrData(reinterpret_cast<void *>(value))
646 sig::Parse(pool_, &signature_, type);
647 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
651 struct selData : ptrData {
658 static void Pointer_finalize(JSObjectRef object) {
659 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
660 apr_pool_destroy(data->pool_);
663 static void Instance_finalize(JSObjectRef object) {
664 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
668 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
669 ffiData *data(new ffiData(function, type));
670 return JSObjectMake(context, Functor_, data);
674 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
675 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
678 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef *exception) { _pooled
680 NSString *string(CYCastNSString(name));
681 if (Class _class = NSClassFromString(string))
682 return CYMakeObject(context, _class);
683 if (NSMutableArray *entry = [Bridge_ objectForKey:string])
684 switch ([[entry objectAtIndex:0] intValue]) {
686 return CYMakeFunction(context, [string cy$symbol], [[entry objectAtIndex:1] UTF8String]);
690 return JSEvaluateScript(JSGetContext(), CYString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
696 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
697 JSValueRef exception(NULL);
698 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
699 CYThrow(context, exception);
702 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
703 size_t size(JSStringGetMaximumUTF8CStringSize(value));
704 char *string(new(pool) char[size]);
705 JSStringGetUTF8CString(value, string, size);
706 JSStringRelease(value);
710 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
711 return CYPoolCString(pool, CYString(context, value));
714 // XXX: this macro is dangerous
715 #define CYCastCString(context, value) ({ \
716 JSValueRef exception(NULL); \
717 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
718 CYThrow(context, exception); \
719 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
720 char *utf8(reinterpret_cast<char *>(alloca(size))); \
721 JSStringGetUTF8CString(string, utf8, size); \
722 JSStringRelease(string); \
726 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
727 if (JSValueIsNull(context, value))
729 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
730 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
731 return reinterpret_cast<SEL>(data->value_);
733 return sel_registerName(CYCastCString(context, value));
736 void *CYCastPointer(JSContextRef context, JSValueRef value) {
737 switch (JSValueGetType(context, value)) {
741 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
743 // XXX: maybe support more than just pointers, like ffis and sels
744 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
745 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
749 JSValueRef exception(NULL);
750 double number(JSValueToNumber(context, value, &exception));
751 CYThrow(context, exception);
752 return reinterpret_cast<void *>(static_cast<uintptr_t>(number));
756 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
757 switch (type->primitive) {
759 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
762 #define CYPoolFFI_(primitive, native) \
763 case sig::primitive ## _P: { \
764 JSValueRef exception(NULL); \
765 double number(JSValueToNumber(context, value, &exception)); \
766 CYThrow(context, exception); \
767 *reinterpret_cast<native *>(data) = number; \
770 CYPoolFFI_(uchar, unsigned char)
771 CYPoolFFI_(char, char)
772 CYPoolFFI_(ushort, unsigned short)
773 CYPoolFFI_(short, short)
774 CYPoolFFI_(ulong, unsigned long)
775 CYPoolFFI_(long, long)
776 CYPoolFFI_(uint, unsigned int)
778 CYPoolFFI_(ulonglong, unsigned long long)
779 CYPoolFFI_(longlong, long long)
780 CYPoolFFI_(float, float)
781 CYPoolFFI_(double, double)
784 case sig::typename_P:
785 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
788 case sig::selector_P:
789 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
793 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
797 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
807 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
812 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
815 switch (type->primitive) {
817 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
820 #define CYFromFFI_(primitive, native) \
821 case sig::primitive ## _P: \
822 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
825 CYFromFFI_(uchar, unsigned char)
826 CYFromFFI_(char, char)
827 CYFromFFI_(ushort, unsigned short)
828 CYFromFFI_(short, short)
829 CYFromFFI_(ulong, unsigned long)
830 CYFromFFI_(long, long)
831 CYFromFFI_(uint, unsigned int)
833 CYFromFFI_(ulonglong, unsigned long long)
834 CYFromFFI_(longlong, long long)
835 CYFromFFI_(float, float)
836 CYFromFFI_(double, double)
839 case sig::typename_P: {
840 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
843 case sig::selector_P: {
844 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
845 selData *data(new selData(sel));
846 value = JSObjectMake(context, Selector_, data);
847 } else value = JSValueMakeNull(context);
850 case sig::pointer_P: {
851 if (void *pointer = *reinterpret_cast<void **>(data)) {
852 ptrData *data(new ptrData(pointer));
853 value = JSObjectMake(context, Pointer_, data);
854 } else value = JSValueMakeNull(context);
857 case sig::string_P: {
858 char *utf8(*reinterpret_cast<char **>(data));
859 value = utf8 == NULL ? JSValueMakeNull(context) : JSValueMakeString(context, CYString(utf8));
870 NSLog(@"CYFromFFI(%c)\n", type->primitive);
883 apr_pool_create(&pool_, NULL);
887 apr_pool_destroy(pool_);
890 operator apr_pool_t *() const {
895 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
897 if (count != signature->count - 1)
898 [NSException raise:NSInvalidArgumentException format:@"incorrect number of arguments to ffi function"];
903 for (unsigned index(0); index != count; ++index) {
904 sig::Element *element(&signature->elements[index + 1]);
906 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
907 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
910 uint8_t value[cif->rtype->size];
911 ffi_call(cif, function, value, values);
913 return CYFromFFI(context, signature->elements[0].type, value);
917 bool stret(ffi_type *ffi_type) {
918 return ffi_type->type == FFI_TYPE_STRUCT && (
919 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
920 struct_forward_array[ffi_type->size] != 0
924 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
929 [NSException raise:NSInvalidArgumentException format:@"too few arguments to objc_msgSend"];
931 id self(CYCastNSObject(context, arguments[0]));
933 return JSValueMakeNull(context);
935 SEL _cmd(CYCastSEL(context, arguments[1]));
936 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
938 [NSException raise:NSInvalidArgumentException format:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self];
940 type = [[method _typeString] UTF8String];
945 sig::Signature signature;
946 sig::Parse(pool, &signature, type);
949 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
951 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
952 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
955 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
956 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
957 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
960 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
963 [NSException raise:NSInvalidArgumentException format:@"incorrect number of arguments to ffi constructor"];
964 void *function(CYCastPointer(context, arguments[0]));
965 const char *type(CYCastCString(context, arguments[1]));
966 return CYMakeFunction(context, function, type);
970 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef *exception) {
971 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
972 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
975 static JSStaticValue Pointer_staticValues[2] = {
976 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
977 {NULL, NULL, NULL, 0}
980 MSInitialize { _pooled
983 NSCFBoolean_ = objc_getClass("NSCFBoolean");
987 struct sockaddr_in address;
988 address.sin_len = sizeof(address);
989 address.sin_family = AF_INET;
990 address.sin_addr.s_addr = INADDR_ANY;
991 address.sin_port = htons(10000 + pid);
993 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
995 CFSocketSignature signature;
996 signature.protocolFamily = AF_INET;
997 signature.socketType = SOCK_STREAM;
998 signature.protocol = IPPROTO_TCP;
999 signature.address = data;
1001 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1002 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1004 JSClassDefinition definition;
1006 definition = kJSClassDefinitionEmpty;
1007 definition.className = "Pointer";
1008 definition.staticValues = Pointer_staticValues;
1009 definition.finalize = &Pointer_finalize;
1010 Pointer_ = JSClassCreate(&definition);
1012 definition = kJSClassDefinitionEmpty;
1013 definition.className = "Functor";
1014 definition.parentClass = Pointer_;
1015 definition.callAsFunction = &ffi_callAsFunction;
1016 Functor_ = JSClassCreate(&definition);
1018 definition = kJSClassDefinitionEmpty;
1019 definition.className = "Selector";
1020 definition.parentClass = Pointer_;
1021 Selector_ = JSClassCreate(&definition);
1023 definition = kJSClassDefinitionEmpty;
1024 definition.className = "Instance_";
1025 definition.getProperty = &Instance_getProperty;
1026 definition.callAsConstructor = &Instance_callAsConstructor;
1027 definition.finalize = &Instance_finalize;
1028 Instance_ = JSClassCreate(&definition);
1030 definition = kJSClassDefinitionEmpty;
1031 definition.getProperty = &Global_getProperty;
1032 JSClassRef Global(JSClassCreate(&definition));
1034 JSContextRef context(JSGlobalContextCreate(Global));
1037 JSObjectRef global(JSContextGetGlobalObject(context));
1039 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1041 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
1043 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcyrver.plist"] retain];
1045 name_ = JSStringCreateWithUTF8CString("name");
1046 message_ = JSStringCreateWithUTF8CString("message");
1047 length_ = JSStringCreateWithUTF8CString("length");
1049 JSValueRef exception(NULL);
1050 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
1051 CYThrow(context, exception);
1052 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1053 CYThrow(context, exception);