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>
43 #include "cycript.hpp"
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include "Pooling.hpp"
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreFoundation/CFLogUtilities.h>
56 #include <CFNetwork/CFNetwork.h>
58 #include <WebKit/WebScriptObject.h>
60 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
65 #include <ext/stdio_filebuf.h>
70 #include "Cycript.tab.hh"
75 #define _assert(test) do { \
77 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
80 #define _trace() do { \
81 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
85 static JSContextRef Context_;
87 static JSClassRef Functor_;
88 static JSClassRef Instance_;
89 static JSClassRef Pointer_;
90 static JSClassRef Selector_;
92 static JSObjectRef Array_;
93 static JSObjectRef Function_;
95 static JSStringRef name_;
96 static JSStringRef message_;
97 static JSStringRef length_;
99 static Class NSCFBoolean_;
101 static NSMutableDictionary *Bridge_;
104 CFHTTPMessageRef message_;
108 JSObjectRef CYMakeObject(JSContextRef context, id object) {
109 return JSObjectMake(context, Instance_, [object retain]);
112 @interface NSMethodSignature (Cycript)
113 - (NSString *) _typeString;
116 @interface NSObject (Cycript)
117 - (bool) cy$isUndefined;
118 - (NSString *) cy$toJSON;
119 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
122 @interface NSString (Cycript)
123 - (void *) cy$symbol;
126 @interface NSNumber (Cycript)
127 - (void *) cy$symbol;
130 @implementation NSObject (Cycript)
132 - (bool) cy$isUndefined {
136 - (NSString *) cy$toJSON {
137 return [self description];
140 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
141 return CYMakeObject(context, self);
146 @implementation WebUndefined (Cycript)
148 - (bool) cy$isUndefined {
152 - (NSString *) cy$toJSON {
156 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
157 return JSValueMakeUndefined(context);
162 @implementation NSArray (Cycript)
164 - (NSString *) cy$toJSON {
165 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
166 [json appendString:@"["];
169 for (id object in self) {
171 [json appendString:@","];
174 if (![object cy$isUndefined])
175 [json appendString:[object cy$toJSON]];
177 [json appendString:@","];
182 [json appendString:@"]"];
188 @implementation NSDictionary (Cycript)
190 - (NSString *) cy$toJSON {
191 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
192 [json appendString:@"({"];
195 for (id key in self) {
197 [json appendString:@","];
200 [json appendString:[key cy$toJSON]];
201 [json appendString:@":"];
202 NSObject *object([self objectForKey:key]);
203 [json appendString:[object cy$toJSON]];
206 [json appendString:@"})"];
212 @implementation NSNumber (Cycript)
214 - (NSString *) cy$toJSON {
215 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
218 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
219 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
222 - (void *) cy$symbol {
223 return [self pointerValue];
228 @implementation NSString (Cycript)
230 - (NSString *) cy$toJSON {
231 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
233 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
234 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
235 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
236 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
237 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
239 CFStringInsert(json, 0, CFSTR("\""));
240 CFStringAppend(json, CFSTR("\""));
242 return [reinterpret_cast<const NSString *>(json) autorelease];
245 - (void *) cy$symbol {
246 return dlsym(RTLD_DEFAULT, [self UTF8String]);
251 @interface CYJSObject : NSDictionary {
253 JSContextRef context_;
256 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
258 - (NSUInteger) count;
259 - (id) objectForKey:(id)key;
260 - (NSEnumerator *) keyEnumerator;
261 - (void) setObject:(id)object forKey:(id)key;
262 - (void) removeObjectForKey:(id)key;
266 @interface CYJSArray : NSArray {
268 JSContextRef context_;
271 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
273 - (NSUInteger) count;
274 - (id) objectAtIndex:(NSUInteger)index;
278 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
279 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
281 JSContextRef CYGetJSContext() {
286 @catch (id error) { \
287 CYThrow(context, error, exception); \
291 void CYThrow(JSContextRef context, JSValueRef value);
293 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
294 if (JSValueIsObjectOfClass(context, object, Instance_))
295 return reinterpret_cast<id>(JSObjectGetPrivate(object));
296 JSValueRef exception(NULL);
297 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
298 CYThrow(context, exception);
300 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
301 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
304 JSStringRef CYCopyJSString(id value) {
305 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
308 JSStringRef CYCopyJSString(const char *value) {
309 return JSStringCreateWithUTF8CString(value);
312 JSStringRef CYCopyJSString(JSStringRef value) {
313 return JSStringRetain(value);
316 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
317 JSValueRef exception(NULL);
318 JSStringRef string(JSValueToStringCopy(context, value, &exception));
319 CYThrow(context, exception);
323 // XXX: this is not a safe handle
329 template <typename Arg0_>
330 CYJSString(Arg0_ arg0) {
331 string_ = CYCopyJSString(arg0);
334 template <typename Arg0_, typename Arg1_>
335 CYJSString(Arg0_ arg0, Arg1_ arg1) {
336 string_ = CYCopyJSString(arg0, arg1);
340 JSStringRelease(string_);
343 operator JSStringRef() const {
348 CFStringRef CYCopyCFString(JSStringRef value) {
349 return JSStringCopyCFString(kCFAllocatorDefault, value);
352 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
353 return CYCopyCFString(CYJSString(context, value));
356 double CYCastDouble(JSContextRef context, JSValueRef value) {
357 JSValueRef exception(NULL);
358 double number(JSValueToNumber(context, value, &exception));
359 CYThrow(context, exception);
363 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
364 double number(CYCastDouble(context, value));
365 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
368 NSString *CYCastNSString(JSStringRef value) {
369 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
372 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
373 switch (JSType type = JSValueGetType(context, value)) {
374 case kJSTypeUndefined:
375 return CFRetain([WebUndefined undefined]);
379 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
381 return CYCopyCFNumber(context, value);
383 return CYCopyCFString(context, value);
385 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
387 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
391 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
392 size_t size(JSPropertyNameArrayGetCount(names));
393 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
394 for (size_t index(0); index != size; ++index)
395 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
399 id CYCastNSObject(JSContextRef context, JSValueRef value) {
400 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
401 return object == nil ? nil : [object autorelease];
404 void CYThrow(JSContextRef context, JSValueRef value) {
407 @throw CYCastNSObject(context, value);
410 JSValueRef CYCastJSValue(JSContextRef context, id value) {
411 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
414 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
415 JSValueRef exception(NULL);
416 JSObjectRef object(JSValueToObject(context, value, &exception));
417 CYThrow(context, exception);
421 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
422 JSValueRef exception(NULL);
423 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
424 CYThrow(context, exception);
428 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
429 JSValueRef exception(NULL);
430 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
431 CYThrow(context, exception);
434 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
435 *exception = CYCastJSValue(context, error);
438 @implementation CYJSObject
440 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
441 if ((self = [super init]) != nil) {
447 - (NSUInteger) count {
448 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
449 size_t size(JSPropertyNameArrayGetCount(names));
450 JSPropertyNameArrayRelease(names);
454 - (id) objectForKey:(id)key {
455 return CYCastNSObject(context_, CYGetProperty(context_, object_, CYJSString(key)));
458 - (NSEnumerator *) keyEnumerator {
459 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
460 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
461 JSPropertyNameArrayRelease(names);
465 - (void) setObject:(id)object forKey:(id)key {
466 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
469 - (void) removeObjectForKey:(id)key {
470 JSValueRef exception(NULL);
471 // XXX: this returns a bool... throw exception, or ignore?
472 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
473 CYThrow(context_, exception);
478 @implementation CYJSArray
480 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
481 if ((self = [super init]) != nil) {
487 - (NSUInteger) count {
488 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
491 - (id) objectAtIndex:(NSUInteger)index {
492 JSValueRef exception(NULL);
493 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
494 CYThrow(context_, exception);
495 id object(CYCastNSObject(context_, value));
496 return object == nil ? [NSNull null] : object;
501 CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value) {
502 id object(CYCastNSObject(context, value));
503 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
506 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
508 case kCFSocketDataCallBack:
509 CFDataRef data(reinterpret_cast<CFDataRef>(value));
510 Client *client(reinterpret_cast<Client *>(info));
512 if (client->message_ == NULL)
513 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
515 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
516 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
517 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
518 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
520 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
521 CFRelease(client->message_);
523 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
526 JSStringRef script(JSStringCreateWithCFString(code));
529 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
530 JSStringRelease(script);
532 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
533 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
535 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result));
536 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
539 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
540 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
543 CFHTTPMessageSetBody(response, body);
546 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
549 CFSocketSendData(socket, NULL, serialized, 0);
550 CFRelease(serialized);
558 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
560 case kCFSocketAcceptCallBack:
561 Client *client(new Client());
563 client->message_ = NULL;
565 CFSocketContext context;
567 context.info = client;
568 context.retain = NULL;
569 context.release = NULL;
570 context.copyDescription = NULL;
572 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
574 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
579 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
581 NSString *name(CYCastNSString(property));
589 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
591 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
592 return CYMakeObject(context, [[data alloc] autorelease]);
601 void *operator new(size_t size) {
603 apr_pool_create(&pool, NULL);
604 void *data(apr_palloc(pool, size));
605 reinterpret_cast<ptrData *>(data)->pool_ = pool;
609 ptrData(void *value) :
615 struct ffiData : ptrData {
616 sig::Signature signature_;
619 ffiData(void (*value)(), const char *type) :
620 ptrData(reinterpret_cast<void *>(value))
622 sig::Parse(pool_, &signature_, type);
623 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
627 struct selData : ptrData {
634 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
635 selData *data(new selData(sel));
636 return JSObjectMake(context, Selector_, data);
639 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
640 ptrData *data(new ptrData(pointer));
641 return JSObjectMake(context, Pointer_, data);
644 static void Pointer_finalize(JSObjectRef object) {
645 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
646 apr_pool_destroy(data->pool_);
649 static void Instance_finalize(JSObjectRef object) {
650 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
654 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
655 ffiData *data(new ffiData(function, type));
656 return JSObjectMake(context, Functor_, data);
659 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
660 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
663 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
664 size_t size(JSStringGetMaximumUTF8CStringSize(value));
665 char *string(new(pool) char[size]);
666 JSStringGetUTF8CString(value, string, size);
667 JSStringRelease(value);
671 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
672 return CYPoolCString(pool, CYJSString(context, value));
675 // XXX: this macro is unhygenic
676 #define CYCastCString(context, value) ({ \
677 JSStringRef string(CYCopyJSString(context, value)); \
678 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
679 char *utf8(reinterpret_cast<char *>(alloca(size))); \
680 JSStringGetUTF8CString(string, utf8, size); \
681 JSStringRelease(string); \
685 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
686 if (JSValueIsNull(context, value))
688 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
689 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
690 return reinterpret_cast<SEL>(data->value_);
692 return sel_registerName(CYCastCString(context, value));
695 void *CYCastPointer(JSContextRef context, JSValueRef value) {
696 switch (JSValueGetType(context, value)) {
700 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
702 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
703 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
707 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
711 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
712 switch (type->primitive) {
714 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
717 #define CYPoolFFI_(primitive, native) \
718 case sig::primitive ## _P: \
719 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
722 CYPoolFFI_(uchar, unsigned char)
723 CYPoolFFI_(char, char)
724 CYPoolFFI_(ushort, unsigned short)
725 CYPoolFFI_(short, short)
726 CYPoolFFI_(ulong, unsigned long)
727 CYPoolFFI_(long, long)
728 CYPoolFFI_(uint, unsigned int)
730 CYPoolFFI_(ulonglong, unsigned long long)
731 CYPoolFFI_(longlong, long long)
732 CYPoolFFI_(float, float)
733 CYPoolFFI_(double, double)
736 case sig::typename_P:
737 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
740 case sig::selector_P:
741 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
745 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
749 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
759 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
764 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
767 switch (type->primitive) {
769 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
772 #define CYFromFFI_(primitive, native) \
773 case sig::primitive ## _P: \
774 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
777 CYFromFFI_(uchar, unsigned char)
778 CYFromFFI_(char, char)
779 CYFromFFI_(ushort, unsigned short)
780 CYFromFFI_(short, short)
781 CYFromFFI_(ulong, unsigned long)
782 CYFromFFI_(long, long)
783 CYFromFFI_(uint, unsigned int)
785 CYFromFFI_(ulonglong, unsigned long long)
786 CYFromFFI_(longlong, long long)
787 CYFromFFI_(float, float)
788 CYFromFFI_(double, double)
791 case sig::typename_P:
792 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
795 case sig::selector_P:
796 if (SEL sel = *reinterpret_cast<SEL *>(data))
797 value = CYMakeSelector(context, sel);
802 if (void *pointer = *reinterpret_cast<void **>(data))
803 value = CYMakePointer(context, pointer);
808 if (char *utf8 = *reinterpret_cast<char **>(data))
809 value = JSValueMakeString(context, CYJSString(utf8));
817 value = JSValueMakeUndefined(context);
821 value = JSValueMakeNull(context);
825 NSLog(@"CYFromFFI(%c)\n", type->primitive);
832 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
834 if (count != signature->count - 1)
835 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
840 for (unsigned index(0); index != count; ++index) {
841 sig::Element *element(&signature->elements[index + 1]);
843 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
844 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
847 uint8_t value[cif->rtype->size];
848 ffi_call(cif, function, value, values);
850 return CYFromFFI(context, signature->elements[0].type, value);
854 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
856 NSString *name(CYCastNSString(property));
857 if (Class _class = NSClassFromString(name))
858 return CYMakeObject(context, _class);
859 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
860 switch ([[entry objectAtIndex:0] intValue]) {
862 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
864 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
867 sig::Signature signature;
868 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
869 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
875 bool stret(ffi_type *ffi_type) {
876 return ffi_type->type == FFI_TYPE_STRUCT && (
877 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
878 struct_forward_array[ffi_type->size] != 0
882 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
887 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
889 id self(CYCastNSObject(context, arguments[0]));
891 return JSValueMakeNull(context);
893 SEL _cmd(CYCastSEL(context, arguments[1]));
894 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
896 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
898 type = [[method _typeString] UTF8String];
903 sig::Signature signature;
904 sig::Parse(pool, &signature, type);
907 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
909 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
910 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
913 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
914 JSValueRef setup[count + 2];
917 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
918 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
921 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
922 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
923 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
926 JSObjectRef sel(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
929 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
930 const char *name(CYCastCString(context, arguments[0]));
931 return CYMakeSelector(context, sel_registerName(name));
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 Functor 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 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
954 static JSStaticValue Pointer_staticValues[2] = {
955 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
956 {NULL, NULL, NULL, 0}
959 /*static JSStaticValue Selector_staticValues[2] = {
960 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
961 {NULL, NULL, NULL, 0}
964 CYDriver::CYDriver(const std::string &filename) :
974 CYDriver::~CYDriver() {
978 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
979 CYDriver::Error error;
980 error.location_ = location;
981 error.message_ = message;
982 driver.errors_.push_back(error);
985 MSInitialize { _pooled
988 NSCFBoolean_ = objc_getClass("NSCFBoolean");
992 struct sockaddr_in address;
993 address.sin_len = sizeof(address);
994 address.sin_family = AF_INET;
995 address.sin_addr.s_addr = INADDR_ANY;
996 address.sin_port = htons(10000 + pid);
998 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1000 CFSocketSignature signature;
1001 signature.protocolFamily = AF_INET;
1002 signature.socketType = SOCK_STREAM;
1003 signature.protocol = IPPROTO_TCP;
1004 signature.address = data;
1006 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1007 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1009 JSClassDefinition definition;
1011 definition = kJSClassDefinitionEmpty;
1012 definition.className = "Pointer";
1013 definition.staticValues = Pointer_staticValues;
1014 definition.finalize = &Pointer_finalize;
1015 Pointer_ = JSClassCreate(&definition);
1017 definition = kJSClassDefinitionEmpty;
1018 definition.className = "Functor";
1019 definition.parentClass = Pointer_;
1020 definition.callAsFunction = &Functor_callAsFunction;
1021 Functor_ = JSClassCreate(&definition);
1023 definition = kJSClassDefinitionEmpty;
1024 definition.className = "Selector";
1025 definition.parentClass = Pointer_;
1026 //definition.staticValues = Selector_staticValues;
1027 definition.callAsFunction = &Selector_callAsFunction;
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, CYJSString("SEL"), JSObjectMakeConstructor(context, Selector_, &sel));
1047 CYSetProperty(context, global, CYJSString("ffi"), JSObjectMakeConstructor(context, Functor_, &ffi));
1049 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1051 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1053 name_ = JSStringCreateWithUTF8CString("name");
1054 message_ = JSStringCreateWithUTF8CString("message");
1055 length_ = JSStringCreateWithUTF8CString("length");
1057 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1058 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));