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>
64 #include <ext/stdio_filebuf.h>
71 #include "Cycript.tab.hh"
76 #define _assert(test) do { \
78 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
81 #define _trace() do { \
82 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
89 #define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
97 [_saved autorelease]; \
101 static JSGlobalContextRef Context_;
102 static JSObjectRef System_;
104 static JSClassRef Functor_;
105 static JSClassRef Instance_;
106 static JSClassRef Pointer_;
107 static JSClassRef Runtime_;
108 static JSClassRef Selector_;
109 static JSClassRef Struct_;
111 static JSObjectRef Array_;
112 static JSObjectRef Function_;
114 static JSStringRef length_;
115 static JSStringRef message_;
116 static JSStringRef name_;
117 static JSStringRef toCYON_;
118 static JSStringRef toJSON_;
120 static Class NSCFBoolean_;
122 static NSArray *Bridge_;
130 static void *operator new(size_t size) {
132 apr_pool_create(&pool, NULL);
133 void *data(apr_palloc(pool, size));
134 reinterpret_cast<CYData *>(data)->pool_ = pool;
138 static void operator delete(void *data) {
139 apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
142 static void Finalize(JSObjectRef object) {
143 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
155 CYValue(void *value) :
161 struct Selector_privateData :
164 Selector_privateData(SEL value) :
169 SEL GetValue() const {
170 return reinterpret_cast<SEL>(value_);
179 Transient = (1 << 0),
180 Uninitialized = (1 << 1),
185 Instance(id value, Flags flags) :
191 virtual ~Instance() {
192 if ((flags_ & Transient) == 0)
193 // XXX: does this handle background threads correctly?
194 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
197 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
198 return JSObjectMake(context, Instance_, new Instance(object, flags));
201 id GetValue() const {
202 return reinterpret_cast<id>(value_);
205 bool IsUninitialized() const {
206 return (flags_ & Uninitialized) != 0;
212 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
214 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
215 lhs.name = apr_pstrdup(pool, rhs.name);
216 if (rhs.type == NULL)
219 lhs.type = new(pool) Type;
220 Copy(pool, *lhs.type, *rhs.type);
222 lhs.offset = rhs.offset;
225 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
226 size_t count(rhs.count);
228 lhs.elements = new(pool) Element[count];
229 for (size_t index(0); index != count; ++index)
230 Copy(pool, lhs.elements[index], rhs.elements[index]);
233 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
234 lhs.primitive = rhs.primitive;
235 lhs.name = apr_pstrdup(pool, rhs.name);
236 lhs.flags = rhs.flags;
238 if (sig::IsAggregate(rhs.primitive))
239 Copy(pool, lhs.data.signature, rhs.data.signature);
241 if (rhs.data.data.type != NULL) {
242 lhs.data.data.type = new(pool) Type;
243 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
246 lhs.data.data.size = rhs.data.data.size;
250 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
252 lhs.alignment = rhs.alignment;
254 if (rhs.elements == NULL)
258 while (rhs.elements[count] != NULL)
261 lhs.elements = new(pool) ffi_type *[count + 1];
262 lhs.elements[count] = NULL;
264 for (size_t index(0); index != count; ++index) {
265 // XXX: if these are libffi native then you can just take them
266 ffi_type *ffi(new(pool) ffi_type);
267 lhs.elements[index] = ffi;
268 sig::Copy(pool, *ffi, *rhs.elements[index]);
275 struct CStringMapLess :
276 std::binary_function<const char *, const char *, bool>
278 _finline bool operator ()(const char *lhs, const char *rhs) const {
279 return strcmp(lhs, rhs) < 0;
283 struct Type_privateData {
289 Type_privateData(apr_pool_t *pool, sig::Type *type) :
294 type_ = new(pool) sig::Type;
295 sig::Copy(pool, *type_, *type);
299 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) :
302 ffi_ = new(pool) ffi_type;
303 sig::Copy(pool, *ffi_, *ffi);
304 type_ = new(pool) sig::Type;
305 sig::Copy(pool, *type_, *type);
310 ffi_ = new(pool_) ffi_type;
312 sig::Element element;
314 element.type = type_;
317 sig::Signature signature;
318 signature.elements = &element;
322 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
334 Type_privateData *type_;
336 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
339 type_(new(pool_) Type_privateData(pool_, type))
344 struct Struct_privateData :
348 Type_privateData *type_;
350 Struct_privateData(JSObjectRef owner) :
356 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
357 static TypeMap Types_;
359 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
360 Struct_privateData *internal(new Struct_privateData(owner));
361 apr_pool_t *pool(internal->pool_);
362 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
363 internal->type_ = typical;
366 internal->value_ = data;
368 size_t size(typical->GetFFI()->size);
369 void *copy(apr_palloc(internal->pool_, size));
370 memcpy(copy, data, size);
371 internal->value_ = copy;
374 return JSObjectMake(context, Struct_, internal);
377 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
382 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
383 switch ([[entry objectAtIndex:0] intValue]) {
385 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
389 sig::Signature signature;
390 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
391 type = signature.elements[0].type;
397 struct Functor_privateData :
400 sig::Signature signature_;
403 Functor_privateData(const char *type, void (*value)()) :
404 CYValue(reinterpret_cast<void *>(value))
406 sig::Parse(pool_, &signature_, type, &Structor_);
407 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
414 JSContextRef context_;
415 JSObjectRef function_;
417 ffoData(const char *type) :
418 Functor_privateData(type, NULL)
423 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
424 Instance::Flags flags;
427 flags = Instance::Transient;
429 flags = Instance::None;
430 object = [object retain];
433 return Instance::Make(context, object, flags);
436 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
438 return [value UTF8String];
440 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
441 char *string(new(pool) char[size]);
442 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
443 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
448 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
449 return JSValueMakeBoolean(context, value);
452 JSValueRef CYCastJSValue(JSContextRef context, double value) {
453 return JSValueMakeNumber(context, value);
456 #define CYCastJSValue_(Type_) \
457 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
458 return JSValueMakeNumber(context, static_cast<double>(value)); \
462 CYCastJSValue_(unsigned int)
463 CYCastJSValue_(long int)
464 CYCastJSValue_(long unsigned int)
465 CYCastJSValue_(long long int)
466 CYCastJSValue_(long long unsigned int)
468 JSValueRef CYJSUndefined(JSContextRef context) {
469 return JSValueMakeUndefined(context);
472 bool CYGetIndex(const char *value, ssize_t &index) {
473 if (value[0] != '0') {
475 index = strtol(value, &end, 10);
476 if (value + strlen(value) == end)
478 } else if (value[1] == '\0') {
486 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
487 return CYGetIndex(CYPoolCString(pool, value), index);
490 @interface NSMethodSignature (Cycript)
491 - (NSString *) _typeString;
494 @interface NSObject (Cycript)
496 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
497 - (JSType) cy$JSType;
499 - (NSObject *) cy$toJSON:(NSString *)key;
500 - (NSString *) cy$toCYON;
501 - (NSString *) cy$toKey;
503 - (NSObject *) cy$getProperty:(NSString *)name;
504 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
505 - (bool) cy$deleteProperty:(NSString *)name;
510 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
513 @interface NSString (Cycript)
514 - (void *) cy$symbol;
517 struct PropertyAttributes {
522 const char *variable;
535 PropertyAttributes(objc_property_t property) :
547 name = property_getName(property);
548 const char *attributes(property_getAttributes(property));
550 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
552 case 'R': readonly = true; break;
553 case 'C': copy = true; break;
554 case '&': retain = true; break;
555 case 'N': nonatomic = true; break;
556 case 'G': getter_ = token + 1; break;
557 case 'S': setter_ = token + 1; break;
558 case 'V': variable = token + 1; break;
562 /*if (variable == NULL) {
563 variable = property_getName(property);
564 size_t size(strlen(variable));
565 char *name(new(pool_) char[size + 2]);
567 memcpy(name + 1, variable, size);
568 name[size + 1] = '\0';
573 const char *Getter() {
575 getter_ = apr_pstrdup(pool_, name);
579 const char *Setter() {
580 if (setter_ == NULL && !readonly) {
581 size_t length(strlen(name));
583 char *temp(new(pool_) char[length + 5]);
589 temp[3] = toupper(name[0]);
590 memcpy(temp + 4, name + 1, length - 1);
593 temp[length + 3] = ':';
594 temp[length + 4] = '\0';
603 @implementation NSObject (Cycript)
605 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
606 return CYMakeInstance(context, self, false);
609 - (JSType) cy$JSType {
610 return kJSTypeObject;
613 - (NSObject *) cy$toJSON:(NSString *)key {
614 return [self description];
617 - (NSString *) cy$toCYON {
618 return [[self cy$toJSON:@""] cy$toCYON];
621 - (NSString *) cy$toKey {
622 return [self cy$toCYON];
625 - (NSObject *) cy$getProperty:(NSString *)name {
626 /*if (![name isEqualToString:@"prototype"])
627 NSLog(@"get:%@", name);*/
631 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
632 //NSLog(@"set:%@", name);
636 - (bool) cy$deleteProperty:(NSString *)name {
637 //NSLog(@"delete:%@", name);
643 @implementation WebUndefined (Cycript)
645 - (JSType) cy$JSType {
646 return kJSTypeUndefined;
649 - (NSObject *) cy$toJSON:(NSString *)key {
653 - (NSString *) cy$toCYON {
657 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
658 return CYJSUndefined(context);
663 @implementation NSNull (Cycript)
665 - (JSType) cy$JSType {
669 - (NSObject *) cy$toJSON:(NSString *)key {
673 - (NSString *) cy$toCYON {
679 @implementation NSArray (Cycript)
681 - (NSString *) cy$toCYON {
682 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
683 [json appendString:@"["];
686 for (id object in self) {
688 [json appendString:@","];
691 if ([object cy$JSType] != kJSTypeUndefined)
692 [json appendString:[object cy$toCYON]];
694 [json appendString:@","];
699 [json appendString:@"]"];
703 - (NSObject *) cy$getProperty:(NSString *)name {
704 if ([name isEqualToString:@"length"])
705 return [NSNumber numberWithUnsignedInteger:[self count]];
708 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
709 return [super cy$getProperty:name];
711 return [self objectAtIndex:index];
716 @implementation NSMutableArray (Cycript)
718 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
720 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
721 return [super cy$setProperty:name to:value];
723 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
728 - (bool) cy$deleteProperty:(NSString *)name {
730 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
731 return [super cy$deleteProperty:name];
733 [self removeObjectAtIndex:index];
740 @implementation NSDictionary (Cycript)
742 - (NSString *) cy$toCYON {
743 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
744 [json appendString:@"{"];
747 for (id key in self) {
749 [json appendString:@","];
752 [json appendString:[key cy$toKey]];
753 [json appendString:@":"];
754 NSObject *object([self objectForKey:key]);
755 [json appendString:[object cy$toCYON]];
758 [json appendString:@"}"];
762 - (NSObject *) cy$getProperty:(NSString *)name {
763 return [self objectForKey:name];
768 @implementation NSMutableDictionary (Cycript)
770 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
771 [self setObject:(value ?: [NSNull null]) forKey:name];
775 - (bool) cy$deleteProperty:(NSString *)name {
776 if ([self objectForKey:name] == nil)
779 [self removeObjectForKey:name];
786 @implementation NSNumber (Cycript)
788 - (JSType) cy$JSType {
789 // XXX: this just seems stupid
790 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
793 - (NSObject *) cy$toJSON:(NSString *)key {
797 - (NSString *) cy$toCYON {
798 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
801 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
802 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
807 @implementation NSString (Cycript)
809 - (JSType) cy$JSType {
810 return kJSTypeString;
813 - (NSObject *) cy$toJSON:(NSString *)key {
817 - (NSString *) cy$toCYON {
818 // XXX: this should use the better code from Output.cpp
819 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
821 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
822 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
823 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
824 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
825 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
827 CFStringInsert(json, 0, CFSTR("\""));
828 CFStringAppend(json, CFSTR("\""));
830 return [reinterpret_cast<const NSString *>(json) autorelease];
833 - (NSString *) cy$toKey {
834 const char *value([self UTF8String]);
835 size_t size(strlen(value));
840 if (DigitRange_[value[0]]) {
842 if (!CYGetIndex(NULL, self, index) || index < 0)
845 if (!WordStartRange_[value[0]])
847 for (size_t i(1); i != size; ++i)
848 if (!WordEndRange_[value[i]])
855 return [self cy$toCYON];
858 - (void *) cy$symbol {
860 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
865 @interface CYJSObject : NSDictionary {
867 JSContextRef context_;
870 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
872 - (NSString *) cy$toJSON:(NSString *)key;
874 - (NSUInteger) count;
875 - (id) objectForKey:(id)key;
876 - (NSEnumerator *) keyEnumerator;
877 - (void) setObject:(id)object forKey:(id)key;
878 - (void) removeObjectForKey:(id)key;
882 @interface CYJSArray : NSArray {
884 JSContextRef context_;
887 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
889 - (NSUInteger) count;
890 - (id) objectAtIndex:(NSUInteger)index;
894 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
895 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
896 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
898 JSGlobalContextRef CYGetJSContext() {
905 @catch (id error) { \
906 CYThrow(context, error, exception); \
910 void CYThrow(JSContextRef context, JSValueRef value);
912 apr_status_t CYPoolRelease_(void *data) {
913 id object(reinterpret_cast<id>(data));
918 id CYPoolRelease(apr_pool_t *pool, id object) {
921 else if (pool == NULL)
922 return [object autorelease];
924 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
929 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
930 return (CFTypeRef) CYPoolRelease(pool, (id) object);
933 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
934 JSValueRef exception(NULL);
935 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
936 CYThrow(context, exception);
937 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
938 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
941 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
942 if (!JSValueIsObjectOfClass(context, object, Instance_))
943 return CYCastNSObject_(pool, context, object);
945 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
946 return data->GetValue();
950 JSStringRef CYCopyJSString(id value) {
951 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
954 JSStringRef CYCopyJSString(const char *value) {
955 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
958 JSStringRef CYCopyJSString(JSStringRef value) {
959 return value == NULL ? NULL : JSStringRetain(value);
962 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
963 if (JSValueIsNull(context, value))
965 JSValueRef exception(NULL);
966 JSStringRef string(JSValueToStringCopy(context, value, &exception));
967 CYThrow(context, exception);
977 JSStringRelease(string_);
981 CYJSString(const CYJSString &rhs) :
982 string_(CYCopyJSString(rhs.string_))
986 template <typename Arg0_>
987 CYJSString(Arg0_ arg0) :
988 string_(CYCopyJSString(arg0))
992 template <typename Arg0_, typename Arg1_>
993 CYJSString(Arg0_ arg0, Arg1_ arg1) :
994 string_(CYCopyJSString(arg0, arg1))
998 CYJSString &operator =(const CYJSString &rhs) {
1000 string_ = CYCopyJSString(rhs.string_);
1013 operator JSStringRef() const {
1018 CFStringRef CYCopyCFString(JSStringRef value) {
1019 return JSStringCopyCFString(kCFAllocatorDefault, value);
1022 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1023 return CYCopyCFString(CYJSString(context, value));
1026 double CYCastDouble(const char *value, size_t size) {
1028 double number(strtod(value, &end));
1029 if (end != value + size)
1034 double CYCastDouble(const char *value) {
1035 return CYCastDouble(value, strlen(value));
1038 double CYCastDouble(JSContextRef context, JSValueRef value) {
1039 JSValueRef exception(NULL);
1040 double number(JSValueToNumber(context, value, &exception));
1041 CYThrow(context, exception);
1045 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1046 double number(CYCastDouble(context, value));
1047 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1050 CFStringRef CYCopyCFString(const char *value) {
1051 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1054 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1055 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1058 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1059 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1062 bool CYCastBool(JSContextRef context, JSValueRef value) {
1063 return JSValueToBoolean(context, value);
1066 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1070 switch (JSType type = JSValueGetType(context, value)) {
1071 case kJSTypeUndefined:
1072 object = [WebUndefined undefined];
1080 case kJSTypeBoolean:
1081 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1086 object = CYCopyCFNumber(context, value);
1091 object = CYCopyCFString(context, value);
1096 // XXX: this might could be more efficient
1097 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1102 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1109 return CYPoolRelease(pool, object);
1111 return CFRetain(object);
1114 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1115 return CYCFType(pool, context, value, true);
1118 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1119 return CYCFType(pool, context, value, false);
1122 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1124 size_t size(JSPropertyNameArrayGetCount(names));
1125 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1126 for (size_t index(0); index != size; ++index)
1127 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1131 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1132 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1135 void CYThrow(JSContextRef context, JSValueRef value) {
1138 @throw CYCastNSObject(NULL, context, value);
1141 JSValueRef CYJSNull(JSContextRef context) {
1142 return JSValueMakeNull(context);
1145 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1146 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1149 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1150 return CYCastJSValue(context, CYJSString(value));
1153 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1155 return CYJSNull(context);
1156 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1157 return [value cy$JSValueInContext:context];
1159 return CYMakeInstance(context, value, false);
1162 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1163 JSValueRef exception(NULL);
1164 JSObjectRef object(JSValueToObject(context, value, &exception));
1165 CYThrow(context, exception);
1169 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1170 JSValueRef exception(NULL);
1171 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1172 CYThrow(context, exception);
1176 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1177 JSValueRef exception(NULL);
1178 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1179 CYThrow(context, exception);
1183 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1184 JSValueRef exception(NULL);
1185 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1186 CYThrow(context, exception);
1189 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1190 if (exception == NULL)
1192 *exception = CYCastJSValue(context, error);
1195 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1196 JSValueRef exception(NULL);
1197 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1198 CYThrow(context, exception);
1202 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1203 // XXX: this isn't actually correct
1204 return value != NULL && JSValueIsObject(context, value);
1207 @implementation CYJSObject
1209 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1210 if ((self = [super init]) != nil) {
1216 - (NSObject *) cy$toJSON:(NSString *)key {
1217 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1218 if (!CYIsCallable(context_, toJSON))
1219 return [super cy$toJSON:key];
1221 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1222 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1223 // XXX: do I really want an NSNull here?!
1224 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1228 - (NSString *) cy$toCYON {
1229 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1230 if (!CYIsCallable(context_, toCYON))
1231 return [super cy$toCYON];
1233 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1234 return CYCastNSString(NULL, CYJSString(context_, value));
1238 - (NSUInteger) count {
1239 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1240 size_t size(JSPropertyNameArrayGetCount(names));
1241 JSPropertyNameArrayRelease(names);
1245 - (id) objectForKey:(id)key {
1246 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1249 - (NSEnumerator *) keyEnumerator {
1250 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1251 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1252 JSPropertyNameArrayRelease(names);
1256 - (void) setObject:(id)object forKey:(id)key {
1257 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1260 - (void) removeObjectForKey:(id)key {
1261 JSValueRef exception(NULL);
1262 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1263 CYThrow(context_, exception);
1268 @implementation CYJSArray
1270 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1271 if ((self = [super init]) != nil) {
1277 - (NSUInteger) count {
1278 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1281 - (id) objectAtIndex:(NSUInteger)index {
1282 JSValueRef exception(NULL);
1283 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1284 CYThrow(context_, exception);
1285 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1290 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1293 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1294 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1299 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1300 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1301 const char *string(CYPoolCString(pool, json));
1307 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1311 JSObjectRef object_;
1319 // XXX: delete object_? ;(
1322 static CYInternal *Get(id self) {
1323 CYInternal *internal(NULL);
1324 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1325 // XXX: do something epic? ;P
1331 static CYInternal *Set(id self) {
1332 CYInternal *internal(NULL);
1333 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1334 if (internal == NULL) {
1335 internal = new CYInternal();
1336 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1339 // XXX: do something epic? ;P
1345 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1346 if (object_ == NULL)
1348 return CYGetProperty(context, object_, name);
1351 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1352 if (object_ == NULL)
1353 object_ = JSObjectMake(context, NULL, NULL);
1354 CYSetProperty(context, object_, name, value);
1358 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1362 NSString *self(CYCastNSObject(pool, context, object));
1363 NSString *name(CYCastNSString(pool, property));
1365 if (CYInternal *internal = CYInternal::Get(self))
1366 if (JSValueRef value = internal->GetProperty(context, property))
1370 if (NSObject *data = [self cy$getProperty:name])
1371 return CYCastJSValue(context, data);
1374 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1375 PropertyAttributes attributes(property);
1376 SEL sel(sel_registerName(attributes.Getter()));
1377 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1384 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1388 NSString *self(CYCastNSObject(pool, context, object));
1389 NSString *name(CYCastNSString(pool, property));
1390 NSString *data(CYCastNSObject(pool, context, value));
1393 if ([self cy$setProperty:name to:data])
1397 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1398 PropertyAttributes attributes(property);
1399 if (const char *setter = attributes.Setter()) {
1400 SEL sel(sel_registerName(setter));
1401 JSValueRef arguments[1] = {value};
1402 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1407 if (CYInternal *internal = CYInternal::Set(self)) {
1408 internal->SetProperty(context, property, value);
1416 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1419 NSString *self(CYCastNSObject(NULL, context, object));
1420 NSString *name(CYCastNSString(NULL, property));
1421 return [self cy$deleteProperty:name];
1426 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1428 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1429 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1434 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1435 Selector_privateData *data(new Selector_privateData(sel));
1436 return JSObjectMake(context, Selector_, data);
1439 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
1440 Pointer *data(new Pointer(pointer, type, owner));
1441 return JSObjectMake(context, Pointer_, data);
1444 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1445 Functor_privateData *data(new Functor_privateData(type, function));
1446 return JSObjectMake(context, Functor_, data);
1449 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1451 const char *string([CYCastNSString(NULL, value) UTF8String]);
1454 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1455 char *string(new(pool) char[size]);
1456 JSStringGetUTF8CString(value, string, size);
1461 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1462 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1465 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1466 return CYGetIndex(CYPoolCString(pool, value), index);
1469 // XXX: this macro is unhygenic
1470 #define CYCastCString(context, value) ({ \
1472 if (value == NULL) \
1474 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1475 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1476 utf8 = reinterpret_cast<char *>(alloca(size)); \
1477 JSStringGetUTF8CString(string, utf8, size); \
1478 JSStringRelease(string); \
1484 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1485 switch (JSValueGetType(context, value)) {
1488 /*case kJSTypeString:
1489 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1491 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1492 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1493 return data->value_;
1496 double number(CYCastDouble(context, value));
1497 if (std::isnan(number))
1498 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1499 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1503 template <typename Type_>
1504 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1505 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1508 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1509 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1510 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1511 return reinterpret_cast<SEL>(data->value_);
1513 return CYCastPointer<SEL>(context, value);
1516 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1517 switch (type->primitive) {
1518 case sig::boolean_P:
1519 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1522 #define CYPoolFFI_(primitive, native) \
1523 case sig::primitive ## _P: \
1524 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1527 CYPoolFFI_(uchar, unsigned char)
1528 CYPoolFFI_(char, char)
1529 CYPoolFFI_(ushort, unsigned short)
1530 CYPoolFFI_(short, short)
1531 CYPoolFFI_(ulong, unsigned long)
1532 CYPoolFFI_(long, long)
1533 CYPoolFFI_(uint, unsigned int)
1534 CYPoolFFI_(int, int)
1535 CYPoolFFI_(ulonglong, unsigned long long)
1536 CYPoolFFI_(longlong, long long)
1537 CYPoolFFI_(float, float)
1538 CYPoolFFI_(double, double)
1541 case sig::typename_P:
1542 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1545 case sig::selector_P:
1546 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1549 case sig::pointer_P:
1550 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1554 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1557 case sig::struct_P: {
1558 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1559 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1560 for (size_t index(0); index != type->data.signature.count; ++index) {
1561 sig::Element *element(&type->data.signature.elements[index]);
1562 ffi_type *field(ffi->elements[index]);
1565 if (aggregate == NULL)
1568 rhs = CYGetProperty(context, aggregate, index);
1569 if (JSValueIsUndefined(context, rhs)) {
1570 if (element->name != NULL)
1571 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1574 if (JSValueIsUndefined(context, rhs)) undefined:
1575 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1579 CYPoolFFI(pool, context, element->type, field, base, rhs);
1581 base += field->size;
1589 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1594 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
1597 switch (type->primitive) {
1598 case sig::boolean_P:
1599 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1602 #define CYFromFFI_(primitive, native) \
1603 case sig::primitive ## _P: \
1604 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1607 CYFromFFI_(uchar, unsigned char)
1608 CYFromFFI_(char, char)
1609 CYFromFFI_(ushort, unsigned short)
1610 CYFromFFI_(short, short)
1611 CYFromFFI_(ulong, unsigned long)
1612 CYFromFFI_(long, long)
1613 CYFromFFI_(uint, unsigned int)
1614 CYFromFFI_(int, int)
1615 CYFromFFI_(ulonglong, unsigned long long)
1616 CYFromFFI_(longlong, long long)
1617 CYFromFFI_(float, float)
1618 CYFromFFI_(double, double)
1620 case sig::object_P: {
1621 if (id object = *reinterpret_cast<id *>(data)) {
1622 value = CYCastJSValue(context, object);
1628 case sig::typename_P:
1629 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1632 case sig::selector_P:
1633 if (SEL sel = *reinterpret_cast<SEL *>(data))
1634 value = CYMakeSelector(context, sel);
1638 case sig::pointer_P:
1639 if (void *pointer = *reinterpret_cast<void **>(data))
1640 value = CYMakePointer(context, pointer, type->data.data.type, owner);
1645 if (char *utf8 = *reinterpret_cast<char **>(data))
1646 value = CYCastJSValue(context, utf8);
1651 value = CYMakeStruct(context, data, type, ffi, owner);
1655 value = CYJSUndefined(context);
1659 value = CYJSNull(context);
1663 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1670 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1671 Type_privateData *typical(internal->type_);
1672 sig::Type *type(typical->type_);
1676 const char *name(CYPoolCString(pool, property));
1677 size_t length(strlen(name));
1678 double number(CYCastDouble(name, length));
1680 size_t count(type->data.signature.count);
1682 if (std::isnan(number)) {
1683 if (property == NULL)
1686 sig::Element *elements(type->data.signature.elements);
1688 for (size_t local(0); local != count; ++local) {
1689 sig::Element *element(&elements[local]);
1690 if (element->name != NULL && strcmp(name, element->name) == 0) {
1698 index = static_cast<ssize_t>(number);
1699 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1704 ffi_type **elements(typical->GetFFI()->elements);
1706 base = reinterpret_cast<uint8_t *>(internal->value_);
1707 for (ssize_t local(0); local != index; ++local)
1708 base += elements[local]->size;
1713 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1715 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1716 Type_privateData *typical(internal->type_);
1718 if (typical->type_ == NULL)
1722 if (!CYGetIndex(pool, property, index))
1725 ffi_type *ffi(typical->GetFFI());
1727 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1728 base += ffi->size * index;
1730 JSObjectRef owner(internal->owner_ ?: object);
1733 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
1737 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1739 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1740 Type_privateData *typical(internal->type_);
1742 if (typical->type_ == NULL)
1746 if (!CYGetIndex(pool, property, index))
1749 ffi_type *ffi(typical->GetFFI());
1751 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1752 base += ffi->size * index;
1755 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
1760 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1762 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1763 Type_privateData *typical(internal->type_);
1768 if (!Index_(pool, internal, property, index, base))
1771 JSObjectRef owner(internal->owner_ ?: object);
1774 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
1778 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1780 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1781 Type_privateData *typical(internal->type_);
1786 if (!Index_(pool, internal, property, index, base))
1790 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1795 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1796 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1797 Type_privateData *typical(internal->type_);
1798 sig::Type *type(typical->type_);
1803 size_t count(type->data.signature.count);
1804 sig::Element *elements(type->data.signature.elements);
1808 for (size_t index(0); index != count; ++index) {
1810 name = elements[index].name;
1813 sprintf(number, "%lu", index);
1817 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1821 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)()) {
1823 if (setups + count != signature->count - 1)
1824 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1826 size_t size(setups + count);
1828 memcpy(values, setup, sizeof(void *) * setups);
1830 for (size_t index(setups); index != size; ++index) {
1831 sig::Element *element(&signature->elements[index + 1]);
1832 ffi_type *ffi(cif->arg_types[index]);
1834 values[index] = new(pool) uint8_t[ffi->size];
1835 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1838 uint8_t value[cif->rtype->size];
1839 ffi_call(cif, function, value, values);
1841 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1845 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1846 ffoData *data(reinterpret_cast<ffoData *>(arg));
1848 JSContextRef context(data->context_);
1850 size_t count(data->cif_.nargs);
1851 JSValueRef values[count];
1853 for (size_t index(0); index != count; ++index)
1854 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
1856 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1857 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1860 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1861 // XXX: in case of exceptions this will leak
1862 ffoData *data(new ffoData(type));
1864 ffi_closure *closure;
1865 _syscall(closure = (ffi_closure *) mmap(
1866 NULL, sizeof(ffi_closure),
1867 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1871 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1872 _assert(status == FFI_OK);
1874 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1876 data->value_ = closure;
1878 data->context_ = CYGetJSContext();
1879 data->function_ = function;
1881 return JSObjectMake(context, Functor_, data);
1884 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1887 NSString *name(CYCastNSString(pool, property));
1888 if (Class _class = NSClassFromString(name))
1889 return CYMakeInstance(context, _class, true);
1890 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1891 switch ([[entry objectAtIndex:0] intValue]) {
1893 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1895 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1897 // XXX: this is horrendously inefficient
1898 sig::Signature signature;
1899 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1901 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1902 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
1908 bool stret(ffi_type *ffi_type) {
1909 return ffi_type->type == FFI_TYPE_STRUCT && (
1910 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1911 struct_forward_array[ffi_type->size] != 0
1916 int *_NSGetArgc(void);
1917 char ***_NSGetArgv(void);
1918 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1921 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1923 NSLog(@"%s", CYCastCString(context, arguments[0]));
1924 return CYJSUndefined(context);
1928 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
1931 Class _class(object_getClass(self));
1932 if (Method method = class_getInstanceMethod(_class, _cmd))
1933 type = method_getTypeEncoding(method);
1936 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1938 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1939 type = CYPoolCString(pool, [method _typeString]);
1947 sig::Signature signature;
1948 sig::Parse(pool, &signature, type, &Structor_);
1951 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1953 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1954 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
1957 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1967 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1969 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1970 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1971 self = data->GetValue();
1972 uninitialized = data->IsUninitialized();
1976 self = CYCastNSObject(pool, context, arguments[0]);
1977 uninitialized = false;
1981 return CYJSNull(context);
1983 _cmd = CYCastSEL(context, arguments[1]);
1986 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
1989 MSHook(void, CYDealloc, id self, SEL sel) {
1990 CYInternal *internal;
1991 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
1992 if (internal != NULL)
1994 _CYDealloc(self, sel);
1997 MSHook(void, objc_registerClassPair, Class _class) {
1998 Class super(class_getSuperclass(_class));
1999 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2000 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2001 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2004 _objc_registerClassPair(_class);
2007 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2010 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2012 Class _class(CYCastNSObject(pool, context, arguments[0]));
2013 $objc_registerClassPair(_class);
2014 return CYJSUndefined(context);
2018 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2019 JSValueRef setup[count + 2];
2022 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2023 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2026 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2028 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2029 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
2032 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2035 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2036 const char *name(CYCastCString(context, arguments[0]));
2037 return CYMakeSelector(context, sel_registerName(name));
2041 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2044 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2046 void *value(CYCastPointer<void *>(context, arguments[0]));
2047 const char *type(CYCastCString(context, arguments[1]));
2051 sig::Signature signature;
2052 sig::Parse(pool, &signature, type, &Structor_);
2054 return CYMakePointer(context, value, signature.elements[0].type, NULL);
2058 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2061 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2062 const char *type(CYCastCString(context, arguments[1]));
2063 JSValueRef exception(NULL);
2064 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
2065 JSObjectRef function(CYCastJSObject(context, arguments[0]));
2066 return CYMakeFunctor(context, function, type);
2067 } else if (exception != NULL) {
2070 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
2071 return CYMakeFunctor(context, function, type);
2076 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2077 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2078 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2081 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2085 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2087 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2088 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2092 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2093 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2096 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2098 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2100 sprintf(string, "%p", internal->value_);
2101 return CYCastJSValue(context, string);
2105 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2107 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2109 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
2114 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2116 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2118 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2119 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2124 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2126 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2128 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2133 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2135 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2136 return CYCastJSValue(context, sel_getName(data->GetValue()));
2140 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2141 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2144 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2146 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2147 const char *name(sel_getName(data->GetValue()));
2149 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2154 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2157 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2159 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2160 Class _class(CYCastNSObject(pool, context, arguments[0]));
2161 bool instance(CYCastBool(context, arguments[1]));
2162 SEL sel(data->GetValue());
2163 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
2164 return CYCastJSValue(context, method_getTypeEncoding(method));
2165 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2166 return CYCastJSValue(context, CYJSString(type));
2168 return CYJSNull(context);
2172 static JSStaticValue CYValue_staticValues[2] = {
2173 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2174 {NULL, NULL, NULL, 0}
2177 static JSStaticFunction Pointer_staticFunctions[4] = {
2178 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2179 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2180 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2184 static JSStaticFunction Functor_staticFunctions[4] = {
2185 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2186 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2187 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2191 /*static JSStaticValue Selector_staticValues[2] = {
2192 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2193 {NULL, NULL, NULL, 0}
2196 static JSStaticFunction Instance_staticFunctions[4] = {
2197 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2198 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2199 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2203 static JSStaticFunction Selector_staticFunctions[5] = {
2204 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2205 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2206 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2207 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2211 CYDriver::CYDriver(const std::string &filename) :
2215 filename_(filename),
2221 CYDriver::~CYDriver() {
2225 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2226 CYDriver::Error error;
2227 error.location_ = location;
2228 error.message_ = message;
2229 driver.errors_.push_back(error);
2232 void CYSetArgs(int argc, const char *argv[]) {
2233 JSContextRef context(CYGetJSContext());
2234 JSValueRef args[argc];
2235 for (int i(0); i != argc; ++i)
2236 args[i] = CYCastJSValue(context, argv[i]);
2237 JSValueRef exception(NULL);
2238 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2239 CYThrow(context, exception);
2240 CYSetProperty(context, System_, CYJSString("args"), array);
2243 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2244 return JSContextGetGlobalObject(context);
2247 MSInitialize { _pooled
2250 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2252 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2254 JSClassDefinition definition;
2256 definition = kJSClassDefinitionEmpty;
2257 definition.className = "Pointer";
2258 definition.staticFunctions = Pointer_staticFunctions;
2259 definition.getProperty = &Pointer_getProperty;
2260 definition.setProperty = &Pointer_setProperty;
2261 definition.finalize = &CYData::Finalize;
2262 Pointer_ = JSClassCreate(&definition);
2264 definition = kJSClassDefinitionEmpty;
2265 definition.className = "Functor";
2266 definition.staticFunctions = Functor_staticFunctions;
2267 definition.callAsFunction = &Functor_callAsFunction;
2268 definition.finalize = &CYData::Finalize;
2269 Functor_ = JSClassCreate(&definition);
2271 definition = kJSClassDefinitionEmpty;
2272 definition.className = "Struct";
2273 definition.getProperty = &Struct_getProperty;
2274 definition.setProperty = &Struct_setProperty;
2275 definition.getPropertyNames = &Struct_getPropertyNames;
2276 definition.finalize = &CYData::Finalize;
2277 Struct_ = JSClassCreate(&definition);
2279 definition = kJSClassDefinitionEmpty;
2280 definition.className = "Selector";
2281 definition.staticValues = CYValue_staticValues;
2282 //definition.staticValues = Selector_staticValues;
2283 definition.staticFunctions = Selector_staticFunctions;
2284 definition.callAsFunction = &Selector_callAsFunction;
2285 definition.finalize = &CYData::Finalize;
2286 Selector_ = JSClassCreate(&definition);
2288 definition = kJSClassDefinitionEmpty;
2289 definition.className = "Instance";
2290 definition.staticValues = CYValue_staticValues;
2291 definition.staticFunctions = Instance_staticFunctions;
2292 definition.getProperty = &Instance_getProperty;
2293 definition.setProperty = &Instance_setProperty;
2294 definition.deleteProperty = &Instance_deleteProperty;
2295 definition.callAsConstructor = &Instance_callAsConstructor;
2296 definition.finalize = &CYData::Finalize;
2297 Instance_ = JSClassCreate(&definition);
2299 definition = kJSClassDefinitionEmpty;
2300 definition.className = "Runtime";
2301 definition.getProperty = &Runtime_getProperty;
2302 Runtime_ = JSClassCreate(&definition);
2304 definition = kJSClassDefinitionEmpty;
2305 //definition.getProperty = &Global_getProperty;
2306 JSClassRef Global(JSClassCreate(&definition));
2308 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2311 JSObjectRef global(CYGetGlobalObject(context));
2313 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2314 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2316 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2317 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
2318 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2320 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2322 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
2323 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2325 System_ = JSObjectMake(context, NULL, NULL);
2326 CYSetProperty(context, global, CYJSString("system"), System_);
2327 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2328 //CYSetProperty(context, System_, CYJSString("global"), global);
2330 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2332 length_ = JSStringCreateWithUTF8CString("length");
2333 message_ = JSStringCreateWithUTF8CString("message");
2334 name_ = JSStringCreateWithUTF8CString("name");
2335 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2336 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2338 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2339 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));