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 #define _assert(test) do { \
75 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
78 #define _trace() do { \
79 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
82 /* Objective-C Handle<> {{{ */
83 template <typename Type_>
85 typedef _H<Type_> This_;
90 _finline void Retain_() {
95 _finline void Clear_() {
101 _finline _H(const This_ &rhs) :
102 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
106 _finline _H(Type_ *value = NULL, bool mended = false) :
117 _finline operator Type_ *() const {
121 _finline This_ &operator =(Type_ *value) {
122 if (value_ != value) {
132 /* APR Pool Helpers {{{ */
133 void *operator new(size_t size, apr_pool_t *pool) {
134 return apr_palloc(pool, size);
137 void *operator new [](size_t size, apr_pool_t *pool) {
138 return apr_palloc(pool, size);
147 apr_pool_create(&pool_, NULL);
151 apr_pool_destroy(pool_);
154 operator apr_pool_t *() const {
160 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
162 static JSContextRef Context_;
164 static JSClassRef Functor_;
165 static JSClassRef Instance_;
166 static JSClassRef Pointer_;
167 static JSClassRef Selector_;
169 static JSObjectRef Array_;
171 static JSStringRef name_;
172 static JSStringRef message_;
173 static JSStringRef length_;
175 static Class NSCFBoolean_;
177 static NSMutableDictionary *Bridge_;
180 CFHTTPMessageRef message_;
184 JSObjectRef CYMakeObject(JSContextRef context, id object) {
185 return JSObjectMake(context, Instance_, [object retain]);
188 @interface NSMethodSignature (Cyrver)
189 - (NSString *) _typeString;
192 @interface NSObject (Cyrver)
193 - (NSString *) cy$toJSON;
194 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
197 @interface NSString (Cyrver)
198 - (void *) cy$symbol;
201 @interface NSNumber (Cyrver)
202 - (void *) cy$symbol;
205 @implementation NSObject (Cyrver)
207 - (NSString *) cy$toJSON {
208 return [self description];
211 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
212 return CYMakeObject(context, self);
217 @implementation WebUndefined (Cyrver)
219 - (NSString *) cy$toJSON {
223 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
224 return JSValueMakeUndefined(context);
229 @implementation NSArray (Cyrver)
231 - (NSString *) cy$toJSON {
232 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
233 [json appendString:@"["];
236 for (id object in self) {
238 [json appendString:@","];
241 [json appendString:[object cy$toJSON]];
244 [json appendString:@"]"];
250 @implementation NSDictionary (Cyrver)
252 - (NSString *) cy$toJSON {
253 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
254 [json appendString:@"("];
255 [json appendString:@"{"];
258 for (id key in self) {
260 [json appendString:@","];
263 [json appendString:[key cy$toJSON]];
264 [json appendString:@":"];
265 NSObject *object([self objectForKey:key]);
266 [json appendString:[object cy$toJSON]];
269 [json appendString:@"})"];
275 @implementation NSNumber (Cyrver)
277 - (NSString *) cy$toJSON {
278 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
281 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
282 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
285 - (void *) cy$symbol {
286 return [self pointerValue];
291 @implementation NSString (Cyrver)
293 - (NSString *) cy$toJSON {
294 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
296 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
297 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
298 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
299 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
300 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
302 CFStringInsert(json, 0, CFSTR("\""));
303 CFStringAppend(json, CFSTR("\""));
305 return [reinterpret_cast<const NSString *>(json) autorelease];
308 - (void *) cy$symbol {
309 return dlsym(RTLD_DEFAULT, [self UTF8String]);
314 @interface CYJSObject : NSDictionary {
316 JSContextRef context_;
319 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
321 - (NSUInteger) count;
322 - (id) objectForKey:(id)key;
323 - (NSEnumerator *) keyEnumerator;
324 - (void) setObject:(id)object forKey:(id)key;
325 - (void) removeObjectForKey:(id)key;
329 @interface CYJSArray : NSArray {
331 JSContextRef context_;
334 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
336 - (NSUInteger) count;
337 - (id) objectAtIndex:(NSUInteger)index;
341 JSContextRef JSGetContext() {
346 @catch (id error) { \
347 CYThrow(context, error, exception); \
351 void CYThrow(JSContextRef context, JSValueRef value);
353 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
354 if (JSValueIsObjectOfClass(context, object, Instance_))
355 return reinterpret_cast<id>(JSObjectGetPrivate(object));
356 JSValueRef exception(NULL);
357 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
358 CYThrow(context, exception);
360 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
361 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
364 JSStringRef CYCopyJSString(id value) {
365 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
368 JSStringRef CYCopyJSString(const char *value) {
369 return JSStringCreateWithUTF8CString(value);
372 JSStringRef CYCopyJSString(JSStringRef value) {
373 return JSStringRetain(value);
376 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
377 JSValueRef exception(NULL);
378 JSStringRef string(JSValueToStringCopy(context, value, &exception));
379 CYThrow(context, exception);
383 // XXX: this is not a safe handle
389 template <typename Arg0_>
390 CYString(Arg0_ arg0) {
391 string_ = CYCopyJSString(arg0);
394 template <typename Arg0_, typename Arg1_>
395 CYString(Arg0_ arg0, Arg1_ arg1) {
396 string_ = CYCopyJSString(arg0, arg1);
400 JSStringRelease(string_);
403 operator JSStringRef() const {
408 CFStringRef CYCopyCFString(JSStringRef value) {
409 return JSStringCopyCFString(kCFAllocatorDefault, value);
412 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
413 return CYCopyCFString(CYString(context, value));
416 double CYCastDouble(JSContextRef context, JSValueRef value) {
417 JSValueRef exception(NULL);
418 double number(JSValueToNumber(context, value, &exception));
419 CYThrow(context, exception);
423 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
424 double number(CYCastDouble(context, value));
425 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
428 NSString *CYCastNSString(JSStringRef value) {
429 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
432 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
433 switch (JSType type = JSValueGetType(context, value)) {
434 case kJSTypeUndefined:
435 return CFRetain([WebUndefined undefined]);
439 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
441 return CYCopyCFNumber(context, value);
443 return CYCopyCFString(context, value);
445 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
447 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
451 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
452 size_t size(JSPropertyNameArrayGetCount(names));
453 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
454 for (size_t index(0); index != size; ++index)
455 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
459 id CYCastNSObject(JSContextRef context, JSValueRef value) {
460 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
461 return object == nil ? nil : [object autorelease];
464 void CYThrow(JSContextRef context, JSValueRef value) {
467 @throw CYCastNSObject(context, value);
470 JSValueRef CYCastJSValue(JSContextRef context, id value) {
471 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
474 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
475 *exception = CYCastJSValue(context, error);
478 @implementation CYJSObject
480 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
481 if ((self = [super init]) != nil) {
487 - (NSUInteger) count {
488 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
489 size_t size(JSPropertyNameArrayGetCount(names));
490 JSPropertyNameArrayRelease(names);
494 - (id) objectForKey:(id)key {
495 JSValueRef exception(NULL);
496 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
497 CYThrow(context_, exception);
498 return CYCastNSObject(context_, value);
501 - (NSEnumerator *) keyEnumerator {
502 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
503 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
504 JSPropertyNameArrayRelease(names);
508 - (void) setObject:(id)object forKey:(id)key {
509 JSValueRef exception(NULL);
510 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
511 CYThrow(context_, exception);
514 - (void) removeObjectForKey:(id)key {
515 JSValueRef exception(NULL);
516 // XXX: this returns a bool... throw exception, or ignore?
517 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
518 CYThrow(context_, exception);
523 @implementation CYJSArray
525 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
526 if ((self = [super init]) != nil) {
532 - (NSUInteger) count {
533 JSValueRef exception(NULL);
534 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
535 CYThrow(context_, exception);
536 return CYCastDouble(context_, value);
539 - (id) objectAtIndex:(NSUInteger)index {
540 JSValueRef exception(NULL);
541 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
542 CYThrow(context_, exception);
543 id object(CYCastNSObject(context_, value));
544 return object == nil ? [NSNull null] : object;
549 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
550 id object(CYCastNSObject(context, value));
551 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
554 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
556 case kCFSocketDataCallBack:
557 CFDataRef data(reinterpret_cast<CFDataRef>(value));
558 Client *client(reinterpret_cast<Client *>(info));
560 if (client->message_ == NULL)
561 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
563 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
564 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
565 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
566 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
568 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
569 CFRelease(client->message_);
571 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
574 JSStringRef script(JSStringCreateWithCFString(code));
577 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
578 JSStringRelease(script);
580 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
581 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
583 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
584 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
587 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
588 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
591 CFHTTPMessageSetBody(response, body);
594 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
597 CFSocketSendData(socket, NULL, serialized, 0);
598 CFRelease(serialized);
606 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
608 case kCFSocketAcceptCallBack:
609 Client *client(new Client());
611 client->message_ = NULL;
613 CFSocketContext context;
615 context.info = client;
616 context.retain = NULL;
617 context.release = NULL;
618 context.copyDescription = NULL;
620 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
622 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
627 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
629 NSString *name(CYCastNSString(property));
637 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
639 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
640 return CYMakeObject(context, [[data alloc] autorelease]);
649 void *operator new(size_t size) {
651 apr_pool_create(&pool, NULL);
652 void *data(apr_palloc(pool, size));
653 reinterpret_cast<ptrData *>(data)->pool_ = pool;
657 ptrData(void *value) :
663 struct ffiData : ptrData {
664 sig::Signature signature_;
667 ffiData(void (*value)(), const char *type) :
668 ptrData(reinterpret_cast<void *>(value))
670 sig::Parse(pool_, &signature_, type);
671 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
675 struct selData : ptrData {
682 static void Pointer_finalize(JSObjectRef object) {
683 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
684 apr_pool_destroy(data->pool_);
687 static void Instance_finalize(JSObjectRef object) {
688 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
692 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
693 ffiData *data(new ffiData(function, type));
694 return JSObjectMake(context, Functor_, data);
698 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
699 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
702 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
703 JSValueRef exception(NULL);
704 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
705 CYThrow(context, exception);
708 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
709 size_t size(JSStringGetMaximumUTF8CStringSize(value));
710 char *string(new(pool) char[size]);
711 JSStringGetUTF8CString(value, string, size);
712 JSStringRelease(value);
716 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
717 return CYPoolCString(pool, CYString(context, value));
720 // XXX: this macro is unhygenic
721 #define CYCastCString(context, value) ({ \
722 JSValueRef exception(NULL); \
723 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
724 CYThrow(context, exception); \
725 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
726 char *utf8(reinterpret_cast<char *>(alloca(size))); \
727 JSStringGetUTF8CString(string, utf8, size); \
728 JSStringRelease(string); \
732 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
733 if (JSValueIsNull(context, value))
735 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
736 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
737 return reinterpret_cast<SEL>(data->value_);
739 return sel_registerName(CYCastCString(context, value));
742 void *CYCastPointer(JSContextRef context, JSValueRef value) {
743 switch (JSValueGetType(context, value)) {
747 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
749 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
750 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
754 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
758 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
759 switch (type->primitive) {
761 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
764 #define CYPoolFFI_(primitive, native) \
765 case sig::primitive ## _P: \
766 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
769 CYPoolFFI_(uchar, unsigned char)
770 CYPoolFFI_(char, char)
771 CYPoolFFI_(ushort, unsigned short)
772 CYPoolFFI_(short, short)
773 CYPoolFFI_(ulong, unsigned long)
774 CYPoolFFI_(long, long)
775 CYPoolFFI_(uint, unsigned int)
777 CYPoolFFI_(ulonglong, unsigned long long)
778 CYPoolFFI_(longlong, long long)
779 CYPoolFFI_(float, float)
780 CYPoolFFI_(double, double)
783 case sig::typename_P:
784 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
787 case sig::selector_P:
788 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
792 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
796 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
806 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
811 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
814 switch (type->primitive) {
816 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
819 #define CYFromFFI_(primitive, native) \
820 case sig::primitive ## _P: \
821 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
824 CYFromFFI_(uchar, unsigned char)
825 CYFromFFI_(char, char)
826 CYFromFFI_(ushort, unsigned short)
827 CYFromFFI_(short, short)
828 CYFromFFI_(ulong, unsigned long)
829 CYFromFFI_(long, long)
830 CYFromFFI_(uint, unsigned int)
832 CYFromFFI_(ulonglong, unsigned long long)
833 CYFromFFI_(longlong, long long)
834 CYFromFFI_(float, float)
835 CYFromFFI_(double, double)
838 case sig::typename_P: {
839 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
842 case sig::selector_P: {
843 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
844 selData *data(new selData(sel));
845 value = JSObjectMake(context, Selector_, data);
849 case sig::pointer_P: {
850 if (void *pointer = *reinterpret_cast<void **>(data)) {
851 ptrData *data(new ptrData(pointer));
852 value = JSObjectMake(context, Pointer_, data);
856 case sig::string_P: {
857 if (char *utf8 = *reinterpret_cast<char **>(data))
858 value = JSValueMakeString(context, CYString(utf8));
866 value = JSValueMakeUndefined(context);
870 value = JSValueMakeNull(context);
874 NSLog(@"CYFromFFI(%c)\n", type->primitive);
881 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
883 if (count != signature->count - 1)
884 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
889 for (unsigned index(0); index != count; ++index) {
890 sig::Element *element(&signature->elements[index + 1]);
892 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
893 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
896 uint8_t value[cif->rtype->size];
897 ffi_call(cif, function, value, values);
899 return CYFromFFI(context, signature->elements[0].type, value);
903 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
905 NSString *name(CYCastNSString(property));
906 if (Class _class = NSClassFromString(name))
907 return CYMakeObject(context, _class);
908 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
909 switch ([[entry objectAtIndex:0] intValue]) {
911 return JSEvaluateScript(JSGetContext(), CYString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
913 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
916 sig::Signature signature;
917 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
918 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
924 bool stret(ffi_type *ffi_type) {
925 return ffi_type->type == FFI_TYPE_STRUCT && (
926 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
927 struct_forward_array[ffi_type->size] != 0
931 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
936 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
938 id self(CYCastNSObject(context, arguments[0]));
940 return JSValueMakeNull(context);
942 SEL _cmd(CYCastSEL(context, arguments[1]));
943 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
945 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
947 type = [[method _typeString] UTF8String];
952 sig::Signature signature;
953 sig::Parse(pool, &signature, type);
956 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
958 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
959 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
962 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
963 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
964 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
967 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
970 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
971 void *function(CYCastPointer(context, arguments[0]));
972 const char *type(CYCastCString(context, arguments[1]));
973 return CYMakeFunction(context, function, type);
977 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
978 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
979 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
982 static JSStaticValue Pointer_staticValues[2] = {
983 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
984 {NULL, NULL, NULL, 0}
987 MSInitialize { _pooled
990 NSCFBoolean_ = objc_getClass("NSCFBoolean");
994 struct sockaddr_in address;
995 address.sin_len = sizeof(address);
996 address.sin_family = AF_INET;
997 address.sin_addr.s_addr = INADDR_ANY;
998 address.sin_port = htons(10000 + pid);
1000 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1002 CFSocketSignature signature;
1003 signature.protocolFamily = AF_INET;
1004 signature.socketType = SOCK_STREAM;
1005 signature.protocol = IPPROTO_TCP;
1006 signature.address = data;
1008 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1009 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1011 JSClassDefinition definition;
1013 definition = kJSClassDefinitionEmpty;
1014 definition.className = "Pointer";
1015 definition.staticValues = Pointer_staticValues;
1016 definition.finalize = &Pointer_finalize;
1017 Pointer_ = JSClassCreate(&definition);
1019 definition = kJSClassDefinitionEmpty;
1020 definition.className = "Functor";
1021 definition.parentClass = Pointer_;
1022 definition.callAsFunction = &ffi_callAsFunction;
1023 Functor_ = JSClassCreate(&definition);
1025 definition = kJSClassDefinitionEmpty;
1026 definition.className = "Selector";
1027 definition.parentClass = Pointer_;
1028 Selector_ = JSClassCreate(&definition);
1030 definition = kJSClassDefinitionEmpty;
1031 definition.className = "Instance_";
1032 definition.getProperty = &Instance_getProperty;
1033 definition.callAsConstructor = &Instance_callAsConstructor;
1034 definition.finalize = &Instance_finalize;
1035 Instance_ = JSClassCreate(&definition);
1037 definition = kJSClassDefinitionEmpty;
1038 definition.getProperty = &Global_getProperty;
1039 JSClassRef Global(JSClassCreate(&definition));
1041 JSContextRef context(JSGlobalContextCreate(Global));
1044 JSObjectRef global(JSContextGetGlobalObject(context));
1046 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1048 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
1050 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcyrver.plist"] retain];
1052 name_ = JSStringCreateWithUTF8CString("name");
1053 message_ = JSStringCreateWithUTF8CString("message");
1054 length_ = JSStringCreateWithUTF8CString("length");
1056 JSValueRef exception(NULL);
1057 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
1058 CYThrow(context, exception);
1059 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1060 CYThrow(context, exception);