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.
42 #include <substrate.h>
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include <apr-1/apr_pools.h>
49 #include <apr-1/apr_strings.h>
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreFoundation/CFLogUtilities.h>
56 #include <CFNetwork/CFNetwork.h>
57 #include <Foundation/Foundation.h>
59 #include <JavaScriptCore/JSBase.h>
60 #include <JavaScriptCore/JSValueRef.h>
61 #include <JavaScriptCore/JSObjectRef.h>
62 #include <JavaScriptCore/JSContextRef.h>
63 #include <JavaScriptCore/JSStringRef.h>
64 #include <JavaScriptCore/JSStringRefCF.h>
66 #include <WebKit/WebScriptObject.h>
68 #include <sys/types.h>
69 #include <sys/socket.h>
70 #include <netinet/in.h>
73 #include <ext/stdio_filebuf.h>
82 #define _assert(test) do { \
84 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
87 #define _trace() do { \
88 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
91 /* Objective-C Handle<> {{{ */
92 template <typename Type_>
94 typedef _H<Type_> This_;
99 _finline void Retain_() {
104 _finline void Clear_() {
110 _finline _H(const This_ &rhs) :
111 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
115 _finline _H(Type_ *value = NULL, bool mended = false) :
126 _finline operator Type_ *() const {
130 _finline This_ &operator =(Type_ *value) {
131 if (value_ != value) {
141 /* APR Pool Helpers {{{ */
142 void *operator new(size_t size, apr_pool_t *pool) {
143 return apr_palloc(pool, size);
146 void *operator new [](size_t size, apr_pool_t *pool) {
147 return apr_palloc(pool, size);
156 apr_pool_create(&pool_, NULL);
160 apr_pool_destroy(pool_);
163 operator apr_pool_t *() const {
167 char *operator ()(const char *data) const {
168 return apr_pstrdup(pool_, data);
171 char *operator ()(const char *data, size_t size) const {
172 return apr_pstrndup(pool_, data, size);
177 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
179 static JSContextRef Context_;
181 static JSClassRef Functor_;
182 static JSClassRef Instance_;
183 static JSClassRef Pointer_;
184 static JSClassRef Selector_;
186 static JSObjectRef Array_;
188 static JSStringRef name_;
189 static JSStringRef message_;
190 static JSStringRef length_;
192 static Class NSCFBoolean_;
194 static NSMutableDictionary *Bridge_;
197 CFHTTPMessageRef message_;
201 JSObjectRef CYMakeObject(JSContextRef context, id object) {
202 return JSObjectMake(context, Instance_, [object retain]);
205 @interface NSMethodSignature (Cycript)
206 - (NSString *) _typeString;
209 @interface NSObject (Cycript)
210 - (NSString *) cy$toJSON;
211 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
214 @interface NSString (Cycript)
215 - (void *) cy$symbol;
218 @interface NSNumber (Cycript)
219 - (void *) cy$symbol;
222 @implementation NSObject (Cycript)
224 - (NSString *) cy$toJSON {
225 return [self description];
228 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
229 return CYMakeObject(context, self);
234 @implementation WebUndefined (Cycript)
236 - (NSString *) cy$toJSON {
240 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
241 return JSValueMakeUndefined(context);
246 @implementation NSArray (Cycript)
248 - (NSString *) cy$toJSON {
249 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
250 [json appendString:@"["];
253 for (id object in self) {
255 [json appendString:@","];
258 [json appendString:[object cy$toJSON]];
261 [json appendString:@"]"];
267 @implementation NSDictionary (Cycript)
269 - (NSString *) cy$toJSON {
270 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
271 [json appendString:@"("];
272 [json appendString:@"{"];
275 for (id key in self) {
277 [json appendString:@","];
280 [json appendString:[key cy$toJSON]];
281 [json appendString:@":"];
282 NSObject *object([self objectForKey:key]);
283 [json appendString:[object cy$toJSON]];
286 [json appendString:@"})"];
292 @implementation NSNumber (Cycript)
294 - (NSString *) cy$toJSON {
295 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
298 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
299 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
302 - (void *) cy$symbol {
303 return [self pointerValue];
308 @implementation NSString (Cycript)
310 - (NSString *) cy$toJSON {
311 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
313 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
314 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
315 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
316 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
317 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
319 CFStringInsert(json, 0, CFSTR("\""));
320 CFStringAppend(json, CFSTR("\""));
322 return [reinterpret_cast<const NSString *>(json) autorelease];
325 - (void *) cy$symbol {
326 return dlsym(RTLD_DEFAULT, [self UTF8String]);
331 @interface CYJSObject : NSDictionary {
333 JSContextRef context_;
336 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
338 - (NSUInteger) count;
339 - (id) objectForKey:(id)key;
340 - (NSEnumerator *) keyEnumerator;
341 - (void) setObject:(id)object forKey:(id)key;
342 - (void) removeObjectForKey:(id)key;
346 @interface CYJSArray : NSArray {
348 JSContextRef context_;
351 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
353 - (NSUInteger) count;
354 - (id) objectAtIndex:(NSUInteger)index;
358 JSContextRef JSGetContext() {
363 @catch (id error) { \
364 CYThrow(context, error, exception); \
368 void CYThrow(JSContextRef context, JSValueRef value);
370 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
371 if (JSValueIsObjectOfClass(context, object, Instance_))
372 return reinterpret_cast<id>(JSObjectGetPrivate(object));
373 JSValueRef exception(NULL);
374 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
375 CYThrow(context, exception);
377 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
378 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
381 JSStringRef CYCopyJSString(id value) {
382 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
385 JSStringRef CYCopyJSString(const char *value) {
386 return JSStringCreateWithUTF8CString(value);
389 JSStringRef CYCopyJSString(JSStringRef value) {
390 return JSStringRetain(value);
393 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
394 JSValueRef exception(NULL);
395 JSStringRef string(JSValueToStringCopy(context, value, &exception));
396 CYThrow(context, exception);
400 // XXX: this is not a safe handle
406 template <typename Arg0_>
407 CYString(Arg0_ arg0) {
408 string_ = CYCopyJSString(arg0);
411 template <typename Arg0_, typename Arg1_>
412 CYString(Arg0_ arg0, Arg1_ arg1) {
413 string_ = CYCopyJSString(arg0, arg1);
417 JSStringRelease(string_);
420 operator JSStringRef() const {
425 CFStringRef CYCopyCFString(JSStringRef value) {
426 return JSStringCopyCFString(kCFAllocatorDefault, value);
429 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
430 return CYCopyCFString(CYString(context, value));
433 double CYCastDouble(JSContextRef context, JSValueRef value) {
434 JSValueRef exception(NULL);
435 double number(JSValueToNumber(context, value, &exception));
436 CYThrow(context, exception);
440 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
441 double number(CYCastDouble(context, value));
442 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
445 NSString *CYCastNSString(JSStringRef value) {
446 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
449 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
450 switch (JSType type = JSValueGetType(context, value)) {
451 case kJSTypeUndefined:
452 return CFRetain([WebUndefined undefined]);
456 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
458 return CYCopyCFNumber(context, value);
460 return CYCopyCFString(context, value);
462 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
464 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
468 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
469 size_t size(JSPropertyNameArrayGetCount(names));
470 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
471 for (size_t index(0); index != size; ++index)
472 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
476 id CYCastNSObject(JSContextRef context, JSValueRef value) {
477 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
478 return object == nil ? nil : [object autorelease];
481 void CYThrow(JSContextRef context, JSValueRef value) {
484 @throw CYCastNSObject(context, value);
487 JSValueRef CYCastJSValue(JSContextRef context, id value) {
488 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
491 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
492 *exception = CYCastJSValue(context, error);
495 @implementation CYJSObject
497 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
498 if ((self = [super init]) != nil) {
504 - (NSUInteger) count {
505 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
506 size_t size(JSPropertyNameArrayGetCount(names));
507 JSPropertyNameArrayRelease(names);
511 - (id) objectForKey:(id)key {
512 JSValueRef exception(NULL);
513 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
514 CYThrow(context_, exception);
515 return CYCastNSObject(context_, value);
518 - (NSEnumerator *) keyEnumerator {
519 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
520 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
521 JSPropertyNameArrayRelease(names);
525 - (void) setObject:(id)object forKey:(id)key {
526 JSValueRef exception(NULL);
527 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
528 CYThrow(context_, exception);
531 - (void) removeObjectForKey:(id)key {
532 JSValueRef exception(NULL);
533 // XXX: this returns a bool... throw exception, or ignore?
534 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
535 CYThrow(context_, exception);
540 @implementation CYJSArray
542 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
543 if ((self = [super init]) != nil) {
549 - (NSUInteger) count {
550 JSValueRef exception(NULL);
551 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
552 CYThrow(context_, exception);
553 return CYCastDouble(context_, value);
556 - (id) objectAtIndex:(NSUInteger)index {
557 JSValueRef exception(NULL);
558 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
559 CYThrow(context_, exception);
560 id object(CYCastNSObject(context_, value));
561 return object == nil ? [NSNull null] : object;
566 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
567 id object(CYCastNSObject(context, value));
568 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
571 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
573 case kCFSocketDataCallBack:
574 CFDataRef data(reinterpret_cast<CFDataRef>(value));
575 Client *client(reinterpret_cast<Client *>(info));
577 if (client->message_ == NULL)
578 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
580 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
581 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
582 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
583 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
585 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
586 CFRelease(client->message_);
588 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
591 JSStringRef script(JSStringCreateWithCFString(code));
594 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
595 JSStringRelease(script);
597 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
598 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
600 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
601 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
604 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
605 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
608 CFHTTPMessageSetBody(response, body);
611 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
614 CFSocketSendData(socket, NULL, serialized, 0);
615 CFRelease(serialized);
623 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
625 case kCFSocketAcceptCallBack:
626 Client *client(new Client());
628 client->message_ = NULL;
630 CFSocketContext context;
632 context.info = client;
633 context.retain = NULL;
634 context.release = NULL;
635 context.copyDescription = NULL;
637 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
639 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
644 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
646 NSString *name(CYCastNSString(property));
654 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
656 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
657 return CYMakeObject(context, [[data alloc] autorelease]);
666 void *operator new(size_t size) {
668 apr_pool_create(&pool, NULL);
669 void *data(apr_palloc(pool, size));
670 reinterpret_cast<ptrData *>(data)->pool_ = pool;
674 ptrData(void *value) :
680 struct ffiData : ptrData {
681 sig::Signature signature_;
684 ffiData(void (*value)(), const char *type) :
685 ptrData(reinterpret_cast<void *>(value))
687 sig::Parse(pool_, &signature_, type);
688 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
692 struct selData : ptrData {
699 static void Pointer_finalize(JSObjectRef object) {
700 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
701 apr_pool_destroy(data->pool_);
704 static void Instance_finalize(JSObjectRef object) {
705 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
709 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
710 ffiData *data(new ffiData(function, type));
711 return JSObjectMake(context, Functor_, data);
715 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
716 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
719 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
720 JSValueRef exception(NULL);
721 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
722 CYThrow(context, exception);
725 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
726 size_t size(JSStringGetMaximumUTF8CStringSize(value));
727 char *string(new(pool) char[size]);
728 JSStringGetUTF8CString(value, string, size);
729 JSStringRelease(value);
733 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
734 return CYPoolCString(pool, CYString(context, value));
737 // XXX: this macro is unhygenic
738 #define CYCastCString(context, value) ({ \
739 JSValueRef exception(NULL); \
740 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
741 CYThrow(context, exception); \
742 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
743 char *utf8(reinterpret_cast<char *>(alloca(size))); \
744 JSStringGetUTF8CString(string, utf8, size); \
745 JSStringRelease(string); \
749 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
750 if (JSValueIsNull(context, value))
752 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
753 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
754 return reinterpret_cast<SEL>(data->value_);
756 return sel_registerName(CYCastCString(context, value));
759 void *CYCastPointer(JSContextRef context, JSValueRef value) {
760 switch (JSValueGetType(context, value)) {
764 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
766 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
767 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
771 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
775 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
776 switch (type->primitive) {
778 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
781 #define CYPoolFFI_(primitive, native) \
782 case sig::primitive ## _P: \
783 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
786 CYPoolFFI_(uchar, unsigned char)
787 CYPoolFFI_(char, char)
788 CYPoolFFI_(ushort, unsigned short)
789 CYPoolFFI_(short, short)
790 CYPoolFFI_(ulong, unsigned long)
791 CYPoolFFI_(long, long)
792 CYPoolFFI_(uint, unsigned int)
794 CYPoolFFI_(ulonglong, unsigned long long)
795 CYPoolFFI_(longlong, long long)
796 CYPoolFFI_(float, float)
797 CYPoolFFI_(double, double)
800 case sig::typename_P:
801 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
804 case sig::selector_P:
805 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
809 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
813 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
823 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
828 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
831 switch (type->primitive) {
833 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
836 #define CYFromFFI_(primitive, native) \
837 case sig::primitive ## _P: \
838 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
841 CYFromFFI_(uchar, unsigned char)
842 CYFromFFI_(char, char)
843 CYFromFFI_(ushort, unsigned short)
844 CYFromFFI_(short, short)
845 CYFromFFI_(ulong, unsigned long)
846 CYFromFFI_(long, long)
847 CYFromFFI_(uint, unsigned int)
849 CYFromFFI_(ulonglong, unsigned long long)
850 CYFromFFI_(longlong, long long)
851 CYFromFFI_(float, float)
852 CYFromFFI_(double, double)
855 case sig::typename_P: {
856 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
859 case sig::selector_P: {
860 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
861 selData *data(new selData(sel));
862 value = JSObjectMake(context, Selector_, data);
866 case sig::pointer_P: {
867 if (void *pointer = *reinterpret_cast<void **>(data)) {
868 ptrData *data(new ptrData(pointer));
869 value = JSObjectMake(context, Pointer_, data);
873 case sig::string_P: {
874 if (char *utf8 = *reinterpret_cast<char **>(data))
875 value = JSValueMakeString(context, CYString(utf8));
883 value = JSValueMakeUndefined(context);
887 value = JSValueMakeNull(context);
891 NSLog(@"CYFromFFI(%c)\n", type->primitive);
898 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
900 if (count != signature->count - 1)
901 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
906 for (unsigned index(0); index != count; ++index) {
907 sig::Element *element(&signature->elements[index + 1]);
909 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
910 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
913 uint8_t value[cif->rtype->size];
914 ffi_call(cif, function, value, values);
916 return CYFromFFI(context, signature->elements[0].type, value);
920 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
922 NSString *name(CYCastNSString(property));
923 if (Class _class = NSClassFromString(name))
924 return CYMakeObject(context, _class);
925 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
926 switch ([[entry objectAtIndex:0] intValue]) {
928 return JSEvaluateScript(JSGetContext(), CYString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
930 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
933 sig::Signature signature;
934 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
935 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
941 bool stret(ffi_type *ffi_type) {
942 return ffi_type->type == FFI_TYPE_STRUCT && (
943 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
944 struct_forward_array[ffi_type->size] != 0
948 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
953 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
955 id self(CYCastNSObject(context, arguments[0]));
957 return JSValueMakeNull(context);
959 SEL _cmd(CYCastSEL(context, arguments[1]));
960 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
962 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
964 type = [[method _typeString] UTF8String];
969 sig::Signature signature;
970 sig::Parse(pool, &signature, type);
973 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
975 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
976 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
979 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
980 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
981 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
984 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
987 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
988 void *function(CYCastPointer(context, arguments[0]));
989 const char *type(CYCastCString(context, arguments[1]));
990 return CYMakeFunction(context, function, type);
994 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
995 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
996 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
999 static JSStaticValue Pointer_staticValues[2] = {
1000 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1001 {NULL, NULL, NULL, 0}
1004 void cyparse(CYParser *parser);
1007 void CYConsole(FILE *fin, FILE *fout, FILE *ferr) {
1013 MSInitialize { _pooled
1016 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1018 pid_t pid(getpid());
1020 struct sockaddr_in address;
1021 address.sin_len = sizeof(address);
1022 address.sin_family = AF_INET;
1023 address.sin_addr.s_addr = INADDR_ANY;
1024 address.sin_port = htons(10000 + pid);
1026 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1028 CFSocketSignature signature;
1029 signature.protocolFamily = AF_INET;
1030 signature.socketType = SOCK_STREAM;
1031 signature.protocol = IPPROTO_TCP;
1032 signature.address = data;
1034 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1035 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1037 JSClassDefinition definition;
1039 definition = kJSClassDefinitionEmpty;
1040 definition.className = "Pointer";
1041 definition.staticValues = Pointer_staticValues;
1042 definition.finalize = &Pointer_finalize;
1043 Pointer_ = JSClassCreate(&definition);
1045 definition = kJSClassDefinitionEmpty;
1046 definition.className = "Functor";
1047 definition.parentClass = Pointer_;
1048 definition.callAsFunction = &ffi_callAsFunction;
1049 Functor_ = JSClassCreate(&definition);
1051 definition = kJSClassDefinitionEmpty;
1052 definition.className = "Selector";
1053 definition.parentClass = Pointer_;
1054 Selector_ = JSClassCreate(&definition);
1056 definition = kJSClassDefinitionEmpty;
1057 definition.className = "Instance_";
1058 definition.getProperty = &Instance_getProperty;
1059 definition.callAsConstructor = &Instance_callAsConstructor;
1060 definition.finalize = &Instance_finalize;
1061 Instance_ = JSClassCreate(&definition);
1063 definition = kJSClassDefinitionEmpty;
1064 definition.getProperty = &Global_getProperty;
1065 JSClassRef Global(JSClassCreate(&definition));
1067 JSContextRef context(JSGlobalContextCreate(Global));
1070 JSObjectRef global(JSContextGetGlobalObject(context));
1072 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1074 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
1076 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1078 name_ = JSStringCreateWithUTF8CString("name");
1079 message_ = JSStringCreateWithUTF8CString("message");
1080 length_ = JSStringCreateWithUTF8CString("length");
1082 JSValueRef exception(NULL);
1083 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
1084 CYThrow(context, exception);
1085 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1086 CYThrow(context, exception);