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>
78 #include "Cycript.tab.hh"
83 #define _assert(test) do { \
85 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
88 #define _trace() do { \
89 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
93 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
95 static JSContextRef Context_;
97 static JSClassRef Functor_;
98 static JSClassRef Instance_;
99 static JSClassRef Pointer_;
100 static JSClassRef Selector_;
102 static JSObjectRef Array_;
104 static JSStringRef name_;
105 static JSStringRef message_;
106 static JSStringRef length_;
108 static Class NSCFBoolean_;
110 static NSMutableDictionary *Bridge_;
113 CFHTTPMessageRef message_;
117 JSObjectRef CYMakeObject(JSContextRef context, id object) {
118 return JSObjectMake(context, Instance_, [object retain]);
121 @interface NSMethodSignature (Cycript)
122 - (NSString *) _typeString;
125 @interface NSObject (Cycript)
126 - (NSString *) cy$toJSON;
127 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
130 @interface NSString (Cycript)
131 - (void *) cy$symbol;
134 @interface NSNumber (Cycript)
135 - (void *) cy$symbol;
138 @implementation NSObject (Cycript)
140 - (NSString *) cy$toJSON {
141 return [self description];
144 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
145 return CYMakeObject(context, self);
150 @implementation WebUndefined (Cycript)
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 [json appendString:[object cy$toJSON]];
177 [json appendString:@"]"];
183 @implementation NSDictionary (Cycript)
185 - (NSString *) cy$toJSON {
186 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
187 [json appendString:@"("];
188 [json appendString:@"{"];
191 for (id key in self) {
193 [json appendString:@","];
196 [json appendString:[key cy$toJSON]];
197 [json appendString:@":"];
198 NSObject *object([self objectForKey:key]);
199 [json appendString:[object cy$toJSON]];
202 [json appendString:@"})"];
208 @implementation NSNumber (Cycript)
210 - (NSString *) cy$toJSON {
211 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
214 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
215 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
218 - (void *) cy$symbol {
219 return [self pointerValue];
224 @implementation NSString (Cycript)
226 - (NSString *) cy$toJSON {
227 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
229 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
230 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
231 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
232 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
233 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
235 CFStringInsert(json, 0, CFSTR("\""));
236 CFStringAppend(json, CFSTR("\""));
238 return [reinterpret_cast<const NSString *>(json) autorelease];
241 - (void *) cy$symbol {
242 return dlsym(RTLD_DEFAULT, [self UTF8String]);
247 @interface CYJSObject : NSDictionary {
249 JSContextRef context_;
252 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
254 - (NSUInteger) count;
255 - (id) objectForKey:(id)key;
256 - (NSEnumerator *) keyEnumerator;
257 - (void) setObject:(id)object forKey:(id)key;
258 - (void) removeObjectForKey:(id)key;
262 @interface CYJSArray : NSArray {
264 JSContextRef context_;
267 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
269 - (NSUInteger) count;
270 - (id) objectAtIndex:(NSUInteger)index;
274 JSContextRef JSGetContext() {
279 @catch (id error) { \
280 CYThrow(context, error, exception); \
284 void CYThrow(JSContextRef context, JSValueRef value);
286 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
287 if (JSValueIsObjectOfClass(context, object, Instance_))
288 return reinterpret_cast<id>(JSObjectGetPrivate(object));
289 JSValueRef exception(NULL);
290 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
291 CYThrow(context, exception);
293 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
294 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
297 JSStringRef CYCopyJSString(id value) {
298 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
301 JSStringRef CYCopyJSString(const char *value) {
302 return JSStringCreateWithUTF8CString(value);
305 JSStringRef CYCopyJSString(JSStringRef value) {
306 return JSStringRetain(value);
309 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
310 JSValueRef exception(NULL);
311 JSStringRef string(JSValueToStringCopy(context, value, &exception));
312 CYThrow(context, exception);
316 // XXX: this is not a safe handle
322 template <typename Arg0_>
323 CYJSString(Arg0_ arg0) {
324 string_ = CYCopyJSString(arg0);
327 template <typename Arg0_, typename Arg1_>
328 CYJSString(Arg0_ arg0, Arg1_ arg1) {
329 string_ = CYCopyJSString(arg0, arg1);
333 JSStringRelease(string_);
336 operator JSStringRef() const {
341 CFStringRef CYCopyCFString(JSStringRef value) {
342 return JSStringCopyCFString(kCFAllocatorDefault, value);
345 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
346 return CYCopyCFString(CYJSString(context, value));
349 double CYCastDouble(JSContextRef context, JSValueRef value) {
350 JSValueRef exception(NULL);
351 double number(JSValueToNumber(context, value, &exception));
352 CYThrow(context, exception);
356 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
357 double number(CYCastDouble(context, value));
358 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
361 NSString *CYCastNSString(JSStringRef value) {
362 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
365 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
366 switch (JSType type = JSValueGetType(context, value)) {
367 case kJSTypeUndefined:
368 return CFRetain([WebUndefined undefined]);
372 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
374 return CYCopyCFNumber(context, value);
376 return CYCopyCFString(context, value);
378 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
380 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
384 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
385 size_t size(JSPropertyNameArrayGetCount(names));
386 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
387 for (size_t index(0); index != size; ++index)
388 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
392 id CYCastNSObject(JSContextRef context, JSValueRef value) {
393 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
394 return object == nil ? nil : [object autorelease];
397 void CYThrow(JSContextRef context, JSValueRef value) {
400 @throw CYCastNSObject(context, value);
403 JSValueRef CYCastJSValue(JSContextRef context, id value) {
404 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
407 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
408 *exception = CYCastJSValue(context, error);
411 @implementation CYJSObject
413 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
414 if ((self = [super init]) != nil) {
420 - (NSUInteger) count {
421 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
422 size_t size(JSPropertyNameArrayGetCount(names));
423 JSPropertyNameArrayRelease(names);
427 - (id) objectForKey:(id)key {
428 JSValueRef exception(NULL);
429 JSValueRef value(JSObjectGetProperty(context_, object_, CYJSString(key), &exception));
430 CYThrow(context_, exception);
431 return CYCastNSObject(context_, value);
434 - (NSEnumerator *) keyEnumerator {
435 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
436 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
437 JSPropertyNameArrayRelease(names);
441 - (void) setObject:(id)object forKey:(id)key {
442 JSValueRef exception(NULL);
443 JSObjectSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
444 CYThrow(context_, exception);
447 - (void) removeObjectForKey:(id)key {
448 JSValueRef exception(NULL);
449 // XXX: this returns a bool... throw exception, or ignore?
450 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
451 CYThrow(context_, exception);
456 @implementation CYJSArray
458 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
459 if ((self = [super init]) != nil) {
465 - (NSUInteger) count {
466 JSValueRef exception(NULL);
467 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
468 CYThrow(context_, exception);
469 return CYCastDouble(context_, value);
472 - (id) objectAtIndex:(NSUInteger)index {
473 JSValueRef exception(NULL);
474 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
475 CYThrow(context_, exception);
476 id object(CYCastNSObject(context_, value));
477 return object == nil ? [NSNull null] : object;
482 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
483 id object(CYCastNSObject(context, value));
484 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
487 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
489 case kCFSocketDataCallBack:
490 CFDataRef data(reinterpret_cast<CFDataRef>(value));
491 Client *client(reinterpret_cast<Client *>(info));
493 if (client->message_ == NULL)
494 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
496 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
497 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
498 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
499 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
501 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
502 CFRelease(client->message_);
504 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
507 JSStringRef script(JSStringCreateWithCFString(code));
510 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
511 JSStringRelease(script);
513 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
514 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
516 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
517 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
520 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
521 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
524 CFHTTPMessageSetBody(response, body);
527 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
530 CFSocketSendData(socket, NULL, serialized, 0);
531 CFRelease(serialized);
539 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
541 case kCFSocketAcceptCallBack:
542 Client *client(new Client());
544 client->message_ = NULL;
546 CFSocketContext context;
548 context.info = client;
549 context.retain = NULL;
550 context.release = NULL;
551 context.copyDescription = NULL;
553 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
555 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
560 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
562 NSString *name(CYCastNSString(property));
570 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
572 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
573 return CYMakeObject(context, [[data alloc] autorelease]);
582 void *operator new(size_t size) {
584 apr_pool_create(&pool, NULL);
585 void *data(apr_palloc(pool, size));
586 reinterpret_cast<ptrData *>(data)->pool_ = pool;
590 ptrData(void *value) :
596 struct ffiData : ptrData {
597 sig::Signature signature_;
600 ffiData(void (*value)(), const char *type) :
601 ptrData(reinterpret_cast<void *>(value))
603 sig::Parse(pool_, &signature_, type);
604 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
608 struct selData : ptrData {
615 static void Pointer_finalize(JSObjectRef object) {
616 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
617 apr_pool_destroy(data->pool_);
620 static void Instance_finalize(JSObjectRef object) {
621 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
625 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
626 ffiData *data(new ffiData(function, type));
627 return JSObjectMake(context, Functor_, data);
631 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
632 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
635 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
636 JSValueRef exception(NULL);
637 JSObjectSetProperty(context, object, CYJSString(name), value, kJSPropertyAttributeNone, &exception);
638 CYThrow(context, exception);
641 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
642 size_t size(JSStringGetMaximumUTF8CStringSize(value));
643 char *string(new(pool) char[size]);
644 JSStringGetUTF8CString(value, string, size);
645 JSStringRelease(value);
649 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
650 return CYPoolCString(pool, CYJSString(context, value));
653 // XXX: this macro is unhygenic
654 #define CYCastCString(context, value) ({ \
655 JSValueRef exception(NULL); \
656 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
657 CYThrow(context, exception); \
658 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
659 char *utf8(reinterpret_cast<char *>(alloca(size))); \
660 JSStringGetUTF8CString(string, utf8, size); \
661 JSStringRelease(string); \
665 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
666 if (JSValueIsNull(context, value))
668 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
669 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
670 return reinterpret_cast<SEL>(data->value_);
672 return sel_registerName(CYCastCString(context, value));
675 void *CYCastPointer(JSContextRef context, JSValueRef value) {
676 switch (JSValueGetType(context, value)) {
680 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
682 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
683 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
687 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
691 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
692 switch (type->primitive) {
694 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
697 #define CYPoolFFI_(primitive, native) \
698 case sig::primitive ## _P: \
699 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
702 CYPoolFFI_(uchar, unsigned char)
703 CYPoolFFI_(char, char)
704 CYPoolFFI_(ushort, unsigned short)
705 CYPoolFFI_(short, short)
706 CYPoolFFI_(ulong, unsigned long)
707 CYPoolFFI_(long, long)
708 CYPoolFFI_(uint, unsigned int)
710 CYPoolFFI_(ulonglong, unsigned long long)
711 CYPoolFFI_(longlong, long long)
712 CYPoolFFI_(float, float)
713 CYPoolFFI_(double, double)
716 case sig::typename_P:
717 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
720 case sig::selector_P:
721 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
725 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
729 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
739 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
744 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
747 switch (type->primitive) {
749 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
752 #define CYFromFFI_(primitive, native) \
753 case sig::primitive ## _P: \
754 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
757 CYFromFFI_(uchar, unsigned char)
758 CYFromFFI_(char, char)
759 CYFromFFI_(ushort, unsigned short)
760 CYFromFFI_(short, short)
761 CYFromFFI_(ulong, unsigned long)
762 CYFromFFI_(long, long)
763 CYFromFFI_(uint, unsigned int)
765 CYFromFFI_(ulonglong, unsigned long long)
766 CYFromFFI_(longlong, long long)
767 CYFromFFI_(float, float)
768 CYFromFFI_(double, double)
771 case sig::typename_P: {
772 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
775 case sig::selector_P: {
776 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
777 selData *data(new selData(sel));
778 value = JSObjectMake(context, Selector_, data);
782 case sig::pointer_P: {
783 if (void *pointer = *reinterpret_cast<void **>(data)) {
784 ptrData *data(new ptrData(pointer));
785 value = JSObjectMake(context, Pointer_, data);
789 case sig::string_P: {
790 if (char *utf8 = *reinterpret_cast<char **>(data))
791 value = JSValueMakeString(context, CYJSString(utf8));
799 value = JSValueMakeUndefined(context);
803 value = JSValueMakeNull(context);
807 NSLog(@"CYFromFFI(%c)\n", type->primitive);
814 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
816 if (count != signature->count - 1)
817 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
822 for (unsigned index(0); index != count; ++index) {
823 sig::Element *element(&signature->elements[index + 1]);
825 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
826 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
829 uint8_t value[cif->rtype->size];
830 ffi_call(cif, function, value, values);
832 return CYFromFFI(context, signature->elements[0].type, value);
836 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
838 NSString *name(CYCastNSString(property));
839 if (Class _class = NSClassFromString(name))
840 return CYMakeObject(context, _class);
841 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
842 switch ([[entry objectAtIndex:0] intValue]) {
844 return JSEvaluateScript(JSGetContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
846 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
849 sig::Signature signature;
850 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
851 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
857 bool stret(ffi_type *ffi_type) {
858 return ffi_type->type == FFI_TYPE_STRUCT && (
859 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
860 struct_forward_array[ffi_type->size] != 0
864 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
869 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
871 id self(CYCastNSObject(context, arguments[0]));
873 return JSValueMakeNull(context);
875 SEL _cmd(CYCastSEL(context, arguments[1]));
876 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
878 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
880 type = [[method _typeString] UTF8String];
885 sig::Signature signature;
886 sig::Parse(pool, &signature, type);
889 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
891 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
892 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
895 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
896 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
897 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
900 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
903 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
904 void *function(CYCastPointer(context, arguments[0]));
905 const char *type(CYCastCString(context, arguments[1]));
906 return CYMakeFunction(context, function, type);
910 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
911 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
912 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
915 static JSStaticValue Pointer_staticValues[2] = {
916 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
917 {NULL, NULL, NULL, 0}
920 CYDriver::CYDriver(const std::string &filename) :
929 CYDriver::~CYDriver() {
933 void CYDriver::Clear() {
942 void cy::parser::error(const cy::parser::location_type &loc, const std::string &msg) {
943 std::cerr << loc << ": " << msg << std::endl;
946 void CYConsole(FILE *fin, FILE *fout, FILE *ferr) {
951 while (!feof(fin)) { _pooled
954 cy::parser parser(driver);
955 if (parser.parse() != 0)
958 for (std::vector<CYSource *>::const_iterator i(driver.source_.begin()); i != driver.source_.end(); ++i) {
959 CYSource *source(*i);
961 std::ostringstream str;
964 std::string code(str.str());
965 std::cout << code << std::endl;
967 JSStringRef script(JSStringCreateWithUTF8CString(code.c_str()));
969 JSContextRef context(JSGetContext());
971 JSValueRef exception(NULL);
972 JSValueRef result(JSEvaluateScript(context, script, NULL, NULL, 0, &exception));
973 JSStringRelease(script);
975 if (exception != NULL)
978 if (!JSValueIsUndefined(context, result)) {
982 json = JSValueToJSONCopy(context, result);
983 } @catch (id error) {
984 CYThrow(context, error, &result);
988 fputs([reinterpret_cast<const NSString *>(json) UTF8String], fout);
998 MSInitialize { _pooled
1001 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1003 pid_t pid(getpid());
1005 struct sockaddr_in address;
1006 address.sin_len = sizeof(address);
1007 address.sin_family = AF_INET;
1008 address.sin_addr.s_addr = INADDR_ANY;
1009 address.sin_port = htons(10000 + pid);
1011 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1013 CFSocketSignature signature;
1014 signature.protocolFamily = AF_INET;
1015 signature.socketType = SOCK_STREAM;
1016 signature.protocol = IPPROTO_TCP;
1017 signature.address = data;
1019 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1020 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1022 JSClassDefinition definition;
1024 definition = kJSClassDefinitionEmpty;
1025 definition.className = "Pointer";
1026 definition.staticValues = Pointer_staticValues;
1027 definition.finalize = &Pointer_finalize;
1028 Pointer_ = JSClassCreate(&definition);
1030 definition = kJSClassDefinitionEmpty;
1031 definition.className = "Functor";
1032 definition.parentClass = Pointer_;
1033 definition.callAsFunction = &ffi_callAsFunction;
1034 Functor_ = JSClassCreate(&definition);
1036 definition = kJSClassDefinitionEmpty;
1037 definition.className = "Selector";
1038 definition.parentClass = Pointer_;
1039 Selector_ = JSClassCreate(&definition);
1041 definition = kJSClassDefinitionEmpty;
1042 definition.className = "Instance_";
1043 definition.getProperty = &Instance_getProperty;
1044 definition.callAsConstructor = &Instance_callAsConstructor;
1045 definition.finalize = &Instance_finalize;
1046 Instance_ = JSClassCreate(&definition);
1048 definition = kJSClassDefinitionEmpty;
1049 definition.getProperty = &Global_getProperty;
1050 JSClassRef Global(JSClassCreate(&definition));
1052 JSContextRef context(JSGlobalContextCreate(Global));
1055 JSObjectRef global(JSContextGetGlobalObject(context));
1057 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1059 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1061 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1063 name_ = JSStringCreateWithUTF8CString("name");
1064 message_ = JSStringCreateWithUTF8CString("message");
1065 length_ = JSStringCreateWithUTF8CString("length");
1067 JSValueRef exception(NULL);
1068 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYJSString("Array"), &exception));
1069 CYThrow(context, exception);
1070 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1071 CYThrow(context, exception);