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));
1310 JSObjectRef object_;
1318 // XXX: delete object_? ;(
1321 static CYInternal *Get(id self) {
1322 CYInternal *internal(NULL);
1323 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1324 // XXX: do something epic? ;P
1330 static CYInternal *Set(id self) {
1331 CYInternal *internal(NULL);
1332 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1333 if (internal == NULL) {
1334 internal = new CYInternal();
1335 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1338 // XXX: do something epic? ;P
1344 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1345 if (object_ == NULL)
1347 return CYGetProperty(context, object_, name);
1350 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1351 if (object_ == NULL)
1352 object_ = JSObjectMake(context, NULL, NULL);
1353 CYSetProperty(context, object_, name, value);
1357 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1361 NSString *self(CYCastNSObject(pool, context, object));
1362 NSString *name(CYCastNSString(pool, property));
1364 if (CYInternal *internal = CYInternal::Get(self))
1365 if (JSValueRef value = internal->GetProperty(context, property))
1369 if (NSObject *data = [self cy$getProperty:name])
1370 return CYCastJSValue(context, data);
1373 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1374 PropertyAttributes attributes(property);
1375 SEL sel(sel_registerName(attributes.Getter()));
1376 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1383 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1387 NSString *self(CYCastNSObject(pool, context, object));
1388 NSString *name(CYCastNSString(pool, property));
1389 NSString *data(CYCastNSObject(pool, context, value));
1392 if ([self cy$setProperty:name to:data])
1396 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1397 PropertyAttributes attributes(property);
1398 if (const char *setter = attributes.Setter()) {
1399 SEL sel(sel_registerName(setter));
1400 JSValueRef arguments[1] = {value};
1401 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1406 if (CYInternal *internal = CYInternal::Set(self)) {
1407 internal->SetProperty(context, property, value);
1415 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1418 NSString *self(CYCastNSObject(NULL, context, object));
1419 NSString *name(CYCastNSString(NULL, property));
1420 return [self cy$deleteProperty:name];
1425 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1427 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1428 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1433 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1434 Selector_privateData *data(new Selector_privateData(sel));
1435 return JSObjectMake(context, Selector_, data);
1438 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
1439 Pointer *data(new Pointer(pointer, type, owner));
1440 return JSObjectMake(context, Pointer_, data);
1443 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1444 Functor_privateData *data(new Functor_privateData(type, function));
1445 return JSObjectMake(context, Functor_, data);
1448 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1450 const char *string([CYCastNSString(NULL, value) UTF8String]);
1452 *length = strlen(string);
1455 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1456 char *string(new(pool) char[size]);
1457 JSStringGetUTF8CString(value, string, size);
1458 // XXX: this is ironic
1460 *length = strlen(string);
1465 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1466 if (!JSValueIsNull(context, value))
1467 return CYPoolCString(pool, CYJSString(context, value), length);
1475 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1476 return CYGetIndex(CYPoolCString(pool, value), index);
1479 // XXX: this macro is unhygenic
1480 #define CYCastCString(context, value) ({ \
1482 if (value == NULL) \
1484 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1485 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1486 utf8 = reinterpret_cast<char *>(alloca(size)); \
1487 JSStringGetUTF8CString(string, utf8, size); \
1488 JSStringRelease(string); \
1494 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1495 switch (JSValueGetType(context, value)) {
1498 /*case kJSTypeString:
1499 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1501 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1502 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1503 return data->value_;
1506 double number(CYCastDouble(context, value));
1507 if (std::isnan(number))
1508 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1509 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1513 template <typename Type_>
1514 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1515 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1518 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1519 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1520 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1521 return reinterpret_cast<SEL>(data->value_);
1523 return CYCastPointer<SEL>(context, value);
1526 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1527 switch (type->primitive) {
1528 case sig::boolean_P:
1529 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1532 #define CYPoolFFI_(primitive, native) \
1533 case sig::primitive ## _P: \
1534 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1537 CYPoolFFI_(uchar, unsigned char)
1538 CYPoolFFI_(char, char)
1539 CYPoolFFI_(ushort, unsigned short)
1540 CYPoolFFI_(short, short)
1541 CYPoolFFI_(ulong, unsigned long)
1542 CYPoolFFI_(long, long)
1543 CYPoolFFI_(uint, unsigned int)
1544 CYPoolFFI_(int, int)
1545 CYPoolFFI_(ulonglong, unsigned long long)
1546 CYPoolFFI_(longlong, long long)
1547 CYPoolFFI_(float, float)
1548 CYPoolFFI_(double, double)
1551 case sig::typename_P:
1552 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1555 case sig::selector_P:
1556 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1559 case sig::pointer_P:
1560 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1564 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1567 case sig::struct_P: {
1568 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1569 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1570 for (size_t index(0); index != type->data.signature.count; ++index) {
1571 sig::Element *element(&type->data.signature.elements[index]);
1572 ffi_type *field(ffi->elements[index]);
1575 if (aggregate == NULL)
1578 rhs = CYGetProperty(context, aggregate, index);
1579 if (JSValueIsUndefined(context, rhs)) {
1580 if (element->name != NULL)
1581 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1584 if (JSValueIsUndefined(context, rhs)) undefined:
1585 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1589 CYPoolFFI(pool, context, element->type, field, base, rhs);
1591 base += field->size;
1599 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1604 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
1607 switch (type->primitive) {
1608 case sig::boolean_P:
1609 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1612 #define CYFromFFI_(primitive, native) \
1613 case sig::primitive ## _P: \
1614 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1617 CYFromFFI_(uchar, unsigned char)
1618 CYFromFFI_(char, char)
1619 CYFromFFI_(ushort, unsigned short)
1620 CYFromFFI_(short, short)
1621 CYFromFFI_(ulong, unsigned long)
1622 CYFromFFI_(long, long)
1623 CYFromFFI_(uint, unsigned int)
1624 CYFromFFI_(int, int)
1625 CYFromFFI_(ulonglong, unsigned long long)
1626 CYFromFFI_(longlong, long long)
1627 CYFromFFI_(float, float)
1628 CYFromFFI_(double, double)
1630 case sig::object_P: {
1631 if (id object = *reinterpret_cast<id *>(data)) {
1632 value = CYCastJSValue(context, object);
1638 case sig::typename_P:
1639 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1642 case sig::selector_P:
1643 if (SEL sel = *reinterpret_cast<SEL *>(data))
1644 value = CYMakeSelector(context, sel);
1648 case sig::pointer_P:
1649 if (void *pointer = *reinterpret_cast<void **>(data))
1650 value = CYMakePointer(context, pointer, type->data.data.type, owner);
1655 if (char *utf8 = *reinterpret_cast<char **>(data))
1656 value = CYCastJSValue(context, utf8);
1661 value = CYMakeStruct(context, data, type, ffi, owner);
1665 value = CYJSUndefined(context);
1669 value = CYJSNull(context);
1673 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1680 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1681 Type_privateData *typical(internal->type_);
1682 sig::Type *type(typical->type_);
1687 const char *name(CYPoolCString(pool, property, &length));
1688 double number(CYCastDouble(name, length));
1690 size_t count(type->data.signature.count);
1692 if (std::isnan(number)) {
1693 if (property == NULL)
1696 sig::Element *elements(type->data.signature.elements);
1698 for (size_t local(0); local != count; ++local) {
1699 sig::Element *element(&elements[local]);
1700 if (element->name != NULL && strcmp(name, element->name) == 0) {
1708 index = static_cast<ssize_t>(number);
1709 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1714 ffi_type **elements(typical->GetFFI()->elements);
1716 base = reinterpret_cast<uint8_t *>(internal->value_);
1717 for (ssize_t local(0); local != index; ++local)
1718 base += elements[local]->size;
1723 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1725 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1726 Type_privateData *typical(internal->type_);
1728 if (typical->type_ == NULL)
1732 if (!CYGetIndex(pool, property, index))
1735 ffi_type *ffi(typical->GetFFI());
1737 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1738 base += ffi->size * index;
1740 JSObjectRef owner(internal->owner_ ?: object);
1743 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
1747 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1749 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1750 Type_privateData *typical(internal->type_);
1752 if (typical->type_ == NULL)
1756 if (!CYGetIndex(pool, property, index))
1759 ffi_type *ffi(typical->GetFFI());
1761 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1762 base += ffi->size * index;
1765 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
1770 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1772 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1773 Type_privateData *typical(internal->type_);
1778 if (!Index_(pool, internal, property, index, base))
1781 JSObjectRef owner(internal->owner_ ?: object);
1784 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
1788 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1790 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1791 Type_privateData *typical(internal->type_);
1796 if (!Index_(pool, internal, property, index, base))
1800 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1805 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1806 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1807 Type_privateData *typical(internal->type_);
1808 sig::Type *type(typical->type_);
1813 size_t count(type->data.signature.count);
1814 sig::Element *elements(type->data.signature.elements);
1818 for (size_t index(0); index != count; ++index) {
1820 name = elements[index].name;
1823 sprintf(number, "%lu", index);
1827 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1831 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)()) {
1833 if (setups + count != signature->count - 1)
1834 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1836 size_t size(setups + count);
1838 memcpy(values, setup, sizeof(void *) * setups);
1840 for (size_t index(setups); index != size; ++index) {
1841 sig::Element *element(&signature->elements[index + 1]);
1842 ffi_type *ffi(cif->arg_types[index]);
1844 values[index] = new(pool) uint8_t[ffi->size];
1845 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1848 uint8_t value[cif->rtype->size];
1849 ffi_call(cif, function, value, values);
1851 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1855 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1856 ffoData *data(reinterpret_cast<ffoData *>(arg));
1858 JSContextRef context(data->context_);
1860 size_t count(data->cif_.nargs);
1861 JSValueRef values[count];
1863 for (size_t index(0); index != count; ++index)
1864 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
1866 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1867 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1870 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1871 // XXX: in case of exceptions this will leak
1872 ffoData *data(new ffoData(type));
1874 ffi_closure *closure;
1875 _syscall(closure = (ffi_closure *) mmap(
1876 NULL, sizeof(ffi_closure),
1877 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1881 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1882 _assert(status == FFI_OK);
1884 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1886 data->value_ = closure;
1888 data->context_ = CYGetJSContext();
1889 data->function_ = function;
1891 return JSObjectMake(context, Functor_, data);
1894 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1897 NSString *name(CYCastNSString(pool, property));
1898 if (Class _class = NSClassFromString(name))
1899 return CYMakeInstance(context, _class, true);
1900 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1901 switch ([[entry objectAtIndex:0] intValue]) {
1903 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1905 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1907 // XXX: this is horrendously inefficient
1908 sig::Signature signature;
1909 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1911 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1912 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
1918 bool stret(ffi_type *ffi_type) {
1919 return ffi_type->type == FFI_TYPE_STRUCT && (
1920 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1921 struct_forward_array[ffi_type->size] != 0
1926 int *_NSGetArgc(void);
1927 char ***_NSGetArgv(void);
1928 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1931 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1933 NSLog(@"%s", CYCastCString(context, arguments[0]));
1934 return CYJSUndefined(context);
1938 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
1941 Class _class(object_getClass(self));
1942 if (Method method = class_getInstanceMethod(_class, _cmd))
1943 type = method_getTypeEncoding(method);
1946 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1948 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1949 type = CYPoolCString(pool, [method _typeString]);
1957 sig::Signature signature;
1958 sig::Parse(pool, &signature, type, &Structor_);
1961 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1963 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1964 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
1967 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1977 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1979 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1980 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1981 self = data->GetValue();
1982 uninitialized = data->IsUninitialized();
1986 self = CYCastNSObject(pool, context, arguments[0]);
1987 uninitialized = false;
1991 return CYJSNull(context);
1993 _cmd = CYCastSEL(context, arguments[1]);
1996 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
1999 void dealloc_(id self, SEL sel) {
2000 CYInternal *internal;
2001 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2002 if (internal != NULL)
2004 if (Method dealloc = class_getInstanceMethod(object_getClass(self), @selector(cy$dealloc)))
2005 reinterpret_cast<void (*)(id, SEL)>(method_getImplementation(dealloc))(self, sel);
2008 MSHook(void, objc_registerClassPair, Class _class) {
2009 Class super(class_getSuperclass(_class));
2010 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2011 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2012 if (!class_addMethod(_class, @selector(dealloc), reinterpret_cast<IMP>(&dealloc_), "v8@0:4")) {
2013 Method dealloc(class_getInstanceMethod(_class, @selector(dealloc)));
2014 class_addMethod(_class, @selector(cy$dealloc), method_getImplementation(dealloc), method_getTypeEncoding(dealloc));
2015 method_setImplementation(dealloc, reinterpret_cast<IMP>(&dealloc_));
2019 _objc_registerClassPair(_class);
2022 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2025 Class _class(CYCastNSObject(pool, context, object));
2026 $objc_registerClassPair(_class);
2027 return CYJSUndefined(context);
2031 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2032 JSValueRef setup[count + 2];
2035 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2036 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2039 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2041 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2042 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
2045 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2048 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2049 const char *name(CYCastCString(context, arguments[0]));
2050 return CYMakeSelector(context, sel_registerName(name));
2054 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2057 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2059 void *value(CYCastPointer<void *>(context, arguments[0]));
2060 const char *type(CYCastCString(context, arguments[1]));
2064 sig::Signature signature;
2065 sig::Parse(pool, &signature, type, &Structor_);
2067 return CYMakePointer(context, value, signature.elements[0].type, NULL);
2071 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2074 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2075 const char *type(CYCastCString(context, arguments[1]));
2076 JSValueRef exception(NULL);
2077 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
2078 JSObjectRef function(CYCastJSObject(context, arguments[0]));
2079 return CYMakeFunctor(context, function, type);
2080 } else if (exception != NULL) {
2083 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
2084 return CYMakeFunctor(context, function, type);
2089 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2090 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2091 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2094 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2098 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2100 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2101 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2105 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2106 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2109 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2111 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2113 sprintf(string, "%p", internal->value_);
2114 return CYCastJSValue(context, string);
2118 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2120 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2122 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
2127 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2129 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2131 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2132 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2137 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2139 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2141 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2146 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2148 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2149 return CYCastJSValue(context, sel_getName(data->GetValue()));
2153 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2154 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2157 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2159 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2160 const char *name(sel_getName(data->GetValue()));
2162 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2167 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2170 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2172 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2173 Class _class(CYCastNSObject(pool, context, arguments[0]));
2174 bool instance(CYCastBool(context, arguments[1]));
2175 SEL sel(data->GetValue());
2176 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
2177 return CYCastJSValue(context, method_getTypeEncoding(method));
2178 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2179 return CYCastJSValue(context, CYJSString(type));
2181 return CYJSNull(context);
2185 static JSStaticValue CYValue_staticValues[2] = {
2186 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2187 {NULL, NULL, NULL, 0}
2190 static JSStaticFunction Pointer_staticFunctions[4] = {
2191 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2192 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2193 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2197 static JSStaticFunction Functor_staticFunctions[4] = {
2198 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2199 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2200 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2204 /*static JSStaticValue Selector_staticValues[2] = {
2205 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2206 {NULL, NULL, NULL, 0}
2209 static JSStaticFunction Instance_staticFunctions[4] = {
2210 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2211 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2212 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2216 static JSStaticFunction Selector_staticFunctions[5] = {
2217 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2218 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2219 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2220 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2224 CYDriver::CYDriver(const std::string &filename) :
2228 filename_(filename),
2234 CYDriver::~CYDriver() {
2238 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2239 CYDriver::Error error;
2240 error.location_ = location;
2241 error.message_ = message;
2242 driver.errors_.push_back(error);
2245 void CYSetArgs(int argc, const char *argv[]) {
2246 JSContextRef context(CYGetJSContext());
2247 JSValueRef args[argc];
2248 for (int i(0); i != argc; ++i)
2249 args[i] = CYCastJSValue(context, argv[i]);
2250 JSValueRef exception(NULL);
2251 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2252 CYThrow(context, exception);
2253 CYSetProperty(context, System_, CYJSString("args"), array);
2256 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2257 return JSContextGetGlobalObject(context);
2260 MSInitialize { _pooled
2263 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2265 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2267 JSClassDefinition definition;
2269 definition = kJSClassDefinitionEmpty;
2270 definition.className = "Pointer";
2271 definition.staticFunctions = Pointer_staticFunctions;
2272 definition.getProperty = &Pointer_getProperty;
2273 definition.setProperty = &Pointer_setProperty;
2274 definition.finalize = &CYData::Finalize;
2275 Pointer_ = JSClassCreate(&definition);
2277 definition = kJSClassDefinitionEmpty;
2278 definition.className = "Functor";
2279 definition.staticFunctions = Functor_staticFunctions;
2280 definition.callAsFunction = &Functor_callAsFunction;
2281 definition.finalize = &CYData::Finalize;
2282 Functor_ = JSClassCreate(&definition);
2284 definition = kJSClassDefinitionEmpty;
2285 definition.className = "Struct";
2286 definition.getProperty = &Struct_getProperty;
2287 definition.setProperty = &Struct_setProperty;
2288 definition.getPropertyNames = &Struct_getPropertyNames;
2289 definition.finalize = &CYData::Finalize;
2290 Struct_ = JSClassCreate(&definition);
2292 definition = kJSClassDefinitionEmpty;
2293 definition.className = "Selector";
2294 definition.staticValues = CYValue_staticValues;
2295 //definition.staticValues = Selector_staticValues;
2296 definition.staticFunctions = Selector_staticFunctions;
2297 definition.callAsFunction = &Selector_callAsFunction;
2298 definition.finalize = &CYData::Finalize;
2299 Selector_ = JSClassCreate(&definition);
2301 definition = kJSClassDefinitionEmpty;
2302 definition.className = "Instance";
2303 definition.staticValues = CYValue_staticValues;
2304 definition.staticFunctions = Instance_staticFunctions;
2305 definition.getProperty = &Instance_getProperty;
2306 definition.setProperty = &Instance_setProperty;
2307 definition.deleteProperty = &Instance_deleteProperty;
2308 definition.callAsConstructor = &Instance_callAsConstructor;
2309 definition.finalize = &CYData::Finalize;
2310 Instance_ = JSClassCreate(&definition);
2312 definition = kJSClassDefinitionEmpty;
2313 definition.className = "Runtime";
2314 definition.getProperty = &Runtime_getProperty;
2315 Runtime_ = JSClassCreate(&definition);
2317 definition = kJSClassDefinitionEmpty;
2318 //definition.getProperty = &Global_getProperty;
2319 JSClassRef Global(JSClassCreate(&definition));
2321 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2324 JSObjectRef global(CYGetGlobalObject(context));
2326 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2327 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2329 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2330 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
2331 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2333 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2335 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
2336 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2338 System_ = JSObjectMake(context, NULL, NULL);
2339 CYSetProperty(context, global, CYJSString("system"), System_);
2340 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2341 //CYSetProperty(context, System_, CYJSString("global"), global);
2343 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2345 length_ = JSStringCreateWithUTF8CString("length");
2346 message_ = JSStringCreateWithUTF8CString("message");
2347 name_ = JSStringCreateWithUTF8CString("name");
2348 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2349 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2351 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2352 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));