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_;
131 CYData(void *value) :
139 void *operator new(size_t size) {
141 apr_pool_create(&pool, NULL);
142 void *data(apr_palloc(pool, size));
143 reinterpret_cast<CYData *>(data)->pool_ = pool;
147 static void Finalize(JSObjectRef object) {
148 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
150 apr_pool_destroy(data->pool_);
154 struct Selector_privateData :
157 Selector_privateData(SEL value) :
162 SEL GetValue() const {
163 return reinterpret_cast<SEL>(value_);
172 Transient = (1 << 0),
173 Uninitialized = (1 << 1),
178 Instance(id value, Flags flags) :
184 virtual ~Instance() {
185 if ((flags_ & Transient) == 0)
186 [GetValue() release];
189 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
190 return JSObjectMake(context, Instance_, new Instance(object, flags));
193 id GetValue() const {
194 return reinterpret_cast<id>(value_);
197 bool IsUninitialized() const {
198 return (flags_ & Uninitialized) != 0;
204 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
206 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
207 lhs.name = apr_pstrdup(pool, rhs.name);
208 if (rhs.type == NULL)
211 lhs.type = new(pool) Type;
212 Copy(pool, *lhs.type, *rhs.type);
214 lhs.offset = rhs.offset;
217 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
218 size_t count(rhs.count);
220 lhs.elements = new(pool) Element[count];
221 for (size_t index(0); index != count; ++index)
222 Copy(pool, lhs.elements[index], rhs.elements[index]);
225 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
226 lhs.primitive = rhs.primitive;
227 lhs.name = apr_pstrdup(pool, rhs.name);
228 lhs.flags = rhs.flags;
230 if (sig::IsAggregate(rhs.primitive))
231 Copy(pool, lhs.data.signature, rhs.data.signature);
233 if (rhs.data.data.type != NULL) {
234 lhs.data.data.type = new(pool) Type;
235 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
238 lhs.data.data.size = rhs.data.data.size;
242 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
244 lhs.alignment = rhs.alignment;
246 if (rhs.elements == NULL)
250 while (rhs.elements[count] != NULL)
253 lhs.elements = new(pool) ffi_type *[count + 1];
254 lhs.elements[count] = NULL;
256 for (size_t index(0); index != count; ++index) {
257 // XXX: if these are libffi native then you can just take them
258 ffi_type *ffi(new(pool) ffi_type);
259 lhs.elements[index] = ffi;
260 sig::Copy(pool, *ffi, *rhs.elements[index]);
267 struct CStringMapLess :
268 std::binary_function<const char *, const char *, bool>
270 _finline bool operator ()(const char *lhs, const char *rhs) const {
271 return strcmp(lhs, rhs) < 0;
275 struct Type_privateData {
281 Type_privateData(apr_pool_t *pool, sig::Type *type) :
285 sig::Copy(pool, type_, *type);
288 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) :
291 ffi_ = new(pool) ffi_type;
292 sig::Copy(pool, *ffi_, *ffi);
293 sig::Copy(pool, type_, *type);
298 ffi_ = new(pool_) ffi_type;
300 sig::Element element;
302 element.type = &type_;
305 sig::Signature signature;
306 signature.elements = &element;
310 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
322 Type_privateData *type_;
324 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
327 type_(new(pool_) Type_privateData(pool_, type))
332 struct Struct_privateData :
336 Type_privateData *type_;
338 Struct_privateData(JSObjectRef owner) :
344 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
345 static TypeMap Types_;
347 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
348 Struct_privateData *internal(new Struct_privateData(owner));
349 apr_pool_t *pool(internal->pool_);
350 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
351 internal->type_ = typical;
354 internal->value_ = data;
356 size_t size(typical->GetFFI()->size);
357 void *copy(apr_palloc(internal->pool_, size));
358 memcpy(copy, data, size);
359 internal->value_ = copy;
362 return JSObjectMake(context, Struct_, internal);
365 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *type) {
370 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
371 switch ([[entry objectAtIndex:0] intValue]) {
374 sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
381 struct Functor_privateData :
384 sig::Signature signature_;
387 Functor_privateData(const char *type, void (*value)()) :
388 CYData(reinterpret_cast<void *>(value))
390 sig::Parse(pool_, &signature_, type, &Structor_);
391 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
398 JSContextRef context_;
399 JSObjectRef function_;
401 ffoData(const char *type) :
402 Functor_privateData(type, NULL)
407 JSValueRef CYMakeInstance(JSContextRef context, id object, bool transient) {
408 Instance::Flags flags;
411 flags = Instance::Transient;
413 flags = Instance::None;
414 object = [object retain];
417 return Instance::Make(context, object, flags);
420 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
422 return [value UTF8String];
424 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
425 char *string(new(pool) char[size]);
426 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
427 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
432 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
433 return JSValueMakeBoolean(context, value);
436 JSValueRef CYCastJSValue(JSContextRef context, double value) {
437 return JSValueMakeNumber(context, value);
440 #define CYCastJSValue_(Type_) \
441 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
442 return JSValueMakeNumber(context, static_cast<double>(value)); \
446 CYCastJSValue_(unsigned int)
447 CYCastJSValue_(long int)
448 CYCastJSValue_(long unsigned int)
449 CYCastJSValue_(long long int)
450 CYCastJSValue_(long long unsigned int)
452 JSValueRef CYJSUndefined(JSContextRef context) {
453 return JSValueMakeUndefined(context);
456 bool CYGetIndex(const char *value, ssize_t &index) {
457 if (value[0] != '0') {
459 index = strtol(value, &end, 10);
460 if (value + strlen(value) == end)
462 } else if (value[1] == '\0') {
470 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
471 return CYGetIndex(CYPoolCString(pool, value), index);
474 @interface NSMethodSignature (Cycript)
475 - (NSString *) _typeString;
478 @interface NSObject (Cycript)
480 - (JSType) cy$JSType;
482 - (NSObject *) cy$toJSON:(NSString *)key;
483 - (NSString *) cy$toCYON;
484 - (NSString *) cy$toKey;
486 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
488 - (NSObject *) cy$getProperty:(NSString *)name;
489 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
490 - (bool) cy$deleteProperty:(NSString *)name;
494 @interface NSString (Cycript)
495 - (void *) cy$symbol;
498 @interface NSNumber (Cycript)
499 - (void *) cy$symbol;
502 struct PropertyAttributes {
507 const char *variable;
520 PropertyAttributes(objc_property_t property) :
532 name = property_getName(property);
533 const char *attributes(property_getAttributes(property));
535 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
537 case 'R': readonly = true; break;
538 case 'C': copy = true; break;
539 case '&': retain = true; break;
540 case 'N': nonatomic = true; break;
541 case 'G': getter_ = token + 1; break;
542 case 'S': setter_ = token + 1; break;
543 case 'V': variable = token + 1; break;
547 /*if (variable == NULL) {
548 variable = property_getName(property);
549 size_t size(strlen(variable));
550 char *name(new(pool_) char[size + 2]);
552 memcpy(name + 1, variable, size);
553 name[size + 1] = '\0';
558 const char *Getter() {
560 getter_ = apr_pstrdup(pool_, name);
564 const char *Setter() {
565 if (setter_ == NULL && !readonly) {
566 size_t length(strlen(name));
568 char *temp(new(pool_) char[length + 5]);
574 temp[3] = toupper(name[0]);
575 memcpy(temp + 4, name + 1, length - 1);
578 temp[length + 3] = ':';
579 temp[length + 4] = '\0';
588 @implementation NSObject (Cycript)
590 - (JSType) cy$JSType {
591 return kJSTypeObject;
594 - (NSObject *) cy$toJSON:(NSString *)key {
595 return [self description];
598 - (NSString *) cy$toCYON {
599 return [[self cy$toJSON:@""] cy$toCYON];
602 - (NSString *) cy$toKey {
603 return [self cy$toCYON];
606 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
607 return CYMakeInstance(context, self, false);
610 - (NSObject *) cy$getProperty:(NSString *)name {
611 /*if (![name isEqualToString:@"prototype"])
612 NSLog(@"get:%@", name);*/
616 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
617 //NSLog(@"set:%@", name);
621 - (bool) cy$deleteProperty:(NSString *)name {
622 //NSLog(@"delete:%@", name);
628 @implementation WebUndefined (Cycript)
630 - (JSType) cy$JSType {
631 return kJSTypeUndefined;
634 - (NSObject *) cy$toJSON:(NSString *)key {
638 - (NSString *) cy$toCYON {
642 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
643 return CYJSUndefined(context);
648 @implementation NSNull (Cycript)
650 - (JSType) cy$JSType {
654 - (NSObject *) cy$toJSON:(NSString *)key {
658 - (NSString *) cy$toCYON {
664 @implementation NSArray (Cycript)
666 - (NSString *) cy$toCYON {
667 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
668 [json appendString:@"["];
671 for (id object in self) {
673 [json appendString:@","];
676 if ([object cy$JSType] != kJSTypeUndefined)
677 [json appendString:[object cy$toCYON]];
679 [json appendString:@","];
684 [json appendString:@"]"];
688 - (NSObject *) cy$getProperty:(NSString *)name {
689 if ([name isEqualToString:@"length"])
690 return [NSNumber numberWithUnsignedInteger:[self count]];
693 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
694 return [super cy$getProperty:name];
696 return [self objectAtIndex:index];
701 @implementation NSMutableArray (Cycript)
703 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
705 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
706 return [super cy$setProperty:name to:value];
708 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
713 - (bool) cy$deleteProperty:(NSString *)name {
715 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
716 return [super cy$deleteProperty:name];
718 [self removeObjectAtIndex:index];
725 @implementation NSDictionary (Cycript)
727 - (NSString *) cy$toCYON {
728 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
729 [json appendString:@"{"];
732 for (id key in self) {
734 [json appendString:@","];
737 [json appendString:[key cy$toKey]];
738 [json appendString:@":"];
739 NSObject *object([self objectForKey:key]);
740 [json appendString:[object cy$toCYON]];
743 [json appendString:@"}"];
747 - (NSObject *) cy$getProperty:(NSString *)name {
748 return [self objectForKey:name];
753 @implementation NSMutableDictionary (Cycript)
755 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
756 [self setObject:(value ?: [NSNull null]) forKey:name];
760 - (bool) cy$deleteProperty:(NSString *)name {
761 if ([self objectForKey:name] == nil)
764 [self removeObjectForKey:name];
771 @implementation NSNumber (Cycript)
773 - (JSType) cy$JSType {
774 // XXX: this just seems stupid
775 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
778 - (NSObject *) cy$toJSON:(NSString *)key {
782 - (NSString *) cy$toCYON {
783 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
786 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
787 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
790 - (void *) cy$symbol {
791 return [self pointerValue];
796 @implementation NSString (Cycript)
798 - (JSType) cy$JSType {
799 return kJSTypeString;
802 - (NSObject *) cy$toJSON:(NSString *)key {
806 - (NSString *) cy$toCYON {
807 // XXX: this should use the better code from Output.cpp
808 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
810 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
811 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
812 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
813 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
814 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
816 CFStringInsert(json, 0, CFSTR("\""));
817 CFStringAppend(json, CFSTR("\""));
819 return [reinterpret_cast<const NSString *>(json) autorelease];
822 - (NSString *) cy$toKey {
823 const char *value([self UTF8String]);
824 size_t size(strlen(value));
829 if (DigitRange_[value[0]]) {
831 if (!CYGetIndex(NULL, self, index) || index < 0)
834 if (!WordStartRange_[value[0]])
836 for (size_t i(1); i != size; ++i)
837 if (!WordEndRange_[value[i]])
844 return [self cy$toCYON];
847 - (void *) cy$symbol {
849 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
854 @interface CYJSObject : NSDictionary {
856 JSContextRef context_;
859 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
861 - (NSString *) cy$toJSON:(NSString *)key;
863 - (NSUInteger) count;
864 - (id) objectForKey:(id)key;
865 - (NSEnumerator *) keyEnumerator;
866 - (void) setObject:(id)object forKey:(id)key;
867 - (void) removeObjectForKey:(id)key;
871 @interface CYJSArray : NSArray {
873 JSContextRef context_;
876 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
878 - (NSUInteger) count;
879 - (id) objectAtIndex:(NSUInteger)index;
883 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
884 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
885 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
887 JSGlobalContextRef CYGetJSContext() {
894 @catch (id error) { \
895 CYThrow(context, error, exception); \
899 void CYThrow(JSContextRef context, JSValueRef value);
901 apr_status_t CYPoolRelease_(void *data) {
902 id object(reinterpret_cast<id>(data));
907 id CYPoolRelease(apr_pool_t *pool, id object) {
910 else if (pool == NULL)
911 return [object autorelease];
913 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
918 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
919 return (CFTypeRef) CYPoolRelease(pool, (id) object);
922 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
923 JSValueRef exception(NULL);
924 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
925 CYThrow(context, exception);
926 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
927 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
930 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
931 if (!JSValueIsObjectOfClass(context, object, Instance_))
932 return CYCastNSObject_(pool, context, object);
934 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
935 return data->GetValue();
939 JSStringRef CYCopyJSString(id value) {
940 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
943 JSStringRef CYCopyJSString(const char *value) {
944 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
947 JSStringRef CYCopyJSString(JSStringRef value) {
948 return value == NULL ? NULL : JSStringRetain(value);
951 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
952 if (JSValueIsNull(context, value))
954 JSValueRef exception(NULL);
955 JSStringRef string(JSValueToStringCopy(context, value, &exception));
956 CYThrow(context, exception);
966 JSStringRelease(string_);
970 CYJSString(const CYJSString &rhs) :
971 string_(CYCopyJSString(rhs.string_))
975 template <typename Arg0_>
976 CYJSString(Arg0_ arg0) :
977 string_(CYCopyJSString(arg0))
981 template <typename Arg0_, typename Arg1_>
982 CYJSString(Arg0_ arg0, Arg1_ arg1) :
983 string_(CYCopyJSString(arg0, arg1))
987 CYJSString &operator =(const CYJSString &rhs) {
989 string_ = CYCopyJSString(rhs.string_);
1002 operator JSStringRef() const {
1007 CFStringRef CYCopyCFString(JSStringRef value) {
1008 return JSStringCopyCFString(kCFAllocatorDefault, value);
1011 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1012 return CYCopyCFString(CYJSString(context, value));
1015 double CYCastDouble(const char *value, size_t size) {
1017 double number(strtod(value, &end));
1018 if (end != value + size)
1023 double CYCastDouble(const char *value) {
1024 return CYCastDouble(value, strlen(value));
1027 double CYCastDouble(JSContextRef context, JSValueRef value) {
1028 JSValueRef exception(NULL);
1029 double number(JSValueToNumber(context, value, &exception));
1030 CYThrow(context, exception);
1034 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1035 double number(CYCastDouble(context, value));
1036 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1039 CFStringRef CYCopyCFString(const char *value) {
1040 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1043 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1044 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1047 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1048 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1051 bool CYCastBool(JSContextRef context, JSValueRef value) {
1052 return JSValueToBoolean(context, value);
1055 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1059 switch (JSType type = JSValueGetType(context, value)) {
1060 case kJSTypeUndefined:
1061 object = [WebUndefined undefined];
1069 case kJSTypeBoolean:
1070 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1075 object = CYCopyCFNumber(context, value);
1080 object = CYCopyCFString(context, value);
1085 // XXX: this might could be more efficient
1086 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1091 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1098 return CYPoolRelease(pool, object);
1100 return CFRetain(object);
1103 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1104 return CYCFType(pool, context, value, true);
1107 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1108 return CYCFType(pool, context, value, false);
1111 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1113 size_t size(JSPropertyNameArrayGetCount(names));
1114 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1115 for (size_t index(0); index != size; ++index)
1116 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1120 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1121 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1124 void CYThrow(JSContextRef context, JSValueRef value) {
1127 @throw CYCastNSObject(NULL, context, value);
1130 JSValueRef CYJSNull(JSContextRef context) {
1131 return JSValueMakeNull(context);
1134 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1135 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1138 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1139 return CYCastJSValue(context, CYJSString(value));
1142 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1143 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context];
1146 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1147 JSValueRef exception(NULL);
1148 JSObjectRef object(JSValueToObject(context, value, &exception));
1149 CYThrow(context, exception);
1153 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1154 JSValueRef exception(NULL);
1155 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1156 CYThrow(context, exception);
1160 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1161 JSValueRef exception(NULL);
1162 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1163 CYThrow(context, exception);
1167 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1168 JSValueRef exception(NULL);
1169 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1170 CYThrow(context, exception);
1173 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1174 if (exception == NULL)
1176 *exception = CYCastJSValue(context, error);
1179 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1180 JSValueRef exception(NULL);
1181 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1182 CYThrow(context, exception);
1186 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1187 // XXX: this isn't actually correct
1188 return value != NULL && JSValueIsObject(context, value);
1191 @implementation CYJSObject
1193 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1194 if ((self = [super init]) != nil) {
1200 - (NSObject *) cy$toJSON:(NSString *)key {
1201 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1202 if (!CYIsCallable(context_, toJSON))
1203 return [super cy$toJSON:key];
1205 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1206 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1207 // XXX: do I really want an NSNull here?!
1208 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1212 - (NSString *) cy$toCYON {
1213 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1214 if (!CYIsCallable(context_, toCYON))
1215 return [super cy$toCYON];
1217 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1218 return CYCastNSString(NULL, CYJSString(context_, value));
1222 - (NSUInteger) count {
1223 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1224 size_t size(JSPropertyNameArrayGetCount(names));
1225 JSPropertyNameArrayRelease(names);
1229 - (id) objectForKey:(id)key {
1230 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1233 - (NSEnumerator *) keyEnumerator {
1234 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1235 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1236 JSPropertyNameArrayRelease(names);
1240 - (void) setObject:(id)object forKey:(id)key {
1241 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1244 - (void) removeObjectForKey:(id)key {
1245 JSValueRef exception(NULL);
1246 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1247 CYThrow(context_, exception);
1252 @implementation CYJSArray
1254 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1255 if ((self = [super init]) != nil) {
1261 - (NSUInteger) count {
1262 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1265 - (id) objectAtIndex:(NSUInteger)index {
1266 JSValueRef exception(NULL);
1267 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1268 CYThrow(context_, exception);
1269 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1274 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1277 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1278 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1283 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1284 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1285 const char *string(CYPoolCString(pool, json));
1291 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1295 NSString *self(CYCastNSObject(pool, context, object));
1296 NSString *name(CYCastNSString(pool, property));
1299 if (NSObject *data = [self cy$getProperty:name])
1300 return CYCastJSValue(context, data);
1303 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1304 PropertyAttributes attributes(property);
1305 SEL sel(sel_registerName(attributes.Getter()));
1306 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1313 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1317 NSString *self(CYCastNSObject(pool, context, object));
1318 NSString *name(CYCastNSString(pool, property));
1319 NSString *data(CYCastNSObject(pool, context, value));
1322 if ([self cy$setProperty:name to:data])
1326 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1327 PropertyAttributes attributes(property);
1328 if (const char *setter = attributes.Setter()) {
1329 SEL sel(sel_registerName(setter));
1330 JSValueRef arguments[1] = {value};
1331 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1340 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1343 NSString *self(CYCastNSObject(NULL, context, object));
1344 NSString *name(CYCastNSString(NULL, property));
1345 return [self cy$deleteProperty:name];
1350 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1352 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1353 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1358 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1359 Selector_privateData *data(new Selector_privateData(sel));
1360 return JSObjectMake(context, Selector_, data);
1363 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
1364 Pointer *data(new Pointer(pointer, type, owner));
1365 return JSObjectMake(context, Pointer_, data);
1368 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1369 Functor_privateData *data(new Functor_privateData(type, function));
1370 return JSObjectMake(context, Functor_, data);
1373 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1375 const char *string([CYCastNSString(NULL, value) UTF8String]);
1377 *length = strlen(string);
1380 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1381 char *string(new(pool) char[size]);
1382 JSStringGetUTF8CString(value, string, size);
1383 // XXX: this is ironic
1385 *length = strlen(string);
1390 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1391 if (!JSValueIsNull(context, value))
1392 return CYPoolCString(pool, CYJSString(context, value), length);
1400 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1401 return CYGetIndex(CYPoolCString(pool, value), index);
1404 // XXX: this macro is unhygenic
1405 #define CYCastCString(context, value) ({ \
1407 if (value == NULL) \
1409 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1410 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1411 utf8 = reinterpret_cast<char *>(alloca(size)); \
1412 JSStringGetUTF8CString(string, utf8, size); \
1413 JSStringRelease(string); \
1419 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1420 switch (JSValueGetType(context, value)) {
1423 /*case kJSTypeString:
1424 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1426 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1427 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1428 return data->value_;
1431 double number(CYCastDouble(context, value));
1432 if (std::isnan(number))
1433 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1434 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1438 template <typename Type_>
1439 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1440 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1443 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1444 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1445 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1446 return reinterpret_cast<SEL>(data->value_);
1448 return CYCastPointer<SEL>(context, value);
1451 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1452 switch (type->primitive) {
1453 case sig::boolean_P:
1454 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1457 #define CYPoolFFI_(primitive, native) \
1458 case sig::primitive ## _P: \
1459 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1462 CYPoolFFI_(uchar, unsigned char)
1463 CYPoolFFI_(char, char)
1464 CYPoolFFI_(ushort, unsigned short)
1465 CYPoolFFI_(short, short)
1466 CYPoolFFI_(ulong, unsigned long)
1467 CYPoolFFI_(long, long)
1468 CYPoolFFI_(uint, unsigned int)
1469 CYPoolFFI_(int, int)
1470 CYPoolFFI_(ulonglong, unsigned long long)
1471 CYPoolFFI_(longlong, long long)
1472 CYPoolFFI_(float, float)
1473 CYPoolFFI_(double, double)
1476 case sig::typename_P:
1477 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1480 case sig::selector_P:
1481 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1484 case sig::pointer_P:
1485 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1489 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1492 case sig::struct_P: {
1493 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1494 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1495 for (size_t index(0); index != type->data.signature.count; ++index) {
1496 sig::Element *element(&type->data.signature.elements[index]);
1497 ffi_type *field(ffi->elements[index]);
1500 if (aggregate == NULL)
1503 rhs = CYGetProperty(context, aggregate, index);
1504 if (JSValueIsUndefined(context, rhs)) {
1505 if (element->name != NULL)
1506 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1509 if (JSValueIsUndefined(context, rhs)) undefined:
1510 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1514 CYPoolFFI(pool, context, element->type, field, base, rhs);
1516 base += field->size;
1524 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1529 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
1532 switch (type->primitive) {
1533 case sig::boolean_P:
1534 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1537 #define CYFromFFI_(primitive, native) \
1538 case sig::primitive ## _P: \
1539 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1542 CYFromFFI_(uchar, unsigned char)
1543 CYFromFFI_(char, char)
1544 CYFromFFI_(ushort, unsigned short)
1545 CYFromFFI_(short, short)
1546 CYFromFFI_(ulong, unsigned long)
1547 CYFromFFI_(long, long)
1548 CYFromFFI_(uint, unsigned int)
1549 CYFromFFI_(int, int)
1550 CYFromFFI_(ulonglong, unsigned long long)
1551 CYFromFFI_(longlong, long long)
1552 CYFromFFI_(float, float)
1553 CYFromFFI_(double, double)
1555 case sig::object_P: {
1556 if (id object = *reinterpret_cast<id *>(data)) {
1557 value = CYCastJSValue(context, object);
1563 case sig::typename_P:
1564 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1567 case sig::selector_P:
1568 if (SEL sel = *reinterpret_cast<SEL *>(data))
1569 value = CYMakeSelector(context, sel);
1573 case sig::pointer_P:
1574 if (void *pointer = *reinterpret_cast<void **>(data))
1575 value = CYMakePointer(context, pointer, type->data.data.type, owner);
1580 if (char *utf8 = *reinterpret_cast<char **>(data))
1581 value = CYCastJSValue(context, utf8);
1586 value = CYMakeStruct(context, data, type, ffi, owner);
1590 value = CYJSUndefined(context);
1594 value = CYJSNull(context);
1598 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1605 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1606 Type_privateData *typical(internal->type_);
1609 const char *name(CYPoolCString(pool, property, &length));
1610 double number(CYCastDouble(name, length));
1612 size_t count(typical->type_.data.signature.count);
1614 if (std::isnan(number)) {
1615 if (property == NULL)
1618 sig::Element *elements(typical->type_.data.signature.elements);
1620 for (size_t local(0); local != count; ++local) {
1621 sig::Element *element(&elements[local]);
1622 if (element->name != NULL && strcmp(name, element->name) == 0) {
1630 index = static_cast<ssize_t>(number);
1631 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1636 ffi_type **elements(typical->GetFFI()->elements);
1638 base = reinterpret_cast<uint8_t *>(internal->value_);
1639 for (ssize_t local(0); local != index; ++local)
1640 base += elements[local]->size;
1645 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1647 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1648 Type_privateData *typical(internal->type_);
1651 if (!CYGetIndex(pool, property, index))
1654 ffi_type *ffi(typical->GetFFI());
1656 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1657 base += ffi->size * index;
1659 JSObjectRef owner(internal->owner_ ?: object);
1662 return CYFromFFI(context, &typical->type_, ffi, base, false, owner);
1666 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1668 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1669 Type_privateData *typical(internal->type_);
1674 if (!Index_(pool, internal, property, index, base))
1677 JSObjectRef owner(internal->owner_ ?: object);
1680 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
1684 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1686 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1687 Type_privateData *typical(internal->type_);
1692 if (!Index_(pool, internal, property, index, base))
1696 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1701 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1702 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1703 Type_privateData *typical(internal->type_);
1705 size_t count(typical->type_.data.signature.count);
1706 sig::Element *elements(typical->type_.data.signature.elements);
1710 for (size_t index(0); index != count; ++index) {
1712 name = elements[index].name;
1715 sprintf(number, "%lu", index);
1719 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1723 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)()) {
1725 if (setups + count != signature->count - 1)
1726 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1728 size_t size(setups + count);
1730 memcpy(values, setup, sizeof(void *) * setups);
1732 for (size_t index(setups); index != size; ++index) {
1733 sig::Element *element(&signature->elements[index + 1]);
1734 ffi_type *ffi(cif->arg_types[index]);
1736 values[index] = new(pool) uint8_t[ffi->size];
1737 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1740 uint8_t value[cif->rtype->size];
1741 ffi_call(cif, function, value, values);
1743 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1747 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1748 ffoData *data(reinterpret_cast<ffoData *>(arg));
1750 JSContextRef context(data->context_);
1752 size_t count(data->cif_.nargs);
1753 JSValueRef values[count];
1755 for (size_t index(0); index != count; ++index)
1756 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
1758 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1759 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1762 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1763 // XXX: in case of exceptions this will leak
1764 ffoData *data(new ffoData(type));
1766 ffi_closure *closure;
1767 _syscall(closure = (ffi_closure *) mmap(
1768 NULL, sizeof(ffi_closure),
1769 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1773 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1774 _assert(status == FFI_OK);
1776 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1778 data->value_ = closure;
1780 data->context_ = CYGetJSContext();
1781 data->function_ = function;
1783 return JSObjectMake(context, Functor_, data);
1786 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1789 NSString *name(CYCastNSString(pool, property));
1790 if (Class _class = NSClassFromString(name))
1791 return CYMakeInstance(context, _class, true);
1792 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1793 switch ([[entry objectAtIndex:0] intValue]) {
1795 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1797 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1799 // XXX: this is horrendously inefficient
1800 sig::Signature signature;
1801 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1803 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1804 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
1810 bool stret(ffi_type *ffi_type) {
1811 return ffi_type->type == FFI_TYPE_STRUCT && (
1812 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1813 struct_forward_array[ffi_type->size] != 0
1818 int *_NSGetArgc(void);
1819 char ***_NSGetArgv(void);
1820 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1823 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1825 NSLog(@"%s", CYCastCString(context, arguments[0]));
1826 return CYJSUndefined(context);
1830 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1834 int argc(CYCastDouble(context, arguments[0]));
1835 char **argv(CYCastPointer<char **>(context, arguments[1]));
1836 NSString *principal(CYCastNSObject(pool, context, arguments[2]));
1837 NSString *delegate(CYCastNSObject(pool, context, arguments[3]));
1839 argc = *_NSGetArgc() - 1;
1840 argv = *_NSGetArgv() + 1;
1841 for (int i(0); i != argc; ++i)
1842 NSLog(@"argv[%i]=%s", i, argv[i]);
1845 return CYCastJSValue(context, UIApplicationMain(argc, argv, principal, delegate));
1849 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
1852 Class _class(object_getClass(self));
1853 if (Method method = class_getInstanceMethod(_class, _cmd))
1854 type = method_getTypeEncoding(method);
1857 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1859 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1860 type = CYPoolCString(pool, [method _typeString]);
1868 sig::Signature signature;
1869 sig::Parse(pool, &signature, type, &Structor_);
1872 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1874 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1875 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
1878 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1888 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1890 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1891 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1892 self = data->GetValue();
1893 uninitialized = data->IsUninitialized();
1897 self = CYCastNSObject(pool, context, arguments[0]);
1898 uninitialized = false;
1902 return CYJSNull(context);
1904 _cmd = CYCastSEL(context, arguments[1]);
1907 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
1910 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1911 JSValueRef setup[count + 2];
1914 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1915 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1918 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1920 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1921 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1924 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1927 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1928 const char *name(CYCastCString(context, arguments[0]));
1929 return CYMakeSelector(context, sel_registerName(name));
1933 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1936 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1937 const char *type(CYCastCString(context, arguments[1]));
1938 JSValueRef exception(NULL);
1939 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1940 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1941 return CYMakeFunctor(context, function, type);
1942 } else if (exception != NULL) {
1945 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1946 return CYMakeFunctor(context, function, type);
1951 JSValueRef CYData_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1952 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
1953 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1956 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1960 static JSValueRef CYData_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1962 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(_this)));
1963 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1967 static JSValueRef CYData_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1968 return CYData_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1971 static JSValueRef CYData_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1973 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(_this)));
1975 sprintf(string, "%p", data->value_);
1976 return CYCastJSValue(context, string);
1980 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1982 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1984 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1989 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1991 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1993 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1994 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1999 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2001 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2003 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2008 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2010 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2011 return CYCastJSValue(context, sel_getName(data->GetValue()));
2015 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2016 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2019 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2021 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2022 const char *name(sel_getName(data->GetValue()));
2024 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2029 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2032 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2034 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2035 Class _class(CYCastNSObject(pool, context, arguments[0]));
2036 bool instance(CYCastBool(context, arguments[1]));
2037 SEL sel(data->GetValue());
2038 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
2039 return CYCastJSValue(context, method_getTypeEncoding(method));
2040 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2041 return CYCastJSValue(context, CYJSString(type));
2043 return CYJSNull(context);
2047 static JSStaticValue CYData_staticValues[2] = {
2048 {"value", &CYData_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2049 {NULL, NULL, NULL, 0}
2052 static JSStaticFunction Pointer_staticFunctions[4] = {
2053 {"toCYON", &CYData_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2054 {"toJSON", &CYData_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2055 {"valueOf", &CYData_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2059 static JSStaticFunction Functor_staticFunctions[4] = {
2060 {"toCYON", &CYData_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2061 {"toJSON", &CYData_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2062 {"valueOf", &CYData_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2066 /*static JSStaticValue Selector_staticValues[2] = {
2067 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2068 {NULL, NULL, NULL, 0}
2071 static JSStaticFunction Instance_staticFunctions[4] = {
2072 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2073 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2074 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2078 static JSStaticFunction Selector_staticFunctions[5] = {
2079 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2080 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2081 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2082 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2086 CYDriver::CYDriver(const std::string &filename) :
2090 filename_(filename),
2096 CYDriver::~CYDriver() {
2100 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2101 CYDriver::Error error;
2102 error.location_ = location;
2103 error.message_ = message;
2104 driver.errors_.push_back(error);
2107 void CYSetArgs(int argc, const char *argv[]) {
2108 JSContextRef context(CYGetJSContext());
2109 JSValueRef args[argc];
2110 for (int i(0); i != argc; ++i)
2111 args[i] = CYCastJSValue(context, argv[i]);
2112 JSValueRef exception(NULL);
2113 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2114 CYThrow(context, exception);
2115 CYSetProperty(context, System_, CYJSString("args"), array);
2118 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2119 return JSContextGetGlobalObject(context);
2122 MSInitialize { _pooled
2125 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2127 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2129 JSClassDefinition definition;
2131 definition = kJSClassDefinitionEmpty;
2132 definition.className = "Pointer";
2133 definition.staticFunctions = Pointer_staticFunctions;
2134 definition.getProperty = &Pointer_getProperty;
2135 definition.finalize = &CYData::Finalize;
2136 Pointer_ = JSClassCreate(&definition);
2138 definition = kJSClassDefinitionEmpty;
2139 definition.className = "Functor";
2140 definition.staticFunctions = Functor_staticFunctions;
2141 definition.callAsFunction = &Functor_callAsFunction;
2142 definition.finalize = &CYData::Finalize;
2143 Functor_ = JSClassCreate(&definition);
2145 definition = kJSClassDefinitionEmpty;
2146 definition.className = "Struct";
2147 definition.getProperty = &Struct_getProperty;
2148 definition.setProperty = &Struct_setProperty;
2149 definition.getPropertyNames = &Struct_getPropertyNames;
2150 definition.finalize = &CYData::Finalize;
2151 Struct_ = JSClassCreate(&definition);
2153 definition = kJSClassDefinitionEmpty;
2154 definition.className = "Selector";
2155 definition.staticValues = CYData_staticValues;
2156 //definition.staticValues = Selector_staticValues;
2157 definition.staticFunctions = Selector_staticFunctions;
2158 definition.callAsFunction = &Selector_callAsFunction;
2159 definition.finalize = &CYData::Finalize;
2160 Selector_ = JSClassCreate(&definition);
2162 definition = kJSClassDefinitionEmpty;
2163 definition.className = "Instance";
2164 definition.staticValues = CYData_staticValues;
2165 definition.staticFunctions = Instance_staticFunctions;
2166 definition.getProperty = &Instance_getProperty;
2167 definition.setProperty = &Instance_setProperty;
2168 definition.deleteProperty = &Instance_deleteProperty;
2169 definition.callAsConstructor = &Instance_callAsConstructor;
2170 definition.finalize = &CYData::Finalize;
2171 Instance_ = JSClassCreate(&definition);
2173 definition = kJSClassDefinitionEmpty;
2174 definition.className = "Runtime";
2175 definition.getProperty = &Runtime_getProperty;
2176 Runtime_ = JSClassCreate(&definition);
2178 definition = kJSClassDefinitionEmpty;
2179 //definition.getProperty = &Global_getProperty;
2180 JSClassRef Global(JSClassCreate(&definition));
2182 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2185 JSObjectRef global(CYGetGlobalObject(context));
2187 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2188 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2190 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2191 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2193 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
2194 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2196 System_ = JSObjectMake(context, NULL, NULL);
2197 CYSetProperty(context, global, CYJSString("system"), System_);
2198 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2199 //CYSetProperty(context, System_, CYJSString("global"), global);
2201 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2203 length_ = JSStringCreateWithUTF8CString("length");
2204 message_ = JSStringCreateWithUTF8CString("message");
2205 name_ = JSStringCreateWithUTF8CString("name");
2206 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2207 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2209 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2210 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));