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 /* APR Pool Helpers {{{ */
92 void *operator new(size_t size, apr_pool_t *pool) {
93 return apr_palloc(pool, size);
96 void *operator new [](size_t size, apr_pool_t *pool) {
97 return apr_palloc(pool, size);
106 apr_pool_create(&pool_, NULL);
110 apr_pool_destroy(pool_);
113 operator apr_pool_t *() const {
117 char *operator ()(const char *data) const {
118 return apr_pstrdup(pool_, data);
121 char *operator ()(const char *data, size_t size) const {
122 return apr_pstrndup(pool_, data, size);
127 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
129 static JSContextRef Context_;
131 static JSClassRef Functor_;
132 static JSClassRef Instance_;
133 static JSClassRef Pointer_;
134 static JSClassRef Selector_;
136 static JSObjectRef Array_;
138 static JSStringRef name_;
139 static JSStringRef message_;
140 static JSStringRef length_;
142 static Class NSCFBoolean_;
144 static NSMutableDictionary *Bridge_;
147 CFHTTPMessageRef message_;
151 JSObjectRef CYMakeObject(JSContextRef context, id object) {
152 return JSObjectMake(context, Instance_, [object retain]);
155 @interface NSMethodSignature (Cycript)
156 - (NSString *) _typeString;
159 @interface NSObject (Cycript)
160 - (NSString *) cy$toJSON;
161 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
164 @interface NSString (Cycript)
165 - (void *) cy$symbol;
168 @interface NSNumber (Cycript)
169 - (void *) cy$symbol;
172 @implementation NSObject (Cycript)
174 - (NSString *) cy$toJSON {
175 return [self description];
178 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
179 return CYMakeObject(context, self);
184 @implementation WebUndefined (Cycript)
186 - (NSString *) cy$toJSON {
190 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
191 return JSValueMakeUndefined(context);
196 @implementation NSArray (Cycript)
198 - (NSString *) cy$toJSON {
199 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
200 [json appendString:@"["];
203 for (id object in self) {
205 [json appendString:@","];
208 [json appendString:[object cy$toJSON]];
211 [json appendString:@"]"];
217 @implementation NSDictionary (Cycript)
219 - (NSString *) cy$toJSON {
220 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
221 [json appendString:@"("];
222 [json appendString:@"{"];
225 for (id key in self) {
227 [json appendString:@","];
230 [json appendString:[key cy$toJSON]];
231 [json appendString:@":"];
232 NSObject *object([self objectForKey:key]);
233 [json appendString:[object cy$toJSON]];
236 [json appendString:@"})"];
242 @implementation NSNumber (Cycript)
244 - (NSString *) cy$toJSON {
245 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
248 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
249 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
252 - (void *) cy$symbol {
253 return [self pointerValue];
258 @implementation NSString (Cycript)
260 - (NSString *) cy$toJSON {
261 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
263 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
264 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
265 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
266 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
267 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
269 CFStringInsert(json, 0, CFSTR("\""));
270 CFStringAppend(json, CFSTR("\""));
272 return [reinterpret_cast<const NSString *>(json) autorelease];
275 - (void *) cy$symbol {
276 return dlsym(RTLD_DEFAULT, [self UTF8String]);
281 @interface CYJSObject : NSDictionary {
283 JSContextRef context_;
286 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
288 - (NSUInteger) count;
289 - (id) objectForKey:(id)key;
290 - (NSEnumerator *) keyEnumerator;
291 - (void) setObject:(id)object forKey:(id)key;
292 - (void) removeObjectForKey:(id)key;
296 @interface CYJSArray : NSArray {
298 JSContextRef context_;
301 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
303 - (NSUInteger) count;
304 - (id) objectAtIndex:(NSUInteger)index;
308 JSContextRef JSGetContext() {
313 @catch (id error) { \
314 CYThrow(context, error, exception); \
318 void CYThrow(JSContextRef context, JSValueRef value);
320 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
321 if (JSValueIsObjectOfClass(context, object, Instance_))
322 return reinterpret_cast<id>(JSObjectGetPrivate(object));
323 JSValueRef exception(NULL);
324 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
325 CYThrow(context, exception);
327 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
328 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
331 JSStringRef CYCopyJSString(id value) {
332 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
335 JSStringRef CYCopyJSString(const char *value) {
336 return JSStringCreateWithUTF8CString(value);
339 JSStringRef CYCopyJSString(JSStringRef value) {
340 return JSStringRetain(value);
343 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
344 JSValueRef exception(NULL);
345 JSStringRef string(JSValueToStringCopy(context, value, &exception));
346 CYThrow(context, exception);
350 // XXX: this is not a safe handle
356 template <typename Arg0_>
357 CYString(Arg0_ arg0) {
358 string_ = CYCopyJSString(arg0);
361 template <typename Arg0_, typename Arg1_>
362 CYString(Arg0_ arg0, Arg1_ arg1) {
363 string_ = CYCopyJSString(arg0, arg1);
367 JSStringRelease(string_);
370 operator JSStringRef() const {
375 CFStringRef CYCopyCFString(JSStringRef value) {
376 return JSStringCopyCFString(kCFAllocatorDefault, value);
379 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
380 return CYCopyCFString(CYString(context, value));
383 double CYCastDouble(JSContextRef context, JSValueRef value) {
384 JSValueRef exception(NULL);
385 double number(JSValueToNumber(context, value, &exception));
386 CYThrow(context, exception);
390 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
391 double number(CYCastDouble(context, value));
392 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
395 NSString *CYCastNSString(JSStringRef value) {
396 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
399 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
400 switch (JSType type = JSValueGetType(context, value)) {
401 case kJSTypeUndefined:
402 return CFRetain([WebUndefined undefined]);
406 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
408 return CYCopyCFNumber(context, value);
410 return CYCopyCFString(context, value);
412 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
414 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
418 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
419 size_t size(JSPropertyNameArrayGetCount(names));
420 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
421 for (size_t index(0); index != size; ++index)
422 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
426 id CYCastNSObject(JSContextRef context, JSValueRef value) {
427 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
428 return object == nil ? nil : [object autorelease];
431 void CYThrow(JSContextRef context, JSValueRef value) {
434 @throw CYCastNSObject(context, value);
437 JSValueRef CYCastJSValue(JSContextRef context, id value) {
438 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
441 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
442 *exception = CYCastJSValue(context, error);
445 @implementation CYJSObject
447 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
448 if ((self = [super init]) != nil) {
454 - (NSUInteger) count {
455 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
456 size_t size(JSPropertyNameArrayGetCount(names));
457 JSPropertyNameArrayRelease(names);
461 - (id) objectForKey:(id)key {
462 JSValueRef exception(NULL);
463 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
464 CYThrow(context_, exception);
465 return CYCastNSObject(context_, value);
468 - (NSEnumerator *) keyEnumerator {
469 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
470 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
471 JSPropertyNameArrayRelease(names);
475 - (void) setObject:(id)object forKey:(id)key {
476 JSValueRef exception(NULL);
477 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
478 CYThrow(context_, exception);
481 - (void) removeObjectForKey:(id)key {
482 JSValueRef exception(NULL);
483 // XXX: this returns a bool... throw exception, or ignore?
484 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
485 CYThrow(context_, exception);
490 @implementation CYJSArray
492 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
493 if ((self = [super init]) != nil) {
499 - (NSUInteger) count {
500 JSValueRef exception(NULL);
501 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
502 CYThrow(context_, exception);
503 return CYCastDouble(context_, value);
506 - (id) objectAtIndex:(NSUInteger)index {
507 JSValueRef exception(NULL);
508 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
509 CYThrow(context_, exception);
510 id object(CYCastNSObject(context_, value));
511 return object == nil ? [NSNull null] : object;
516 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
517 id object(CYCastNSObject(context, value));
518 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
521 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
523 case kCFSocketDataCallBack:
524 CFDataRef data(reinterpret_cast<CFDataRef>(value));
525 Client *client(reinterpret_cast<Client *>(info));
527 if (client->message_ == NULL)
528 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
530 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
531 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
532 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
533 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
535 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
536 CFRelease(client->message_);
538 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
541 JSStringRef script(JSStringCreateWithCFString(code));
544 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
545 JSStringRelease(script);
547 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
548 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
550 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
551 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
554 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
555 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
558 CFHTTPMessageSetBody(response, body);
561 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
564 CFSocketSendData(socket, NULL, serialized, 0);
565 CFRelease(serialized);
573 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
575 case kCFSocketAcceptCallBack:
576 Client *client(new Client());
578 client->message_ = NULL;
580 CFSocketContext context;
582 context.info = client;
583 context.retain = NULL;
584 context.release = NULL;
585 context.copyDescription = NULL;
587 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
589 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
594 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
596 NSString *name(CYCastNSString(property));
604 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
606 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
607 return CYMakeObject(context, [[data alloc] autorelease]);
616 void *operator new(size_t size) {
618 apr_pool_create(&pool, NULL);
619 void *data(apr_palloc(pool, size));
620 reinterpret_cast<ptrData *>(data)->pool_ = pool;
624 ptrData(void *value) :
630 struct ffiData : ptrData {
631 sig::Signature signature_;
634 ffiData(void (*value)(), const char *type) :
635 ptrData(reinterpret_cast<void *>(value))
637 sig::Parse(pool_, &signature_, type);
638 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
642 struct selData : ptrData {
649 static void Pointer_finalize(JSObjectRef object) {
650 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
651 apr_pool_destroy(data->pool_);
654 static void Instance_finalize(JSObjectRef object) {
655 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
659 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
660 ffiData *data(new ffiData(function, type));
661 return JSObjectMake(context, Functor_, data);
665 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
666 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
669 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
670 JSValueRef exception(NULL);
671 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
672 CYThrow(context, exception);
675 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
676 size_t size(JSStringGetMaximumUTF8CStringSize(value));
677 char *string(new(pool) char[size]);
678 JSStringGetUTF8CString(value, string, size);
679 JSStringRelease(value);
683 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
684 return CYPoolCString(pool, CYString(context, value));
687 // XXX: this macro is unhygenic
688 #define CYCastCString(context, value) ({ \
689 JSValueRef exception(NULL); \
690 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
691 CYThrow(context, exception); \
692 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
693 char *utf8(reinterpret_cast<char *>(alloca(size))); \
694 JSStringGetUTF8CString(string, utf8, size); \
695 JSStringRelease(string); \
699 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
700 if (JSValueIsNull(context, value))
702 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
703 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
704 return reinterpret_cast<SEL>(data->value_);
706 return sel_registerName(CYCastCString(context, value));
709 void *CYCastPointer(JSContextRef context, JSValueRef value) {
710 switch (JSValueGetType(context, value)) {
714 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
716 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
717 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
721 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
725 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
726 switch (type->primitive) {
728 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
731 #define CYPoolFFI_(primitive, native) \
732 case sig::primitive ## _P: \
733 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
736 CYPoolFFI_(uchar, unsigned char)
737 CYPoolFFI_(char, char)
738 CYPoolFFI_(ushort, unsigned short)
739 CYPoolFFI_(short, short)
740 CYPoolFFI_(ulong, unsigned long)
741 CYPoolFFI_(long, long)
742 CYPoolFFI_(uint, unsigned int)
744 CYPoolFFI_(ulonglong, unsigned long long)
745 CYPoolFFI_(longlong, long long)
746 CYPoolFFI_(float, float)
747 CYPoolFFI_(double, double)
750 case sig::typename_P:
751 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
754 case sig::selector_P:
755 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
759 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
763 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
773 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
778 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
781 switch (type->primitive) {
783 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
786 #define CYFromFFI_(primitive, native) \
787 case sig::primitive ## _P: \
788 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
791 CYFromFFI_(uchar, unsigned char)
792 CYFromFFI_(char, char)
793 CYFromFFI_(ushort, unsigned short)
794 CYFromFFI_(short, short)
795 CYFromFFI_(ulong, unsigned long)
796 CYFromFFI_(long, long)
797 CYFromFFI_(uint, unsigned int)
799 CYFromFFI_(ulonglong, unsigned long long)
800 CYFromFFI_(longlong, long long)
801 CYFromFFI_(float, float)
802 CYFromFFI_(double, double)
805 case sig::typename_P: {
806 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
809 case sig::selector_P: {
810 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
811 selData *data(new selData(sel));
812 value = JSObjectMake(context, Selector_, data);
816 case sig::pointer_P: {
817 if (void *pointer = *reinterpret_cast<void **>(data)) {
818 ptrData *data(new ptrData(pointer));
819 value = JSObjectMake(context, Pointer_, data);
823 case sig::string_P: {
824 if (char *utf8 = *reinterpret_cast<char **>(data))
825 value = JSValueMakeString(context, CYString(utf8));
833 value = JSValueMakeUndefined(context);
837 value = JSValueMakeNull(context);
841 NSLog(@"CYFromFFI(%c)\n", type->primitive);
848 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
850 if (count != signature->count - 1)
851 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
856 for (unsigned index(0); index != count; ++index) {
857 sig::Element *element(&signature->elements[index + 1]);
859 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
860 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
863 uint8_t value[cif->rtype->size];
864 ffi_call(cif, function, value, values);
866 return CYFromFFI(context, signature->elements[0].type, value);
870 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
872 NSString *name(CYCastNSString(property));
873 if (Class _class = NSClassFromString(name))
874 return CYMakeObject(context, _class);
875 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
876 switch ([[entry objectAtIndex:0] intValue]) {
878 return JSEvaluateScript(JSGetContext(), CYString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
880 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
883 sig::Signature signature;
884 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
885 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
891 bool stret(ffi_type *ffi_type) {
892 return ffi_type->type == FFI_TYPE_STRUCT && (
893 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
894 struct_forward_array[ffi_type->size] != 0
898 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
903 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
905 id self(CYCastNSObject(context, arguments[0]));
907 return JSValueMakeNull(context);
909 SEL _cmd(CYCastSEL(context, arguments[1]));
910 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
912 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
914 type = [[method _typeString] UTF8String];
919 sig::Signature signature;
920 sig::Parse(pool, &signature, type);
923 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
925 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
926 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
929 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
930 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
931 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
934 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
937 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
938 void *function(CYCastPointer(context, arguments[0]));
939 const char *type(CYCastCString(context, arguments[1]));
940 return CYMakeFunction(context, function, type);
944 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
945 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
946 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
949 static JSStaticValue Pointer_staticValues[2] = {
950 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
951 {NULL, NULL, NULL, 0}
954 void cyparse(CYParser *parser);
957 void CYConsole(FILE *fin, FILE *fout, FILE *ferr) {
963 MSInitialize { _pooled
966 NSCFBoolean_ = objc_getClass("NSCFBoolean");
970 struct sockaddr_in address;
971 address.sin_len = sizeof(address);
972 address.sin_family = AF_INET;
973 address.sin_addr.s_addr = INADDR_ANY;
974 address.sin_port = htons(10000 + pid);
976 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
978 CFSocketSignature signature;
979 signature.protocolFamily = AF_INET;
980 signature.socketType = SOCK_STREAM;
981 signature.protocol = IPPROTO_TCP;
982 signature.address = data;
984 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
985 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
987 JSClassDefinition definition;
989 definition = kJSClassDefinitionEmpty;
990 definition.className = "Pointer";
991 definition.staticValues = Pointer_staticValues;
992 definition.finalize = &Pointer_finalize;
993 Pointer_ = JSClassCreate(&definition);
995 definition = kJSClassDefinitionEmpty;
996 definition.className = "Functor";
997 definition.parentClass = Pointer_;
998 definition.callAsFunction = &ffi_callAsFunction;
999 Functor_ = JSClassCreate(&definition);
1001 definition = kJSClassDefinitionEmpty;
1002 definition.className = "Selector";
1003 definition.parentClass = Pointer_;
1004 Selector_ = JSClassCreate(&definition);
1006 definition = kJSClassDefinitionEmpty;
1007 definition.className = "Instance_";
1008 definition.getProperty = &Instance_getProperty;
1009 definition.callAsConstructor = &Instance_callAsConstructor;
1010 definition.finalize = &Instance_finalize;
1011 Instance_ = JSClassCreate(&definition);
1013 definition = kJSClassDefinitionEmpty;
1014 definition.getProperty = &Global_getProperty;
1015 JSClassRef Global(JSClassCreate(&definition));
1017 JSContextRef context(JSGlobalContextCreate(Global));
1020 JSObjectRef global(JSContextGetGlobalObject(context));
1022 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1024 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
1026 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1028 name_ = JSStringCreateWithUTF8CString("name");
1029 message_ = JSStringCreateWithUTF8CString("message");
1030 length_ = JSStringCreateWithUTF8CString("length");
1032 JSValueRef exception(NULL);
1033 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
1034 CYThrow(context, exception);
1035 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1036 CYThrow(context, exception);