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 Internal_;
115 static JSClassRef Pointer_;
116 static JSClassRef Runtime_;
117 static JSClassRef Selector_;
118 static JSClassRef Struct_;
119 static JSClassRef Type_;
121 static JSClassRef ObjectiveC_Classes_;
122 static JSClassRef ObjectiveC_Image_Classes_;
123 static JSClassRef ObjectiveC_Images_;
124 static JSClassRef ObjectiveC_Protocols_;
126 static JSObjectRef Array_;
127 static JSObjectRef Function_;
129 static JSStringRef Result_;
131 static JSStringRef length_;
132 static JSStringRef message_;
133 static JSStringRef name_;
134 static JSStringRef toCYON_;
135 static JSStringRef toJSON_;
137 static Class NSCFBoolean_;
138 static Class NSCFType_;
139 static Class NSMessageBuilder_;
140 static Class NSZombie_;
141 static Class Object_;
143 static NSArray *Bridge_;
151 static void *operator new(size_t size, apr_pool_t *pool) {
152 void *data(apr_palloc(pool, size));
153 reinterpret_cast<CYData *>(data)->pool_ = pool;
157 static void *operator new(size_t size) {
159 apr_pool_create(&pool, NULL);
160 return operator new(size, pool);
163 static void operator delete(void *data) {
164 apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
167 static void Finalize(JSObjectRef object) {
168 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
180 CYValue(void *value) :
185 CYValue(const CYValue &rhs) :
191 struct Selector_privateData :
194 Selector_privateData(SEL value) :
199 SEL GetValue() const {
200 return reinterpret_cast<SEL>(value_);
209 Transient = (1 << 0),
210 Uninitialized = (1 << 1),
215 Instance(id value, Flags flags) :
221 virtual ~Instance() {
222 if ((flags_ & Transient) == 0)
223 // XXX: does this handle background threads correctly?
224 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
227 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
228 return JSObjectMake(context, Instance_, new Instance(object, flags));
231 id GetValue() const {
232 return reinterpret_cast<id>(value_);
235 bool IsUninitialized() const {
236 return (flags_ & Uninitialized) != 0;
245 Internal(id value, JSObjectRef owner) :
251 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
252 return JSObjectMake(context, Internal_, new Internal(object, owner));
255 id GetValue() const {
256 return reinterpret_cast<id>(value_);
262 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
264 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
265 lhs.name = apr_pstrdup(pool, rhs.name);
266 if (rhs.type == NULL)
269 lhs.type = new(pool) Type;
270 Copy(pool, *lhs.type, *rhs.type);
272 lhs.offset = rhs.offset;
275 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
276 size_t count(rhs.count);
278 lhs.elements = new(pool) Element[count];
279 for (size_t index(0); index != count; ++index)
280 Copy(pool, lhs.elements[index], rhs.elements[index]);
283 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
284 lhs.primitive = rhs.primitive;
285 lhs.name = apr_pstrdup(pool, rhs.name);
286 lhs.flags = rhs.flags;
288 if (sig::IsAggregate(rhs.primitive))
289 Copy(pool, lhs.data.signature, rhs.data.signature);
291 if (rhs.data.data.type != NULL) {
292 lhs.data.data.type = new(pool) Type;
293 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
296 lhs.data.data.size = rhs.data.data.size;
300 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
302 lhs.alignment = rhs.alignment;
304 if (rhs.elements == NULL)
308 while (rhs.elements[count] != NULL)
311 lhs.elements = new(pool) ffi_type *[count + 1];
312 lhs.elements[count] = NULL;
314 for (size_t index(0); index != count; ++index) {
315 // XXX: if these are libffi native then you can just take them
316 ffi_type *ffi(new(pool) ffi_type);
317 lhs.elements[index] = ffi;
318 sig::Copy(pool, *ffi, *rhs.elements[index]);
325 struct CStringMapLess :
326 std::binary_function<const char *, const char *, bool>
328 _finline bool operator ()(const char *lhs, const char *rhs) const {
329 return strcmp(lhs, rhs) < 0;
333 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
338 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
339 switch ([[entry objectAtIndex:0] intValue]) {
341 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
345 sig::Signature signature;
346 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
347 type = signature.elements[0].type;
353 struct Type_privateData :
359 void Set(sig::Type *type) {
360 type_ = new(pool_) sig::Type;
361 sig::Copy(pool_, *type_, *type);
364 Type_privateData(apr_pool_t *pool, const char *type) :
370 sig::Signature signature;
371 sig::Parse(pool_, &signature, type, &Structor_);
372 type_ = signature.elements[0].type;
375 Type_privateData(sig::Type *type) :
382 Type_privateData(sig::Type *type, ffi_type *ffi) {
383 ffi_ = new(pool_) ffi_type;
384 sig::Copy(pool_, *ffi_, *ffi);
390 ffi_ = new(pool_) ffi_type;
392 sig::Element element;
394 element.type = type_;
397 sig::Signature signature;
398 signature.elements = &element;
402 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
414 Type_privateData *type_;
416 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
419 type_(new(pool_) Type_privateData(type))
424 struct Struct_privateData :
428 Type_privateData *type_;
430 Struct_privateData(JSObjectRef owner) :
436 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
437 static TypeMap Types_;
439 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
440 Struct_privateData *internal(new Struct_privateData(owner));
441 apr_pool_t *pool(internal->pool_);
442 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
443 internal->type_ = typical;
446 internal->value_ = data;
448 size_t size(typical->GetFFI()->size);
449 void *copy(apr_palloc(internal->pool_, size));
450 memcpy(copy, data, size);
451 internal->value_ = copy;
454 return JSObjectMake(context, Struct_, internal);
457 struct Functor_privateData :
460 sig::Signature signature_;
463 Functor_privateData(const char *type, void (*value)()) :
464 CYValue(reinterpret_cast<void *>(value))
466 sig::Parse(pool_, &signature_, type, &Structor_);
467 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
474 JSContextRef context_;
475 JSObjectRef function_;
477 ffoData(const char *type) :
478 Functor_privateData(type, NULL)
483 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
484 Instance::Flags flags;
487 flags = Instance::Transient;
489 flags = Instance::None;
490 object = [object retain];
493 return Instance::Make(context, object, flags);
496 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
498 return [value UTF8String];
500 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
501 char *string(new(pool) char[size]);
502 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
503 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
508 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
509 return JSValueMakeBoolean(context, value);
512 JSValueRef CYCastJSValue(JSContextRef context, double value) {
513 return JSValueMakeNumber(context, value);
516 #define CYCastJSValue_(Type_) \
517 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
518 return JSValueMakeNumber(context, static_cast<double>(value)); \
522 CYCastJSValue_(unsigned int)
523 CYCastJSValue_(long int)
524 CYCastJSValue_(long unsigned int)
525 CYCastJSValue_(long long int)
526 CYCastJSValue_(long long unsigned int)
528 JSValueRef CYJSUndefined(JSContextRef context) {
529 return JSValueMakeUndefined(context);
532 bool CYGetIndex(const char *value, ssize_t &index) {
533 if (value[0] != '0') {
535 index = strtol(value, &end, 10);
536 if (value + strlen(value) == end)
538 } else if (value[1] == '\0') {
546 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
547 return CYGetIndex(CYPoolCString(pool, value), index);
550 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
552 @interface NSMethodSignature (Cycript)
553 - (NSString *) _typeString;
556 @interface NSObject (Cycript)
558 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
559 - (JSType) cy$JSType;
561 - (NSObject *) cy$toJSON:(NSString *)key;
562 - (NSString *) cy$toCYON;
563 - (NSString *) cy$toKey;
565 - (NSObject *) cy$getProperty:(NSString *)name;
566 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
567 - (bool) cy$deleteProperty:(NSString *)name;
572 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
575 @interface NSString (Cycript)
576 - (void *) cy$symbol;
579 struct PropertyAttributes {
584 const char *variable;
597 PropertyAttributes(objc_property_t property) :
609 name = property_getName(property);
610 const char *attributes(property_getAttributes(property));
612 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
614 case 'R': readonly = true; break;
615 case 'C': copy = true; break;
616 case '&': retain = true; break;
617 case 'N': nonatomic = true; break;
618 case 'G': getter_ = token + 1; break;
619 case 'S': setter_ = token + 1; break;
620 case 'V': variable = token + 1; break;
624 /*if (variable == NULL) {
625 variable = property_getName(property);
626 size_t size(strlen(variable));
627 char *name(new(pool_) char[size + 2]);
629 memcpy(name + 1, variable, size);
630 name[size + 1] = '\0';
635 const char *Getter() {
637 getter_ = apr_pstrdup(pool_, name);
641 const char *Setter() {
642 if (setter_ == NULL && !readonly) {
643 size_t length(strlen(name));
645 char *temp(new(pool_) char[length + 5]);
651 temp[3] = toupper(name[0]);
652 memcpy(temp + 4, name + 1, length - 1);
655 temp[length + 3] = ':';
656 temp[length + 4] = '\0';
665 @implementation NSProxy (Cycript)
667 - (NSObject *) cy$toJSON:(NSString *)key {
668 return [self description];
671 - (NSString *) cy$toCYON {
672 return [[self cy$toJSON:@""] cy$toCYON];
677 @implementation NSObject (Cycript)
679 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
680 return CYMakeInstance(context, self, false);
683 - (JSType) cy$JSType {
684 return kJSTypeObject;
687 - (NSObject *) cy$toJSON:(NSString *)key {
688 return [self description];
691 - (NSString *) cy$toCYON {
692 return [[self cy$toJSON:@""] cy$toCYON];
695 - (NSString *) cy$toKey {
696 return [self cy$toCYON];
699 - (NSObject *) cy$getProperty:(NSString *)name {
700 /*if (![name isEqualToString:@"prototype"])
701 NSLog(@"get:%@", name);*/
705 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
706 //NSLog(@"set:%@", name);
710 - (bool) cy$deleteProperty:(NSString *)name {
711 //NSLog(@"delete:%@", name);
717 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
718 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
721 @implementation WebUndefined (Cycript)
723 - (JSType) cy$JSType {
724 return kJSTypeUndefined;
727 - (NSObject *) cy$toJSON:(NSString *)key {
731 - (NSString *) cy$toCYON {
735 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
736 return CYJSUndefined(context);
741 @implementation NSNull (Cycript)
743 - (JSType) cy$JSType {
747 - (NSObject *) cy$toJSON:(NSString *)key {
751 - (NSString *) cy$toCYON {
757 @implementation NSArray (Cycript)
759 - (NSString *) cy$toCYON {
760 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
761 [json appendString:@"["];
764 for (id object in self) {
766 [json appendString:@","];
769 if ([object cy$JSType] != kJSTypeUndefined)
770 [json appendString:CYPoolNSCYON(NULL, object)];
772 [json appendString:@","];
777 [json appendString:@"]"];
781 - (NSObject *) cy$getProperty:(NSString *)name {
782 if ([name isEqualToString:@"length"])
783 return [NSNumber numberWithUnsignedInteger:[self count]];
786 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
787 return [super cy$getProperty:name];
789 return [self objectAtIndex:index];
794 @implementation NSMutableArray (Cycript)
796 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
798 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
799 return [super cy$setProperty:name to:value];
801 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
806 - (bool) cy$deleteProperty:(NSString *)name {
808 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
809 return [super cy$deleteProperty:name];
811 [self removeObjectAtIndex:index];
818 @implementation NSDictionary (Cycript)
820 - (NSString *) cy$toCYON {
821 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
822 [json appendString:@"{"];
825 for (id key in self) {
827 [json appendString:@","];
830 [json appendString:[key cy$toKey]];
831 [json appendString:@":"];
832 NSObject *object([self objectForKey:key]);
833 [json appendString:CYPoolNSCYON(NULL, object)];
836 [json appendString:@"}"];
840 - (NSObject *) cy$getProperty:(NSString *)name {
841 return [self objectForKey:name];
846 @implementation NSMutableDictionary (Cycript)
848 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
849 [self setObject:(value ?: [NSNull null]) forKey:name];
853 - (bool) cy$deleteProperty:(NSString *)name {
854 if ([self objectForKey:name] == nil)
857 [self removeObjectForKey:name];
864 @implementation NSNumber (Cycript)
866 - (JSType) cy$JSType {
867 // XXX: this just seems stupid
868 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
871 - (NSObject *) cy$toJSON:(NSString *)key {
875 - (NSString *) cy$toCYON {
876 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
879 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
880 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
885 @implementation NSString (Cycript)
887 - (JSType) cy$JSType {
888 return kJSTypeString;
891 - (NSObject *) cy$toJSON:(NSString *)key {
895 - (NSString *) cy$toCYON {
896 // XXX: this should use the better code from Output.cpp
897 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
899 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
900 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
901 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
902 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
903 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
905 CFStringInsert(json, 0, CFSTR("\""));
906 CFStringAppend(json, CFSTR("\""));
908 return [reinterpret_cast<const NSString *>(json) autorelease];
911 - (NSString *) cy$toKey {
912 const char *value([self UTF8String]);
913 size_t size(strlen(value));
918 if (DigitRange_[value[0]]) {
920 if (!CYGetIndex(NULL, self, index) || index < 0)
923 if (!WordStartRange_[value[0]])
925 for (size_t i(1); i != size; ++i)
926 if (!WordEndRange_[value[i]])
933 return [self cy$toCYON];
936 - (void *) cy$symbol {
938 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
943 @interface CYJSObject : NSDictionary {
945 JSContextRef context_;
948 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
950 - (NSString *) cy$toJSON:(NSString *)key;
952 - (NSUInteger) count;
953 - (id) objectForKey:(id)key;
954 - (NSEnumerator *) keyEnumerator;
955 - (void) setObject:(id)object forKey:(id)key;
956 - (void) removeObjectForKey:(id)key;
960 @interface CYJSArray : NSArray {
962 JSContextRef context_;
965 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
967 - (NSUInteger) count;
968 - (id) objectAtIndex:(NSUInteger)index;
972 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
973 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
974 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
979 @catch (id error) { \
980 CYThrow(context, error, exception); \
984 void CYThrow(JSContextRef context, JSValueRef value);
986 apr_status_t CYPoolRelease_(void *data) {
987 id object(reinterpret_cast<id>(data));
992 id CYPoolRelease(apr_pool_t *pool, id object) {
995 else if (pool == NULL)
996 return [object autorelease];
998 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1003 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1004 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1007 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1008 JSValueRef exception(NULL);
1009 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1010 CYThrow(context, exception);
1011 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1012 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1015 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1016 if (!JSValueIsObjectOfClass(context, object, Instance_))
1017 return CYCastNSObject_(pool, context, object);
1019 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1020 return data->GetValue();
1024 JSStringRef CYCopyJSString(id value) {
1025 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1028 JSStringRef CYCopyJSString(const char *value) {
1029 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1032 JSStringRef CYCopyJSString(JSStringRef value) {
1033 return value == NULL ? NULL : JSStringRetain(value);
1036 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1037 if (JSValueIsNull(context, value))
1039 JSValueRef exception(NULL);
1040 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1041 CYThrow(context, exception);
1047 JSStringRef string_;
1050 if (string_ != NULL)
1051 JSStringRelease(string_);
1055 CYJSString(const CYJSString &rhs) :
1056 string_(CYCopyJSString(rhs.string_))
1060 template <typename Arg0_>
1061 CYJSString(Arg0_ arg0) :
1062 string_(CYCopyJSString(arg0))
1066 template <typename Arg0_, typename Arg1_>
1067 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1068 string_(CYCopyJSString(arg0, arg1))
1072 CYJSString &operator =(const CYJSString &rhs) {
1074 string_ = CYCopyJSString(rhs.string_);
1087 operator JSStringRef() const {
1092 CFStringRef CYCopyCFString(JSStringRef value) {
1093 return JSStringCopyCFString(kCFAllocatorDefault, value);
1096 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1097 return CYCopyCFString(CYJSString(context, value));
1100 double CYCastDouble(const char *value, size_t size) {
1102 double number(strtod(value, &end));
1103 if (end != value + size)
1108 double CYCastDouble(const char *value) {
1109 return CYCastDouble(value, strlen(value));
1112 double CYCastDouble(JSContextRef context, JSValueRef value) {
1113 JSValueRef exception(NULL);
1114 double number(JSValueToNumber(context, value, &exception));
1115 CYThrow(context, exception);
1119 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1120 double number(CYCastDouble(context, value));
1121 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1124 CFStringRef CYCopyCFString(const char *value) {
1125 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1128 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1129 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1132 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1133 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1136 bool CYCastBool(JSContextRef context, JSValueRef value) {
1137 return JSValueToBoolean(context, value);
1140 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1144 switch (JSType type = JSValueGetType(context, value)) {
1145 case kJSTypeUndefined:
1146 object = [WebUndefined undefined];
1154 case kJSTypeBoolean:
1155 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1160 object = CYCopyCFNumber(context, value);
1165 object = CYCopyCFString(context, value);
1170 // XXX: this might could be more efficient
1171 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1176 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1183 return CYPoolRelease(pool, object);
1185 return CFRetain(object);
1188 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1189 return CYCFType(pool, context, value, true);
1192 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1193 return CYCFType(pool, context, value, false);
1196 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1198 size_t size(JSPropertyNameArrayGetCount(names));
1199 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1200 for (size_t index(0); index != size; ++index)
1201 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1205 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1206 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1209 void CYThrow(JSContextRef context, JSValueRef value) {
1212 @throw CYCastNSObject(NULL, context, value);
1215 JSValueRef CYJSNull(JSContextRef context) {
1216 return JSValueMakeNull(context);
1219 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1220 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1223 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1224 return CYCastJSValue(context, CYJSString(value));
1227 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1229 return CYJSNull(context);
1230 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1231 return [value cy$JSValueInContext:context];
1233 return CYMakeInstance(context, value, false);
1236 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1237 JSValueRef exception(NULL);
1238 JSObjectRef object(JSValueToObject(context, value, &exception));
1239 CYThrow(context, exception);
1243 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1244 JSValueRef exception(NULL);
1245 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1246 CYThrow(context, exception);
1250 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1251 JSValueRef exception(NULL);
1252 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1253 CYThrow(context, exception);
1257 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1258 JSValueRef exception(NULL);
1259 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1260 CYThrow(context, exception);
1263 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1264 if (exception == NULL)
1266 *exception = CYCastJSValue(context, error);
1269 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1270 JSValueRef exception(NULL);
1271 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1272 CYThrow(context, exception);
1276 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1277 // XXX: this isn't actually correct
1278 return value != NULL && JSValueIsObject(context, value);
1281 @implementation CYJSObject
1283 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1284 if ((self = [super init]) != nil) {
1290 - (NSObject *) cy$toJSON:(NSString *)key {
1291 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1292 if (!CYIsCallable(context_, toJSON))
1293 return [super cy$toJSON:key];
1295 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1296 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1297 // XXX: do I really want an NSNull here?!
1298 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1302 - (NSString *) cy$toCYON {
1303 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1304 if (!CYIsCallable(context_, toCYON))
1305 return [super cy$toCYON];
1307 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1308 return CYCastNSString(NULL, CYJSString(context_, value));
1312 - (NSUInteger) count {
1313 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1314 size_t size(JSPropertyNameArrayGetCount(names));
1315 JSPropertyNameArrayRelease(names);
1319 - (id) objectForKey:(id)key {
1320 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1323 - (NSEnumerator *) keyEnumerator {
1324 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1325 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1326 JSPropertyNameArrayRelease(names);
1330 - (void) setObject:(id)object forKey:(id)key {
1331 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1334 - (void) removeObjectForKey:(id)key {
1335 JSValueRef exception(NULL);
1336 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1337 CYThrow(context_, exception);
1342 @implementation CYJSArray
1344 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1345 if ((self = [super init]) != nil) {
1351 - (NSUInteger) count {
1352 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1355 - (id) objectAtIndex:(NSUInteger)index {
1356 JSValueRef exception(NULL);
1357 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1358 CYThrow(context_, exception);
1359 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1364 NSString *CYCopyNSCYON(id value) {
1365 Class _class(object_getClass(value));
1366 SEL sel(@selector(cy$toCYON));
1370 if (Method toCYON = class_getInstanceMethod(_class, sel))
1371 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1372 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1373 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1374 string = [value cy$toCYON];
1377 if (value == NSZombie_)
1378 string = @"_NSZombie_";
1379 else if (_class == NSZombie_)
1380 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1381 else if (value == NSMessageBuilder_ || value == Object_)
1384 string = [NSString stringWithFormat:@"%@", value];
1387 // XXX: frowny pants
1389 string = @"undefined";
1390 return [string retain];
1393 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1396 return CYCopyNSCYON(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1401 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1402 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1405 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1406 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1407 const char *string(CYPoolCString(pool, json));
1413 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1417 JSObjectRef object_;
1425 // XXX: delete object_? ;(
1428 static CYInternal *Get(id self) {
1429 CYInternal *internal(NULL);
1430 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1431 // XXX: do something epic? ;P
1437 static CYInternal *Set(id self) {
1438 CYInternal *internal(NULL);
1439 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1440 if (internal == NULL) {
1441 internal = new CYInternal();
1442 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1445 // XXX: do something epic? ;P
1451 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1452 if (object_ == NULL)
1454 return CYGetProperty(context, object_, name);
1457 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1458 if (object_ == NULL)
1459 object_ = JSObjectMake(context, NULL, NULL);
1460 CYSetProperty(context, object_, name, value);
1464 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1465 Selector_privateData *data(new Selector_privateData(sel));
1466 return JSObjectMake(context, Selector_, data);
1469 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1470 Pointer *data(new Pointer(pointer, type, owner));
1471 return JSObjectMake(context, Pointer_, data);
1474 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1475 Functor_privateData *data(new Functor_privateData(type, function));
1476 return JSObjectMake(context, Functor_, data);
1479 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1481 const char *string([CYCastNSString(NULL, value) UTF8String]);
1484 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1485 char *string(new(pool) char[size]);
1486 JSStringGetUTF8CString(value, string, size);
1491 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1492 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1495 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1496 return CYGetIndex(CYPoolCString(pool, value), index);
1499 // XXX: this macro is unhygenic
1500 #define CYCastCString(context, value) ({ \
1502 if (value == NULL) \
1504 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1505 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1506 utf8 = reinterpret_cast<char *>(alloca(size)); \
1507 JSStringGetUTF8CString(string, utf8, size); \
1508 JSStringRelease(string); \
1514 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1515 switch (JSValueGetType(context, value)) {
1518 /*case kJSTypeString:
1519 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1521 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1522 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1523 return data->value_;
1526 double number(CYCastDouble(context, value));
1527 if (std::isnan(number))
1528 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1529 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1533 template <typename Type_>
1534 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1535 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1538 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1539 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1540 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1541 return reinterpret_cast<SEL>(data->value_);
1543 return CYCastPointer<SEL>(context, value);
1546 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1547 switch (type->primitive) {
1548 case sig::boolean_P:
1549 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1552 #define CYPoolFFI_(primitive, native) \
1553 case sig::primitive ## _P: \
1554 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1557 CYPoolFFI_(uchar, unsigned char)
1558 CYPoolFFI_(char, char)
1559 CYPoolFFI_(ushort, unsigned short)
1560 CYPoolFFI_(short, short)
1561 CYPoolFFI_(ulong, unsigned long)
1562 CYPoolFFI_(long, long)
1563 CYPoolFFI_(uint, unsigned int)
1564 CYPoolFFI_(int, int)
1565 CYPoolFFI_(ulonglong, unsigned long long)
1566 CYPoolFFI_(longlong, long long)
1567 CYPoolFFI_(float, float)
1568 CYPoolFFI_(double, double)
1571 case sig::typename_P:
1572 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1575 case sig::selector_P:
1576 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1579 case sig::pointer_P:
1580 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1584 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1587 case sig::struct_P: {
1588 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1589 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1590 for (size_t index(0); index != type->data.signature.count; ++index) {
1591 sig::Element *element(&type->data.signature.elements[index]);
1592 ffi_type *field(ffi->elements[index]);
1595 if (aggregate == NULL)
1598 rhs = CYGetProperty(context, aggregate, index);
1599 if (JSValueIsUndefined(context, rhs)) {
1600 if (element->name != NULL)
1601 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1604 if (JSValueIsUndefined(context, rhs)) undefined:
1605 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1609 CYPoolFFI(pool, context, element->type, field, base, rhs);
1611 base += field->size;
1619 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1624 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1627 switch (type->primitive) {
1628 case sig::boolean_P:
1629 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1632 #define CYFromFFI_(primitive, native) \
1633 case sig::primitive ## _P: \
1634 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1637 CYFromFFI_(uchar, unsigned char)
1638 CYFromFFI_(char, char)
1639 CYFromFFI_(ushort, unsigned short)
1640 CYFromFFI_(short, short)
1641 CYFromFFI_(ulong, unsigned long)
1642 CYFromFFI_(long, long)
1643 CYFromFFI_(uint, unsigned int)
1644 CYFromFFI_(int, int)
1645 CYFromFFI_(ulonglong, unsigned long long)
1646 CYFromFFI_(longlong, long long)
1647 CYFromFFI_(float, float)
1648 CYFromFFI_(double, double)
1650 case sig::object_P: {
1651 if (id object = *reinterpret_cast<id *>(data)) {
1652 value = CYCastJSValue(context, object);
1658 case sig::typename_P:
1659 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1662 case sig::selector_P:
1663 if (SEL sel = *reinterpret_cast<SEL *>(data))
1664 value = CYMakeSelector(context, sel);
1668 case sig::pointer_P:
1669 if (void *pointer = *reinterpret_cast<void **>(data))
1670 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1675 if (char *utf8 = *reinterpret_cast<char **>(data))
1676 value = CYCastJSValue(context, utf8);
1681 value = CYMakeStruct(context, data, type, ffi, owner);
1685 value = CYJSUndefined(context);
1689 value = CYJSNull(context);
1693 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1700 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1704 id self(CYCastNSObject(pool, context, object));
1705 NSString *name(CYCastNSString(pool, property));
1707 if (CYInternal *internal = CYInternal::Get(self))
1708 if (JSValueRef value = internal->GetProperty(context, property))
1712 if (NSObject *data = [self cy$getProperty:name])
1713 return CYCastJSValue(context, data);
1716 const char *string(CYPoolCString(pool, name));
1717 Class _class(object_getClass(self));
1719 if (objc_property_t property = class_getProperty(_class, string)) {
1720 PropertyAttributes attributes(property);
1721 SEL sel(sel_registerName(attributes.Getter()));
1722 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1725 if (SEL sel = sel_getUid(string))
1726 // XXX: possibly use a more "awesome" check?
1727 if (class_getInstanceMethod(_class, sel) != NULL)
1728 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1734 static JSValueRef Instance_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1735 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1736 return Internal::Make(context, internal->GetValue(), object);
1739 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1743 id self(CYCastNSObject(pool, context, object));
1744 NSString *name(CYCastNSString(pool, property));
1745 NSString *data(CYCastNSObject(pool, context, value));
1748 if ([self cy$setProperty:name to:data])
1752 const char *string(CYPoolCString(pool, name));
1753 Class _class(object_getClass(self));
1755 if (objc_property_t property = class_getProperty(_class, string)) {
1756 PropertyAttributes attributes(property);
1757 if (const char *setter = attributes.Setter()) {
1758 SEL sel(sel_registerName(setter));
1759 JSValueRef arguments[1] = {value};
1760 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1765 size_t length(strlen(string));
1767 char set[length + 5];
1773 if (string[0] != '\0') {
1774 set[3] = toupper(string[0]);
1775 memcpy(set + 4, string + 1, length - 1);
1778 set[length + 3] = ':';
1779 set[length + 4] = '\0';
1781 if (SEL sel = sel_getUid(set))
1782 // XXX: possibly use a more "awesome" check?
1783 if (class_getInstanceMethod(_class, sel) != NULL) {
1784 JSValueRef arguments[1] = {value};
1785 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1788 if (CYInternal *internal = CYInternal::Set(self)) {
1789 internal->SetProperty(context, property, value);
1797 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1800 id self(CYCastNSObject(NULL, context, object));
1801 NSString *name(CYCastNSString(NULL, property));
1802 return [self cy$deleteProperty:name];
1807 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1809 NSString *self(CYCastNSObject(pool, context, object));
1810 Class _class(object_getClass(self));
1814 objc_property_t *data(class_copyPropertyList(_class, &size));
1815 for (size_t i(0); i != size; ++i)
1816 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1821 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1823 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1824 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1829 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1830 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1834 id self(internal->GetValue());
1835 const char *name(CYPoolCString(pool, property));
1837 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
1838 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1839 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1846 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1847 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1851 id self(internal->GetValue());
1852 const char *name(CYPoolCString(pool, property));
1854 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
1855 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1856 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1864 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1865 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1868 id self(internal->GetValue());
1869 Class _class(object_getClass(self));
1871 for (Class super(_class); super != NULL; super = class_getSuperclass(super)) {
1873 Ivar *data(class_copyIvarList(super, &size));
1874 for (size_t i(0); i != size; ++i)
1875 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1880 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1881 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1882 return internal->owner_;
1885 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1886 Type_privateData *typical(internal->type_);
1887 sig::Type *type(typical->type_);
1891 const char *name(CYPoolCString(pool, property));
1892 size_t length(strlen(name));
1893 double number(CYCastDouble(name, length));
1895 size_t count(type->data.signature.count);
1897 if (std::isnan(number)) {
1898 if (property == NULL)
1901 sig::Element *elements(type->data.signature.elements);
1903 for (size_t local(0); local != count; ++local) {
1904 sig::Element *element(&elements[local]);
1905 if (element->name != NULL && strcmp(name, element->name) == 0) {
1913 index = static_cast<ssize_t>(number);
1914 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1919 ffi_type **elements(typical->GetFFI()->elements);
1921 base = reinterpret_cast<uint8_t *>(internal->value_);
1922 for (ssize_t local(0); local != index; ++local)
1923 base += elements[local]->size;
1928 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
1929 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1930 Type_privateData *typical(internal->type_);
1932 ffi_type *ffi(typical->GetFFI());
1934 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1935 base += ffi->size * index;
1937 JSObjectRef owner(internal->owner_ ?: object);
1940 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
1944 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1946 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1947 Type_privateData *typical(internal->type_);
1949 if (typical->type_ == NULL)
1953 if (!CYGetIndex(pool, property, index))
1956 return Pointer_getIndex(context, object, index, exception);
1959 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1960 return Pointer_getIndex(context, object, 0, exception);
1963 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
1964 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1965 Type_privateData *typical(internal->type_);
1967 ffi_type *ffi(typical->GetFFI());
1969 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1970 base += ffi->size * index;
1973 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
1978 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1980 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1981 Type_privateData *typical(internal->type_);
1983 if (typical->type_ == NULL)
1987 if (!CYGetIndex(pool, property, index))
1990 return Pointer_setIndex(context, object, 0, value, exception);
1993 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1994 return Pointer_setIndex(context, object, 0, value, exception);
1997 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1998 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
1999 Type_privateData *typical(internal->type_);
2000 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2003 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2005 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2006 Type_privateData *typical(internal->type_);
2011 if (!Index_(pool, internal, property, index, base))
2014 JSObjectRef owner(internal->owner_ ?: object);
2017 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2021 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2023 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2024 Type_privateData *typical(internal->type_);
2029 if (!Index_(pool, internal, property, index, base))
2033 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2038 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2039 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2040 Type_privateData *typical(internal->type_);
2041 sig::Type *type(typical->type_);
2046 size_t count(type->data.signature.count);
2047 sig::Element *elements(type->data.signature.elements);
2051 for (size_t index(0); index != count; ++index) {
2053 name = elements[index].name;
2056 sprintf(number, "%lu", index);
2060 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2064 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)()) {
2066 if (setups + count != signature->count - 1)
2067 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2069 size_t size(setups + count);
2071 memcpy(values, setup, sizeof(void *) * setups);
2073 for (size_t index(setups); index != size; ++index) {
2074 sig::Element *element(&signature->elements[index + 1]);
2075 ffi_type *ffi(cif->arg_types[index]);
2077 values[index] = new(pool) uint8_t[ffi->size];
2078 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2081 uint8_t value[cif->rtype->size];
2082 ffi_call(cif, function, value, values);
2084 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2088 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
2089 ffoData *data(reinterpret_cast<ffoData *>(arg));
2091 JSContextRef context(data->context_);
2093 size_t count(data->cif_.nargs);
2094 JSValueRef values[count];
2096 for (size_t index(0); index != count; ++index)
2097 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
2099 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
2100 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
2103 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2104 // XXX: in case of exceptions this will leak
2105 ffoData *data(new ffoData(type));
2107 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2108 NULL, sizeof(ffi_closure),
2109 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2113 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
2114 _assert(status == FFI_OK);
2116 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2118 data->value_ = closure;
2120 data->context_ = CYGetJSContext();
2121 data->function_ = function;
2123 return JSObjectMake(context, Functor_, data);
2126 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2129 NSString *name(CYCastNSString(pool, property));
2130 if (Class _class = NSClassFromString(name))
2131 return CYMakeInstance(context, _class, true);
2136 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2137 size_t size(objc_getClassList(NULL, 0));
2138 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2141 size_t writ(objc_getClassList(data, size));
2144 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2150 for (size_t i(0); i != writ; ++i)
2151 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2157 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2158 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2162 const char *name(CYPoolCString(pool, property));
2164 const char **data(objc_copyClassNamesForImage(internal, &size));
2166 for (size_t i(0); i != size; ++i)
2167 if (strcmp(name, data[i]) == 0) {
2168 if (Class _class = objc_getClass(name)) {
2169 value = CYMakeInstance(context, _class, true);
2181 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2182 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2184 const char **data(objc_copyClassNamesForImage(internal, &size));
2185 for (size_t i(0); i != size; ++i)
2186 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2190 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2193 const char *name(CYPoolCString(pool, property));
2195 const char **data(objc_copyImageNames(&size));
2196 for (size_t i(0); i != size; ++i)
2197 if (strcmp(name, data[i]) == 0) {
2206 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2207 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2212 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2214 const char **data(objc_copyImageNames(&size));
2215 for (size_t i(0); i != size; ++i)
2216 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2220 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2223 NSString *name(CYCastNSString(pool, property));
2224 if (Protocol *protocol = NSProtocolFromString(name))
2225 return CYMakeInstance(context, protocol, true);
2230 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2232 Protocol **data(objc_copyProtocolList(&size));
2233 for (size_t i(0); i != size; ++i)
2234 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2238 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2241 NSString *name(CYCastNSString(pool, property));
2242 if (Class _class = NSClassFromString(name))
2243 return CYMakeInstance(context, _class, true);
2244 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2245 switch ([[entry objectAtIndex:0] intValue]) {
2247 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2249 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2251 // XXX: this is horrendously inefficient
2252 sig::Signature signature;
2253 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2255 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2256 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2262 bool stret(ffi_type *ffi_type) {
2263 return ffi_type->type == FFI_TYPE_STRUCT && (
2264 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2265 struct_forward_array[ffi_type->size] != 0
2270 int *_NSGetArgc(void);
2271 char ***_NSGetArgv(void);
2272 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2275 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2277 NSLog(@"%s", CYCastCString(context, arguments[0]));
2278 return CYJSUndefined(context);
2282 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2285 Class _class(object_getClass(self));
2286 if (Method method = class_getInstanceMethod(_class, _cmd))
2287 type = method_getTypeEncoding(method);
2291 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2293 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2294 type = CYPoolCString(pool, [method _typeString]);
2303 sig::Signature signature;
2304 sig::Parse(pool, &signature, type, &Structor_);
2307 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2309 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2310 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2313 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2323 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2325 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2326 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2327 self = data->GetValue();
2328 uninitialized = data->IsUninitialized();
2332 self = CYCastNSObject(pool, context, arguments[0]);
2333 uninitialized = false;
2337 return CYJSNull(context);
2339 _cmd = CYCastSEL(context, arguments[1]);
2342 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2345 MSHook(void, CYDealloc, id self, SEL sel) {
2346 CYInternal *internal;
2347 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2348 if (internal != NULL)
2350 _CYDealloc(self, sel);
2353 MSHook(void, objc_registerClassPair, Class _class) {
2354 Class super(class_getSuperclass(_class));
2355 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2356 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2357 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2360 _objc_registerClassPair(_class);
2363 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2366 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2368 Class _class(CYCastNSObject(pool, context, arguments[0]));
2369 $objc_registerClassPair(_class);
2370 return CYJSUndefined(context);
2374 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2375 JSValueRef setup[count + 2];
2378 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2379 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2382 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2384 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2385 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
2388 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2391 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2392 const char *name(CYCastCString(context, arguments[0]));
2393 return CYMakeSelector(context, sel_registerName(name));
2397 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2400 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2402 void *value(CYCastPointer<void *>(context, arguments[0]));
2403 const char *type(CYCastCString(context, arguments[1]));
2407 sig::Signature signature;
2408 sig::Parse(pool, &signature, type, &Structor_);
2410 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2414 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2415 Type_privateData *internal(new Type_privateData(NULL, type));
2416 return JSObjectMake(context, Type_, internal);
2419 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2422 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2423 const char *type(CYCastCString(context, arguments[0]));
2424 return CYMakeType(context, object, type);
2428 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2431 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2432 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2433 sig::Type *type(internal->type_);
2434 ffi_type *ffi(internal->GetFFI());
2436 uint8_t value[ffi->size];
2438 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2439 return CYFromFFI(context, type, ffi, value);
2443 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2446 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2447 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2448 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2450 void *value(malloc(internal->GetFFI()->size * size));
2451 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2455 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2458 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2459 const char *type(CYCastCString(context, arguments[1]));
2460 JSValueRef exception(NULL);
2461 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
2462 JSObjectRef function(CYCastJSObject(context, arguments[0]));
2463 return CYMakeFunctor(context, function, type);
2464 } else if (exception != NULL) {
2467 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
2468 return CYMakeFunctor(context, function, type);
2473 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2474 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2475 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2478 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2482 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2484 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2485 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2489 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2490 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2493 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2495 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2497 sprintf(string, "%p", internal->value_);
2498 return CYCastJSValue(context, string);
2502 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2504 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2506 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
2511 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2513 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2515 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2516 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2521 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2523 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2525 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2530 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2532 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2533 return CYCastJSValue(context, sel_getName(data->GetValue()));
2537 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2538 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2541 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2543 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2544 const char *name(sel_getName(internal->GetValue()));
2546 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2551 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2554 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2556 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2557 Class _class(CYCastNSObject(pool, context, arguments[0]));
2558 SEL sel(internal->GetValue());
2559 if (Method method = class_getInstanceMethod(_class, sel))
2560 return CYCastJSValue(context, method_getTypeEncoding(method));
2561 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2562 return CYCastJSValue(context, CYJSString(type));
2564 return CYJSNull(context);
2568 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2570 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2572 const char *type(sig::Unparse(pool, internal->type_));
2574 return CYCastJSValue(context, CYJSString(type));
2579 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2581 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2583 const char *type(sig::Unparse(pool, internal->type_));
2585 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
2590 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2591 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
2594 static JSStaticValue CYValue_staticValues[2] = {
2595 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2596 {NULL, NULL, NULL, 0}
2599 static JSStaticValue Pointer_staticValues[2] = {
2600 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontDelete},
2601 {NULL, NULL, NULL, 0}
2604 static JSStaticFunction Pointer_staticFunctions[4] = {
2605 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2606 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2607 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2611 static JSStaticFunction Struct_staticFunctions[2] = {
2612 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2616 static JSStaticFunction Functor_staticFunctions[4] = {
2617 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2618 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2619 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2623 /*static JSStaticValue Selector_staticValues[2] = {
2624 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2625 {NULL, NULL, NULL, 0}
2628 static JSStaticValue Instance_staticValues[3] = {
2629 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2630 {"$cyi", &Instance_getProperty_$cyi, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2631 {NULL, NULL, NULL, 0}
2634 static JSStaticFunction Instance_staticFunctions[4] = {
2635 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2636 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2637 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2641 static JSStaticFunction Internal_staticFunctions[2] = {
2642 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2646 static JSStaticFunction Selector_staticFunctions[5] = {
2647 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2648 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2649 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2650 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2654 static JSStaticFunction Type_staticFunctions[4] = {
2655 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2656 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2657 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2661 CYDriver::CYDriver(const std::string &filename) :
2665 filename_(filename),
2671 CYDriver::~CYDriver() {
2675 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2676 CYDriver::Error error;
2677 error.location_ = location;
2678 error.message_ = message;
2679 driver.errors_.push_back(error);
2682 void CYSetArgs(int argc, const char *argv[]) {
2683 JSContextRef context(CYGetJSContext());
2684 JSValueRef args[argc];
2685 for (int i(0); i != argc; ++i)
2686 args[i] = CYCastJSValue(context, argv[i]);
2687 JSValueRef exception(NULL);
2688 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2689 CYThrow(context, exception);
2690 CYSetProperty(context, System_, CYJSString("args"), array);
2693 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2694 return JSContextGetGlobalObject(context);
2697 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
2698 JSContextRef context(CYGetJSContext());
2699 JSValueRef exception(NULL), result;
2702 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
2703 } catch (const char *error) {
2707 if (exception != NULL) { error:
2712 if (JSValueIsUndefined(context, result))
2715 const char *json(CYPoolCCYON(pool, context, result, &exception));
2716 if (exception != NULL)
2719 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
2723 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
2724 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
2732 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
2733 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
2746 const char * volatile data_;
2749 // XXX: this is "tre lame"
2750 @interface CYClient_ : NSObject {
2753 - (void) execute:(NSValue *)value;
2757 @implementation CYClient_
2759 - (void) execute:(NSValue *)value {
2760 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
2761 const char *data(execute->data_);
2762 execute->data_ = NULL;
2763 execute->data_ = CYExecute(execute->pool_, data);
2772 apr_thread_t *thread_;
2774 CYClient(int socket) :
2780 _syscall(close(socket_));
2783 void Handle() { _pooled
2784 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
2788 if (!CYRecvAll(socket_, &size, sizeof(size)))
2792 char *data(new(pool) char[size + 1]);
2793 if (!CYRecvAll(socket_, data, size))
2797 CYDriver driver("");
2798 cy::parser parser(driver);
2800 driver.data_ = data;
2801 driver.size_ = size;
2804 if (parser.parse() != 0 || !driver.errors_.empty()) {
2806 size = _not(size_t);
2808 std::ostringstream str;
2809 driver.source_->Show(str);
2810 std::string code(str.str());
2811 CYExecute_ execute = {pool, code.c_str()};
2812 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
2813 json = execute.data_;
2814 size = json == NULL ? _not(size_t) : strlen(json);
2817 if (!CYSendAll(socket_, &size, sizeof(size)))
2820 if (!CYSendAll(socket_, json, size))
2826 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
2827 CYClient *client(reinterpret_cast<CYClient *>(data));
2833 static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
2835 int socket(_syscall(accept(Socket_, NULL, NULL)));
2836 CYClient *client(new CYClient(socket));
2837 apr_threadattr_t *attr;
2838 _aprcall(apr_threadattr_create(&attr, Pool_));
2839 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
2846 pid_t pid(getpid());
2848 sprintf(path, "/tmp/.s.cy.%u", pid);
2852 MSInitialize { _pooled
2853 _aprcall(apr_initialize());
2854 _aprcall(apr_pool_create(&Pool_, NULL));
2856 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2858 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2859 NSCFType_ = objc_getClass("NSCFType");
2860 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2861 NSZombie_ = objc_getClass("_NSZombie_");
2862 Object_ = objc_getClass("Object");
2864 Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
2866 struct sockaddr_un address;
2867 memset(&address, 0, sizeof(address));
2868 address.sun_family = AF_UNIX;
2870 pid_t pid(getpid());
2871 sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
2874 _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
2876 _syscall(listen(Socket_, 0));
2878 apr_threadattr_t *attr;
2879 _aprcall(apr_threadattr_create(&attr, Pool_));
2881 apr_thread_t *thread;
2882 _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
2884 NSLog(@"failed to setup Cyrver");
2888 JSGlobalContextRef CYGetJSContext() {
2889 if (Context_ == NULL) {
2890 JSClassDefinition definition;
2892 definition = kJSClassDefinitionEmpty;
2893 definition.className = "Functor";
2894 definition.staticFunctions = Functor_staticFunctions;
2895 definition.callAsFunction = &Functor_callAsFunction;
2896 definition.finalize = &CYData::Finalize;
2897 Functor_ = JSClassCreate(&definition);
2899 definition = kJSClassDefinitionEmpty;
2900 definition.className = "Instance";
2901 definition.staticValues = Instance_staticValues;
2902 definition.staticFunctions = Instance_staticFunctions;
2903 definition.getProperty = &Instance_getProperty;
2904 definition.setProperty = &Instance_setProperty;
2905 definition.deleteProperty = &Instance_deleteProperty;
2906 definition.getPropertyNames = &Instance_getPropertyNames;
2907 definition.callAsConstructor = &Instance_callAsConstructor;
2908 definition.finalize = &CYData::Finalize;
2909 Instance_ = JSClassCreate(&definition);
2911 definition = kJSClassDefinitionEmpty;
2912 definition.className = "Internal";
2913 definition.staticFunctions = Internal_staticFunctions;
2914 definition.getProperty = &Internal_getProperty;
2915 definition.setProperty = &Internal_setProperty;
2916 definition.getPropertyNames = &Internal_getPropertyNames;
2917 definition.finalize = &CYData::Finalize;
2918 Internal_ = JSClassCreate(&definition);
2920 definition = kJSClassDefinitionEmpty;
2921 definition.className = "Pointer";
2922 definition.staticValues = Pointer_staticValues;
2923 definition.staticFunctions = Pointer_staticFunctions;
2924 definition.getProperty = &Pointer_getProperty;
2925 definition.setProperty = &Pointer_setProperty;
2926 definition.finalize = &CYData::Finalize;
2927 Pointer_ = JSClassCreate(&definition);
2929 definition = kJSClassDefinitionEmpty;
2930 definition.className = "Selector";
2931 definition.staticValues = CYValue_staticValues;
2932 //definition.staticValues = Selector_staticValues;
2933 definition.staticFunctions = Selector_staticFunctions;
2934 definition.callAsFunction = &Selector_callAsFunction;
2935 definition.finalize = &CYData::Finalize;
2936 Selector_ = JSClassCreate(&definition);
2938 definition = kJSClassDefinitionEmpty;
2939 definition.className = "Struct";
2940 definition.staticFunctions = Struct_staticFunctions;
2941 definition.getProperty = &Struct_getProperty;
2942 definition.setProperty = &Struct_setProperty;
2943 definition.getPropertyNames = &Struct_getPropertyNames;
2944 definition.finalize = &CYData::Finalize;
2945 Struct_ = JSClassCreate(&definition);
2947 definition = kJSClassDefinitionEmpty;
2948 definition.className = "Type";
2949 definition.staticFunctions = Type_staticFunctions;
2950 //definition.getProperty = &Type_getProperty;
2951 definition.callAsFunction = &Type_callAsFunction;
2952 definition.callAsConstructor = &Type_callAsConstructor;
2953 definition.finalize = &CYData::Finalize;
2954 Type_ = JSClassCreate(&definition);
2956 definition = kJSClassDefinitionEmpty;
2957 definition.className = "Runtime";
2958 definition.getProperty = &Runtime_getProperty;
2959 Runtime_ = JSClassCreate(&definition);
2961 definition = kJSClassDefinitionEmpty;
2962 definition.className = "ObjectiveC::Classes";
2963 definition.getProperty = &ObjectiveC_Classes_getProperty;
2964 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2965 ObjectiveC_Classes_ = JSClassCreate(&definition);
2967 definition = kJSClassDefinitionEmpty;
2968 definition.className = "ObjectiveC::Images";
2969 definition.getProperty = &ObjectiveC_Images_getProperty;
2970 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2971 ObjectiveC_Images_ = JSClassCreate(&definition);
2973 definition = kJSClassDefinitionEmpty;
2974 definition.className = "ObjectiveC::Image::Classes";
2975 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2976 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2977 definition.finalize = &CYData::Finalize;
2978 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2980 definition = kJSClassDefinitionEmpty;
2981 definition.className = "ObjectiveC::Protocols";
2982 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2983 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2984 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2986 definition = kJSClassDefinitionEmpty;
2987 //definition.getProperty = &Global_getProperty;
2988 JSClassRef Global(JSClassCreate(&definition));
2990 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2993 JSObjectRef global(CYGetGlobalObject(context));
2995 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2996 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
2997 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
2999 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3000 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3001 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3003 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
3004 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, NULL));
3005 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3006 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
3007 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3009 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3011 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3013 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3014 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3016 System_ = JSObjectMake(context, NULL, NULL);
3017 CYSetProperty(context, global, CYJSString("system"), System_);
3018 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3019 //CYSetProperty(context, System_, CYJSString("global"), global);
3021 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3023 Result_ = JSStringCreateWithUTF8CString("_");
3025 length_ = JSStringCreateWithUTF8CString("length");
3026 message_ = JSStringCreateWithUTF8CString("message");
3027 name_ = JSStringCreateWithUTF8CString("name");
3028 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3029 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3031 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3032 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));