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>
78 #include "Cycript.tab.hh"
83 #define _assert(test) do { \
85 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
88 #define _trace() do { \
89 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
92 /* APR Pool Helpers {{{ */
93 void *operator new(size_t size, apr_pool_t *pool) {
94 return apr_palloc(pool, size);
97 void *operator new [](size_t size, apr_pool_t *pool) {
98 return apr_palloc(pool, size);
107 apr_pool_create(&pool_, NULL);
111 apr_pool_destroy(pool_);
114 operator apr_pool_t *() const {
118 char *operator ()(const char *data) const {
119 return apr_pstrdup(pool_, data);
122 char *operator ()(const char *data, size_t size) const {
123 return apr_pstrndup(pool_, data, size);
128 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
130 static JSContextRef Context_;
132 static JSClassRef Functor_;
133 static JSClassRef Instance_;
134 static JSClassRef Pointer_;
135 static JSClassRef Selector_;
137 static JSObjectRef Array_;
139 static JSStringRef name_;
140 static JSStringRef message_;
141 static JSStringRef length_;
143 static Class NSCFBoolean_;
145 static NSMutableDictionary *Bridge_;
148 CFHTTPMessageRef message_;
152 JSObjectRef CYMakeObject(JSContextRef context, id object) {
153 return JSObjectMake(context, Instance_, [object retain]);
156 @interface NSMethodSignature (Cycript)
157 - (NSString *) _typeString;
160 @interface NSObject (Cycript)
161 - (NSString *) cy$toJSON;
162 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
165 @interface NSString (Cycript)
166 - (void *) cy$symbol;
169 @interface NSNumber (Cycript)
170 - (void *) cy$symbol;
173 @implementation NSObject (Cycript)
175 - (NSString *) cy$toJSON {
176 return [self description];
179 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
180 return CYMakeObject(context, self);
185 @implementation WebUndefined (Cycript)
187 - (NSString *) cy$toJSON {
191 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
192 return JSValueMakeUndefined(context);
197 @implementation NSArray (Cycript)
199 - (NSString *) cy$toJSON {
200 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
201 [json appendString:@"["];
204 for (id object in self) {
206 [json appendString:@","];
209 [json appendString:[object cy$toJSON]];
212 [json appendString:@"]"];
218 @implementation NSDictionary (Cycript)
220 - (NSString *) cy$toJSON {
221 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
222 [json appendString:@"("];
223 [json appendString:@"{"];
226 for (id key in self) {
228 [json appendString:@","];
231 [json appendString:[key cy$toJSON]];
232 [json appendString:@":"];
233 NSObject *object([self objectForKey:key]);
234 [json appendString:[object cy$toJSON]];
237 [json appendString:@"})"];
243 @implementation NSNumber (Cycript)
245 - (NSString *) cy$toJSON {
246 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
249 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
250 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
253 - (void *) cy$symbol {
254 return [self pointerValue];
259 @implementation NSString (Cycript)
261 - (NSString *) cy$toJSON {
262 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
264 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
265 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
266 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
267 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
268 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
270 CFStringInsert(json, 0, CFSTR("\""));
271 CFStringAppend(json, CFSTR("\""));
273 return [reinterpret_cast<const NSString *>(json) autorelease];
276 - (void *) cy$symbol {
277 return dlsym(RTLD_DEFAULT, [self UTF8String]);
282 @interface CYJSObject : NSDictionary {
284 JSContextRef context_;
287 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
289 - (NSUInteger) count;
290 - (id) objectForKey:(id)key;
291 - (NSEnumerator *) keyEnumerator;
292 - (void) setObject:(id)object forKey:(id)key;
293 - (void) removeObjectForKey:(id)key;
297 @interface CYJSArray : NSArray {
299 JSContextRef context_;
302 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
304 - (NSUInteger) count;
305 - (id) objectAtIndex:(NSUInteger)index;
309 JSContextRef JSGetContext() {
314 @catch (id error) { \
315 CYThrow(context, error, exception); \
319 void CYThrow(JSContextRef context, JSValueRef value);
321 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
322 if (JSValueIsObjectOfClass(context, object, Instance_))
323 return reinterpret_cast<id>(JSObjectGetPrivate(object));
324 JSValueRef exception(NULL);
325 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
326 CYThrow(context, exception);
328 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
329 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
332 JSStringRef CYCopyJSString(id value) {
333 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
336 JSStringRef CYCopyJSString(const char *value) {
337 return JSStringCreateWithUTF8CString(value);
340 JSStringRef CYCopyJSString(JSStringRef value) {
341 return JSStringRetain(value);
344 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
345 JSValueRef exception(NULL);
346 JSStringRef string(JSValueToStringCopy(context, value, &exception));
347 CYThrow(context, exception);
351 // XXX: this is not a safe handle
357 template <typename Arg0_>
358 CYString(Arg0_ arg0) {
359 string_ = CYCopyJSString(arg0);
362 template <typename Arg0_, typename Arg1_>
363 CYString(Arg0_ arg0, Arg1_ arg1) {
364 string_ = CYCopyJSString(arg0, arg1);
368 JSStringRelease(string_);
371 operator JSStringRef() const {
376 CFStringRef CYCopyCFString(JSStringRef value) {
377 return JSStringCopyCFString(kCFAllocatorDefault, value);
380 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
381 return CYCopyCFString(CYString(context, value));
384 double CYCastDouble(JSContextRef context, JSValueRef value) {
385 JSValueRef exception(NULL);
386 double number(JSValueToNumber(context, value, &exception));
387 CYThrow(context, exception);
391 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
392 double number(CYCastDouble(context, value));
393 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
396 NSString *CYCastNSString(JSStringRef value) {
397 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
400 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
401 switch (JSType type = JSValueGetType(context, value)) {
402 case kJSTypeUndefined:
403 return CFRetain([WebUndefined undefined]);
407 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
409 return CYCopyCFNumber(context, value);
411 return CYCopyCFString(context, value);
413 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
415 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
419 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
420 size_t size(JSPropertyNameArrayGetCount(names));
421 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
422 for (size_t index(0); index != size; ++index)
423 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
427 id CYCastNSObject(JSContextRef context, JSValueRef value) {
428 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
429 return object == nil ? nil : [object autorelease];
432 void CYThrow(JSContextRef context, JSValueRef value) {
435 @throw CYCastNSObject(context, value);
438 JSValueRef CYCastJSValue(JSContextRef context, id value) {
439 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
442 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
443 *exception = CYCastJSValue(context, error);
446 @implementation CYJSObject
448 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
449 if ((self = [super init]) != nil) {
455 - (NSUInteger) count {
456 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
457 size_t size(JSPropertyNameArrayGetCount(names));
458 JSPropertyNameArrayRelease(names);
462 - (id) objectForKey:(id)key {
463 JSValueRef exception(NULL);
464 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
465 CYThrow(context_, exception);
466 return CYCastNSObject(context_, value);
469 - (NSEnumerator *) keyEnumerator {
470 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
471 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
472 JSPropertyNameArrayRelease(names);
476 - (void) setObject:(id)object forKey:(id)key {
477 JSValueRef exception(NULL);
478 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
479 CYThrow(context_, exception);
482 - (void) removeObjectForKey:(id)key {
483 JSValueRef exception(NULL);
484 // XXX: this returns a bool... throw exception, or ignore?
485 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
486 CYThrow(context_, exception);
491 @implementation CYJSArray
493 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
494 if ((self = [super init]) != nil) {
500 - (NSUInteger) count {
501 JSValueRef exception(NULL);
502 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
503 CYThrow(context_, exception);
504 return CYCastDouble(context_, value);
507 - (id) objectAtIndex:(NSUInteger)index {
508 JSValueRef exception(NULL);
509 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
510 CYThrow(context_, exception);
511 id object(CYCastNSObject(context_, value));
512 return object == nil ? [NSNull null] : object;
517 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
518 id object(CYCastNSObject(context, value));
519 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
522 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
524 case kCFSocketDataCallBack:
525 CFDataRef data(reinterpret_cast<CFDataRef>(value));
526 Client *client(reinterpret_cast<Client *>(info));
528 if (client->message_ == NULL)
529 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
531 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
532 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
533 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
534 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
536 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
537 CFRelease(client->message_);
539 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
542 JSStringRef script(JSStringCreateWithCFString(code));
545 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
546 JSStringRelease(script);
548 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
549 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
551 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
552 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
555 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
556 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
559 CFHTTPMessageSetBody(response, body);
562 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
565 CFSocketSendData(socket, NULL, serialized, 0);
566 CFRelease(serialized);
574 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
576 case kCFSocketAcceptCallBack:
577 Client *client(new Client());
579 client->message_ = NULL;
581 CFSocketContext context;
583 context.info = client;
584 context.retain = NULL;
585 context.release = NULL;
586 context.copyDescription = NULL;
588 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
590 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
595 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
597 NSString *name(CYCastNSString(property));
605 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
607 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
608 return CYMakeObject(context, [[data alloc] autorelease]);
617 void *operator new(size_t size) {
619 apr_pool_create(&pool, NULL);
620 void *data(apr_palloc(pool, size));
621 reinterpret_cast<ptrData *>(data)->pool_ = pool;
625 ptrData(void *value) :
631 struct ffiData : ptrData {
632 sig::Signature signature_;
635 ffiData(void (*value)(), const char *type) :
636 ptrData(reinterpret_cast<void *>(value))
638 sig::Parse(pool_, &signature_, type);
639 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
643 struct selData : ptrData {
650 static void Pointer_finalize(JSObjectRef object) {
651 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
652 apr_pool_destroy(data->pool_);
655 static void Instance_finalize(JSObjectRef object) {
656 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
660 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
661 ffiData *data(new ffiData(function, type));
662 return JSObjectMake(context, Functor_, data);
666 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
667 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
670 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
671 JSValueRef exception(NULL);
672 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
673 CYThrow(context, exception);
676 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
677 size_t size(JSStringGetMaximumUTF8CStringSize(value));
678 char *string(new(pool) char[size]);
679 JSStringGetUTF8CString(value, string, size);
680 JSStringRelease(value);
684 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
685 return CYPoolCString(pool, CYString(context, value));
688 // XXX: this macro is unhygenic
689 #define CYCastCString(context, value) ({ \
690 JSValueRef exception(NULL); \
691 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
692 CYThrow(context, exception); \
693 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
694 char *utf8(reinterpret_cast<char *>(alloca(size))); \
695 JSStringGetUTF8CString(string, utf8, size); \
696 JSStringRelease(string); \
700 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
701 if (JSValueIsNull(context, value))
703 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
704 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
705 return reinterpret_cast<SEL>(data->value_);
707 return sel_registerName(CYCastCString(context, value));
710 void *CYCastPointer(JSContextRef context, JSValueRef value) {
711 switch (JSValueGetType(context, value)) {
715 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
717 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
718 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
722 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
726 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
727 switch (type->primitive) {
729 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
732 #define CYPoolFFI_(primitive, native) \
733 case sig::primitive ## _P: \
734 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
737 CYPoolFFI_(uchar, unsigned char)
738 CYPoolFFI_(char, char)
739 CYPoolFFI_(ushort, unsigned short)
740 CYPoolFFI_(short, short)
741 CYPoolFFI_(ulong, unsigned long)
742 CYPoolFFI_(long, long)
743 CYPoolFFI_(uint, unsigned int)
745 CYPoolFFI_(ulonglong, unsigned long long)
746 CYPoolFFI_(longlong, long long)
747 CYPoolFFI_(float, float)
748 CYPoolFFI_(double, double)
751 case sig::typename_P:
752 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
755 case sig::selector_P:
756 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
760 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
764 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
774 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
779 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
782 switch (type->primitive) {
784 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
787 #define CYFromFFI_(primitive, native) \
788 case sig::primitive ## _P: \
789 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
792 CYFromFFI_(uchar, unsigned char)
793 CYFromFFI_(char, char)
794 CYFromFFI_(ushort, unsigned short)
795 CYFromFFI_(short, short)
796 CYFromFFI_(ulong, unsigned long)
797 CYFromFFI_(long, long)
798 CYFromFFI_(uint, unsigned int)
800 CYFromFFI_(ulonglong, unsigned long long)
801 CYFromFFI_(longlong, long long)
802 CYFromFFI_(float, float)
803 CYFromFFI_(double, double)
806 case sig::typename_P: {
807 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
810 case sig::selector_P: {
811 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
812 selData *data(new selData(sel));
813 value = JSObjectMake(context, Selector_, data);
817 case sig::pointer_P: {
818 if (void *pointer = *reinterpret_cast<void **>(data)) {
819 ptrData *data(new ptrData(pointer));
820 value = JSObjectMake(context, Pointer_, data);
824 case sig::string_P: {
825 if (char *utf8 = *reinterpret_cast<char **>(data))
826 value = JSValueMakeString(context, CYString(utf8));
834 value = JSValueMakeUndefined(context);
838 value = JSValueMakeNull(context);
842 NSLog(@"CYFromFFI(%c)\n", type->primitive);
849 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
851 if (count != signature->count - 1)
852 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
857 for (unsigned index(0); index != count; ++index) {
858 sig::Element *element(&signature->elements[index + 1]);
860 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
861 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
864 uint8_t value[cif->rtype->size];
865 ffi_call(cif, function, value, values);
867 return CYFromFFI(context, signature->elements[0].type, value);
871 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
873 NSString *name(CYCastNSString(property));
874 if (Class _class = NSClassFromString(name))
875 return CYMakeObject(context, _class);
876 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
877 switch ([[entry objectAtIndex:0] intValue]) {
879 return JSEvaluateScript(JSGetContext(), CYString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
881 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
884 sig::Signature signature;
885 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
886 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
892 bool stret(ffi_type *ffi_type) {
893 return ffi_type->type == FFI_TYPE_STRUCT && (
894 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
895 struct_forward_array[ffi_type->size] != 0
899 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
904 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
906 id self(CYCastNSObject(context, arguments[0]));
908 return JSValueMakeNull(context);
910 SEL _cmd(CYCastSEL(context, arguments[1]));
911 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
913 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
915 type = [[method _typeString] UTF8String];
920 sig::Signature signature;
921 sig::Parse(pool, &signature, type);
924 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
926 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
927 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
930 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
931 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
932 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
935 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
938 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
939 void *function(CYCastPointer(context, arguments[0]));
940 const char *type(CYCastCString(context, arguments[1]));
941 return CYMakeFunction(context, function, type);
945 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
946 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
947 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
950 static JSStaticValue Pointer_staticValues[2] = {
951 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
952 {NULL, NULL, NULL, 0}
955 CYParser::CYParser() {
959 CYParser::~CYParser() {
965 void cy::parser::error(const cy::parser::location_type &loc, const std::string &msg) {
966 std::cerr << loc << ": " << msg << std::endl;
969 void CYConsole(FILE *fin, FILE *fout, FILE *ferr) {
972 cy::parser parser(&driver);
976 MSInitialize { _pooled
979 NSCFBoolean_ = objc_getClass("NSCFBoolean");
983 struct sockaddr_in address;
984 address.sin_len = sizeof(address);
985 address.sin_family = AF_INET;
986 address.sin_addr.s_addr = INADDR_ANY;
987 address.sin_port = htons(10000 + pid);
989 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
991 CFSocketSignature signature;
992 signature.protocolFamily = AF_INET;
993 signature.socketType = SOCK_STREAM;
994 signature.protocol = IPPROTO_TCP;
995 signature.address = data;
997 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
998 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1000 JSClassDefinition definition;
1002 definition = kJSClassDefinitionEmpty;
1003 definition.className = "Pointer";
1004 definition.staticValues = Pointer_staticValues;
1005 definition.finalize = &Pointer_finalize;
1006 Pointer_ = JSClassCreate(&definition);
1008 definition = kJSClassDefinitionEmpty;
1009 definition.className = "Functor";
1010 definition.parentClass = Pointer_;
1011 definition.callAsFunction = &ffi_callAsFunction;
1012 Functor_ = JSClassCreate(&definition);
1014 definition = kJSClassDefinitionEmpty;
1015 definition.className = "Selector";
1016 definition.parentClass = Pointer_;
1017 Selector_ = JSClassCreate(&definition);
1019 definition = kJSClassDefinitionEmpty;
1020 definition.className = "Instance_";
1021 definition.getProperty = &Instance_getProperty;
1022 definition.callAsConstructor = &Instance_callAsConstructor;
1023 definition.finalize = &Instance_finalize;
1024 Instance_ = JSClassCreate(&definition);
1026 definition = kJSClassDefinitionEmpty;
1027 definition.getProperty = &Global_getProperty;
1028 JSClassRef Global(JSClassCreate(&definition));
1030 JSContextRef context(JSGlobalContextCreate(Global));
1033 JSObjectRef global(JSContextGetGlobalObject(context));
1035 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1037 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
1039 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1041 name_ = JSStringCreateWithUTF8CString("name");
1042 message_ = JSStringCreateWithUTF8CString("message");
1043 length_ = JSStringCreateWithUTF8CString("length");
1045 JSValueRef exception(NULL);
1046 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
1047 CYThrow(context, exception);
1048 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1049 CYThrow(context, exception);