1 /* Cycript - 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 <WebKit/WebScriptObject.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
66 #include <ext/stdio_filebuf.h>
74 #include "Cycript.tab.hh"
78 #include <apr-1/apr_thread_proc.h>
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__); \
94 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
96 #define CYPoolCatch(value) \
97 @catch (NSException *error) { \
98 _saved = [error retain]; \
104 [_saved autorelease]; \
108 static JSGlobalContextRef Context_;
109 static JSObjectRef System_;
110 static JSObjectRef ObjectiveC_;
112 static JSClassRef Functor_;
113 static JSClassRef Instance_;
114 static JSClassRef Pointer_;
115 static JSClassRef Runtime_;
116 static JSClassRef Selector_;
117 static JSClassRef Struct_;
118 static JSClassRef Type_;
120 static JSClassRef ObjectiveC_Classes_;
121 static JSClassRef ObjectiveC_Image_Classes_;
122 static JSClassRef ObjectiveC_Images_;
123 static JSClassRef ObjectiveC_Protocols_;
125 static JSObjectRef Array_;
126 static JSObjectRef Function_;
128 static JSStringRef Result_;
130 static JSStringRef length_;
131 static JSStringRef message_;
132 static JSStringRef name_;
133 static JSStringRef toCYON_;
134 static JSStringRef toJSON_;
136 static Class NSCFBoolean_;
137 static Class NSCFType_;
138 static Class NSMessageBuilder_;
139 static Class NSZombie_;
140 static Class Object_;
142 static NSArray *Bridge_;
150 static void *operator new(size_t size, apr_pool_t *pool) {
151 void *data(apr_palloc(pool, size));
152 reinterpret_cast<CYData *>(data)->pool_ = pool;
156 static void *operator new(size_t size) {
158 apr_pool_create(&pool, NULL);
159 return operator new(size, pool);
162 static void operator delete(void *data) {
163 apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
166 static void Finalize(JSObjectRef object) {
167 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
179 CYValue(void *value) :
185 struct Selector_privateData :
188 Selector_privateData(SEL value) :
193 SEL GetValue() const {
194 return reinterpret_cast<SEL>(value_);
203 Transient = (1 << 0),
204 Uninitialized = (1 << 1),
209 Instance(id value, Flags flags) :
215 virtual ~Instance() {
216 if ((flags_ & Transient) == 0)
217 // XXX: does this handle background threads correctly?
218 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
221 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
222 return JSObjectMake(context, Instance_, new Instance(object, flags));
225 id GetValue() const {
226 return reinterpret_cast<id>(value_);
229 bool IsUninitialized() const {
230 return (flags_ & Uninitialized) != 0;
236 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
238 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
239 lhs.name = apr_pstrdup(pool, rhs.name);
240 if (rhs.type == NULL)
243 lhs.type = new(pool) Type;
244 Copy(pool, *lhs.type, *rhs.type);
246 lhs.offset = rhs.offset;
249 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
250 size_t count(rhs.count);
252 lhs.elements = new(pool) Element[count];
253 for (size_t index(0); index != count; ++index)
254 Copy(pool, lhs.elements[index], rhs.elements[index]);
257 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
258 lhs.primitive = rhs.primitive;
259 lhs.name = apr_pstrdup(pool, rhs.name);
260 lhs.flags = rhs.flags;
262 if (sig::IsAggregate(rhs.primitive))
263 Copy(pool, lhs.data.signature, rhs.data.signature);
265 if (rhs.data.data.type != NULL) {
266 lhs.data.data.type = new(pool) Type;
267 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
270 lhs.data.data.size = rhs.data.data.size;
274 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
276 lhs.alignment = rhs.alignment;
278 if (rhs.elements == NULL)
282 while (rhs.elements[count] != NULL)
285 lhs.elements = new(pool) ffi_type *[count + 1];
286 lhs.elements[count] = NULL;
288 for (size_t index(0); index != count; ++index) {
289 // XXX: if these are libffi native then you can just take them
290 ffi_type *ffi(new(pool) ffi_type);
291 lhs.elements[index] = ffi;
292 sig::Copy(pool, *ffi, *rhs.elements[index]);
299 struct CStringMapLess :
300 std::binary_function<const char *, const char *, bool>
302 _finline bool operator ()(const char *lhs, const char *rhs) const {
303 return strcmp(lhs, rhs) < 0;
307 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
312 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
313 switch ([[entry objectAtIndex:0] intValue]) {
315 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
319 sig::Signature signature;
320 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
321 type = signature.elements[0].type;
327 struct Type_privateData :
333 void Set(sig::Type *type) {
334 type_ = new(pool_) sig::Type;
335 sig::Copy(pool_, *type_, *type);
338 Type_privateData(apr_pool_t *pool, const char *type) :
344 sig::Signature signature;
345 sig::Parse(pool_, &signature, type, &Structor_);
346 type_ = signature.elements[0].type;
349 Type_privateData(sig::Type *type) :
356 Type_privateData(sig::Type *type, ffi_type *ffi) {
357 ffi_ = new(pool_) ffi_type;
358 sig::Copy(pool_, *ffi_, *ffi);
364 ffi_ = new(pool_) ffi_type;
366 sig::Element element;
368 element.type = type_;
371 sig::Signature signature;
372 signature.elements = &element;
376 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
388 Type_privateData *type_;
390 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
393 type_(new(pool_) Type_privateData(type))
398 struct Struct_privateData :
402 Type_privateData *type_;
404 Struct_privateData(JSObjectRef owner) :
410 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
411 static TypeMap Types_;
413 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
414 Struct_privateData *internal(new Struct_privateData(owner));
415 apr_pool_t *pool(internal->pool_);
416 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
417 internal->type_ = typical;
420 internal->value_ = data;
422 size_t size(typical->GetFFI()->size);
423 void *copy(apr_palloc(internal->pool_, size));
424 memcpy(copy, data, size);
425 internal->value_ = copy;
428 return JSObjectMake(context, Struct_, internal);
431 struct Functor_privateData :
434 sig::Signature signature_;
437 Functor_privateData(const char *type, void (*value)()) :
438 CYValue(reinterpret_cast<void *>(value))
440 sig::Parse(pool_, &signature_, type, &Structor_);
441 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
448 JSContextRef context_;
449 JSObjectRef function_;
451 ffoData(const char *type) :
452 Functor_privateData(type, NULL)
457 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
458 Instance::Flags flags;
461 flags = Instance::Transient;
463 flags = Instance::None;
464 object = [object retain];
467 return Instance::Make(context, object, flags);
470 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
472 return [value UTF8String];
474 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
475 char *string(new(pool) char[size]);
476 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
477 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
482 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
483 return JSValueMakeBoolean(context, value);
486 JSValueRef CYCastJSValue(JSContextRef context, double value) {
487 return JSValueMakeNumber(context, value);
490 #define CYCastJSValue_(Type_) \
491 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
492 return JSValueMakeNumber(context, static_cast<double>(value)); \
496 CYCastJSValue_(unsigned int)
497 CYCastJSValue_(long int)
498 CYCastJSValue_(long unsigned int)
499 CYCastJSValue_(long long int)
500 CYCastJSValue_(long long unsigned int)
502 JSValueRef CYJSUndefined(JSContextRef context) {
503 return JSValueMakeUndefined(context);
506 bool CYGetIndex(const char *value, ssize_t &index) {
507 if (value[0] != '0') {
509 index = strtol(value, &end, 10);
510 if (value + strlen(value) == end)
512 } else if (value[1] == '\0') {
520 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
521 return CYGetIndex(CYPoolCString(pool, value), index);
524 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
526 @interface NSMethodSignature (Cycript)
527 - (NSString *) _typeString;
530 @interface NSObject (Cycript)
532 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
533 - (JSType) cy$JSType;
535 - (NSObject *) cy$toJSON:(NSString *)key;
536 - (NSString *) cy$toCYON;
537 - (NSString *) cy$toKey;
539 - (NSObject *) cy$getProperty:(NSString *)name;
540 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
541 - (bool) cy$deleteProperty:(NSString *)name;
546 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
549 @interface NSString (Cycript)
550 - (void *) cy$symbol;
553 struct PropertyAttributes {
558 const char *variable;
571 PropertyAttributes(objc_property_t property) :
583 name = property_getName(property);
584 const char *attributes(property_getAttributes(property));
586 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
588 case 'R': readonly = true; break;
589 case 'C': copy = true; break;
590 case '&': retain = true; break;
591 case 'N': nonatomic = true; break;
592 case 'G': getter_ = token + 1; break;
593 case 'S': setter_ = token + 1; break;
594 case 'V': variable = token + 1; break;
598 /*if (variable == NULL) {
599 variable = property_getName(property);
600 size_t size(strlen(variable));
601 char *name(new(pool_) char[size + 2]);
603 memcpy(name + 1, variable, size);
604 name[size + 1] = '\0';
609 const char *Getter() {
611 getter_ = apr_pstrdup(pool_, name);
615 const char *Setter() {
616 if (setter_ == NULL && !readonly) {
617 size_t length(strlen(name));
619 char *temp(new(pool_) char[length + 5]);
625 temp[3] = toupper(name[0]);
626 memcpy(temp + 4, name + 1, length - 1);
629 temp[length + 3] = ':';
630 temp[length + 4] = '\0';
639 @implementation NSProxy (Cycript)
641 - (NSObject *) cy$toJSON:(NSString *)key {
642 return [self description];
645 - (NSString *) cy$toCYON {
646 return [[self cy$toJSON:@""] cy$toCYON];
651 @implementation NSObject (Cycript)
653 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
654 return CYMakeInstance(context, self, false);
657 - (JSType) cy$JSType {
658 return kJSTypeObject;
661 - (NSObject *) cy$toJSON:(NSString *)key {
662 return [self description];
665 - (NSString *) cy$toCYON {
666 return [[self cy$toJSON:@""] cy$toCYON];
669 - (NSString *) cy$toKey {
670 return [self cy$toCYON];
673 - (NSObject *) cy$getProperty:(NSString *)name {
674 /*if (![name isEqualToString:@"prototype"])
675 NSLog(@"get:%@", name);*/
679 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
680 //NSLog(@"set:%@", name);
684 - (bool) cy$deleteProperty:(NSString *)name {
685 //NSLog(@"delete:%@", name);
691 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
692 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
695 @implementation WebUndefined (Cycript)
697 - (JSType) cy$JSType {
698 return kJSTypeUndefined;
701 - (NSObject *) cy$toJSON:(NSString *)key {
705 - (NSString *) cy$toCYON {
709 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
710 return CYJSUndefined(context);
715 @implementation NSNull (Cycript)
717 - (JSType) cy$JSType {
721 - (NSObject *) cy$toJSON:(NSString *)key {
725 - (NSString *) cy$toCYON {
731 @implementation NSArray (Cycript)
733 - (NSString *) cy$toCYON {
734 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
735 [json appendString:@"["];
738 for (id object in self) {
740 [json appendString:@","];
743 if ([object cy$JSType] != kJSTypeUndefined)
744 [json appendString:CYPoolNSCYON(NULL, object)];
746 [json appendString:@","];
751 [json appendString:@"]"];
755 - (NSObject *) cy$getProperty:(NSString *)name {
756 if ([name isEqualToString:@"length"])
757 return [NSNumber numberWithUnsignedInteger:[self count]];
760 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
761 return [super cy$getProperty:name];
763 return [self objectAtIndex:index];
768 @implementation NSMutableArray (Cycript)
770 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
772 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
773 return [super cy$setProperty:name to:value];
775 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
780 - (bool) cy$deleteProperty:(NSString *)name {
782 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
783 return [super cy$deleteProperty:name];
785 [self removeObjectAtIndex:index];
792 @implementation NSDictionary (Cycript)
794 - (NSString *) cy$toCYON {
795 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
796 [json appendString:@"{"];
799 for (id key in self) {
801 [json appendString:@","];
804 [json appendString:[key cy$toKey]];
805 [json appendString:@":"];
806 NSObject *object([self objectForKey:key]);
807 [json appendString:CYPoolNSCYON(NULL, object)];
810 [json appendString:@"}"];
814 - (NSObject *) cy$getProperty:(NSString *)name {
815 return [self objectForKey:name];
820 @implementation NSMutableDictionary (Cycript)
822 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
823 [self setObject:(value ?: [NSNull null]) forKey:name];
827 - (bool) cy$deleteProperty:(NSString *)name {
828 if ([self objectForKey:name] == nil)
831 [self removeObjectForKey:name];
838 @implementation NSNumber (Cycript)
840 - (JSType) cy$JSType {
841 // XXX: this just seems stupid
842 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
845 - (NSObject *) cy$toJSON:(NSString *)key {
849 - (NSString *) cy$toCYON {
850 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
853 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
854 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
859 @implementation NSString (Cycript)
861 - (JSType) cy$JSType {
862 return kJSTypeString;
865 - (NSObject *) cy$toJSON:(NSString *)key {
869 - (NSString *) cy$toCYON {
870 // XXX: this should use the better code from Output.cpp
871 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
873 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
874 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
875 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
876 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
877 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
879 CFStringInsert(json, 0, CFSTR("\""));
880 CFStringAppend(json, CFSTR("\""));
882 return [reinterpret_cast<const NSString *>(json) autorelease];
885 - (NSString *) cy$toKey {
886 const char *value([self UTF8String]);
887 size_t size(strlen(value));
892 if (DigitRange_[value[0]]) {
894 if (!CYGetIndex(NULL, self, index) || index < 0)
897 if (!WordStartRange_[value[0]])
899 for (size_t i(1); i != size; ++i)
900 if (!WordEndRange_[value[i]])
907 return [self cy$toCYON];
910 - (void *) cy$symbol {
912 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
917 @interface CYJSObject : NSDictionary {
919 JSContextRef context_;
922 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
924 - (NSString *) cy$toJSON:(NSString *)key;
926 - (NSUInteger) count;
927 - (id) objectForKey:(id)key;
928 - (NSEnumerator *) keyEnumerator;
929 - (void) setObject:(id)object forKey:(id)key;
930 - (void) removeObjectForKey:(id)key;
934 @interface CYJSArray : NSArray {
936 JSContextRef context_;
939 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
941 - (NSUInteger) count;
942 - (id) objectAtIndex:(NSUInteger)index;
946 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
947 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
948 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
953 @catch (id error) { \
954 CYThrow(context, error, exception); \
958 void CYThrow(JSContextRef context, JSValueRef value);
960 apr_status_t CYPoolRelease_(void *data) {
961 id object(reinterpret_cast<id>(data));
966 id CYPoolRelease(apr_pool_t *pool, id object) {
969 else if (pool == NULL)
970 return [object autorelease];
972 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
977 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
978 return (CFTypeRef) CYPoolRelease(pool, (id) object);
981 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
982 JSValueRef exception(NULL);
983 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
984 CYThrow(context, exception);
985 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
986 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
989 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
990 if (!JSValueIsObjectOfClass(context, object, Instance_))
991 return CYCastNSObject_(pool, context, object);
993 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
994 return data->GetValue();
998 JSStringRef CYCopyJSString(id value) {
999 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1002 JSStringRef CYCopyJSString(const char *value) {
1003 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1006 JSStringRef CYCopyJSString(JSStringRef value) {
1007 return value == NULL ? NULL : JSStringRetain(value);
1010 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1011 if (JSValueIsNull(context, value))
1013 JSValueRef exception(NULL);
1014 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1015 CYThrow(context, exception);
1021 JSStringRef string_;
1024 if (string_ != NULL)
1025 JSStringRelease(string_);
1029 CYJSString(const CYJSString &rhs) :
1030 string_(CYCopyJSString(rhs.string_))
1034 template <typename Arg0_>
1035 CYJSString(Arg0_ arg0) :
1036 string_(CYCopyJSString(arg0))
1040 template <typename Arg0_, typename Arg1_>
1041 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1042 string_(CYCopyJSString(arg0, arg1))
1046 CYJSString &operator =(const CYJSString &rhs) {
1048 string_ = CYCopyJSString(rhs.string_);
1061 operator JSStringRef() const {
1066 CFStringRef CYCopyCFString(JSStringRef value) {
1067 return JSStringCopyCFString(kCFAllocatorDefault, value);
1070 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1071 return CYCopyCFString(CYJSString(context, value));
1074 double CYCastDouble(const char *value, size_t size) {
1076 double number(strtod(value, &end));
1077 if (end != value + size)
1082 double CYCastDouble(const char *value) {
1083 return CYCastDouble(value, strlen(value));
1086 double CYCastDouble(JSContextRef context, JSValueRef value) {
1087 JSValueRef exception(NULL);
1088 double number(JSValueToNumber(context, value, &exception));
1089 CYThrow(context, exception);
1093 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1094 double number(CYCastDouble(context, value));
1095 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1098 CFStringRef CYCopyCFString(const char *value) {
1099 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1102 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1103 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1106 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1107 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1110 bool CYCastBool(JSContextRef context, JSValueRef value) {
1111 return JSValueToBoolean(context, value);
1114 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1118 switch (JSType type = JSValueGetType(context, value)) {
1119 case kJSTypeUndefined:
1120 object = [WebUndefined undefined];
1128 case kJSTypeBoolean:
1129 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1134 object = CYCopyCFNumber(context, value);
1139 object = CYCopyCFString(context, value);
1144 // XXX: this might could be more efficient
1145 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1150 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1157 return CYPoolRelease(pool, object);
1159 return CFRetain(object);
1162 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1163 return CYCFType(pool, context, value, true);
1166 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1167 return CYCFType(pool, context, value, false);
1170 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1172 size_t size(JSPropertyNameArrayGetCount(names));
1173 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1174 for (size_t index(0); index != size; ++index)
1175 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1179 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1180 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1183 void CYThrow(JSContextRef context, JSValueRef value) {
1186 @throw CYCastNSObject(NULL, context, value);
1189 JSValueRef CYJSNull(JSContextRef context) {
1190 return JSValueMakeNull(context);
1193 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1194 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1197 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1198 return CYCastJSValue(context, CYJSString(value));
1201 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1203 return CYJSNull(context);
1204 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1205 return [value cy$JSValueInContext:context];
1207 return CYMakeInstance(context, value, false);
1210 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1211 JSValueRef exception(NULL);
1212 JSObjectRef object(JSValueToObject(context, value, &exception));
1213 CYThrow(context, exception);
1217 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1218 JSValueRef exception(NULL);
1219 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1220 CYThrow(context, exception);
1224 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1225 JSValueRef exception(NULL);
1226 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1227 CYThrow(context, exception);
1231 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1232 JSValueRef exception(NULL);
1233 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1234 CYThrow(context, exception);
1237 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1238 if (exception == NULL)
1240 *exception = CYCastJSValue(context, error);
1243 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1244 JSValueRef exception(NULL);
1245 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1246 CYThrow(context, exception);
1250 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1251 // XXX: this isn't actually correct
1252 return value != NULL && JSValueIsObject(context, value);
1255 @implementation CYJSObject
1257 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1258 if ((self = [super init]) != nil) {
1264 - (NSObject *) cy$toJSON:(NSString *)key {
1265 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1266 if (!CYIsCallable(context_, toJSON))
1267 return [super cy$toJSON:key];
1269 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1270 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1271 // XXX: do I really want an NSNull here?!
1272 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1276 - (NSString *) cy$toCYON {
1277 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1278 if (!CYIsCallable(context_, toCYON))
1279 return [super cy$toCYON];
1281 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1282 return CYCastNSString(NULL, CYJSString(context_, value));
1286 - (NSUInteger) count {
1287 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1288 size_t size(JSPropertyNameArrayGetCount(names));
1289 JSPropertyNameArrayRelease(names);
1293 - (id) objectForKey:(id)key {
1294 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1297 - (NSEnumerator *) keyEnumerator {
1298 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1299 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1300 JSPropertyNameArrayRelease(names);
1304 - (void) setObject:(id)object forKey:(id)key {
1305 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1308 - (void) removeObjectForKey:(id)key {
1309 JSValueRef exception(NULL);
1310 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1311 CYThrow(context_, exception);
1316 @implementation CYJSArray
1318 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1319 if ((self = [super init]) != nil) {
1325 - (NSUInteger) count {
1326 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1329 - (id) objectAtIndex:(NSUInteger)index {
1330 JSValueRef exception(NULL);
1331 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1332 CYThrow(context_, exception);
1333 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1338 NSString *CYCopyNSCYON(id value) {
1339 Class _class(object_getClass(value));
1340 SEL sel(@selector(cy$toCYON));
1344 if (Method toCYON = class_getInstanceMethod(_class, sel))
1345 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1346 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1347 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1348 string = [value cy$toCYON];
1351 if (value == NSZombie_)
1352 string = @"_NSZombie_";
1353 else if (_class == NSZombie_)
1354 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1355 else if (value == NSMessageBuilder_ || value == Object_)
1358 string = [NSString stringWithFormat:@"%@", value];
1361 // XXX: frowny pants
1363 string = @"undefined";
1364 return [string retain];
1367 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1370 return CYCopyNSCYON(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1375 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1376 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1379 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1380 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1381 const char *string(CYPoolCString(pool, json));
1387 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1391 JSObjectRef object_;
1399 // XXX: delete object_? ;(
1402 static CYInternal *Get(id self) {
1403 CYInternal *internal(NULL);
1404 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1405 // XXX: do something epic? ;P
1411 static CYInternal *Set(id self) {
1412 CYInternal *internal(NULL);
1413 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1414 if (internal == NULL) {
1415 internal = new CYInternal();
1416 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1419 // XXX: do something epic? ;P
1425 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1426 if (object_ == NULL)
1428 return CYGetProperty(context, object_, name);
1431 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1432 if (object_ == NULL)
1433 object_ = JSObjectMake(context, NULL, NULL);
1434 CYSetProperty(context, object_, name, value);
1438 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1439 Selector_privateData *data(new Selector_privateData(sel));
1440 return JSObjectMake(context, Selector_, data);
1443 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
1444 Pointer *data(new Pointer(pointer, type, owner));
1445 return JSObjectMake(context, Pointer_, data);
1448 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1449 Functor_privateData *data(new Functor_privateData(type, function));
1450 return JSObjectMake(context, Functor_, data);
1453 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1455 const char *string([CYCastNSString(NULL, value) UTF8String]);
1458 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1459 char *string(new(pool) char[size]);
1460 JSStringGetUTF8CString(value, string, size);
1465 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1466 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1469 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1470 return CYGetIndex(CYPoolCString(pool, value), index);
1473 // XXX: this macro is unhygenic
1474 #define CYCastCString(context, value) ({ \
1476 if (value == NULL) \
1478 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1479 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1480 utf8 = reinterpret_cast<char *>(alloca(size)); \
1481 JSStringGetUTF8CString(string, utf8, size); \
1482 JSStringRelease(string); \
1488 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1489 switch (JSValueGetType(context, value)) {
1492 /*case kJSTypeString:
1493 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1495 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1496 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1497 return data->value_;
1500 double number(CYCastDouble(context, value));
1501 if (std::isnan(number))
1502 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1503 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1507 template <typename Type_>
1508 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1509 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1512 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1513 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1514 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1515 return reinterpret_cast<SEL>(data->value_);
1517 return CYCastPointer<SEL>(context, value);
1520 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1521 switch (type->primitive) {
1522 case sig::boolean_P:
1523 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1526 #define CYPoolFFI_(primitive, native) \
1527 case sig::primitive ## _P: \
1528 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1531 CYPoolFFI_(uchar, unsigned char)
1532 CYPoolFFI_(char, char)
1533 CYPoolFFI_(ushort, unsigned short)
1534 CYPoolFFI_(short, short)
1535 CYPoolFFI_(ulong, unsigned long)
1536 CYPoolFFI_(long, long)
1537 CYPoolFFI_(uint, unsigned int)
1538 CYPoolFFI_(int, int)
1539 CYPoolFFI_(ulonglong, unsigned long long)
1540 CYPoolFFI_(longlong, long long)
1541 CYPoolFFI_(float, float)
1542 CYPoolFFI_(double, double)
1545 case sig::typename_P:
1546 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1549 case sig::selector_P:
1550 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1553 case sig::pointer_P:
1554 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1558 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1561 case sig::struct_P: {
1562 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1563 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1564 for (size_t index(0); index != type->data.signature.count; ++index) {
1565 sig::Element *element(&type->data.signature.elements[index]);
1566 ffi_type *field(ffi->elements[index]);
1569 if (aggregate == NULL)
1572 rhs = CYGetProperty(context, aggregate, index);
1573 if (JSValueIsUndefined(context, rhs)) {
1574 if (element->name != NULL)
1575 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1578 if (JSValueIsUndefined(context, rhs)) undefined:
1579 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1583 CYPoolFFI(pool, context, element->type, field, base, rhs);
1585 base += field->size;
1593 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1598 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1601 switch (type->primitive) {
1602 case sig::boolean_P:
1603 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1606 #define CYFromFFI_(primitive, native) \
1607 case sig::primitive ## _P: \
1608 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1611 CYFromFFI_(uchar, unsigned char)
1612 CYFromFFI_(char, char)
1613 CYFromFFI_(ushort, unsigned short)
1614 CYFromFFI_(short, short)
1615 CYFromFFI_(ulong, unsigned long)
1616 CYFromFFI_(long, long)
1617 CYFromFFI_(uint, unsigned int)
1618 CYFromFFI_(int, int)
1619 CYFromFFI_(ulonglong, unsigned long long)
1620 CYFromFFI_(longlong, long long)
1621 CYFromFFI_(float, float)
1622 CYFromFFI_(double, double)
1624 case sig::object_P: {
1625 if (id object = *reinterpret_cast<id *>(data)) {
1626 value = CYCastJSValue(context, object);
1632 case sig::typename_P:
1633 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1636 case sig::selector_P:
1637 if (SEL sel = *reinterpret_cast<SEL *>(data))
1638 value = CYMakeSelector(context, sel);
1642 case sig::pointer_P:
1643 if (void *pointer = *reinterpret_cast<void **>(data))
1644 value = CYMakePointer(context, pointer, type->data.data.type, owner);
1649 if (char *utf8 = *reinterpret_cast<char **>(data))
1650 value = CYCastJSValue(context, utf8);
1655 value = CYMakeStruct(context, data, type, ffi, owner);
1659 value = CYJSUndefined(context);
1663 value = CYJSNull(context);
1667 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1674 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1678 NSString *self(CYCastNSObject(pool, context, object));
1679 NSString *name(CYCastNSString(pool, property));
1681 if (CYInternal *internal = CYInternal::Get(self))
1682 if (JSValueRef value = internal->GetProperty(context, property))
1686 if (NSObject *data = [self cy$getProperty:name])
1687 return CYCastJSValue(context, data);
1690 const char *string(CYPoolCString(pool, name));
1692 if (objc_property_t property = class_getProperty(object_getClass(self), string)) {
1693 PropertyAttributes attributes(property);
1694 SEL sel(sel_registerName(attributes.Getter()));
1695 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1698 if (Ivar ivar = object_getInstanceVariable(self, string, NULL)) {
1699 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1700 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1707 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1711 NSString *self(CYCastNSObject(pool, context, object));
1712 NSString *name(CYCastNSString(pool, property));
1713 NSString *data(CYCastNSObject(pool, context, value));
1716 if ([self cy$setProperty:name to:data])
1720 const char *string(CYPoolCString(pool, name));
1722 if (objc_property_t property = class_getProperty(object_getClass(self), string)) {
1723 PropertyAttributes attributes(property);
1724 if (const char *setter = attributes.Setter()) {
1725 SEL sel(sel_registerName(setter));
1726 JSValueRef arguments[1] = {value};
1727 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1732 if (Ivar ivar = object_getInstanceVariable(self, string, NULL)) {
1733 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1734 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1738 if (CYInternal *internal = CYInternal::Set(self)) {
1739 internal->SetProperty(context, property, value);
1747 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1750 NSString *self(CYCastNSObject(NULL, context, object));
1751 NSString *name(CYCastNSString(NULL, property));
1752 return [self cy$deleteProperty:name];
1757 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1759 NSString *self(CYCastNSObject(pool, context, object));
1760 Class _class(object_getClass(self));
1764 objc_property_t *data(class_copyPropertyList(_class, &size));
1765 for (size_t i(0); i != size; ++i)
1766 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1770 for (Class super(_class); super != NULL; super = class_getSuperclass(super)) {
1772 Ivar *data(class_copyIvarList(super, &size));
1773 for (size_t i(0); i != size; ++i)
1774 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1779 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1781 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1782 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1787 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1788 Type_privateData *typical(internal->type_);
1789 sig::Type *type(typical->type_);
1793 const char *name(CYPoolCString(pool, property));
1794 size_t length(strlen(name));
1795 double number(CYCastDouble(name, length));
1797 size_t count(type->data.signature.count);
1799 if (std::isnan(number)) {
1800 if (property == NULL)
1803 sig::Element *elements(type->data.signature.elements);
1805 for (size_t local(0); local != count; ++local) {
1806 sig::Element *element(&elements[local]);
1807 if (element->name != NULL && strcmp(name, element->name) == 0) {
1815 index = static_cast<ssize_t>(number);
1816 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1821 ffi_type **elements(typical->GetFFI()->elements);
1823 base = reinterpret_cast<uint8_t *>(internal->value_);
1824 for (ssize_t local(0); local != index; ++local)
1825 base += elements[local]->size;
1830 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1832 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1833 Type_privateData *typical(internal->type_);
1835 if (typical->type_ == NULL)
1839 if (!CYGetIndex(pool, property, index))
1842 ffi_type *ffi(typical->GetFFI());
1844 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1845 base += ffi->size * index;
1847 JSObjectRef owner(internal->owner_ ?: object);
1850 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
1854 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1856 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1857 Type_privateData *typical(internal->type_);
1859 if (typical->type_ == NULL)
1863 if (!CYGetIndex(pool, property, index))
1866 ffi_type *ffi(typical->GetFFI());
1868 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1869 base += ffi->size * index;
1872 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
1877 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1879 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1880 Type_privateData *typical(internal->type_);
1885 if (!Index_(pool, internal, property, index, base))
1888 JSObjectRef owner(internal->owner_ ?: object);
1891 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
1895 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1897 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1898 Type_privateData *typical(internal->type_);
1903 if (!Index_(pool, internal, property, index, base))
1907 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1912 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1913 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1914 Type_privateData *typical(internal->type_);
1915 sig::Type *type(typical->type_);
1920 size_t count(type->data.signature.count);
1921 sig::Element *elements(type->data.signature.elements);
1925 for (size_t index(0); index != count; ++index) {
1927 name = elements[index].name;
1930 sprintf(number, "%lu", index);
1934 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1938 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1940 if (setups + count != signature->count - 1)
1941 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1943 size_t size(setups + count);
1945 memcpy(values, setup, sizeof(void *) * setups);
1947 for (size_t index(setups); index != size; ++index) {
1948 sig::Element *element(&signature->elements[index + 1]);
1949 ffi_type *ffi(cif->arg_types[index]);
1951 values[index] = new(pool) uint8_t[ffi->size];
1952 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1955 uint8_t value[cif->rtype->size];
1956 ffi_call(cif, function, value, values);
1958 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1962 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1963 ffoData *data(reinterpret_cast<ffoData *>(arg));
1965 JSContextRef context(data->context_);
1967 size_t count(data->cif_.nargs);
1968 JSValueRef values[count];
1970 for (size_t index(0); index != count; ++index)
1971 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1973 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1974 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1977 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1978 // XXX: in case of exceptions this will leak
1979 ffoData *data(new ffoData(type));
1981 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1982 NULL, sizeof(ffi_closure),
1983 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1987 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1988 _assert(status == FFI_OK);
1990 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1992 data->value_ = closure;
1994 data->context_ = CYGetJSContext();
1995 data->function_ = function;
1997 return JSObjectMake(context, Functor_, data);
2000 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2003 NSString *name(CYCastNSString(pool, property));
2004 if (Class _class = NSClassFromString(name))
2005 return CYMakeInstance(context, _class, true);
2010 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2011 size_t size(objc_getClassList(NULL, 0));
2012 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2015 size_t writ(objc_getClassList(data, size));
2018 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2024 for (size_t i(0); i != writ; ++i)
2025 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2031 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2032 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2036 const char *name(CYPoolCString(pool, property));
2038 const char **data(objc_copyClassNamesForImage(internal, &size));
2040 for (size_t i(0); i != size; ++i)
2041 if (strcmp(name, data[i]) == 0) {
2042 if (Class _class = objc_getClass(name)) {
2043 value = CYMakeInstance(context, _class, true);
2055 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2056 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2058 const char **data(objc_copyClassNamesForImage(internal, &size));
2059 for (size_t i(0); i != size; ++i)
2060 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2064 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2067 const char *name(CYPoolCString(pool, property));
2069 const char **data(objc_copyImageNames(&size));
2070 for (size_t i(0); i != size; ++i)
2071 if (strcmp(name, data[i]) == 0) {
2080 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2081 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2086 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2088 const char **data(objc_copyImageNames(&size));
2089 for (size_t i(0); i != size; ++i)
2090 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2094 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2097 NSString *name(CYCastNSString(pool, property));
2098 if (Protocol *protocol = NSProtocolFromString(name))
2099 return CYMakeInstance(context, protocol, true);
2104 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2106 Protocol **data(objc_copyProtocolList(&size));
2107 for (size_t i(0); i != size; ++i)
2108 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2112 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2115 NSString *name(CYCastNSString(pool, property));
2116 if (Class _class = NSClassFromString(name))
2117 return CYMakeInstance(context, _class, true);
2118 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2119 switch ([[entry objectAtIndex:0] intValue]) {
2121 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2123 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2125 // XXX: this is horrendously inefficient
2126 sig::Signature signature;
2127 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2129 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2130 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2136 bool stret(ffi_type *ffi_type) {
2137 return ffi_type->type == FFI_TYPE_STRUCT && (
2138 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2139 struct_forward_array[ffi_type->size] != 0
2144 int *_NSGetArgc(void);
2145 char ***_NSGetArgv(void);
2146 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2149 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2151 NSLog(@"%s", CYCastCString(context, arguments[0]));
2152 return CYJSUndefined(context);
2156 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2159 Class _class(object_getClass(self));
2160 if (Method method = class_getInstanceMethod(_class, _cmd))
2161 type = method_getTypeEncoding(method);
2165 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2167 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2168 type = CYPoolCString(pool, [method _typeString]);
2177 sig::Signature signature;
2178 sig::Parse(pool, &signature, type, &Structor_);
2181 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2183 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2184 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2187 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2197 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2199 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2200 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2201 self = data->GetValue();
2202 uninitialized = data->IsUninitialized();
2206 self = CYCastNSObject(pool, context, arguments[0]);
2207 uninitialized = false;
2211 return CYJSNull(context);
2213 _cmd = CYCastSEL(context, arguments[1]);
2216 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2219 MSHook(void, CYDealloc, id self, SEL sel) {
2220 CYInternal *internal;
2221 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2222 if (internal != NULL)
2224 _CYDealloc(self, sel);
2227 MSHook(void, objc_registerClassPair, Class _class) {
2228 Class super(class_getSuperclass(_class));
2229 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2230 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2231 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2234 _objc_registerClassPair(_class);
2237 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2240 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2242 Class _class(CYCastNSObject(pool, context, arguments[0]));
2243 $objc_registerClassPair(_class);
2244 return CYJSUndefined(context);
2248 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2249 JSValueRef setup[count + 2];
2252 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2253 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2256 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2258 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2259 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
2262 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2265 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2266 const char *name(CYCastCString(context, arguments[0]));
2267 return CYMakeSelector(context, sel_registerName(name));
2271 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2274 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2276 void *value(CYCastPointer<void *>(context, arguments[0]));
2277 const char *type(CYCastCString(context, arguments[1]));
2281 sig::Signature signature;
2282 sig::Parse(pool, &signature, type, &Structor_);
2284 return CYMakePointer(context, value, signature.elements[0].type, NULL);
2288 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2289 Type_privateData *internal(new Type_privateData(NULL, type));
2290 return JSObjectMake(context, Type_, internal);
2293 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2296 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2297 const char *type(CYCastCString(context, arguments[0]));
2298 return CYMakeType(context, object, type);
2302 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2305 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2306 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2307 sig::Type *type(internal->type_);
2308 ffi_type *ffi(internal->GetFFI());
2310 uint8_t value[ffi->size];
2312 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2313 return CYFromFFI(context, type, ffi, value);
2317 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2320 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2321 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2322 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2324 void *value(malloc(internal->GetFFI()->size * size));
2325 return CYMakePointer(context, value, internal->type_, NULL);
2329 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2332 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2333 const char *type(CYCastCString(context, arguments[1]));
2334 JSValueRef exception(NULL);
2335 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
2336 JSObjectRef function(CYCastJSObject(context, arguments[0]));
2337 return CYMakeFunctor(context, function, type);
2338 } else if (exception != NULL) {
2341 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
2342 return CYMakeFunctor(context, function, type);
2347 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2348 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2349 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2352 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2356 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2358 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2359 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2363 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2364 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2367 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2369 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2371 sprintf(string, "%p", internal->value_);
2372 return CYCastJSValue(context, string);
2376 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2378 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2380 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
2385 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2387 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2389 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2390 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2395 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2397 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2399 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2404 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2406 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2407 return CYCastJSValue(context, sel_getName(data->GetValue()));
2411 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2412 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2415 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2417 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2418 const char *name(sel_getName(internal->GetValue()));
2420 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2425 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2428 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2430 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2431 Class _class(CYCastNSObject(pool, context, arguments[0]));
2432 SEL sel(internal->GetValue());
2433 if (Method method = class_getInstanceMethod(_class, sel))
2434 return CYCastJSValue(context, method_getTypeEncoding(method));
2435 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2436 return CYCastJSValue(context, CYJSString(type));
2438 return CYJSNull(context);
2442 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2444 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2446 const char *type(sig::Unparse(pool, internal->type_));
2448 return CYCastJSValue(context, CYJSString(type));
2453 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2455 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2457 const char *type(sig::Unparse(pool, internal->type_));
2459 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
2464 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2465 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
2468 static JSStaticValue CYValue_staticValues[2] = {
2469 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2470 {NULL, NULL, NULL, 0}
2473 static JSStaticFunction Pointer_staticFunctions[4] = {
2474 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2475 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2476 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2480 static JSStaticFunction Functor_staticFunctions[4] = {
2481 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2482 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2483 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2487 /*static JSStaticValue Selector_staticValues[2] = {
2488 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2489 {NULL, NULL, NULL, 0}
2492 static JSStaticFunction Instance_staticFunctions[4] = {
2493 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2494 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2495 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2499 static JSStaticFunction Selector_staticFunctions[5] = {
2500 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2501 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2502 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2503 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2507 static JSStaticFunction Type_staticFunctions[5] = {
2508 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2509 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2510 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2514 CYDriver::CYDriver(const std::string &filename) :
2518 filename_(filename),
2524 CYDriver::~CYDriver() {
2528 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2529 CYDriver::Error error;
2530 error.location_ = location;
2531 error.message_ = message;
2532 driver.errors_.push_back(error);
2535 void CYSetArgs(int argc, const char *argv[]) {
2536 JSContextRef context(CYGetJSContext());
2537 JSValueRef args[argc];
2538 for (int i(0); i != argc; ++i)
2539 args[i] = CYCastJSValue(context, argv[i]);
2540 JSValueRef exception(NULL);
2541 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2542 CYThrow(context, exception);
2543 CYSetProperty(context, System_, CYJSString("args"), array);
2546 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2547 return JSContextGetGlobalObject(context);
2550 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
2551 JSContextRef context(CYGetJSContext());
2552 JSValueRef exception(NULL), result;
2555 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
2556 } catch (const char *error) {
2560 if (exception != NULL) { error:
2565 if (JSValueIsUndefined(context, result))
2568 const char *json(CYPoolCCYON(pool, context, result, &exception));
2569 if (exception != NULL)
2572 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
2576 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
2577 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
2585 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
2586 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
2599 const char * volatile data_;
2602 // XXX: this is "tre lame"
2603 @interface CYClient_ : NSObject {
2606 - (void) execute:(NSValue *)value;
2610 @implementation CYClient_
2612 - (void) execute:(NSValue *)value {
2613 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
2614 const char *data(execute->data_);
2615 execute->data_ = NULL;
2616 execute->data_ = CYExecute(execute->pool_, data);
2625 apr_thread_t *thread_;
2627 CYClient(int socket) :
2633 _syscall(close(socket_));
2636 void Handle() { _pooled
2637 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
2641 if (!CYRecvAll(socket_, &size, sizeof(size)))
2645 char *data(new(pool) char[size + 1]);
2646 if (!CYRecvAll(socket_, data, size))
2650 CYDriver driver("");
2651 cy::parser parser(driver);
2653 driver.data_ = data;
2654 driver.size_ = size;
2657 if (parser.parse() != 0 || !driver.errors_.empty()) {
2659 size = _not(size_t);
2661 std::ostringstream str;
2662 driver.source_->Show(str);
2663 std::string code(str.str());
2664 CYExecute_ execute = {pool, code.c_str()};
2665 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
2666 json = execute.data_;
2667 size = json == NULL ? _not(size_t) : strlen(json);
2670 if (!CYSendAll(socket_, &size, sizeof(size)))
2673 if (!CYSendAll(socket_, json, size))
2679 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
2680 CYClient *client(reinterpret_cast<CYClient *>(data));
2686 static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
2688 int socket(_syscall(accept(Socket_, NULL, NULL)));
2689 CYClient *client(new CYClient(socket));
2690 apr_threadattr_t *attr;
2691 _aprcall(apr_threadattr_create(&attr, Pool_));
2692 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
2699 pid_t pid(getpid());
2701 sprintf(path, "/tmp/.s.cy.%u", pid);
2705 MSInitialize { _pooled
2706 _aprcall(apr_initialize());
2707 _aprcall(apr_pool_create(&Pool_, NULL));
2709 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2711 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2712 NSCFType_ = objc_getClass("NSCFType");
2713 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2714 NSZombie_ = objc_getClass("_NSZombie_");
2715 Object_ = objc_getClass("Object");
2717 Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
2719 struct sockaddr_un address;
2720 memset(&address, 0, sizeof(address));
2721 address.sun_family = AF_UNIX;
2723 pid_t pid(getpid());
2724 sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
2727 _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
2729 _syscall(listen(Socket_, 0));
2731 apr_threadattr_t *attr;
2732 _aprcall(apr_threadattr_create(&attr, Pool_));
2734 apr_thread_t *thread;
2735 _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
2737 NSLog(@"failed to setup Cyrver");
2741 JSGlobalContextRef CYGetJSContext() {
2742 if (Context_ == NULL) {
2743 JSClassDefinition definition;
2745 definition = kJSClassDefinitionEmpty;
2746 definition.className = "Functor";
2747 definition.staticFunctions = Functor_staticFunctions;
2748 definition.callAsFunction = &Functor_callAsFunction;
2749 definition.finalize = &CYData::Finalize;
2750 Functor_ = JSClassCreate(&definition);
2752 definition = kJSClassDefinitionEmpty;
2753 definition.className = "Instance";
2754 definition.staticValues = CYValue_staticValues;
2755 definition.staticFunctions = Instance_staticFunctions;
2756 definition.getProperty = &Instance_getProperty;
2757 definition.setProperty = &Instance_setProperty;
2758 definition.deleteProperty = &Instance_deleteProperty;
2759 definition.getPropertyNames = &Instance_getPropertyNames;
2760 definition.callAsConstructor = &Instance_callAsConstructor;
2761 definition.finalize = &CYData::Finalize;
2762 Instance_ = JSClassCreate(&definition);
2764 definition = kJSClassDefinitionEmpty;
2765 definition.className = "Pointer";
2766 definition.staticFunctions = Pointer_staticFunctions;
2767 definition.getProperty = &Pointer_getProperty;
2768 definition.setProperty = &Pointer_setProperty;
2769 definition.finalize = &CYData::Finalize;
2770 Pointer_ = JSClassCreate(&definition);
2772 definition = kJSClassDefinitionEmpty;
2773 definition.className = "Selector";
2774 definition.staticValues = CYValue_staticValues;
2775 //definition.staticValues = Selector_staticValues;
2776 definition.staticFunctions = Selector_staticFunctions;
2777 definition.callAsFunction = &Selector_callAsFunction;
2778 definition.finalize = &CYData::Finalize;
2779 Selector_ = JSClassCreate(&definition);
2781 definition = kJSClassDefinitionEmpty;
2782 definition.className = "Struct";
2783 definition.getProperty = &Struct_getProperty;
2784 definition.setProperty = &Struct_setProperty;
2785 definition.getPropertyNames = &Struct_getPropertyNames;
2786 definition.finalize = &CYData::Finalize;
2787 Struct_ = JSClassCreate(&definition);
2789 definition = kJSClassDefinitionEmpty;
2790 definition.className = "Type";
2791 definition.staticFunctions = Type_staticFunctions;
2792 //definition.getProperty = &Type_getProperty;
2793 definition.callAsFunction = &Type_callAsFunction;
2794 definition.callAsConstructor = &Type_callAsConstructor;
2795 definition.finalize = &CYData::Finalize;
2796 Type_ = JSClassCreate(&definition);
2798 definition = kJSClassDefinitionEmpty;
2799 definition.className = "Runtime";
2800 definition.getProperty = &Runtime_getProperty;
2801 Runtime_ = JSClassCreate(&definition);
2803 definition = kJSClassDefinitionEmpty;
2804 definition.className = "ObjectiveC::Classes";
2805 definition.getProperty = &ObjectiveC_Classes_getProperty;
2806 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2807 ObjectiveC_Classes_ = JSClassCreate(&definition);
2809 definition = kJSClassDefinitionEmpty;
2810 definition.className = "ObjectiveC::Images";
2811 definition.getProperty = &ObjectiveC_Images_getProperty;
2812 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2813 ObjectiveC_Images_ = JSClassCreate(&definition);
2815 definition = kJSClassDefinitionEmpty;
2816 definition.className = "ObjectiveC::Image::Classes";
2817 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2818 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2819 definition.finalize = &CYData::Finalize;
2820 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2822 definition = kJSClassDefinitionEmpty;
2823 definition.className = "ObjectiveC::Protocols";
2824 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2825 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2826 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2828 definition = kJSClassDefinitionEmpty;
2829 //definition.getProperty = &Global_getProperty;
2830 JSClassRef Global(JSClassCreate(&definition));
2832 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2835 JSObjectRef global(CYGetGlobalObject(context));
2837 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2838 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
2839 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
2841 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2842 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2843 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2845 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2846 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, NULL));
2847 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
2848 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2849 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
2851 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2853 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2855 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
2856 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2858 System_ = JSObjectMake(context, NULL, NULL);
2859 CYSetProperty(context, global, CYJSString("system"), System_);
2860 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2861 //CYSetProperty(context, System_, CYJSString("global"), global);
2863 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2865 Result_ = JSStringCreateWithUTF8CString("_");
2867 length_ = JSStringCreateWithUTF8CString("length");
2868 message_ = JSStringCreateWithUTF8CString("message");
2869 name_ = JSStringCreateWithUTF8CString("name");
2870 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2871 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2873 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2874 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));