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:@"("];
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 JSContextRef CYGetJSContext() {
283 @catch (id error) { \
284 CYThrow(context, error, exception); \
288 void CYThrow(JSContextRef context, JSValueRef value);
290 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
291 if (JSValueIsObjectOfClass(context, object, Instance_))
292 return reinterpret_cast<id>(JSObjectGetPrivate(object));
293 JSValueRef exception(NULL);
294 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
295 CYThrow(context, exception);
297 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
298 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
301 JSStringRef CYCopyJSString(id value) {
302 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
305 JSStringRef CYCopyJSString(const char *value) {
306 return JSStringCreateWithUTF8CString(value);
309 JSStringRef CYCopyJSString(JSStringRef value) {
310 return JSStringRetain(value);
313 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
314 JSValueRef exception(NULL);
315 JSStringRef string(JSValueToStringCopy(context, value, &exception));
316 CYThrow(context, exception);
320 // XXX: this is not a safe handle
326 template <typename Arg0_>
327 CYJSString(Arg0_ arg0) {
328 string_ = CYCopyJSString(arg0);
331 template <typename Arg0_, typename Arg1_>
332 CYJSString(Arg0_ arg0, Arg1_ arg1) {
333 string_ = CYCopyJSString(arg0, arg1);
337 JSStringRelease(string_);
340 operator JSStringRef() const {
345 CFStringRef CYCopyCFString(JSStringRef value) {
346 return JSStringCopyCFString(kCFAllocatorDefault, value);
349 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
350 return CYCopyCFString(CYJSString(context, value));
353 double CYCastDouble(JSContextRef context, JSValueRef value) {
354 JSValueRef exception(NULL);
355 double number(JSValueToNumber(context, value, &exception));
356 CYThrow(context, exception);
360 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
361 double number(CYCastDouble(context, value));
362 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
365 NSString *CYCastNSString(JSStringRef value) {
366 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
369 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
370 switch (JSType type = JSValueGetType(context, value)) {
371 case kJSTypeUndefined:
372 return CFRetain([WebUndefined undefined]);
376 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
378 return CYCopyCFNumber(context, value);
380 return CYCopyCFString(context, value);
382 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
384 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
388 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
389 size_t size(JSPropertyNameArrayGetCount(names));
390 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
391 for (size_t index(0); index != size; ++index)
392 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
396 id CYCastNSObject(JSContextRef context, JSValueRef value) {
397 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
398 return object == nil ? nil : [object autorelease];
401 void CYThrow(JSContextRef context, JSValueRef value) {
404 @throw CYCastNSObject(context, value);
407 JSValueRef CYCastJSValue(JSContextRef context, id value) {
408 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
411 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
412 *exception = CYCastJSValue(context, error);
415 @implementation CYJSObject
417 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
418 if ((self = [super init]) != nil) {
424 - (NSUInteger) count {
425 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
426 size_t size(JSPropertyNameArrayGetCount(names));
427 JSPropertyNameArrayRelease(names);
431 - (id) objectForKey:(id)key {
432 JSValueRef exception(NULL);
433 JSValueRef value(JSObjectGetProperty(context_, object_, CYJSString(key), &exception));
434 CYThrow(context_, exception);
435 return CYCastNSObject(context_, value);
438 - (NSEnumerator *) keyEnumerator {
439 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
440 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
441 JSPropertyNameArrayRelease(names);
445 - (void) setObject:(id)object forKey:(id)key {
446 JSValueRef exception(NULL);
447 JSObjectSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
448 CYThrow(context_, exception);
451 - (void) removeObjectForKey:(id)key {
452 JSValueRef exception(NULL);
453 // XXX: this returns a bool... throw exception, or ignore?
454 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
455 CYThrow(context_, exception);
460 @implementation CYJSArray
462 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
463 if ((self = [super init]) != nil) {
469 - (NSUInteger) count {
470 JSValueRef exception(NULL);
471 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
472 CYThrow(context_, exception);
473 return CYCastDouble(context_, value);
476 - (id) objectAtIndex:(NSUInteger)index {
477 JSValueRef exception(NULL);
478 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
479 CYThrow(context_, exception);
480 id object(CYCastNSObject(context_, value));
481 return object == nil ? [NSNull null] : object;
486 CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value) {
487 id object(CYCastNSObject(context, value));
488 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
491 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
493 case kCFSocketDataCallBack:
494 CFDataRef data(reinterpret_cast<CFDataRef>(value));
495 Client *client(reinterpret_cast<Client *>(info));
497 if (client->message_ == NULL)
498 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
500 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
501 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
502 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
503 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
505 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
506 CFRelease(client->message_);
508 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
511 JSStringRef script(JSStringCreateWithCFString(code));
514 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
515 JSStringRelease(script);
517 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
518 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
520 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result));
521 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
524 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
525 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
528 CFHTTPMessageSetBody(response, body);
531 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
534 CFSocketSendData(socket, NULL, serialized, 0);
535 CFRelease(serialized);
543 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
545 case kCFSocketAcceptCallBack:
546 Client *client(new Client());
548 client->message_ = NULL;
550 CFSocketContext context;
552 context.info = client;
553 context.retain = NULL;
554 context.release = NULL;
555 context.copyDescription = NULL;
557 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
559 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
564 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
566 NSString *name(CYCastNSString(property));
574 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
576 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
577 return CYMakeObject(context, [[data alloc] autorelease]);
586 void *operator new(size_t size) {
588 apr_pool_create(&pool, NULL);
589 void *data(apr_palloc(pool, size));
590 reinterpret_cast<ptrData *>(data)->pool_ = pool;
594 ptrData(void *value) :
600 struct ffiData : ptrData {
601 sig::Signature signature_;
604 ffiData(void (*value)(), const char *type) :
605 ptrData(reinterpret_cast<void *>(value))
607 sig::Parse(pool_, &signature_, type);
608 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
612 struct selData : ptrData {
619 static void Pointer_finalize(JSObjectRef object) {
620 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
621 apr_pool_destroy(data->pool_);
624 static void Instance_finalize(JSObjectRef object) {
625 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
629 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
630 ffiData *data(new ffiData(function, type));
631 return JSObjectMake(context, Functor_, data);
635 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
636 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
639 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
640 JSValueRef exception(NULL);
641 JSObjectSetProperty(context, object, CYJSString(name), value, kJSPropertyAttributeNone, &exception);
642 CYThrow(context, exception);
645 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
646 size_t size(JSStringGetMaximumUTF8CStringSize(value));
647 char *string(new(pool) char[size]);
648 JSStringGetUTF8CString(value, string, size);
649 JSStringRelease(value);
653 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
654 return CYPoolCString(pool, CYJSString(context, value));
657 // XXX: this macro is unhygenic
658 #define CYCastCString(context, value) ({ \
659 JSValueRef exception(NULL); \
660 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
661 CYThrow(context, exception); \
662 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
663 char *utf8(reinterpret_cast<char *>(alloca(size))); \
664 JSStringGetUTF8CString(string, utf8, size); \
665 JSStringRelease(string); \
669 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
670 if (JSValueIsNull(context, value))
672 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
673 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
674 return reinterpret_cast<SEL>(data->value_);
676 return sel_registerName(CYCastCString(context, value));
679 void *CYCastPointer(JSContextRef context, JSValueRef value) {
680 switch (JSValueGetType(context, value)) {
684 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
686 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
687 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
691 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
695 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
696 switch (type->primitive) {
698 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
701 #define CYPoolFFI_(primitive, native) \
702 case sig::primitive ## _P: \
703 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
706 CYPoolFFI_(uchar, unsigned char)
707 CYPoolFFI_(char, char)
708 CYPoolFFI_(ushort, unsigned short)
709 CYPoolFFI_(short, short)
710 CYPoolFFI_(ulong, unsigned long)
711 CYPoolFFI_(long, long)
712 CYPoolFFI_(uint, unsigned int)
714 CYPoolFFI_(ulonglong, unsigned long long)
715 CYPoolFFI_(longlong, long long)
716 CYPoolFFI_(float, float)
717 CYPoolFFI_(double, double)
720 case sig::typename_P:
721 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
724 case sig::selector_P:
725 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
729 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
733 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
743 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
748 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
751 switch (type->primitive) {
753 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
756 #define CYFromFFI_(primitive, native) \
757 case sig::primitive ## _P: \
758 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
761 CYFromFFI_(uchar, unsigned char)
762 CYFromFFI_(char, char)
763 CYFromFFI_(ushort, unsigned short)
764 CYFromFFI_(short, short)
765 CYFromFFI_(ulong, unsigned long)
766 CYFromFFI_(long, long)
767 CYFromFFI_(uint, unsigned int)
769 CYFromFFI_(ulonglong, unsigned long long)
770 CYFromFFI_(longlong, long long)
771 CYFromFFI_(float, float)
772 CYFromFFI_(double, double)
775 case sig::typename_P: {
776 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
779 case sig::selector_P: {
780 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
781 selData *data(new selData(sel));
782 value = JSObjectMake(context, Selector_, data);
786 case sig::pointer_P: {
787 if (void *pointer = *reinterpret_cast<void **>(data)) {
788 ptrData *data(new ptrData(pointer));
789 value = JSObjectMake(context, Pointer_, data);
793 case sig::string_P: {
794 if (char *utf8 = *reinterpret_cast<char **>(data))
795 value = JSValueMakeString(context, CYJSString(utf8));
803 value = JSValueMakeUndefined(context);
807 value = JSValueMakeNull(context);
811 NSLog(@"CYFromFFI(%c)\n", type->primitive);
818 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
820 if (count != signature->count - 1)
821 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
826 for (unsigned index(0); index != count; ++index) {
827 sig::Element *element(&signature->elements[index + 1]);
829 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
830 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
833 uint8_t value[cif->rtype->size];
834 ffi_call(cif, function, value, values);
836 return CYFromFFI(context, signature->elements[0].type, value);
840 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
842 NSString *name(CYCastNSString(property));
843 if (Class _class = NSClassFromString(name))
844 return CYMakeObject(context, _class);
845 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
846 switch ([[entry objectAtIndex:0] intValue]) {
848 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
850 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
853 sig::Signature signature;
854 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
855 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
861 bool stret(ffi_type *ffi_type) {
862 return ffi_type->type == FFI_TYPE_STRUCT && (
863 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
864 struct_forward_array[ffi_type->size] != 0
868 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
873 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
875 id self(CYCastNSObject(context, arguments[0]));
877 return JSValueMakeNull(context);
879 SEL _cmd(CYCastSEL(context, arguments[1]));
880 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
882 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
884 type = [[method _typeString] UTF8String];
889 sig::Signature signature;
890 sig::Parse(pool, &signature, type);
893 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
895 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
896 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
899 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
900 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
901 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
904 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
907 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
908 void *function(CYCastPointer(context, arguments[0]));
909 const char *type(CYCastCString(context, arguments[1]));
910 return CYMakeFunction(context, function, type);
914 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
915 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
916 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
919 static JSStaticValue Pointer_staticValues[2] = {
920 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
921 {NULL, NULL, NULL, 0}
924 CYDriver::CYDriver(const std::string &filename) :
934 CYDriver::~CYDriver() {
938 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
939 CYDriver::Error error;
940 error.location_ = location;
941 error.message_ = message;
942 driver.errors_.push_back(error);
945 MSInitialize { _pooled
948 NSCFBoolean_ = objc_getClass("NSCFBoolean");
952 struct sockaddr_in address;
953 address.sin_len = sizeof(address);
954 address.sin_family = AF_INET;
955 address.sin_addr.s_addr = INADDR_ANY;
956 address.sin_port = htons(10000 + pid);
958 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
960 CFSocketSignature signature;
961 signature.protocolFamily = AF_INET;
962 signature.socketType = SOCK_STREAM;
963 signature.protocol = IPPROTO_TCP;
964 signature.address = data;
966 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
967 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
969 JSClassDefinition definition;
971 definition = kJSClassDefinitionEmpty;
972 definition.className = "Pointer";
973 definition.staticValues = Pointer_staticValues;
974 definition.finalize = &Pointer_finalize;
975 Pointer_ = JSClassCreate(&definition);
977 definition = kJSClassDefinitionEmpty;
978 definition.className = "Functor";
979 definition.parentClass = Pointer_;
980 definition.callAsFunction = &ffi_callAsFunction;
981 Functor_ = JSClassCreate(&definition);
983 definition = kJSClassDefinitionEmpty;
984 definition.className = "Selector";
985 definition.parentClass = Pointer_;
986 Selector_ = JSClassCreate(&definition);
988 definition = kJSClassDefinitionEmpty;
989 definition.className = "Instance_";
990 definition.getProperty = &Instance_getProperty;
991 definition.callAsConstructor = &Instance_callAsConstructor;
992 definition.finalize = &Instance_finalize;
993 Instance_ = JSClassCreate(&definition);
995 definition = kJSClassDefinitionEmpty;
996 definition.getProperty = &Global_getProperty;
997 JSClassRef Global(JSClassCreate(&definition));
999 JSContextRef context(JSGlobalContextCreate(Global));
1002 JSObjectRef global(JSContextGetGlobalObject(context));
1004 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1006 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1008 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1010 name_ = JSStringCreateWithUTF8CString("name");
1011 message_ = JSStringCreateWithUTF8CString("message");
1012 length_ = JSStringCreateWithUTF8CString("length");
1014 JSValueRef exception(NULL);
1015 JSValueRef value(JSObjectGetProperty(CYGetJSContext(), global, CYJSString("Array"), &exception));
1016 CYThrow(context, exception);
1017 Array_ = JSValueToObject(CYGetJSContext(), value, &exception);
1018 CYThrow(context, exception);