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_;
94 static JSStringRef name_;
95 static JSStringRef message_;
96 static JSStringRef length_;
98 static Class NSCFBoolean_;
100 static NSMutableDictionary *Bridge_;
103 CFHTTPMessageRef message_;
107 JSObjectRef CYMakeObject(JSContextRef context, id object) {
108 return JSObjectMake(context, Instance_, [object retain]);
111 @interface NSMethodSignature (Cycript)
112 - (NSString *) _typeString;
115 @interface NSObject (Cycript)
116 - (bool) cy$isUndefined;
117 - (NSString *) cy$toJSON;
118 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
121 @interface NSString (Cycript)
122 - (void *) cy$symbol;
125 @interface NSNumber (Cycript)
126 - (void *) cy$symbol;
129 @implementation NSObject (Cycript)
131 - (bool) cy$isUndefined {
135 - (NSString *) cy$toJSON {
136 return [self description];
139 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
140 return CYMakeObject(context, self);
145 @implementation WebUndefined (Cycript)
147 - (bool) cy$isUndefined {
151 - (NSString *) cy$toJSON {
155 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
156 return JSValueMakeUndefined(context);
161 @implementation NSArray (Cycript)
163 - (NSString *) cy$toJSON {
164 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
165 [json appendString:@"["];
168 for (id object in self) {
170 [json appendString:@","];
173 if (![object cy$isUndefined])
174 [json appendString:[object cy$toJSON]];
176 [json appendString:@","];
181 [json appendString:@"]"];
187 @implementation NSDictionary (Cycript)
189 - (NSString *) cy$toJSON {
190 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
191 [json appendString:@"({"];
194 for (id key in self) {
196 [json appendString:@","];
199 [json appendString:[key cy$toJSON]];
200 [json appendString:@":"];
201 NSObject *object([self objectForKey:key]);
202 [json appendString:[object cy$toJSON]];
205 [json appendString:@"})"];
211 @implementation NSNumber (Cycript)
213 - (NSString *) cy$toJSON {
214 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
217 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
218 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
221 - (void *) cy$symbol {
222 return [self pointerValue];
227 @implementation NSString (Cycript)
229 - (NSString *) cy$toJSON {
230 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
232 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
233 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
234 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
235 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
236 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
238 CFStringInsert(json, 0, CFSTR("\""));
239 CFStringAppend(json, CFSTR("\""));
241 return [reinterpret_cast<const NSString *>(json) autorelease];
244 - (void *) cy$symbol {
245 return dlsym(RTLD_DEFAULT, [self UTF8String]);
250 @interface CYJSObject : NSDictionary {
252 JSContextRef context_;
255 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
257 - (NSUInteger) count;
258 - (id) objectForKey:(id)key;
259 - (NSEnumerator *) keyEnumerator;
260 - (void) setObject:(id)object forKey:(id)key;
261 - (void) removeObjectForKey:(id)key;
265 @interface CYJSArray : NSArray {
267 JSContextRef context_;
270 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
272 - (NSUInteger) count;
273 - (id) objectAtIndex:(NSUInteger)index;
277 JSContextRef CYGetJSContext() {
282 @catch (id error) { \
283 CYThrow(context, error, exception); \
287 void CYThrow(JSContextRef context, JSValueRef value);
289 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
290 if (JSValueIsObjectOfClass(context, object, Instance_))
291 return reinterpret_cast<id>(JSObjectGetPrivate(object));
292 JSValueRef exception(NULL);
293 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
294 CYThrow(context, exception);
296 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
297 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
300 JSStringRef CYCopyJSString(id value) {
301 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
304 JSStringRef CYCopyJSString(const char *value) {
305 return JSStringCreateWithUTF8CString(value);
308 JSStringRef CYCopyJSString(JSStringRef value) {
309 return JSStringRetain(value);
312 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
313 JSValueRef exception(NULL);
314 JSStringRef string(JSValueToStringCopy(context, value, &exception));
315 CYThrow(context, exception);
319 // XXX: this is not a safe handle
325 template <typename Arg0_>
326 CYJSString(Arg0_ arg0) {
327 string_ = CYCopyJSString(arg0);
330 template <typename Arg0_, typename Arg1_>
331 CYJSString(Arg0_ arg0, Arg1_ arg1) {
332 string_ = CYCopyJSString(arg0, arg1);
336 JSStringRelease(string_);
339 operator JSStringRef() const {
344 CFStringRef CYCopyCFString(JSStringRef value) {
345 return JSStringCopyCFString(kCFAllocatorDefault, value);
348 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
349 return CYCopyCFString(CYJSString(context, value));
352 double CYCastDouble(JSContextRef context, JSValueRef value) {
353 JSValueRef exception(NULL);
354 double number(JSValueToNumber(context, value, &exception));
355 CYThrow(context, exception);
359 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
360 double number(CYCastDouble(context, value));
361 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
364 NSString *CYCastNSString(JSStringRef value) {
365 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
368 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
369 switch (JSType type = JSValueGetType(context, value)) {
370 case kJSTypeUndefined:
371 return CFRetain([WebUndefined undefined]);
375 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
377 return CYCopyCFNumber(context, value);
379 return CYCopyCFString(context, value);
381 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
383 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
387 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
388 size_t size(JSPropertyNameArrayGetCount(names));
389 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
390 for (size_t index(0); index != size; ++index)
391 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
395 id CYCastNSObject(JSContextRef context, JSValueRef value) {
396 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
397 return object == nil ? nil : [object autorelease];
400 void CYThrow(JSContextRef context, JSValueRef value) {
403 @throw CYCastNSObject(context, value);
406 JSValueRef CYCastJSValue(JSContextRef context, id value) {
407 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
410 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
411 *exception = CYCastJSValue(context, error);
414 @implementation CYJSObject
416 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
417 if ((self = [super init]) != nil) {
423 - (NSUInteger) count {
424 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
425 size_t size(JSPropertyNameArrayGetCount(names));
426 JSPropertyNameArrayRelease(names);
430 - (id) objectForKey:(id)key {
431 JSValueRef exception(NULL);
432 JSValueRef value(JSObjectGetProperty(context_, object_, CYJSString(key), &exception));
433 CYThrow(context_, exception);
434 return CYCastNSObject(context_, value);
437 - (NSEnumerator *) keyEnumerator {
438 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
439 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
440 JSPropertyNameArrayRelease(names);
444 - (void) setObject:(id)object forKey:(id)key {
445 JSValueRef exception(NULL);
446 JSObjectSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
447 CYThrow(context_, exception);
450 - (void) removeObjectForKey:(id)key {
451 JSValueRef exception(NULL);
452 // XXX: this returns a bool... throw exception, or ignore?
453 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
454 CYThrow(context_, exception);
459 @implementation CYJSArray
461 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
462 if ((self = [super init]) != nil) {
468 - (NSUInteger) count {
469 JSValueRef exception(NULL);
470 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
471 CYThrow(context_, exception);
472 return CYCastDouble(context_, value);
475 - (id) objectAtIndex:(NSUInteger)index {
476 JSValueRef exception(NULL);
477 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
478 CYThrow(context_, exception);
479 id object(CYCastNSObject(context_, value));
480 return object == nil ? [NSNull null] : object;
485 CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value) {
486 id object(CYCastNSObject(context, value));
487 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
490 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
492 case kCFSocketDataCallBack:
493 CFDataRef data(reinterpret_cast<CFDataRef>(value));
494 Client *client(reinterpret_cast<Client *>(info));
496 if (client->message_ == NULL)
497 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
499 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
500 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
501 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
502 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
504 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
505 CFRelease(client->message_);
507 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
510 JSStringRef script(JSStringCreateWithCFString(code));
513 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
514 JSStringRelease(script);
516 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
517 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
519 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result));
520 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
523 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
524 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
527 CFHTTPMessageSetBody(response, body);
530 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
533 CFSocketSendData(socket, NULL, serialized, 0);
534 CFRelease(serialized);
542 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
544 case kCFSocketAcceptCallBack:
545 Client *client(new Client());
547 client->message_ = NULL;
549 CFSocketContext context;
551 context.info = client;
552 context.retain = NULL;
553 context.release = NULL;
554 context.copyDescription = NULL;
556 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
558 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
563 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
565 NSString *name(CYCastNSString(property));
573 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
575 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
576 return CYMakeObject(context, [[data alloc] autorelease]);
585 void *operator new(size_t size) {
587 apr_pool_create(&pool, NULL);
588 void *data(apr_palloc(pool, size));
589 reinterpret_cast<ptrData *>(data)->pool_ = pool;
593 ptrData(void *value) :
599 struct ffiData : ptrData {
600 sig::Signature signature_;
603 ffiData(void (*value)(), const char *type) :
604 ptrData(reinterpret_cast<void *>(value))
606 sig::Parse(pool_, &signature_, type);
607 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
611 struct selData : ptrData {
618 static void Pointer_finalize(JSObjectRef object) {
619 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
620 apr_pool_destroy(data->pool_);
623 static void Instance_finalize(JSObjectRef object) {
624 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
628 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
629 ffiData *data(new ffiData(function, type));
630 return JSObjectMake(context, Functor_, data);
634 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
635 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
638 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
639 JSValueRef exception(NULL);
640 JSObjectSetProperty(context, object, CYJSString(name), value, kJSPropertyAttributeNone, &exception);
641 CYThrow(context, exception);
644 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
645 size_t size(JSStringGetMaximumUTF8CStringSize(value));
646 char *string(new(pool) char[size]);
647 JSStringGetUTF8CString(value, string, size);
648 JSStringRelease(value);
652 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
653 return CYPoolCString(pool, CYJSString(context, value));
656 // XXX: this macro is unhygenic
657 #define CYCastCString(context, value) ({ \
658 JSValueRef exception(NULL); \
659 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
660 CYThrow(context, exception); \
661 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
662 char *utf8(reinterpret_cast<char *>(alloca(size))); \
663 JSStringGetUTF8CString(string, utf8, size); \
664 JSStringRelease(string); \
668 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
669 if (JSValueIsNull(context, value))
671 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
672 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
673 return reinterpret_cast<SEL>(data->value_);
675 return sel_registerName(CYCastCString(context, value));
678 void *CYCastPointer(JSContextRef context, JSValueRef value) {
679 switch (JSValueGetType(context, value)) {
683 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
685 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
686 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
690 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
694 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
695 switch (type->primitive) {
697 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
700 #define CYPoolFFI_(primitive, native) \
701 case sig::primitive ## _P: \
702 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
705 CYPoolFFI_(uchar, unsigned char)
706 CYPoolFFI_(char, char)
707 CYPoolFFI_(ushort, unsigned short)
708 CYPoolFFI_(short, short)
709 CYPoolFFI_(ulong, unsigned long)
710 CYPoolFFI_(long, long)
711 CYPoolFFI_(uint, unsigned int)
713 CYPoolFFI_(ulonglong, unsigned long long)
714 CYPoolFFI_(longlong, long long)
715 CYPoolFFI_(float, float)
716 CYPoolFFI_(double, double)
719 case sig::typename_P:
720 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
723 case sig::selector_P:
724 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
728 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
732 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
742 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
747 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
750 switch (type->primitive) {
752 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
755 #define CYFromFFI_(primitive, native) \
756 case sig::primitive ## _P: \
757 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
760 CYFromFFI_(uchar, unsigned char)
761 CYFromFFI_(char, char)
762 CYFromFFI_(ushort, unsigned short)
763 CYFromFFI_(short, short)
764 CYFromFFI_(ulong, unsigned long)
765 CYFromFFI_(long, long)
766 CYFromFFI_(uint, unsigned int)
768 CYFromFFI_(ulonglong, unsigned long long)
769 CYFromFFI_(longlong, long long)
770 CYFromFFI_(float, float)
771 CYFromFFI_(double, double)
774 case sig::typename_P: {
775 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
778 case sig::selector_P: {
779 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
780 selData *data(new selData(sel));
781 value = JSObjectMake(context, Selector_, data);
785 case sig::pointer_P: {
786 if (void *pointer = *reinterpret_cast<void **>(data)) {
787 ptrData *data(new ptrData(pointer));
788 value = JSObjectMake(context, Pointer_, data);
792 case sig::string_P: {
793 if (char *utf8 = *reinterpret_cast<char **>(data))
794 value = JSValueMakeString(context, CYJSString(utf8));
802 value = JSValueMakeUndefined(context);
806 value = JSValueMakeNull(context);
810 NSLog(@"CYFromFFI(%c)\n", type->primitive);
817 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
819 if (count != signature->count - 1)
820 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
825 for (unsigned index(0); index != count; ++index) {
826 sig::Element *element(&signature->elements[index + 1]);
828 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
829 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
832 uint8_t value[cif->rtype->size];
833 ffi_call(cif, function, value, values);
835 return CYFromFFI(context, signature->elements[0].type, value);
839 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
841 NSString *name(CYCastNSString(property));
842 if (Class _class = NSClassFromString(name))
843 return CYMakeObject(context, _class);
844 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
845 switch ([[entry objectAtIndex:0] intValue]) {
847 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
849 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
852 sig::Signature signature;
853 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
854 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
860 bool stret(ffi_type *ffi_type) {
861 return ffi_type->type == FFI_TYPE_STRUCT && (
862 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
863 struct_forward_array[ffi_type->size] != 0
867 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
872 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
874 id self(CYCastNSObject(context, arguments[0]));
876 return JSValueMakeNull(context);
878 SEL _cmd(CYCastSEL(context, arguments[1]));
879 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
881 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
883 type = [[method _typeString] UTF8String];
888 sig::Signature signature;
889 sig::Parse(pool, &signature, type);
892 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
894 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
895 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
898 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
899 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
900 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
903 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
906 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
907 void *function(CYCastPointer(context, arguments[0]));
908 const char *type(CYCastCString(context, arguments[1]));
909 return CYMakeFunction(context, function, type);
913 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
914 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
915 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
918 static JSStaticValue Pointer_staticValues[2] = {
919 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
920 {NULL, NULL, NULL, 0}
923 CYDriver::CYDriver(const std::string &filename) :
933 CYDriver::~CYDriver() {
937 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
938 CYDriver::Error error;
939 error.location_ = location;
940 error.message_ = message;
941 driver.errors_.push_back(error);
944 MSInitialize { _pooled
947 NSCFBoolean_ = objc_getClass("NSCFBoolean");
951 struct sockaddr_in address;
952 address.sin_len = sizeof(address);
953 address.sin_family = AF_INET;
954 address.sin_addr.s_addr = INADDR_ANY;
955 address.sin_port = htons(10000 + pid);
957 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
959 CFSocketSignature signature;
960 signature.protocolFamily = AF_INET;
961 signature.socketType = SOCK_STREAM;
962 signature.protocol = IPPROTO_TCP;
963 signature.address = data;
965 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
966 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
968 JSClassDefinition definition;
970 definition = kJSClassDefinitionEmpty;
971 definition.className = "Pointer";
972 definition.staticValues = Pointer_staticValues;
973 definition.finalize = &Pointer_finalize;
974 Pointer_ = JSClassCreate(&definition);
976 definition = kJSClassDefinitionEmpty;
977 definition.className = "Functor";
978 definition.parentClass = Pointer_;
979 definition.callAsFunction = &ffi_callAsFunction;
980 Functor_ = JSClassCreate(&definition);
982 definition = kJSClassDefinitionEmpty;
983 definition.className = "Selector";
984 definition.parentClass = Pointer_;
985 Selector_ = JSClassCreate(&definition);
987 definition = kJSClassDefinitionEmpty;
988 definition.className = "Instance_";
989 definition.getProperty = &Instance_getProperty;
990 definition.callAsConstructor = &Instance_callAsConstructor;
991 definition.finalize = &Instance_finalize;
992 Instance_ = JSClassCreate(&definition);
994 definition = kJSClassDefinitionEmpty;
995 definition.getProperty = &Global_getProperty;
996 JSClassRef Global(JSClassCreate(&definition));
998 JSContextRef context(JSGlobalContextCreate(Global));
1001 JSObjectRef global(JSContextGetGlobalObject(context));
1003 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1005 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1007 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1009 name_ = JSStringCreateWithUTF8CString("name");
1010 message_ = JSStringCreateWithUTF8CString("message");
1011 length_ = JSStringCreateWithUTF8CString("length");
1013 JSValueRef exception(NULL);
1014 JSValueRef value(JSObjectGetProperty(CYGetJSContext(), global, CYJSString("Array"), &exception));
1015 CYThrow(context, exception);
1016 Array_ = JSValueToObject(CYGetJSContext(), value, &exception);
1017 CYThrow(context, exception);