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 "Pooling.hpp"
52 #include <CoreFoundation/CoreFoundation.h>
53 #include <CoreFoundation/CFLogUtilities.h>
55 #include <CFNetwork/CFNetwork.h>
56 #include <Foundation/Foundation.h>
58 #include <JavaScriptCore/JSBase.h>
59 #include <JavaScriptCore/JSValueRef.h>
60 #include <JavaScriptCore/JSObjectRef.h>
61 #include <JavaScriptCore/JSContextRef.h>
62 #include <JavaScriptCore/JSStringRef.h>
63 #include <JavaScriptCore/JSStringRefCF.h>
65 #include <WebKit/WebScriptObject.h>
67 #include <sys/types.h>
68 #include <sys/socket.h>
69 #include <netinet/in.h>
72 #include <ext/stdio_filebuf.h>
77 #include "Cycript.tab.hh"
82 #define _assert(test) do { \
84 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
87 #define _trace() do { \
88 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
92 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
94 static JSContextRef Context_;
96 static JSClassRef Functor_;
97 static JSClassRef Instance_;
98 static JSClassRef Pointer_;
99 static JSClassRef Selector_;
101 static JSObjectRef Array_;
103 static JSStringRef name_;
104 static JSStringRef message_;
105 static JSStringRef length_;
107 static Class NSCFBoolean_;
109 static NSMutableDictionary *Bridge_;
112 CFHTTPMessageRef message_;
116 JSObjectRef CYMakeObject(JSContextRef context, id object) {
117 return JSObjectMake(context, Instance_, [object retain]);
120 @interface NSMethodSignature (Cycript)
121 - (NSString *) _typeString;
124 @interface NSObject (Cycript)
125 - (NSString *) cy$toJSON;
126 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
129 @interface NSString (Cycript)
130 - (void *) cy$symbol;
133 @interface NSNumber (Cycript)
134 - (void *) cy$symbol;
137 @implementation NSObject (Cycript)
139 - (NSString *) cy$toJSON {
140 return [self description];
143 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
144 return CYMakeObject(context, self);
149 @implementation WebUndefined (Cycript)
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 [json appendString:[object cy$toJSON]];
176 [json appendString:@"]"];
182 @implementation NSDictionary (Cycript)
184 - (NSString *) cy$toJSON {
185 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
186 [json appendString:@"("];
187 [json appendString:@"{"];
190 for (id key in self) {
192 [json appendString:@","];
195 [json appendString:[key cy$toJSON]];
196 [json appendString:@":"];
197 NSObject *object([self objectForKey:key]);
198 [json appendString:[object cy$toJSON]];
201 [json appendString:@"})"];
207 @implementation NSNumber (Cycript)
209 - (NSString *) cy$toJSON {
210 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
213 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
214 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
217 - (void *) cy$symbol {
218 return [self pointerValue];
223 @implementation NSString (Cycript)
225 - (NSString *) cy$toJSON {
226 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
228 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
229 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
230 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
231 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
232 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
234 CFStringInsert(json, 0, CFSTR("\""));
235 CFStringAppend(json, CFSTR("\""));
237 return [reinterpret_cast<const NSString *>(json) autorelease];
240 - (void *) cy$symbol {
241 return dlsym(RTLD_DEFAULT, [self UTF8String]);
246 @interface CYJSObject : NSDictionary {
248 JSContextRef context_;
251 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
253 - (NSUInteger) count;
254 - (id) objectForKey:(id)key;
255 - (NSEnumerator *) keyEnumerator;
256 - (void) setObject:(id)object forKey:(id)key;
257 - (void) removeObjectForKey:(id)key;
261 @interface CYJSArray : NSArray {
263 JSContextRef context_;
266 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
268 - (NSUInteger) count;
269 - (id) objectAtIndex:(NSUInteger)index;
273 JSContextRef JSGetContext() {
278 @catch (id error) { \
279 CYThrow(context, error, exception); \
283 void CYThrow(JSContextRef context, JSValueRef value);
285 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
286 if (JSValueIsObjectOfClass(context, object, Instance_))
287 return reinterpret_cast<id>(JSObjectGetPrivate(object));
288 JSValueRef exception(NULL);
289 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
290 CYThrow(context, exception);
292 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
293 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
296 JSStringRef CYCopyJSString(id value) {
297 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
300 JSStringRef CYCopyJSString(const char *value) {
301 return JSStringCreateWithUTF8CString(value);
304 JSStringRef CYCopyJSString(JSStringRef value) {
305 return JSStringRetain(value);
308 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
309 JSValueRef exception(NULL);
310 JSStringRef string(JSValueToStringCopy(context, value, &exception));
311 CYThrow(context, exception);
315 // XXX: this is not a safe handle
321 template <typename Arg0_>
322 CYJSString(Arg0_ arg0) {
323 string_ = CYCopyJSString(arg0);
326 template <typename Arg0_, typename Arg1_>
327 CYJSString(Arg0_ arg0, Arg1_ arg1) {
328 string_ = CYCopyJSString(arg0, arg1);
332 JSStringRelease(string_);
335 operator JSStringRef() const {
340 CFStringRef CYCopyCFString(JSStringRef value) {
341 return JSStringCopyCFString(kCFAllocatorDefault, value);
344 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
345 return CYCopyCFString(CYJSString(context, value));
348 double CYCastDouble(JSContextRef context, JSValueRef value) {
349 JSValueRef exception(NULL);
350 double number(JSValueToNumber(context, value, &exception));
351 CYThrow(context, exception);
355 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
356 double number(CYCastDouble(context, value));
357 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
360 NSString *CYCastNSString(JSStringRef value) {
361 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
364 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
365 switch (JSType type = JSValueGetType(context, value)) {
366 case kJSTypeUndefined:
367 return CFRetain([WebUndefined undefined]);
371 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
373 return CYCopyCFNumber(context, value);
375 return CYCopyCFString(context, value);
377 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
379 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
383 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
384 size_t size(JSPropertyNameArrayGetCount(names));
385 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
386 for (size_t index(0); index != size; ++index)
387 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
391 id CYCastNSObject(JSContextRef context, JSValueRef value) {
392 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
393 return object == nil ? nil : [object autorelease];
396 void CYThrow(JSContextRef context, JSValueRef value) {
399 @throw CYCastNSObject(context, value);
402 JSValueRef CYCastJSValue(JSContextRef context, id value) {
403 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
406 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
407 *exception = CYCastJSValue(context, error);
410 @implementation CYJSObject
412 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
413 if ((self = [super init]) != nil) {
419 - (NSUInteger) count {
420 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
421 size_t size(JSPropertyNameArrayGetCount(names));
422 JSPropertyNameArrayRelease(names);
426 - (id) objectForKey:(id)key {
427 JSValueRef exception(NULL);
428 JSValueRef value(JSObjectGetProperty(context_, object_, CYJSString(key), &exception));
429 CYThrow(context_, exception);
430 return CYCastNSObject(context_, value);
433 - (NSEnumerator *) keyEnumerator {
434 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
435 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
436 JSPropertyNameArrayRelease(names);
440 - (void) setObject:(id)object forKey:(id)key {
441 JSValueRef exception(NULL);
442 JSObjectSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
443 CYThrow(context_, exception);
446 - (void) removeObjectForKey:(id)key {
447 JSValueRef exception(NULL);
448 // XXX: this returns a bool... throw exception, or ignore?
449 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
450 CYThrow(context_, exception);
455 @implementation CYJSArray
457 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
458 if ((self = [super init]) != nil) {
464 - (NSUInteger) count {
465 JSValueRef exception(NULL);
466 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
467 CYThrow(context_, exception);
468 return CYCastDouble(context_, value);
471 - (id) objectAtIndex:(NSUInteger)index {
472 JSValueRef exception(NULL);
473 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
474 CYThrow(context_, exception);
475 id object(CYCastNSObject(context_, value));
476 return object == nil ? [NSNull null] : object;
481 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
482 id object(CYCastNSObject(context, value));
483 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
486 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
488 case kCFSocketDataCallBack:
489 CFDataRef data(reinterpret_cast<CFDataRef>(value));
490 Client *client(reinterpret_cast<Client *>(info));
492 if (client->message_ == NULL)
493 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
495 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
496 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
497 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
498 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
500 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
501 CFRelease(client->message_);
503 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
506 JSStringRef script(JSStringCreateWithCFString(code));
509 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
510 JSStringRelease(script);
512 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
513 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
515 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
516 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
519 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
520 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
523 CFHTTPMessageSetBody(response, body);
526 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
529 CFSocketSendData(socket, NULL, serialized, 0);
530 CFRelease(serialized);
538 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
540 case kCFSocketAcceptCallBack:
541 Client *client(new Client());
543 client->message_ = NULL;
545 CFSocketContext context;
547 context.info = client;
548 context.retain = NULL;
549 context.release = NULL;
550 context.copyDescription = NULL;
552 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
554 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
559 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
561 NSString *name(CYCastNSString(property));
569 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
571 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
572 return CYMakeObject(context, [[data alloc] autorelease]);
581 void *operator new(size_t size) {
583 apr_pool_create(&pool, NULL);
584 void *data(apr_palloc(pool, size));
585 reinterpret_cast<ptrData *>(data)->pool_ = pool;
589 ptrData(void *value) :
595 struct ffiData : ptrData {
596 sig::Signature signature_;
599 ffiData(void (*value)(), const char *type) :
600 ptrData(reinterpret_cast<void *>(value))
602 sig::Parse(pool_, &signature_, type);
603 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
607 struct selData : ptrData {
614 static void Pointer_finalize(JSObjectRef object) {
615 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
616 apr_pool_destroy(data->pool_);
619 static void Instance_finalize(JSObjectRef object) {
620 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
624 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
625 ffiData *data(new ffiData(function, type));
626 return JSObjectMake(context, Functor_, data);
630 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
631 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
634 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
635 JSValueRef exception(NULL);
636 JSObjectSetProperty(context, object, CYJSString(name), value, kJSPropertyAttributeNone, &exception);
637 CYThrow(context, exception);
640 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
641 size_t size(JSStringGetMaximumUTF8CStringSize(value));
642 char *string(new(pool) char[size]);
643 JSStringGetUTF8CString(value, string, size);
644 JSStringRelease(value);
648 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
649 return CYPoolCString(pool, CYJSString(context, value));
652 // XXX: this macro is unhygenic
653 #define CYCastCString(context, value) ({ \
654 JSValueRef exception(NULL); \
655 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
656 CYThrow(context, exception); \
657 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
658 char *utf8(reinterpret_cast<char *>(alloca(size))); \
659 JSStringGetUTF8CString(string, utf8, size); \
660 JSStringRelease(string); \
664 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
665 if (JSValueIsNull(context, value))
667 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
668 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
669 return reinterpret_cast<SEL>(data->value_);
671 return sel_registerName(CYCastCString(context, value));
674 void *CYCastPointer(JSContextRef context, JSValueRef value) {
675 switch (JSValueGetType(context, value)) {
679 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
681 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
682 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
686 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
690 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
691 switch (type->primitive) {
693 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
696 #define CYPoolFFI_(primitive, native) \
697 case sig::primitive ## _P: \
698 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
701 CYPoolFFI_(uchar, unsigned char)
702 CYPoolFFI_(char, char)
703 CYPoolFFI_(ushort, unsigned short)
704 CYPoolFFI_(short, short)
705 CYPoolFFI_(ulong, unsigned long)
706 CYPoolFFI_(long, long)
707 CYPoolFFI_(uint, unsigned int)
709 CYPoolFFI_(ulonglong, unsigned long long)
710 CYPoolFFI_(longlong, long long)
711 CYPoolFFI_(float, float)
712 CYPoolFFI_(double, double)
715 case sig::typename_P:
716 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
719 case sig::selector_P:
720 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
724 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
728 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
738 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
743 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
746 switch (type->primitive) {
748 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
751 #define CYFromFFI_(primitive, native) \
752 case sig::primitive ## _P: \
753 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
756 CYFromFFI_(uchar, unsigned char)
757 CYFromFFI_(char, char)
758 CYFromFFI_(ushort, unsigned short)
759 CYFromFFI_(short, short)
760 CYFromFFI_(ulong, unsigned long)
761 CYFromFFI_(long, long)
762 CYFromFFI_(uint, unsigned int)
764 CYFromFFI_(ulonglong, unsigned long long)
765 CYFromFFI_(longlong, long long)
766 CYFromFFI_(float, float)
767 CYFromFFI_(double, double)
770 case sig::typename_P: {
771 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
774 case sig::selector_P: {
775 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
776 selData *data(new selData(sel));
777 value = JSObjectMake(context, Selector_, data);
781 case sig::pointer_P: {
782 if (void *pointer = *reinterpret_cast<void **>(data)) {
783 ptrData *data(new ptrData(pointer));
784 value = JSObjectMake(context, Pointer_, data);
788 case sig::string_P: {
789 if (char *utf8 = *reinterpret_cast<char **>(data))
790 value = JSValueMakeString(context, CYJSString(utf8));
798 value = JSValueMakeUndefined(context);
802 value = JSValueMakeNull(context);
806 NSLog(@"CYFromFFI(%c)\n", type->primitive);
813 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
815 if (count != signature->count - 1)
816 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
821 for (unsigned index(0); index != count; ++index) {
822 sig::Element *element(&signature->elements[index + 1]);
824 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
825 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
828 uint8_t value[cif->rtype->size];
829 ffi_call(cif, function, value, values);
831 return CYFromFFI(context, signature->elements[0].type, value);
835 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
837 NSString *name(CYCastNSString(property));
838 if (Class _class = NSClassFromString(name))
839 return CYMakeObject(context, _class);
840 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
841 switch ([[entry objectAtIndex:0] intValue]) {
843 return JSEvaluateScript(JSGetContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
845 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
848 sig::Signature signature;
849 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
850 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
856 bool stret(ffi_type *ffi_type) {
857 return ffi_type->type == FFI_TYPE_STRUCT && (
858 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
859 struct_forward_array[ffi_type->size] != 0
863 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
868 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
870 id self(CYCastNSObject(context, arguments[0]));
872 return JSValueMakeNull(context);
874 SEL _cmd(CYCastSEL(context, arguments[1]));
875 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
877 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
879 type = [[method _typeString] UTF8String];
884 sig::Signature signature;
885 sig::Parse(pool, &signature, type);
888 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
890 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
891 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
894 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
895 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
896 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
899 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
902 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
903 void *function(CYCastPointer(context, arguments[0]));
904 const char *type(CYCastCString(context, arguments[1]));
905 return CYMakeFunction(context, function, type);
909 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
910 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
911 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
914 static JSStaticValue Pointer_staticValues[2] = {
915 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
916 {NULL, NULL, NULL, 0}
919 CYDriver::CYDriver(const std::string &filename) :
926 CYDriver::~CYDriver() {
932 void cy::parser::error(const cy::parser::location_type &loc, const std::string &msg) {
933 std::cerr << loc << ": " << msg << std::endl;
936 void CYConsole(FILE *fin, FILE *fout, FILE *ferr) {
938 CYDriver driver("<stdin>");
939 cy::parser parser(driver);
940 if (parser.parse() == 0)
941 driver.source_->Part(std::cout);
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(JSGetContext(), global, CYJSString("Array"), &exception));
1015 CYThrow(context, exception);
1016 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1017 CYThrow(context, exception);